@logswap/sdk 0.5.102 → 0.5.104
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 +14 -418
- package/dist/actions.d.ts +0 -39
- package/dist/actions.js +0 -39
- package/dist/admin.d.ts +0 -106
- package/dist/admin.js +1 -96
- package/dist/chains.d.ts +0 -49
- package/dist/chains.js +0 -30
- package/dist/claims.d.ts +0 -32
- package/dist/claims.js +0 -30
- package/dist/client.d.ts +0 -116
- package/dist/client.js +1 -231
- package/dist/fees.d.ts +1 -45
- package/dist/fees.js +0 -44
- package/dist/fpool.d.ts +4 -612
- package/dist/fpool.js +14 -490
- package/dist/generated.js +0 -30
- package/dist/history.d.ts +0 -61
- package/dist/history.js +5 -74
- package/dist/ids.d.ts +0 -30
- package/dist/ids.js +0 -31
- package/dist/index.d.ts +0 -7
- package/dist/index.js +0 -7
- package/dist/indexer.d.ts +0 -68
- package/dist/indexer.js +1 -77
- package/dist/keys.d.ts +0 -50
- package/dist/keys.js +0 -35
- package/dist/liquidity.d.ts +0 -128
- package/dist/liquidity.js +1 -107
- package/dist/onboard.d.ts +0 -52
- package/dist/onboard.js +1 -59
- package/dist/pools.d.ts +3 -157
- package/dist/pools.js +1 -164
- package/dist/positions.d.ts +0 -102
- package/dist/positions.js +1 -90
- package/dist/quote.d.ts +0 -14
- package/dist/quote.js +0 -14
- package/dist/swap.d.ts +0 -31
- package/dist/swap.js +5 -37
- package/dist/tokencache.d.ts +0 -48
- package/dist/tokencache.js +1 -73
- package/dist/write.d.ts +1 -87
- package/dist/write.js +1 -87
- package/package.json +3 -8
- package/src/actions.ts +0 -208
- package/src/admin.ts +0 -350
- package/src/chains.ts +0 -278
- package/src/claims.ts +0 -111
- package/src/client.ts +0 -436
- package/src/fees.ts +0 -138
- package/src/fpool.ts +0 -2049
- package/src/generated.ts +0 -4345
- package/src/history.ts +0 -383
- package/src/ids.ts +0 -78
- package/src/index.ts +0 -26
- package/src/indexer.ts +0 -264
- package/src/keys.ts +0 -138
- package/src/liquidity.ts +0 -456
- package/src/onboard.ts +0 -253
- package/src/pools.ts +0 -465
- package/src/positions.ts +0 -297
- package/src/quote.ts +0 -36
- package/src/swap.ts +0 -181
- package/src/tokencache.ts +0 -178
- package/src/write.ts +0 -236
package/dist/fpool.js
CHANGED
|
@@ -1,46 +1,5 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* fpool.ts — the `ManagerF` surface: n bases, one quote, one shared floor.
|
|
3
|
-
*
|
|
4
|
-
* The other primitive. `ManagerC` gives every position its own floor on a tick ladder;
|
|
5
|
-
* `ManagerF` gives every share the SAME floor and deletes the ladder, the accumulators and the
|
|
6
|
-
* per-position accounting with it. Reading the two side by side is the fastest way to understand
|
|
7
|
-
* either.
|
|
8
|
-
*
|
|
9
|
-
* **A pool is an ID, not an address.** Both primitives are singletons now, so neither has a
|
|
10
|
-
* per-pool deployment — but they are addressed differently and for a reason. The C manager rides
|
|
11
|
-
* its whole `PoolKey` in calldata because that key is small, fixed and wholly needed. An F-pool
|
|
12
|
-
* key is variable-length and only ever partially needed (no swap path is O(n)), so it is stored
|
|
13
|
-
* once at `initialize` and every later call names `(poolId, j)`. Callers hold a `bytes32`.
|
|
14
|
-
*
|
|
15
|
-
* **Two products, one contract.** The basket (n > 1) and the launch (n = 1, the creator alone on
|
|
16
|
-
* the lever) are the same bytecode under two key fields — the KIND (what the manager promises
|
|
17
|
-
* structurally) and the POLICY (the pool's policy: its roles, its gates, the terms of every harvest
|
|
18
|
-
* and release) — and nothing in the maths. `describeFPool` below reports
|
|
19
|
-
* which shape a given pool is, because a UI has to decide what to render.
|
|
20
|
-
*
|
|
21
|
-
* **The roles are the policy's** (policy.md; F version 41). The manager holds no authority, gate or list: it asks
|
|
22
|
-
* the pool's policy `may(poolId, action, who)` and acts on the answer (the one thing it caches is the operator,
|
|
23
|
-
* admitted with no call). One policy contract, `PolicyF`, serves every F pool; its kinds — public, desk, POL, pad —
|
|
24
|
-
* are parameter sets, every one an immutable ({@link FPolicyTerms}). The policy's AUTHORITY (immutable; the LOG
|
|
25
|
-
* Authority of the day on the LOG's own instances) appoints each pool's OPERATOR, who runs the pool: funds it
|
|
26
|
-
* ({@link fPoolDeploy}), harvests, closes, sets its gate modes and its name. `getFPool` carries the policy and what
|
|
27
|
-
* it declared (`flags`), {@link getFPoolRoles} reads the roles FROM the policy, and every setting is a write to the
|
|
28
|
-
* policy ({@link fPoolAppointOperator}, {@link fPoolSetSwapMode}, {@link fPoolSetMintMode}, {@link fPolicySetRights}, …).
|
|
29
|
-
* A policy has no setter of its own: a change is a new policy, approved by the registry; the key's policy is the
|
|
30
|
-
* pool's for life.
|
|
31
|
-
*
|
|
32
|
-
* **Zaps live on the ROUTER, not here.** `RouterF` is F's own router and its own Permit2 spender (decision 096: one
|
|
33
|
-
* router per manager; a second spender is a second signature, not a second on-chain approval). See
|
|
34
|
-
* `fPoolZapIn`/`fPoolZapOut` below, which target `addresses.routerF`; a wallet's Permit2 allowance for it is
|
|
35
|
-
* `onboardToken(c, "F", token, need)`.
|
|
36
|
-
*/
|
|
37
1
|
import { decodeAbiParameters, encodeAbiParameters, encodeFunctionData, erc20Abi, keccak256 } from "viem";
|
|
38
2
|
import { managerFAbi, lensFAbi, routerFAbi, policyFAbi, policyRegistryAbi } from "./generated.js";
|
|
39
|
-
/**
|
|
40
|
-
* One contract, one ABI (F version 12): `harvest`, `claim`, `close`, `deployLiquidity`, the fee list are `ManagerF`'s own
|
|
41
|
-
* code. The roles left it for the policy in F version 15; since F 41 there is one policy contract, {@link policyFAbi}
|
|
42
|
-
* (`PolicyF`, policy.md): every F pool's operator, gate modes and lists.
|
|
43
|
-
*/
|
|
44
3
|
export { managerFAbi, policyFAbi };
|
|
45
4
|
import { clientChainId } from "./client.js";
|
|
46
5
|
import { FEE_LIST, FEE_LIST_BP } from "./keys.js";
|
|
@@ -49,18 +8,9 @@ import { fallBackUnlessRejected, signerFor } from "./write.js";
|
|
|
49
8
|
import { getEventLogs } from "./history.js";
|
|
50
9
|
const WAD = 10n ** 18n;
|
|
51
10
|
const ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";
|
|
52
|
-
/**
|
|
53
|
-
* The bits a policy declares at birth, in `Pool.flags` (decision 098; `ASK_SWAP` / `ASK_MINT` before): with a gate bit off nothing is
|
|
54
|
-
* asked; with it on the manager admits the cached operator with no policy call and asks the policy about everyone else.
|
|
55
|
-
*/
|
|
56
11
|
export const GATE_SWAP = 1;
|
|
57
12
|
export const GATE_MINT = 2;
|
|
58
|
-
/** `GATE_SWAP | GATE_MINT`: the bits `setGates` carries (`SEED_TO_DEAD` is the birth's alone). */
|
|
59
13
|
export const GATES = GATE_SWAP | GATE_MINT;
|
|
60
|
-
/**
|
|
61
|
-
* The lens's raw F pool struct — what the manager's `getPool` returned. Since F version 25 the
|
|
62
|
-
* manager's typed views are behind `extsload` (decisions 062) and the lens reads them; one call.
|
|
63
|
-
*/
|
|
64
14
|
async function rawFPool(c, poolId) {
|
|
65
15
|
const [p] = await c.public.readContract({
|
|
66
16
|
address: c.addresses.lensF,
|
|
@@ -72,7 +22,6 @@ async function rawFPool(c, poolId) {
|
|
|
72
22
|
throw new Error(`logswap: no F pool with id ${poolId}`);
|
|
73
23
|
return p;
|
|
74
24
|
}
|
|
75
|
-
/** Read a basket pool whole: one lens call (`pool`, F version 25) plus the policy's terms (cached per policy). The name is a log query apart: {@link fPoolNameOf}. */
|
|
76
25
|
export async function getFPool(c, poolId) {
|
|
77
26
|
const v = await c.public.readContract({
|
|
78
27
|
address: c.addresses.lensF,
|
|
@@ -81,11 +30,6 @@ export async function getFPool(c, poolId) {
|
|
|
81
30
|
args: [poolId],
|
|
82
31
|
});
|
|
83
32
|
const p = v.pool;
|
|
84
|
-
// A pool that was never created reads as an all-zero struct rather than reverting, so the
|
|
85
|
-
// absence has to be named here or every caller mistakes "no such pool" for "a pool holding
|
|
86
|
-
// nothing". `quote` is the manager's own existence test (`_live`), and it is what the create
|
|
87
|
-
// flow's resumability turns on: an initialized-but-unseeded pool MUST still read, so this
|
|
88
|
-
// cannot be a check on `seeded`.
|
|
89
33
|
if (/^0x0{40}$/i.test(p.quote))
|
|
90
34
|
throw new Error(`logswap: no F pool with id ${poolId}`);
|
|
91
35
|
const kind = await fPoolKindOfPolicy(c, p.policy);
|
|
@@ -94,7 +38,7 @@ export async function getFPool(c, poolId) {
|
|
|
94
38
|
quote: p.quote,
|
|
95
39
|
bases: v.baseAssets.map((l) => l.base),
|
|
96
40
|
liquidityWeights: v.baseAssets.map((l) => l.liquidityWeight),
|
|
97
|
-
x: v.baseAssets.map((l) => l.x),
|
|
41
|
+
x: v.baseAssets.map((l) => l.x),
|
|
98
42
|
Q: p.Q,
|
|
99
43
|
L: p.L,
|
|
100
44
|
swapFee: p.swapFee,
|
|
@@ -113,15 +57,13 @@ export async function getFPool(c, poolId) {
|
|
|
113
57
|
seeded: p.seeded,
|
|
114
58
|
gen: Number(p.gen),
|
|
115
59
|
totalSupply: p.shares,
|
|
116
|
-
reserves: v.baseAssets.map((l) => l.reserve),
|
|
60
|
+
reserves: v.baseAssets.map((l) => l.reserve),
|
|
117
61
|
virtualReserves: v.baseAssets.map((l) => l.virtualReserve),
|
|
118
62
|
kappa: v.baseAssets.map((l) => l.kappa),
|
|
119
63
|
};
|
|
120
64
|
}
|
|
121
|
-
/** The policy's birth-time declaration that the deploy's shares are the pool's (`seedToDead`, a pad's), in `flags`. */
|
|
122
65
|
export const SEED_TO_DEAD = 4;
|
|
123
66
|
const termsCache = new Map();
|
|
124
|
-
/** The label a policy's terms spell (see {@link FPoolKind}). Pure. */
|
|
125
67
|
export function fPolicyKindOf(t) {
|
|
126
68
|
if (t.open)
|
|
127
69
|
return "public";
|
|
@@ -131,10 +73,6 @@ export function fPolicyKindOf(t) {
|
|
|
131
73
|
return "pol";
|
|
132
74
|
return "desk";
|
|
133
75
|
}
|
|
134
|
-
/**
|
|
135
|
-
* A policy's terms, read once per policy address and cached for the client's chain (the policies sit at one address on
|
|
136
|
-
* every release chain): every field is an immutable, so the first read is the last. A failed read is not cached.
|
|
137
|
-
*/
|
|
138
76
|
export async function fPolicyTermsOf(c, policy) {
|
|
139
77
|
const key = `${await clientChainId(c)}:${policy.toLowerCase()}`;
|
|
140
78
|
let hit = termsCache.get(key);
|
|
@@ -170,18 +108,13 @@ export async function fPolicyTermsOf(c, policy) {
|
|
|
170
108
|
return { ...t, kind: fPolicyKindOf(t) };
|
|
171
109
|
});
|
|
172
110
|
termsCache.set(key, hit);
|
|
173
|
-
hit.catch(() => termsCache.delete(key));
|
|
111
|
+
hit.catch(() => termsCache.delete(key));
|
|
174
112
|
}
|
|
175
113
|
return hit;
|
|
176
114
|
}
|
|
177
|
-
/** What a policy IS, as a label: {@link fPolicyTermsOf}'s `kind`. One read per policy address, cached. */
|
|
178
115
|
export async function fPoolKindOfPolicy(c, policy) {
|
|
179
116
|
return (await fPolicyTermsOf(c, policy)).kind;
|
|
180
117
|
}
|
|
181
|
-
/**
|
|
182
|
-
* The pool's label — the last `NameSet` its policy emitted for it: the operator's word, mutable, never identity. Nothing is
|
|
183
|
-
* stored on chain (policy.md §4.3), so this is a log query — pass `indexer`, or set the client's. "" when never named.
|
|
184
|
-
*/
|
|
185
118
|
export async function fPoolNameOf(c, poolId, opts = {}) {
|
|
186
119
|
const policy = opts.policy ?? (await fPoolPolicyOf(c, poolId));
|
|
187
120
|
const ev = policyFAbi.find((x) => x.type === "event" && x.name === "NameSet");
|
|
@@ -191,7 +124,6 @@ export async function fPoolNameOf(c, poolId, opts = {}) {
|
|
|
191
124
|
const last = logs[logs.length - 1];
|
|
192
125
|
return last ? bytes32ToText(last.args.name) : "";
|
|
193
126
|
}
|
|
194
|
-
/** The deployment's policy for a slot — the one a key names when no `policy` is given. */
|
|
195
127
|
export function fPoolPolicyFor(c, slot) {
|
|
196
128
|
const a = c.addresses;
|
|
197
129
|
const policy = slot === "public" ? a.publicPolicy : slot === "private" ? a.privatePolicy : slot === "pol" ? a.polPolicy : a.padPolicy;
|
|
@@ -199,14 +131,11 @@ export function fPoolPolicyFor(c, slot) {
|
|
|
199
131
|
throw new Error(`logswap: this deployment carries no ${slot} policy`);
|
|
200
132
|
return policy;
|
|
201
133
|
}
|
|
202
|
-
/** The policy a pool named in its key — one read; {@link getFPool} carries it too. */
|
|
203
134
|
export async function fPoolPolicyOf(c, poolId) {
|
|
204
135
|
return (await rawFPool(c, poolId)).policy;
|
|
205
136
|
}
|
|
206
137
|
const MODES = ["open", "listed", "operator"];
|
|
207
|
-
/** The gate modes in `IPolicyF.Mode` order — the index is the on-chain ordinal. */
|
|
208
138
|
export const fPoolModes = MODES;
|
|
209
|
-
/** Read a pool's roles from its policy. `state` saves the `getPool` round trip when the policy is already in hand. */
|
|
210
139
|
export async function getFPoolRoles(c, poolId, state) {
|
|
211
140
|
const policy = state?.policy ?? (await fPoolPolicyOf(c, poolId));
|
|
212
141
|
const rd = (functionName, args = []) => c.public.readContract({ address: policy, abi: policyFAbi, functionName, args });
|
|
@@ -218,26 +147,20 @@ export async function getFPoolRoles(c, poolId, state) {
|
|
|
218
147
|
]);
|
|
219
148
|
return { policy, authority, operator, swapMode: MODES[Number(swap)] ?? "open", mintMode: MODES[Number(mint)] ?? "open" };
|
|
220
149
|
}
|
|
221
|
-
/**
|
|
222
|
-
* What a harvest may take now (policy.md §9): the income `I = min(unharvested, Q)` always; capital on top of it up to
|
|
223
|
-
* `Q − I − quoteBuffer·L` (`QuoteTooThin` past it), none where the policy is income-only (`IncomeOnly`) or the pool a pad
|
|
224
|
-
* (`SEED_TO_DEAD`: the manager's own rule, `HarvestLimit`). Nothing on an unfunded pool.
|
|
225
|
-
*/
|
|
226
150
|
export function fPoolHarvestRoom(s, t) {
|
|
227
151
|
if (s.L === 0n)
|
|
228
152
|
return { income: 0n, capital: 0n };
|
|
229
153
|
const income = s.unharvested < s.Q ? s.unharvested : s.Q;
|
|
230
154
|
if (t.incomeHarvestOnly || (s.flags & SEED_TO_DEAD) !== 0)
|
|
231
155
|
return { income, capital: 0n };
|
|
232
|
-
const keep = income + (s.L * t.quoteBuffer + WAD - 1n) / WAD;
|
|
156
|
+
const keep = income + (s.L * t.quoteBuffer + WAD - 1n) / WAD;
|
|
233
157
|
return { income, capital: s.Q > keep ? s.Q - keep : 0n };
|
|
234
158
|
}
|
|
235
159
|
export async function describeFPool(c, s) {
|
|
236
|
-
// an unfunded pool has no L: nothing earned, nothing to harvest
|
|
237
160
|
const terms = await fPolicyTermsOf(c, s.policy);
|
|
238
161
|
const { income, capital } = fPoolHarvestRoom(s, terms);
|
|
239
162
|
return {
|
|
240
|
-
shape: s.kind === "pad" ? "launch" : "basket",
|
|
163
|
+
shape: s.kind === "pad" ? "launch" : "basket",
|
|
241
164
|
legs: s.bases.length,
|
|
242
165
|
atFloor: s.Q === 0n,
|
|
243
166
|
unharvested: s.L > 0n ? s.unharvested : 0n,
|
|
@@ -246,15 +169,9 @@ export async function describeFPool(c, s) {
|
|
|
246
169
|
harvestable: income + capital,
|
|
247
170
|
};
|
|
248
171
|
}
|
|
249
|
-
/** `p_j = e^{x_j}`, lossy the way any float conversion is. Compare in log space when it matters. */
|
|
250
172
|
export function fPoolPriceOf(x, scale = 1) {
|
|
251
173
|
return Math.exp(Number(x) / 1e18) * scale;
|
|
252
174
|
}
|
|
253
|
-
/**
|
|
254
|
-
* Value per share at the pool's own marks, WAD. Uncapped, `V = L + Q`. Capped (decisions 061), leg
|
|
255
|
-
* j's base is worth `L_j·R_j/R̃_j`, less than `L_j` by the phantom the cap removed — the lens's
|
|
256
|
-
* `shareValue`, without the call.
|
|
257
|
-
*/
|
|
258
175
|
export function fPoolShareValue(s) {
|
|
259
176
|
if (s.totalSupply === 0n)
|
|
260
177
|
return 0n;
|
|
@@ -269,12 +186,6 @@ export function fPoolShareValue(s) {
|
|
|
269
186
|
}
|
|
270
187
|
return (v * WAD) / s.totalSupply;
|
|
271
188
|
}
|
|
272
|
-
/**
|
|
273
|
-
* All three F swaps go through the ROUTER's `swapExactIn` overload — the same surface as a C
|
|
274
|
-
* swap: Permit2 pull, `minOut`, recipient, deadline. The manager's direct `swapQuoteIn` etc.
|
|
275
|
-
* remain callable (plain allowance to the manager, settle to caller) but are the primitive's
|
|
276
|
-
* interface, not the SDK's: routing everywhere is what keeps the two pools identical to use.
|
|
277
|
-
*/
|
|
278
189
|
async function fSwap(c, a, kind, k = 0) {
|
|
279
190
|
const st = await getFPool(c, a.poolId);
|
|
280
191
|
const pull = kind === FPoolQuoteKind.QuoteIn ? st.quote : st.bases[a.j];
|
|
@@ -286,57 +197,24 @@ export async function fPoolSwapQuoteIn(c, a) {
|
|
|
286
197
|
export async function fPoolSwapBaseIn(c, a) {
|
|
287
198
|
return fSwap(c, a, FPoolQuoteKind.BaseIn);
|
|
288
199
|
}
|
|
289
|
-
/**
|
|
290
|
-
* Base j → base k. Needs no quote, works at Q = 0, and cannot cross the floor: X is held
|
|
291
|
-
* exactly up to the in-kind fee. Note it moves BOTH quote prices — p_j down, p_k up — because the
|
|
292
|
-
* pool has one coordinate per asset and every trade moves at least one.
|
|
293
|
-
*/
|
|
294
200
|
export async function fPoolSwapBaseForBase(c, a) {
|
|
295
201
|
return fSwap(c, a, FPoolQuoteKind.BaseForBase, a.k);
|
|
296
202
|
}
|
|
297
|
-
|
|
298
|
-
/** Deposit dL/L of every reserve, receive shares ∝ dL. logFloor is untouched by construction. */
|
|
299
|
-
export async function fPoolMint(c,
|
|
300
|
-
/** `maxQuoteIn` is required: the quote leg is Q·dL/L at landing, and Q moves with every swap. */
|
|
301
|
-
a) {
|
|
302
|
-
// shares go to `to` (the account by default); on a gated pool `to` must be allowed. `payer` (F 42, decision 107) is the
|
|
303
|
-
// account the caller declares as funding the mint, read by `SharesMinted` alone: on this direct call, the sender itself.
|
|
203
|
+
export async function fPoolMint(c, a) {
|
|
304
204
|
return writeFPool(c, a.poolId, "mint", [a.account, a.to ?? a.account, a.dL, a.maxQuoteIn], a.account);
|
|
305
205
|
}
|
|
306
|
-
|
|
307
|
-
* Burn shares for the pro-rata slice of every reserve. Available at any Q, and after dissolution.
|
|
308
|
-
* By owner: the account burns its own shares; an
|
|
309
|
-
* operator may pass another owner's address, as on the C manager's `burnById`.
|
|
310
|
-
*/
|
|
311
|
-
export async function fPoolBurn(c,
|
|
312
|
-
/** `minQuoteOut` is required: the quote slice is Q·shares/S at landing. See {@link fPoolPreviewBurn}. */
|
|
313
|
-
a) {
|
|
206
|
+
export async function fPoolBurn(c, a) {
|
|
314
207
|
return writeFPool(c, a.poolId, "burn", [a.owner ?? a.account, a.shares, a.minQuoteOut], a.account);
|
|
315
208
|
}
|
|
316
|
-
/**
|
|
317
|
-
* What burning `shares` returns at today's state — the manager's own arithmetic: every reserve and
|
|
318
|
-
* the quote pro rata, rounded down (FPoolManager.burn). Exact until the next swap or mint.
|
|
319
|
-
*/
|
|
320
209
|
export function fPoolPreviewBurn(st, shares) {
|
|
321
210
|
if (st.totalSupply === 0n)
|
|
322
211
|
return { quoteOut: 0n, basesOut: st.reserves.map(() => 0n) };
|
|
323
212
|
return { quoteOut: (st.Q * shares) / st.totalSupply, basesOut: st.reserves.map((r) => (r * shares) / st.totalSupply) };
|
|
324
213
|
}
|
|
325
|
-
/**
|
|
326
|
-
* The quote {@link fPoolMint} pulls for `dL` at today's state: Q·dL/L, rounded up (the pool never
|
|
327
|
-
* under-collects), before any mint fee — so bound it with {@link withSlippage} (`"input"`).
|
|
328
|
-
*/
|
|
329
214
|
export function fPoolPreviewMintQuote(st, dL) {
|
|
330
215
|
return st.L === 0n ? 0n : (st.Q * dL + st.L - 1n) / st.L;
|
|
331
216
|
}
|
|
332
|
-
// ─── zaps (on the router — one router, one Permit2 spender) ───────────────────
|
|
333
|
-
/**
|
|
334
|
-
* Quote needed to zap into exposure `dL`. An UPPER bound: buying each leg raises its mark, so the
|
|
335
|
-
* mint consumes less base than was bought for it and every zap ends with a refund. Size from this
|
|
336
|
-
* and expect change back — do not treat it as exact.
|
|
337
|
-
*/
|
|
338
217
|
export async function fPoolPreviewZapIn(c, poolId, dL) {
|
|
339
|
-
// read-only lives on the LENS (LensF: the previews)
|
|
340
218
|
const { lensFAbi } = await import("./generated.js");
|
|
341
219
|
return c.public.readContract({
|
|
342
220
|
address: c.addresses.lensF,
|
|
@@ -345,37 +223,15 @@ export async function fPoolPreviewZapIn(c, poolId, dL) {
|
|
|
345
223
|
args: [poolId, dL],
|
|
346
224
|
});
|
|
347
225
|
}
|
|
348
|
-
/**
|
|
349
|
-
* Buy `dL` of the basket with quote alone.
|
|
350
|
-
*
|
|
351
|
-
* The imbalanced part goes through the pool's own curve before anything is minted. That is not a
|
|
352
|
-
* penalty: minting against a quote-only deposit would be a zero-slippage, zero-fee swap at stale
|
|
353
|
-
* spot, paid for by the existing LPs. Routing it through
|
|
354
|
-
* the curve deletes the subsidy and hands the fee and impact to the incumbents instead.
|
|
355
|
-
*/
|
|
356
226
|
export async function fPoolZapIn(c, a) {
|
|
357
227
|
const to = a.to ?? a.account;
|
|
358
228
|
const st = await getFPool(c, a.poolId);
|
|
359
229
|
return writeRouter(c, "zapIn", [a.poolId, a.dL, a.maxQuoteIn, a.minShares ?? 0n, to, a.deadline ?? defaultDeadline()], a.account, [st.quote]);
|
|
360
230
|
}
|
|
361
|
-
|
|
362
|
-
* Sell shares into ONE token — the quote, or any base.
|
|
363
|
-
*
|
|
364
|
-
* Into a base the other legs route through `swapBaseForBase`, which needs no quote and cannot
|
|
365
|
-
* cross the floor; only the burn's own quote slice touches the quote leg. Into the quote every
|
|
366
|
-
* base leg is sold, which is the one path a drained quote leg can block.
|
|
367
|
-
*/
|
|
368
|
-
export async function fPoolZapOut(c,
|
|
369
|
-
/** `minOut` is required: the sale routes every leg through the curve. See {@link fPoolPreviewZapOut}. */
|
|
370
|
-
a) {
|
|
231
|
+
export async function fPoolZapOut(c, a) {
|
|
371
232
|
const to = a.to ?? a.account;
|
|
372
233
|
return writeRouter(c, "zapOut", [a.poolId, a.shares, a.tokenOut, a.minOut, to, a.deadline ?? defaultDeadline()], a.account);
|
|
373
234
|
}
|
|
374
|
-
/**
|
|
375
|
-
* What {@link fPoolZapOut} returns at today's state: the router's own `zapOut`, simulated as the
|
|
376
|
-
* holder with no bound. Exact, but it needs what the real call needs — the shares, and the router
|
|
377
|
-
* as the holder's ERC-6909 operator — so it throws where the zap-out itself would revert.
|
|
378
|
-
*/
|
|
379
235
|
export async function fPoolPreviewZapOut(c, a) {
|
|
380
236
|
const { result } = await c.public.simulateContract({
|
|
381
237
|
address: c.addresses.routerF,
|
|
@@ -386,27 +242,10 @@ export async function fPoolPreviewZapOut(c, a) {
|
|
|
386
242
|
});
|
|
387
243
|
return result;
|
|
388
244
|
}
|
|
389
|
-
/**
|
|
390
|
-
* Roll a retired generation's bundle into the pool's live one, on the
|
|
391
|
-
* router under one lock: redeem `shares` of generation `gen` in place — the legs, the quote and
|
|
392
|
-
* any unpulled dividend come back — buy through the pool's own curve only what the live
|
|
393
|
-
* generation's ratio lacks, mint `dL` of it to `to`, and refund the rest in kind. Quote the
|
|
394
|
-
* bundle does not cover is pulled from the payer, at most `maxQuoteIn`; surplus base is
|
|
395
|
-
* refunded, never sold. Size `dL` with {@link fPoolPreviewRollIn}. The router must be the
|
|
396
|
-
* caller's ERC-6909 operator ({@link approveRouterForFPool}).
|
|
397
|
-
*/
|
|
398
245
|
export async function fPoolRollIn(c, a) {
|
|
399
246
|
const to = a.to ?? a.account;
|
|
400
247
|
return writeRouter(c, "rollIn", [a.poolId, BigInt(a.gen), a.shares, a.dL, a.maxQuoteIn ?? 0n, a.minShares ?? 0n, to, a.deadline ?? defaultDeadline()], a.account);
|
|
401
248
|
}
|
|
402
|
-
/**
|
|
403
|
-
* The roll `holder`'s `shares` of retired generation `gen` fund into the live one WITHOUT a
|
|
404
|
-
* trade: the largest `dL` the bundle's base covers on every leg, and the quote the bundle is
|
|
405
|
-
* short of (pass it as `maxQuoteIn`) or over (refunded — the up direction's distribution) at
|
|
406
|
-
* that `dL`. A leg the live generation admitted since makes `dL` zero: such a roll must buy, so
|
|
407
|
-
* size it below with `previewZapIn` in mind. Zero for the live generation, or before the next
|
|
408
|
-
* seed.
|
|
409
|
-
*/
|
|
410
249
|
export async function fPoolPreviewRollIn(c, poolId, gen, holder, shares) {
|
|
411
250
|
const { lensFAbi } = await import("./generated.js");
|
|
412
251
|
const [dL, quoteShort, quoteExcess] = (await c.public.readContract({
|
|
@@ -417,35 +256,13 @@ export async function fPoolPreviewRollIn(c, poolId, gen, holder, shares) {
|
|
|
417
256
|
}));
|
|
418
257
|
return { dL, quoteShort, quoteExcess };
|
|
419
258
|
}
|
|
420
|
-
// ─── the floor lever (the operator's) ─────────────────────────────────────────
|
|
421
|
-
/**
|
|
422
|
-
* Harvest (policy.md §9): take this generation's income — `L·(refLogFloor − logFloor)`, the fees since the floor was last
|
|
423
|
-
* referenced — and `extra` of capital on top of it, out of the bid; price-neutral, no base moves. Both accrue as a DIVIDEND to
|
|
424
|
-
* every share, settled lazily on each holder's next transfer, mint or burn or pulled with {@link fPoolClaim}; the income is taxed
|
|
425
|
-
* on the payer's slice (the operator's; 0xdead's on a pad, whose net slice goes to the operator) at the policy's `incomeTaxRate`.
|
|
426
|
-
* The operator's own settled dividend — this harvest's and anything pending — is paid to `to` in the same call: one transaction,
|
|
427
|
-
* and the operator (usually a contract) routes the payout through `to`. The operator's alone (`NotOperator`). `extra` must fit the
|
|
428
|
-
* room ({@link fPoolHarvestRoom}): 0 on a pad (`HarvestLimit`) and under an income-only policy (`IncomeOnly`), within the buffer
|
|
429
|
-
* otherwise (`QuoteTooThin`).
|
|
430
|
-
*/
|
|
431
259
|
export async function fPoolHarvest(c, a) {
|
|
432
260
|
return writeFPool(c, a.poolId, "harvest", [a.extra ?? 0n, a.to ?? a.account], a.account);
|
|
433
261
|
}
|
|
434
|
-
/**
|
|
435
|
-
* Pull an owner's settled dividend on a generation's shares without moving them;
|
|
436
|
-
* anyone with shares. `gen` defaults to the live generation; a retired generation's harvests
|
|
437
|
-
* stay claimable under its own id. By owner (F 42), as {@link fPoolBurn} and {@link fPoolRedeem}: the account claims its
|
|
438
|
-
* own, and an ERC-6909 operator may pass another `owner`. Paid to `to` (the account by default).
|
|
439
|
-
*/
|
|
440
262
|
export async function fPoolClaim(c, a) {
|
|
441
263
|
const gen = a.gen ?? (await fPoolGen(c, a.poolId));
|
|
442
264
|
return writeFPool(c, a.poolId, "claim", [BigInt(gen), a.owner ?? a.account, a.to ?? a.account], a.account);
|
|
443
265
|
}
|
|
444
|
-
/**
|
|
445
|
-
* A holder's claimable dividend as of now on generation `gen` (the live one by default) — banked
|
|
446
|
-
* plus pending on the current balance; under a lien, the free fraction's only: the locked
|
|
447
|
-
* fraction's is the lien's ({@link fPoolLienOf}, decisions 063).
|
|
448
|
-
*/
|
|
449
266
|
export async function fPoolDividendOf(c, poolId, holder, gen) {
|
|
450
267
|
const g = gen ?? (await fPoolGen(c, poolId));
|
|
451
268
|
return c.public.readContract({
|
|
@@ -455,11 +272,6 @@ export async function fPoolDividendOf(c, poolId, holder, gen) {
|
|
|
455
272
|
args: [poolId, BigInt(g), holder],
|
|
456
273
|
});
|
|
457
274
|
}
|
|
458
|
-
/**
|
|
459
|
-
* The lien on `owner`'s shares of `poolId`'s generation `gen` (the live one by default). `owed` counts
|
|
460
|
-
* what has been banked into it; the locked fraction of the owner's pending since its last bank is
|
|
461
|
-
* not yet in it — {@link fPoolBankLien} banks it.
|
|
462
|
-
*/
|
|
463
275
|
export async function fPoolLienOf(c, poolId, owner, gen) {
|
|
464
276
|
const g = gen ?? (await fPoolGen(c, poolId));
|
|
465
277
|
const [locker, amount, owed] = await c.public.readContract({
|
|
@@ -470,35 +282,21 @@ export async function fPoolLienOf(c, poolId, owner, gen) {
|
|
|
470
282
|
});
|
|
471
283
|
return { locker, amount, owed };
|
|
472
284
|
}
|
|
473
|
-
/**
|
|
474
|
-
* Lock `amount` of `owner`'s shares for the caller, the locker (`account`). Paid with the owner's
|
|
475
|
-
* per-id allowance to the locker — the owner first sends `approve(locker, shareId, amount)` on the
|
|
476
|
-
* F manager ({@link fPoolApproveShares}) — or an operator grant. One locker per (id, owner) while a
|
|
477
|
-
* lien stands. In practice the lending contract calls `lock` itself; this is the EOA path.
|
|
478
|
-
*/
|
|
479
285
|
export async function fPoolLock(c, a) {
|
|
480
286
|
const g = a.gen ?? (await fPoolGen(c, a.poolId));
|
|
481
287
|
return writeFPool0(c, "lienLock", [fPoolShareId(a.poolId, g), a.owner, a.amount], a.account);
|
|
482
288
|
}
|
|
483
|
-
/**
|
|
484
|
-
* The locker's `unlock`: `amount` of the lien lifted with its share of the lien's dividend, credited
|
|
485
|
-
* to `to` — the owner (a release) or anyone else (a seizure, the shares moving to `to`). It banks
|
|
486
|
-
* first. The locker's alone.
|
|
487
|
-
*/
|
|
488
289
|
export async function fPoolUnlock(c, a) {
|
|
489
290
|
const g = a.gen ?? (await fPoolGen(c, a.poolId));
|
|
490
291
|
return writeFPool0(c, "lienUnlock", [fPoolShareId(a.poolId, g), a.owner, a.amount, a.to], a.account);
|
|
491
292
|
}
|
|
492
|
-
/** Bank the owner's pending into the lien now — `unlock(id, owner, 0, owner)`: dividends bank lazily. The locker's. */
|
|
493
293
|
export async function fPoolBankLien(c, a) {
|
|
494
294
|
return fPoolUnlock(c, { ...a, amount: 0n, to: a.owner });
|
|
495
295
|
}
|
|
496
|
-
/** The owner's per-id allowance to a locker on the F manager's ERC-6909 shares — what `lock` spends. */
|
|
497
296
|
export async function fPoolApproveShares(c, a) {
|
|
498
297
|
const g = a.gen ?? (await fPoolGen(c, a.poolId));
|
|
499
298
|
return writeFPool0(c, "approve", [a.spender, fPoolShareId(a.poolId, g), a.amount], a.account);
|
|
500
299
|
}
|
|
501
|
-
// ─── internals ────────────────────────────────────────────────────────────────
|
|
502
300
|
function defaultDeadline() {
|
|
503
301
|
return BigInt(Math.floor(Date.now() / 1000) + 1800);
|
|
504
302
|
}
|
|
@@ -513,15 +311,11 @@ async function writeFPool(c, poolId, functionName, args, account) {
|
|
|
513
311
|
address: c.addresses.managerF,
|
|
514
312
|
abi: managerFAbi,
|
|
515
313
|
functionName,
|
|
516
|
-
// Every manager write is keyed by poolId as its FIRST parameter; prepending it here, in the
|
|
517
|
-
// one place all seven helpers share, is what keeps a caller from ever omitting it. The `as
|
|
518
|
-
// never` casts blind tsc to arg counts, so this file's encode test is the real guard.
|
|
519
314
|
args: [poolId, ...args],
|
|
520
315
|
account: signerFor(c, account),
|
|
521
316
|
});
|
|
522
317
|
return wallet.writeContract(request);
|
|
523
318
|
}
|
|
524
|
-
/** A manager write that is NOT keyed by a poolId — `multicall`. */
|
|
525
319
|
async function writeFPool0(c, functionName, args, account) {
|
|
526
320
|
const wallet = requireWallet(c);
|
|
527
321
|
const { request } = await c.public.simulateContract({
|
|
@@ -533,9 +327,7 @@ async function writeFPool0(c, functionName, args, account) {
|
|
|
533
327
|
});
|
|
534
328
|
return wallet.writeContract(request);
|
|
535
329
|
}
|
|
536
|
-
async function writeRouter(c, functionName, args, account,
|
|
537
|
-
/** Tokens the call pulls: missing Permit2 allowances are SIGNED and ride in the same tx. */
|
|
538
|
-
pullTokens = []) {
|
|
330
|
+
async function writeRouter(c, functionName, args, account, pullTokens = []) {
|
|
539
331
|
const wallet = requireWallet(c);
|
|
540
332
|
let fn = functionName;
|
|
541
333
|
let sendArgs = args;
|
|
@@ -558,14 +350,6 @@ pullTokens = []) {
|
|
|
558
350
|
});
|
|
559
351
|
return wallet.writeContract(request);
|
|
560
352
|
}
|
|
561
|
-
// ─── token readiness (two pull paths, not one) ────────────────────────────────
|
|
562
|
-
//
|
|
563
|
-
// The F screens have TWO spenders to satisfy, and confusing them was a shipped bug. Direct
|
|
564
|
-
// manager calls (swaps, mint, burn) pull with plain `transferFrom`, so the MANAGER needs an
|
|
565
|
-
// ERC-20 allowance. The router's zaps pull through Permit2 when the deployment carries one, so a
|
|
566
|
-
// plain approval to the router does nothing there and the zap reverts `NotAllowed()` — that leg
|
|
567
|
-
// is `onboardToken`'s job. This helper covers the manager leg; a UI needs both.
|
|
568
|
-
/** Plain ERC-20 approval to the F manager — the allowance every DIRECT call pulls against. */
|
|
569
353
|
export async function approveTokenForFPoolManager(c, token) {
|
|
570
354
|
const wallet = requireWallet(c);
|
|
571
355
|
return c.wallet.writeContract({
|
|
@@ -577,7 +361,6 @@ export async function approveTokenForFPoolManager(c, token) {
|
|
|
577
361
|
chain: c.wallet.chain,
|
|
578
362
|
});
|
|
579
363
|
}
|
|
580
|
-
/** Does `owner` have enough allowance on `token` for the MANAGER to pull `need`? */
|
|
581
364
|
export async function fPoolManagerAllowanceOk(c, token, owner, need) {
|
|
582
365
|
const allowance = (await c.public.readContract({
|
|
583
366
|
address: token,
|
|
@@ -587,12 +370,6 @@ export async function fPoolManagerAllowanceOk(c, token, owner, need) {
|
|
|
587
370
|
}));
|
|
588
371
|
return allowance >= need;
|
|
589
372
|
}
|
|
590
|
-
// ─── ERC-6909 operator (zapOut needs it) ──────────────────────────────────────
|
|
591
|
-
//
|
|
592
|
-
// The singleton's shares are ERC-6909, so the router cannot `transferFrom` them the way it could
|
|
593
|
-
// an ERC-20 LP token. The holder approves it once as an operator. This is the one place the move
|
|
594
|
-
// off a per-pool ERC-20 costs a user-visible step, so the SDK names it rather than letting the
|
|
595
|
-
// first `fPoolZapOut` revert with something unreadable.
|
|
596
373
|
export async function isRouterOperatorForFPool(c, owner) {
|
|
597
374
|
return c.public.readContract({
|
|
598
375
|
address: c.addresses.managerF,
|
|
@@ -601,7 +378,6 @@ export async function isRouterOperatorForFPool(c, owner) {
|
|
|
601
378
|
args: [owner, c.addresses.routerF],
|
|
602
379
|
});
|
|
603
380
|
}
|
|
604
|
-
/** Approve the router to move this account's F-pool shares. Needed once, before any `fPoolZapOut`. */
|
|
605
381
|
export async function approveRouterForFPool(c, account) {
|
|
606
382
|
const wallet = requireWallet(c);
|
|
607
383
|
const { request } = await c.public.simulateContract({
|
|
@@ -613,32 +389,18 @@ export async function approveRouterForFPool(c, account) {
|
|
|
613
389
|
});
|
|
614
390
|
return wallet.writeContract(request);
|
|
615
391
|
}
|
|
616
|
-
// ─── ids ──────────────────────────────────────────────────────────────────────
|
|
617
|
-
//
|
|
618
|
-
// One ERC-6909 space, split structurally on bit 255 — the C manager's scheme. Derived here rather
|
|
619
|
-
// than read from the chain: it is pure, and a client that has to call to learn an id cannot build
|
|
620
|
-
// a multicall that uses it.
|
|
621
|
-
/**
|
|
622
|
-
* The ERC-6909 id carrying generation `gen` of a pool's shares: bit 255 set (the
|
|
623
|
-
* share flag), the pool id's top 239 bits, the generation in the low 16. Each generation's shares
|
|
624
|
-
* are their own asset — a retired one is a claim on its bundle, the live one on the pool.
|
|
625
|
-
*/
|
|
626
392
|
export function fPoolShareId(poolId, gen = 0n) {
|
|
627
393
|
return (1n << 255n) | ((BigInt(poolId) >> 17n) << 16n) | BigInt(gen);
|
|
628
394
|
}
|
|
629
|
-
/** The generation a share id carries — its low 16 bits. */
|
|
630
395
|
export function fPoolGenOfShareId(id) {
|
|
631
396
|
return Number(id & 0xffffn);
|
|
632
397
|
}
|
|
633
|
-
/** The pool's live generation, one read. */
|
|
634
398
|
export async function fPoolGen(c, poolId) {
|
|
635
399
|
return Number((await rawFPool(c, poolId)).gen);
|
|
636
400
|
}
|
|
637
|
-
/** The ERC-6909 id carrying claims on a token. Bit 255 clear, so it can never meet a share id. */
|
|
638
401
|
export function fPoolClaimId(token) {
|
|
639
402
|
return BigInt(token);
|
|
640
403
|
}
|
|
641
|
-
/** A holder's shares of generation `gen` — the live one by default. */
|
|
642
404
|
export async function fPoolShareBalance(c, poolId, owner, gen) {
|
|
643
405
|
const g = gen ?? (await fPoolGen(c, poolId));
|
|
644
406
|
return c.public.readContract({
|
|
@@ -648,7 +410,6 @@ export async function fPoolShareBalance(c, poolId, owner, gen) {
|
|
|
648
410
|
args: [owner, fPoolShareId(poolId, g)],
|
|
649
411
|
});
|
|
650
412
|
}
|
|
651
|
-
/** A retired generation's bundle: what is left to redeem — supply, quote, base per leg index. */
|
|
652
413
|
export async function fPoolBundleOf(c, poolId, gen) {
|
|
653
414
|
const [supply, quote, base] = await c.public.readContract({
|
|
654
415
|
address: c.addresses.lensF,
|
|
@@ -658,7 +419,6 @@ export async function fPoolBundleOf(c, poolId, gen) {
|
|
|
658
419
|
});
|
|
659
420
|
return { supply, quote, base: [...base] };
|
|
660
421
|
}
|
|
661
|
-
/** A holder's claims on a pool's retired generations — one row per generation still held. */
|
|
662
422
|
export async function fPoolClaimsOf(c, poolId, owner) {
|
|
663
423
|
const { lensFAbi } = await import("./generated.js");
|
|
664
424
|
const rows = (await c.public.readContract({
|
|
@@ -669,11 +429,6 @@ export async function fPoolClaimsOf(c, poolId, owner) {
|
|
|
669
429
|
}));
|
|
670
430
|
return rows.map((r) => ({ gen: Number(r.gen), shares: r.shares, base: [...r.base], quote: r.quote, dividend: r.dividend }));
|
|
671
431
|
}
|
|
672
|
-
/**
|
|
673
|
-
* Redeem `shares` of a RETIRED generation: its bundle, pro rata — the base per
|
|
674
|
-
* leg and the quote — plus the owner's settled dividend. Not `burn`: nothing can move a bundle's
|
|
675
|
-
* ratio, so there is no slippage to bound. The owner, or an operator of theirs.
|
|
676
|
-
*/
|
|
677
432
|
export async function fPoolRedeem(c, a) {
|
|
678
433
|
return writeFPool(c, a.poolId, "redeem", [BigInt(a.gen), a.owner ?? a.account, a.shares], a.account);
|
|
679
434
|
}
|
|
@@ -685,28 +440,18 @@ export async function fPoolClaimBalance(c, token, owner) {
|
|
|
685
440
|
args: [owner, fPoolClaimId(token)],
|
|
686
441
|
});
|
|
687
442
|
}
|
|
688
|
-
// ─── the quoter ───────────────────────────────────────────────────────────────
|
|
689
443
|
export var FPoolQuoteKind;
|
|
690
444
|
(function (FPoolQuoteKind) {
|
|
691
445
|
FPoolQuoteKind[FPoolQuoteKind["QuoteIn"] = 0] = "QuoteIn";
|
|
692
446
|
FPoolQuoteKind[FPoolQuoteKind["BaseIn"] = 1] = "BaseIn";
|
|
693
447
|
FPoolQuoteKind[FPoolQuoteKind["BaseForBase"] = 2] = "BaseForBase";
|
|
694
448
|
})(FPoolQuoteKind || (FPoolQuoteKind = {}));
|
|
695
|
-
/**
|
|
696
|
-
* An EXACT quote — what execution returns, not an estimate.
|
|
697
|
-
*
|
|
698
|
-
* `quoteSwap` runs the real swap and reverts with the answer, so the value has to be decoded out
|
|
699
|
-
* of the revert rather than returned. That is the point of the pattern: there is no second pricing
|
|
700
|
-
* path to drift from the first. It needs no tokens, no approvals and no balance, so it works from
|
|
701
|
-
* a disconnected wallet — unlike `fPoolPreviewZapIn`, which is a genuine upper bound.
|
|
702
|
-
*/
|
|
703
449
|
export async function fPoolQuoteSwap(c, a) {
|
|
704
450
|
try {
|
|
705
451
|
await c.public.simulateContract({
|
|
706
452
|
address: c.addresses.routerF,
|
|
707
453
|
abi: routerFAbi,
|
|
708
454
|
functionName: "quoteSwap",
|
|
709
|
-
// the taker matters only on a gated pool: the connected account, or the zero address
|
|
710
455
|
args: [a.poolId, a.kind, BigInt(a.j), BigInt(a.k ?? 0), a.amountIn, a.taker ?? c.wallet?.account?.address ?? ZERO_ADDRESS],
|
|
711
456
|
});
|
|
712
457
|
}
|
|
@@ -714,48 +459,38 @@ export async function fPoolQuoteSwap(c, a) {
|
|
|
714
459
|
const hit = findQuoteResult(err);
|
|
715
460
|
if (hit !== null)
|
|
716
461
|
return hit;
|
|
717
|
-
throw err;
|
|
462
|
+
throw err;
|
|
718
463
|
}
|
|
719
464
|
throw new Error("logswap: quoteSwap returned without reverting, which it must never do");
|
|
720
465
|
}
|
|
721
466
|
const ZERO_SALT = `0x${"0".repeat(64)}`;
|
|
722
|
-
// ─── the fee list (policy.md §6) ──────────────────────────────────────────────
|
|
723
|
-
/** `FeeParams.FEE_LIST` in bp: the eight swap fees an F pool may be born with. The key carries the index. */
|
|
724
467
|
export const F_FEE_LIST_BP = FEE_LIST_BP;
|
|
725
|
-
/** The list in WAD (1 bp = 1e14). No zero: the fee-free pool cannot be born. */
|
|
726
468
|
export const F_FEE_LIST = FEE_LIST;
|
|
727
|
-
/** The fee at `idx` of the list, WAD. Throws off the list. */
|
|
728
469
|
export function fFeeOf(idx) {
|
|
729
470
|
const fee = Number.isInteger(idx) ? F_FEE_LIST[idx] : undefined;
|
|
730
471
|
if (fee === undefined)
|
|
731
472
|
throw new Error(`logswap: swap fee index ${idx} is off the F fee list (0..${F_FEE_LIST.length - 1})`);
|
|
732
473
|
return fee;
|
|
733
474
|
}
|
|
734
|
-
/** The mint fee's index for a swap fee's: the next entry, the same at the top (`FeeParams.mintIdx`). Every pair has `mintFee ≥ 2·swapFee` but the top's (200 → 200 bp). */
|
|
735
475
|
export function fMintFeeIdxOf(swapFeeIdx) {
|
|
736
476
|
fFeeOf(swapFeeIdx);
|
|
737
477
|
return Math.min(swapFeeIdx + 1, F_FEE_LIST.length - 1);
|
|
738
478
|
}
|
|
739
|
-
/** The mint fee, WAD of newly-minted L, a pool born at `swapFeeIdx` charges on outside mints. */
|
|
740
479
|
export function fMintFeeOf(swapFeeIdx) {
|
|
741
480
|
return fFeeOf(fMintFeeIdxOf(swapFeeIdx));
|
|
742
481
|
}
|
|
743
|
-
/** The list index of a WAD fee. Throws when the fee is not one of the eight: no F pool can be born at it. */
|
|
744
482
|
export function fFeeIndexOf(fee) {
|
|
745
483
|
const idx = F_FEE_LIST.indexOf(fee);
|
|
746
484
|
if (idx < 0)
|
|
747
485
|
throw new Error(`logswap: swap fee ${fee} is not on the F fee list (${F_FEE_LIST_BP.join(", ")} bp)`);
|
|
748
486
|
return idx;
|
|
749
487
|
}
|
|
750
|
-
/** Whether a policy's `feeMask` admits `idx`: a bit per index, an empty mask admitting all eight. */
|
|
751
488
|
export function fFeeListed(feeMask, idx) {
|
|
752
489
|
return Number.isInteger(idx) && idx >= 0 && idx < F_FEE_LIST.length && (feeMask === 0 || ((feeMask >> idx) & 1) === 1);
|
|
753
490
|
}
|
|
754
|
-
/** The indices a policy's `feeMask` admits, ascending. */
|
|
755
491
|
export function fFeesAllowed(feeMask) {
|
|
756
492
|
return F_FEE_LIST.map((_, i) => i).filter((i) => fFeeListed(feeMask, i));
|
|
757
493
|
}
|
|
758
|
-
/** The swap fee index of create arguments given either way; both given must agree. */
|
|
759
494
|
export function fPoolSwapFeeIdxOf(a) {
|
|
760
495
|
if (a.swapFeeIdx !== undefined) {
|
|
761
496
|
const fee = fFeeOf(a.swapFeeIdx);
|
|
@@ -767,7 +502,6 @@ export function fPoolSwapFeeIdxOf(a) {
|
|
|
767
502
|
return fFeeIndexOf(a.swapFee);
|
|
768
503
|
throw new Error("logswap: an F pool needs its swap fee — `swapFeeIdx` (into the list) or `swapFee` (WAD, on the list)");
|
|
769
504
|
}
|
|
770
|
-
/** `bytes32` ⇄ short UTF-8 text, for the pool and sponsor labels. */
|
|
771
505
|
export function textToBytes32(text) {
|
|
772
506
|
const b = new TextEncoder().encode(text);
|
|
773
507
|
if (b.length > 31)
|
|
@@ -778,17 +512,15 @@ export function textToBytes32(text) {
|
|
|
778
512
|
}
|
|
779
513
|
export function bytes32ToText(word) {
|
|
780
514
|
if (!word)
|
|
781
|
-
return "";
|
|
515
|
+
return "";
|
|
782
516
|
const bytes = (word.slice(2).match(/../g) ?? []).map((h) => parseInt(h, 16));
|
|
783
517
|
const end = bytes.findIndex((x) => x === 0);
|
|
784
518
|
return new TextDecoder().decode(new Uint8Array(end === -1 ? bytes : bytes.slice(0, end)));
|
|
785
519
|
}
|
|
786
|
-
/** Sort legs by base address (the key's canonical order), carrying companion arrays along. */
|
|
787
520
|
export function sortFPoolLegs(bases, ...companions) {
|
|
788
521
|
const idx = bases.map((_, i) => i).sort((a, b) => (bases[a].toLowerCase() < bases[b].toLowerCase() ? -1 : 1));
|
|
789
522
|
return { bases: idx.map((i) => bases[i]), companions: companions.map((arr) => idx.map((i) => arr[i])) };
|
|
790
523
|
}
|
|
791
|
-
/** The key's ABI as `abi.encode(key)` lays it out: what {@link fPoolIdOfKey} hashes. */
|
|
792
524
|
export const F_POOL_KEY_ABI = [
|
|
793
525
|
{
|
|
794
526
|
type: "tuple",
|
|
@@ -801,26 +533,13 @@ export const F_POOL_KEY_ABI = [
|
|
|
801
533
|
],
|
|
802
534
|
},
|
|
803
535
|
];
|
|
804
|
-
/**
|
|
805
|
-
* An F pool's id: `keccak256(abi.encode(key))`, offline — what `initialize` computes inline. The
|
|
806
|
-
* manager's `idOf` getter was cut in F version 21; this is the same hash (checked against Foundry's encoder in the
|
|
807
|
-
* tests). The key must be the one the pool was initialized with: bases sorted ({@link fPoolKeyOf} sorts them).
|
|
808
|
-
*/
|
|
809
536
|
export function fPoolIdOfKey(key) {
|
|
810
537
|
return keccak256(encodeAbiParameters(F_POOL_KEY_ABI, [key]));
|
|
811
538
|
}
|
|
812
|
-
/** The key as the manager hashes it: bases sorted, the fee as its index, the slot's policy filled in when none is named. No kind in it (049). */
|
|
813
539
|
export function fPoolKeyOf(c, a) {
|
|
814
540
|
const { bases } = sortFPoolLegs(a.bases);
|
|
815
541
|
return { quote: a.quote, bases, swapFeeIdx: fPoolSwapFeeIdxOf(a), policy: a.policy ?? fPoolPolicyFor(c, a.kind), salt: a.salt ?? ZERO_SALT };
|
|
816
542
|
}
|
|
817
|
-
/**
|
|
818
|
-
* List the pool — `initialize(key)` (policy.md §9): no funds move; the pool is inactive until its operator funds it
|
|
819
|
-
* ({@link fPoolDeploy}). Anyone under an open policy (salt zero), the policy's authority alone under a closed one
|
|
820
|
-
* (`Refused`); refused past the policy's sunset (`PolicyNotApproved`), off the policy's fee mask (`FeeNotListed`), quote or
|
|
821
|
-
* base list (`QuoteNotListed`, `BaseNotListed`), or with more legs than it allows (`TooManyLegs`). Returns the tx hash;
|
|
822
|
-
* read the id with {@link fPoolIdOf}.
|
|
823
|
-
*/
|
|
824
543
|
export async function fPoolInitialize(c, a) {
|
|
825
544
|
const key = fPoolKeyOf(c, a);
|
|
826
545
|
const wallet = requireWallet(c);
|
|
@@ -833,18 +552,9 @@ export async function fPoolInitialize(c, a) {
|
|
|
833
552
|
});
|
|
834
553
|
return c.wallet.writeContract(request);
|
|
835
554
|
}
|
|
836
|
-
/**
|
|
837
|
-
* The pool id is the key's hash — pure, so it can be read before or after creation. Computed
|
|
838
|
-
* locally since F version 21 ({@link fPoolIdOfKey}; the manager's `idOf` is gone): no RPC. Still
|
|
839
|
-
* async, so callers written against the read keep working.
|
|
840
|
-
*/
|
|
841
555
|
export async function fPoolIdOf(c, a) {
|
|
842
556
|
return fPoolIdOfKey(fPoolKeyOf(c, a));
|
|
843
557
|
}
|
|
844
|
-
/**
|
|
845
|
-
* Rebuild a live pool's KEY from its id: the `PoolCreated` log carries every field, the salt included (F 41). The result
|
|
846
|
-
* is checked against the id.
|
|
847
|
-
*/
|
|
848
558
|
export async function fPoolKeyOfPool(c, poolId, opts = {}) {
|
|
849
559
|
const ev = managerFAbi.find((x) => x.type === "event" && x.name === "PoolCreated");
|
|
850
560
|
const { logs } = await getEventLogs(c, { indexer: opts.indexer, address: c.addresses.managerF, event: ev, args: { poolId }, fromBlock: opts.fromBlock });
|
|
@@ -858,33 +568,13 @@ export async function fPoolKeyOfPool(c, poolId, opts = {}) {
|
|
|
858
568
|
}
|
|
859
569
|
return key;
|
|
860
570
|
}
|
|
861
|
-
/**
|
|
862
|
-
* The reserve a leg holds at a mark: `R = Lj·e^{−x}`, WAD math. A deployment names the TOTAL base
|
|
863
|
-
* reserve and the price that values it, and the price follows from the pair, `p = Lj / R` — so this is
|
|
864
|
-
* the one conversion from a wanted mark to what the pool will hold, done here, on the way in. Float
|
|
865
|
-
* precision (~1e-16 relative) is what a deployment needs: any reserve is legal, and the mark
|
|
866
|
-
* the pool derives from it is the one the sponsor meant to within that.
|
|
867
|
-
*/
|
|
868
571
|
export function fPoolReserveAt(Lj, x, k = 0) {
|
|
869
|
-
// on a capped pool (decisions 061) the mark reads the virtual reserve R̃ = R + c, and the
|
|
870
|
-
// deployment puts c = R·k/(1 − k): so the REAL reserve for a mark is L_j·e^{−x}·(1 − k)
|
|
871
572
|
const e = Math.exp(-Number(x) / 1e18) * (1 - k);
|
|
872
573
|
return (Lj * BigInt(Math.round(e * 1e18))) / 10n ** 18n;
|
|
873
574
|
}
|
|
874
|
-
/**
|
|
875
|
-
* The cap constant k = e^{−lnCapOverSeed} (decisions 061, 075): every leg's phantom is c_j = r_j·k/(1 − k), and the
|
|
876
|
-
* generation's liquidity is its base value over 1 − k. 0 on an uncapped pool. It no longer depends on the bid:
|
|
877
|
-
* the cap is a ratio of the cap price to each asset's own seed price.
|
|
878
|
-
*/
|
|
879
575
|
export function fPoolCapK(lnCapOverSeed) {
|
|
880
576
|
return lnCapOverSeed === 0 ? 0 : Math.exp(-lnCapOverSeed / 1e6);
|
|
881
577
|
}
|
|
882
|
-
/**
|
|
883
|
-
* The pool's `lnCapOverSeed` = ln(cap price / seed price) (1e-6 log units) for a leverage λ: ln(λ/(λ − 1))
|
|
884
|
-
* (decisions 061), so λ = 1/(1 − seed/cap) = L / (base value) and the cap sits λ/(λ − 1) × the seed price — λ = 2
|
|
885
|
-
* puts it at twice. **λ = 1 is uncapped**: cap ∞, `lnCapOverSeed` 0. A λ under 1, or one so close to
|
|
886
|
-
* 1 (or so large) that d leaves a uint24 of 1e-6 units, is refused.
|
|
887
|
-
*/
|
|
888
578
|
export function fPoolCapOfLeverage(lambda) {
|
|
889
579
|
if (lambda === 1)
|
|
890
580
|
return 0;
|
|
@@ -895,14 +585,9 @@ export function fPoolCapOfLeverage(lambda) {
|
|
|
895
585
|
throw new Error(`logswap: leverage ${lambda} needs a cap outside a uint24 of 1e-6 units`);
|
|
896
586
|
return d;
|
|
897
587
|
}
|
|
898
|
-
/** The leverage λ = 1/(1 − e^{−x}) for x = `lnCapOverSeed` (1e-6 log units); 1 for an uncapped pool (cap ∞). */
|
|
899
588
|
export function fPoolLeverageOfCap(lnCapOverSeed) {
|
|
900
589
|
return lnCapOverSeed === 0 ? 1 : 1 / (1 - Math.exp(-lnCapOverSeed / 1e6));
|
|
901
590
|
}
|
|
902
|
-
/**
|
|
903
|
-
* The leverage tag of a pool from its `lnCapOverSeed` (decisions 061): `1×` means no cap — the only way a tag
|
|
904
|
-
* reads 1× — and a capped pool always reads above it, so the two can never be confused on screen.
|
|
905
|
-
*/
|
|
906
591
|
export function fPoolLeverage(lnCapOverSeed) {
|
|
907
592
|
if (lnCapOverSeed === 0)
|
|
908
593
|
return { lambda: 1, capped: false, capOverSeed: Infinity, label: "1×" };
|
|
@@ -911,20 +596,12 @@ export function fPoolLeverage(lnCapOverSeed) {
|
|
|
911
596
|
const label = rounded <= 1 ? "≈1×" : `${String(rounded)}×`;
|
|
912
597
|
return { lambda, capped: true, capOverSeed: Math.exp(lnCapOverSeed / 1e6), label };
|
|
913
598
|
}
|
|
914
|
-
/** The `lnCapOverSeed` from deployment args: as given, else from `leverage`, else 0 (uncapped, cap ∞). Both given and disagreeing is refused. */
|
|
915
599
|
export function fPoolCapOfArgs(a) {
|
|
916
600
|
const fromLeverage = a.leverage === undefined ? undefined : fPoolCapOfLeverage(a.leverage);
|
|
917
601
|
if (a.lnCapOverSeed !== undefined && fromLeverage !== undefined && a.lnCapOverSeed !== fromLeverage)
|
|
918
602
|
throw new Error(`logswap: lnCapOverSeed ${a.lnCapOverSeed} and leverage ${a.leverage} (${fromLeverage}) disagree — pass one`);
|
|
919
603
|
return a.lnCapOverSeed ?? fromLeverage ?? 0;
|
|
920
604
|
}
|
|
921
|
-
/**
|
|
922
|
-
* The `baseAssets` (and cap) a deployment sends for a wanted book — what the old seed did with reserves and
|
|
923
|
-
* marks, as the amounts and prices the manager takes now. Per asset: the reserve `r_j` (given as `r0`, or
|
|
924
|
-
* {@link fPoolReserveAt} the wanted mark `x0`) and the price that makes its value `L_j · (1 − k)`:
|
|
925
|
-
* `priceX36 = ceil(L_j(1 − k) · 1e36 / r_j)`. A zero weight is an asset left out. Sorted by base address, the
|
|
926
|
-
* key's order, with the companions carried along.
|
|
927
|
-
*/
|
|
928
605
|
export function fPoolBook(a) {
|
|
929
606
|
const sum = a.weights.reduce((x, y) => x + y, 0n);
|
|
930
607
|
if (sum !== WAD)
|
|
@@ -948,11 +625,6 @@ export function fPoolBook(a) {
|
|
|
948
625
|
const { companions } = sortFPoolLegs(a.bases, rows);
|
|
949
626
|
return { baseAssets: companions[0], lnCapOverSeed };
|
|
950
627
|
}
|
|
951
|
-
/**
|
|
952
|
-
* The allocation a `deployLiquidity` book implies: asset `j`'s value `amount_j · priceX36_j / 1e36` over the sum,
|
|
953
|
-
* normalized as the manager does it (cumulative shares, floored), so the weights sum to exactly 1e18. A zero-value
|
|
954
|
-
* book has no allocation (`[]`). What an indexer derives from `LiquidityDeployed` instead of reading the weights.
|
|
955
|
-
*/
|
|
956
628
|
export function fPoolBookWeights(baseAssets) {
|
|
957
629
|
const values = baseAssets.map((x) => (x.amount * x.priceX36) / 10n ** 36n);
|
|
958
630
|
const total = values.reduce((x, y) => x + y, 0n);
|
|
@@ -968,10 +640,6 @@ export function fPoolBookWeights(baseAssets) {
|
|
|
968
640
|
return w;
|
|
969
641
|
});
|
|
970
642
|
}
|
|
971
|
-
/**
|
|
972
|
-
* The book's total liquidity `L` from a `LiquidityDeployed` input: the values' sum over `1 − k`, `k = e^{−cap}`.
|
|
973
|
-
* Exact when uncapped; with a cap it carries the float error of `k` (~1e-16 relative) — read the pool for the wei.
|
|
974
|
-
*/
|
|
975
643
|
export function fPoolBookL(baseAssets, lnCapOverSeed) {
|
|
976
644
|
const total = baseAssets.reduce((x, a) => x + (a.amount * a.priceX36) / 10n ** 36n, 0n);
|
|
977
645
|
if (lnCapOverSeed === 0)
|
|
@@ -979,47 +647,16 @@ export function fPoolBookL(baseAssets, lnCapOverSeed) {
|
|
|
979
647
|
const oneMinusK = BigInt(Math.round((1 - fPoolCapK(lnCapOverSeed)) * 1e18));
|
|
980
648
|
return (total * WAD) / oneMinusK;
|
|
981
649
|
}
|
|
982
|
-
/**
|
|
983
|
-
* Put liquidity into the pool, the authority's: `deployLiquidity` (F 38, decisions 083, 084). It SETS THE BOOK:
|
|
984
|
-
* `baseAssets[j].amount` is the total base reserve of asset `j` after the call (0 removes it), `quoteAmount` the
|
|
985
|
-
* total bid, and the manager settles each figure against what the pool holds — a larger total is pulled from the
|
|
986
|
-
* caller, a smaller one pushed to `to` — so one call can replace an asset by another. Pass the book outright
|
|
987
|
-
* (`baseAssets`, `lnCapOverSeed`) or the sponsor's terms ({@link fPoolBook}: `weights`, `L0` and marks `x0` or
|
|
988
|
-
* reserves `r0`, in any order). On an UNFUNDED pool (new, or after {@link fPoolClose}) it funds the first or the next
|
|
989
|
-
* generation. On a LIVE pool it is a regeneration that sets the book: income settles to `to`, the policy picks the
|
|
990
|
-
* carried holder, every other holder is frozen into the closing generation's bundle ({@link fPoolRedeem}), and the
|
|
991
|
-
* carried book becomes the one named, at the supplied prices. A pad is forward-only ({@link fPoolRegenerate}).
|
|
992
|
-
*/
|
|
993
|
-
/**
|
|
994
|
-
* Fund the pool — `deployLiquidity(poolId, baseAssets, quoteAmount, lnCapOverSeed)` (policy.md §9): the book of this generation,
|
|
995
|
-
* on an INACTIVE pool — listed and never funded, or closed (`PoolActive` otherwise). The operator's alone (`NotOperator`): it pays
|
|
996
|
-
* every leg's amount and `quoteAmount` by plain allowance to the manager ({@link approveTokenForFPoolManager}) and holds the shares —
|
|
997
|
-
* all but `MIN_SHARES`, which go to 0xdead; every share does on a pad. Refused past the policy's sunset (`PolicyNotApproved`),
|
|
998
|
-
* under its buffer (`QuoteTooThin`), with a cap under its `lnCapMin` (`CapTooClose`). An amount of 0 leaves a leg dormant. Pass the
|
|
999
|
-
* book raw (`baseAssets` + `lnCapOverSeed`) or as a {@link FPoolBookSpec}.
|
|
1000
|
-
*/
|
|
1001
650
|
export async function fPoolDeploy(c, a) {
|
|
1002
651
|
const { baseAssets, lnCapOverSeed } = "baseAssets" in a ? a : fPoolBook(a);
|
|
1003
652
|
return writeFPool(c, a.poolId, "deployLiquidity", [baseAssets, a.quoteAmount, lnCapOverSeed], a.account);
|
|
1004
653
|
}
|
|
1005
|
-
/**
|
|
1006
|
-
* Close the pool (policy.md §9) — at any bid. The manager harvests the income first (a dividend to every share, the operator's
|
|
1007
|
-
* paid to `to`), freezes every reserve and the bid into generation `gen`'s bundle — every share of it redeems pro rata
|
|
1008
|
-
* ({@link fPoolRedeem}), forever — and moves the counter to `gen + 1`, the generation the next {@link fPoolDeploy} opens under
|
|
1009
|
-
* the same id, policy, roles and gates. The operator's alone. Throws before sending on a pad: a pad never closes
|
|
1010
|
-
* (`PadNeverCloses`). Pass `flags` when in hand to save the read.
|
|
1011
|
-
*/
|
|
1012
654
|
export async function fPoolClose(c, a) {
|
|
1013
655
|
const flags = a.flags ?? (await getFPool(c, a.poolId)).flags;
|
|
1014
656
|
if ((flags & SEED_TO_DEAD) !== 0)
|
|
1015
657
|
throw new Error("logswap: a pad never closes (PadNeverCloses) — a fresh start is a new pad");
|
|
1016
658
|
return writeFPool(c, a.poolId, "close", [a.to ?? a.account], a.account);
|
|
1017
659
|
}
|
|
1018
|
-
/**
|
|
1019
|
-
* The relaunch's calls — what `regenerate` was (policy.md §9): `close(poolId, to)`, `redeem(poolId, gen, operator, shares)` for the
|
|
1020
|
-
* operator's own shares of the generation closed (left out at 0), then `deployLiquidity` with the next book. Pure, so a form can show
|
|
1021
|
-
* what it is about to send; {@link fPoolRelaunch} sends them as one `multicall`.
|
|
1022
|
-
*/
|
|
1023
660
|
export function fPoolRelaunchCalls(a) {
|
|
1024
661
|
const { baseAssets, lnCapOverSeed } = "baseAssets" in a ? a : fPoolBook(a);
|
|
1025
662
|
const enc = (functionName, args) => encodeFunctionData({ abi: managerFAbi, functionName, args });
|
|
@@ -1029,13 +666,6 @@ export function fPoolRelaunchCalls(a) {
|
|
|
1029
666
|
calls.push(enc("deployLiquidity", [a.poolId, baseAssets, a.quoteAmount, lnCapOverSeed]));
|
|
1030
667
|
return calls;
|
|
1031
668
|
}
|
|
1032
|
-
/**
|
|
1033
|
-
* Relaunch the pool as ONE transaction: close generation `gen`, redeem the operator's own shares of it (its funds come back),
|
|
1034
|
-
* fund `gen + 1` with the book given — the manager's `multicall`, the operator as sender. Every other holder is frozen into the
|
|
1035
|
-
* bundle and redeems it ({@link fPoolRedeem}); the new book may re-weight any of the key's bases and pick its own cap. The
|
|
1036
|
-
* deploy pulls its amounts and `quoteAmount` from the operator in the same transaction the redeem pays it, so the allowances
|
|
1037
|
-
* must cover the pull. Not on a pad (a pad never closes); not on an inactive pool (fund it with {@link fPoolDeploy}).
|
|
1038
|
-
*/
|
|
1039
669
|
export async function fPoolRelaunch(c, a) {
|
|
1040
670
|
const s = await getFPool(c, a.poolId);
|
|
1041
671
|
if ((s.flags & SEED_TO_DEAD) !== 0)
|
|
@@ -1045,16 +675,8 @@ export async function fPoolRelaunch(c, a) {
|
|
|
1045
675
|
const shares = await fPoolShareBalance(c, a.poolId, a.account, s.gen);
|
|
1046
676
|
return writeFPool0(c, "multicall", [fPoolRelaunchCalls({ ...a, gen: s.gen, shares })], a.account);
|
|
1047
677
|
}
|
|
1048
|
-
/** Where a pad's seed lives: `deployLiquidity` mints every share of a pad here itself. */
|
|
1049
678
|
export const DEAD_ADDRESS = "0x000000000000000000000000000000000000dEaD";
|
|
1050
|
-
/** The manager's `MIN_SHARES`: the deploy mints this much to 0xdead on every pool, the rest to the operator — or, on a pad, to 0xdead too. */
|
|
1051
679
|
export const F_MIN_SHARES = 1000n;
|
|
1052
|
-
/**
|
|
1053
|
-
* The launch's calls, in order — the batch {@link fPoolLaunch} sends. Pure, so a form can show
|
|
1054
|
-
* what it is about to send, and a test can decode it. Legs are sorted here with their weights and
|
|
1055
|
-
* reserves (the key's canonical order; `openBuy.j` is re-indexed to match), and the weights are
|
|
1056
|
-
* checked here, where the message is readable.
|
|
1057
|
-
*/
|
|
1058
680
|
export function fPoolLaunchCalls(poolId, a) {
|
|
1059
681
|
if (!a.policy)
|
|
1060
682
|
throw new Error("logswap: fPoolLaunchCalls needs the key's policy — fPoolLaunch fills it from the deployment");
|
|
@@ -1066,29 +688,18 @@ export function fPoolLaunchCalls(poolId, a) {
|
|
|
1066
688
|
if (!a.initialized)
|
|
1067
689
|
calls.push(enc("initialize", [key]));
|
|
1068
690
|
calls.push(enc("deployLiquidity", [poolId, baseAssets, a.quoteAmount, lnCapOverSeed]));
|
|
1069
|
-
// gen 0 by construction: a launch is the pool's FIRST deployment — a later one is `fPoolDeploy` on the closed pool.
|
|
1070
|
-
// No transfer to 0xdead: on a pad `deployLiquidity` mints every share there itself.
|
|
1071
691
|
for (const row of fPoolGenesisRows(a)) {
|
|
1072
692
|
const j = bases.indexOf(a.bases[row.j]);
|
|
1073
693
|
if (j < 0)
|
|
1074
694
|
throw new Error(`logswap: genesis row j = ${row.j} is not a leg`);
|
|
1075
695
|
calls.push(enc(row.side === "buy" ? "swapQuoteIn" : "swapBaseIn", [poolId, BigInt(j), row.amountIn, row.minOut ?? 0n, a.account]));
|
|
1076
696
|
}
|
|
1077
|
-
// the name and the gate modes are the POLICY's, not the manager's: they cannot ride in this batch — `fPoolLaunch`
|
|
1078
|
-
// sends the name right after, as the same operator; the modes are `fPoolSetSwapMode` / `fPoolSetMintMode`
|
|
1079
697
|
calls.push(...(a.extra ?? []));
|
|
1080
698
|
return calls;
|
|
1081
699
|
}
|
|
1082
|
-
/** The genesis rows in the order they run: `openBuy` first when given, then `openBatch`. Legs as given. */
|
|
1083
700
|
export function fPoolGenesisRows(a) {
|
|
1084
701
|
return [...(a.openBuy ? [{ side: "buy", ...a.openBuy }] : []), ...(a.openBatch ?? [])];
|
|
1085
702
|
}
|
|
1086
|
-
/**
|
|
1087
|
-
* What each genesis row returned, read by simulating the launch's `multicall` on the chain — the
|
|
1088
|
-
* contract's own rounding, no re-implementation. Exact at send time: the pool is new, and nothing
|
|
1089
|
-
* can trade between the seed and the rows. Needs the creator's funds and allowances, as the launch
|
|
1090
|
-
* does. One output per row, in {@link fPoolGenesisRows} order: base for a buy, quote for a sell.
|
|
1091
|
-
*/
|
|
1092
703
|
export async function fPoolGenesisOutputs(c, poolId, a) {
|
|
1093
704
|
const rows = fPoolGenesisRows(a);
|
|
1094
705
|
if (rows.length === 0)
|
|
@@ -1102,14 +713,9 @@ export async function fPoolGenesisOutputs(c, poolId, a) {
|
|
|
1102
713
|
account: signerFor(c, a.account),
|
|
1103
714
|
});
|
|
1104
715
|
const results = result;
|
|
1105
|
-
const first = (a.initialized ? 0 : 1) + 1;
|
|
716
|
+
const first = (a.initialized ? 0 : 1) + 1;
|
|
1106
717
|
return rows.map((_, i) => decodeAbiParameters([{ type: "uint256" }], results[first + i])[0]);
|
|
1107
718
|
}
|
|
1108
|
-
/**
|
|
1109
|
-
* The transfers that pay the recipients: each row's output (`outs`, aligned with
|
|
1110
|
-
* {@link fPoolGenesisRows}) to its `recipient`, summed per (token, recipient), zero amounts dropped.
|
|
1111
|
-
* The token is the leg's base for a buy and the quote for a sell. Pure.
|
|
1112
|
-
*/
|
|
1113
719
|
export function fPoolGenesisTransfers(a, outs) {
|
|
1114
720
|
const out = new Map();
|
|
1115
721
|
fPoolGenesisRows(a).forEach((row, i) => {
|
|
@@ -1125,7 +731,6 @@ export function fPoolGenesisTransfers(a, outs) {
|
|
|
1125
731
|
});
|
|
1126
732
|
return [...out.values()];
|
|
1127
733
|
}
|
|
1128
|
-
/** Pay genesis recipients with plain ERC-20 transfers, one transaction each, in order. For a launch that did not deliver itself. */
|
|
1129
734
|
export async function fPoolSendGenesisTransfers(c, a) {
|
|
1130
735
|
const wallet = requireWallet(c);
|
|
1131
736
|
const hashes = [];
|
|
@@ -1141,7 +746,6 @@ export async function fPoolSendGenesisTransfers(c, a) {
|
|
|
1141
746
|
}
|
|
1142
747
|
return hashes;
|
|
1143
748
|
}
|
|
1144
|
-
/** Whether the wallet runs a batch of calls atomically (EIP-5792 `atomic` capability), on the client's chain. A wallet without it, or one that errors, says no. */
|
|
1145
749
|
export async function fPoolWalletBatchesAtomically(c, account) {
|
|
1146
750
|
try {
|
|
1147
751
|
const wallet = requireWallet(c);
|
|
@@ -1153,29 +757,10 @@ export async function fPoolWalletBatchesAtomically(c, account) {
|
|
|
1153
757
|
return false;
|
|
1154
758
|
}
|
|
1155
759
|
}
|
|
1156
|
-
/**
|
|
1157
|
-
* Create a pool as ONE transaction: `initialize`, `deployLiquidity`, the opening buys — the manager's `multicall`, one sender
|
|
1158
|
-
* throughout. Either every call lands or none does; there is no half-built pool to resume. The sender must be the policy's
|
|
1159
|
-
* AUTHORITY: it is the pool's operator at birth, and `deployLiquidity` is the operator's (`NotOperator`). Under an open
|
|
1160
|
-
* policy anyone may list a pool ({@link fPoolInitialize}) but only the LOG — its authority — funds it, so a launch under the
|
|
1161
|
-
* public policy is the LOG's; a sponsor launches under its own policy.
|
|
1162
|
-
*
|
|
1163
|
-
* Why the manager and not the router: every one of these entries authenticates by `msg.sender`. Routed, the router would be
|
|
1164
|
-
* the sender — the operator, the holder of the seed shares. `multicall` is delegatecall-to-self, so the sender survives.
|
|
1165
|
-
*
|
|
1166
|
-
* What the batch PULLS, by plain allowance to the manager (never Permit2): `r0[j]` of each base, `quoteAmount` of quote, plus
|
|
1167
|
-
* each opening buy's `amountIn` of quote. Grant those first — one `approve` per token, once ever
|
|
1168
|
-
* ({@link approveTokenForFPoolManager}, {@link fPoolManagerAllowanceOk}).
|
|
1169
|
-
*
|
|
1170
|
-
* Returns the hash and the pool's id (the key's hash, {@link fPoolIdOf}). The name, when given, is a second transaction on
|
|
1171
|
-
* the policy ({@link fPoolSetName}); the gate modes are {@link fPoolSetSwapMode} / {@link fPoolSetMintMode} after it.
|
|
1172
|
-
*/
|
|
1173
760
|
export async function fPoolLaunch(c, a) {
|
|
1174
761
|
const poolId = await fPoolIdOf(c, a);
|
|
1175
762
|
const policy = a.policy ?? fPoolPolicyFor(c, a.kind);
|
|
1176
763
|
let args = { ...a, policy };
|
|
1177
|
-
// With recipients, each row's minOut is pinned to its simulated output and the transfers pay
|
|
1178
|
-
// exactly that: a row that returns less reverts the launch, a wei of surplus stays with the creator.
|
|
1179
764
|
let transfers = [];
|
|
1180
765
|
const rows = fPoolGenesisRows(a);
|
|
1181
766
|
if (rows.some((r) => r.recipient)) {
|
|
@@ -1210,75 +795,42 @@ export async function fPoolLaunch(c, a) {
|
|
|
1210
795
|
await fPoolSetName(c, { poolId, name: a.name, account: a.account, policy });
|
|
1211
796
|
return { hash, poolId, transfers, delivered };
|
|
1212
797
|
}
|
|
1213
|
-
// ─── the roles, on the policy ─────────────────────────────────────────────
|
|
1214
|
-
//
|
|
1215
|
-
// Every write here goes to the pool's POLICY, not the manager: the manager holds no role. `policy` may be passed when in
|
|
1216
|
-
// hand (`FPoolState.policy`, `FPoolRoles.policy`); otherwise it is read once. The policy syncs the manager itself
|
|
1217
|
-
// (`setGates`), which stamps the block: no swap lands in the block of a change (047). Every mode and list write reverts
|
|
1218
|
-
// `GatesUnavailable` on an open policy: a public pool can never be gated.
|
|
1219
|
-
/** A write on a policy. */
|
|
1220
798
|
async function writePolicy(c, policy, functionName, args, account) {
|
|
1221
799
|
const wallet = requireWallet(c);
|
|
1222
800
|
const { request } = await c.public.simulateContract({ address: policy, abi: policyFAbi, functionName, args, account: signerFor(c, account) });
|
|
1223
801
|
return wallet.writeContract(request);
|
|
1224
802
|
}
|
|
1225
|
-
/** A write keyed by poolId, on the pool's policy. */
|
|
1226
803
|
async function writePoolPolicy(c, a, functionName, args) {
|
|
1227
804
|
const policy = a.policy ?? (await fPoolPolicyOf(c, a.poolId));
|
|
1228
805
|
return writePolicy(c, policy, functionName, [a.poolId, ...args], a.account);
|
|
1229
806
|
}
|
|
1230
|
-
/**
|
|
1231
|
-
* Appoint the pool's operator (the AUTHORITY's; zero resets it to the authority): the account that funds, harvests, closes and sets the
|
|
1232
|
-
* pool's modes and name, admitted by the gates with no policy call. Immediate, with no acceptance step, so check the address; it may be
|
|
1233
|
-
* a contract (an executor). `InactivePool` on a pool the policy never held.
|
|
1234
|
-
*/
|
|
1235
807
|
export async function fPoolAppointOperator(c, a) {
|
|
1236
808
|
return writePoolPolicy(c, a, "appointOperator", [a.operator]);
|
|
1237
809
|
}
|
|
1238
|
-
/**
|
|
1239
|
-
* Set the pool's swap gate (the OPERATOR's): `open`, `listed` (the policy's swap list, {@link fPolicySetRights}; the operator always
|
|
1240
|
-
* passes) or `operator`. The mint mode must stay at least as restrictive (`ModeOrder`). `burn`, `redeem` and `claim` are never gated.
|
|
1241
|
-
*/
|
|
1242
810
|
export async function fPoolSetSwapMode(c, a) {
|
|
1243
811
|
return writePoolPolicy(c, a, "setSwapMode", [MODES.indexOf(a.mode)]);
|
|
1244
812
|
}
|
|
1245
|
-
/** Set the pool's mint gate (the OPERATOR's): at least as restrictive as the swap mode (`ModeOrder`); `listed` consults the policy's mint list. */
|
|
1246
813
|
export async function fPoolSetMintMode(c, a) {
|
|
1247
814
|
return writePoolPolicy(c, a, "setMintMode", [MODES.indexOf(a.mode)]);
|
|
1248
815
|
}
|
|
1249
|
-
/** The bits of `PolicyF.rights`: listed for swaps; listed for mints, which implies swaps. */
|
|
1250
816
|
export const RIGHT_SWAP = 1;
|
|
1251
817
|
export const RIGHT_MINT = 2;
|
|
1252
|
-
/** The on-chain bits of a right (`MINT` is written as `MINT | SWAP`, as the policy does). */
|
|
1253
818
|
export function fPolicyRightBits(right) {
|
|
1254
819
|
return right === "none" ? 0 : right === "swap" ? RIGHT_SWAP : RIGHT_SWAP | RIGHT_MINT;
|
|
1255
820
|
}
|
|
1256
|
-
/** The right the bits spell. */
|
|
1257
821
|
export function fPolicyRightOf(bits) {
|
|
1258
822
|
const b = Number(bits);
|
|
1259
823
|
return (b & RIGHT_MINT) !== 0 ? "mint" : (b & RIGHT_SWAP) !== 0 ? "swap" : "none";
|
|
1260
824
|
}
|
|
1261
|
-
/**
|
|
1262
|
-
* List addresses on the POLICY (the AUTHORITY's): `swap` admits them where a pool's swap mode is `listed`, `mint` where its mint mode is
|
|
1263
|
-
* — and to swap as well (`MINT ⇒ SWAP`); `none` unlists. One pair of lists per policy, shared by every pool under it (policy.md §4.2);
|
|
1264
|
-
* the modes are each pool's. Stamps nothing: an address removed in a block can still swap in that block.
|
|
1265
|
-
*/
|
|
1266
825
|
export async function fPolicySetRights(c, a) {
|
|
1267
826
|
return writePolicy(c, a.policy, "setRights", [a.who, fPolicyRightBits(a.right)], a.account);
|
|
1268
827
|
}
|
|
1269
|
-
/** What `policy` lists `who` for now (`rights`). */
|
|
1270
828
|
export async function fPolicyRightsOf(c, policy, who) {
|
|
1271
829
|
return fPolicyRightOf((await c.public.readContract({ address: policy, abi: policyFAbi, functionName: "rights", args: [who] })));
|
|
1272
830
|
}
|
|
1273
|
-
/** Label the pool (the OPERATOR's): a `NameSet` event on the policy, nothing stored — mutable, never identity. At most 31 bytes of UTF-8. */
|
|
1274
831
|
export async function fPoolSetName(c, a) {
|
|
1275
832
|
return writePoolPolicy(c, a, "setName", [textToBytes32(a.name)]);
|
|
1276
833
|
}
|
|
1277
|
-
/**
|
|
1278
|
-
* What the PROTOCOL says an address is — "Keyrock" — on the REGISTRY. Only its
|
|
1279
|
-
* owner, the LOG authority, may write it, which is what makes it an attestation rather than a
|
|
1280
|
-
* claim anyone could make about themselves.
|
|
1281
|
-
*/
|
|
1282
834
|
export async function fPoolSetSponsorName(c, a) {
|
|
1283
835
|
const wallet = requireWallet(c);
|
|
1284
836
|
const registry = await registryAddress(c);
|
|
@@ -1291,7 +843,6 @@ export async function fPoolSetSponsorName(c, a) {
|
|
|
1291
843
|
});
|
|
1292
844
|
return wallet.writeContract(request);
|
|
1293
845
|
}
|
|
1294
|
-
/** The protocol's attestation for an address, or "" when unattested — which most addresses are, and every address on a deployment with no registry. */
|
|
1295
846
|
export async function fPoolSponsorName(c, who) {
|
|
1296
847
|
const registry = c.addresses.policyRegistry ?? (await fPoolRegistryOf(c));
|
|
1297
848
|
if (registry === ZERO_ADDRESS)
|
|
@@ -1299,7 +850,6 @@ export async function fPoolSponsorName(c, who) {
|
|
|
1299
850
|
const word = (await c.public.readContract({ address: registry, abi: policyRegistryAbi, functionName: "sponsorName", args: [who] }));
|
|
1300
851
|
return bytes32ToText(word);
|
|
1301
852
|
}
|
|
1302
|
-
/** The registry the manager asks at every birth — `addresses.policyRegistry`, else the manager's word; zero on a bare deployment. */
|
|
1303
853
|
export async function fPoolRegistryOf(c) {
|
|
1304
854
|
if (c.addresses.policyRegistry)
|
|
1305
855
|
return c.addresses.policyRegistry;
|
|
@@ -1311,15 +861,9 @@ async function registryAddress(c) {
|
|
|
1311
861
|
throw new Error("logswap: this deployment carries no policy registry");
|
|
1312
862
|
return registry;
|
|
1313
863
|
}
|
|
1314
|
-
/** Who runs the pool (policy.md §2): its operator — the one account the manager admits to fund, harvest and close. Empty on a pool the policy never held. */
|
|
1315
864
|
export function fPoolRunners(s) {
|
|
1316
865
|
return s.operator === ZERO_ADDRESS ? [] : [s.operator];
|
|
1317
866
|
}
|
|
1318
|
-
/**
|
|
1319
|
-
* Move shares (ERC-6909 `transfer`) — to another holder, or to `0xdead` to lock them for good.
|
|
1320
|
-
* Burning to the dead address is a sponsor's way to make its liquidity permanent: the shares can
|
|
1321
|
-
* never be redeemed.
|
|
1322
|
-
*/
|
|
1323
867
|
export async function fPoolTransferShares(c, a) {
|
|
1324
868
|
const wallet = requireWallet(c);
|
|
1325
869
|
const gen = a.gen ?? (await fPoolGen(c, a.poolId));
|
|
@@ -1332,12 +876,6 @@ export async function fPoolTransferShares(c, a) {
|
|
|
1332
876
|
});
|
|
1333
877
|
return wallet.writeContract(request);
|
|
1334
878
|
}
|
|
1335
|
-
/**
|
|
1336
|
-
* Every F pool ever created, from `PoolCreated` logs alone — plus the terms of each distinct policy, read once and cached.
|
|
1337
|
-
* Possible only because the event carries the full key (quote, policy, bases, swapFeeIdx, salt) and the creator — the poolId is a hash and
|
|
1338
|
-
* could never be inverted; contracts PR #17 exists for exactly this call. With `indexer`, the logs come from it (the node
|
|
1339
|
-
* when it fails): a scan from block 0 per call is what made the first load wait on the node.
|
|
1340
|
-
*/
|
|
1341
879
|
export async function discoverFPools(c, opts = {}) {
|
|
1342
880
|
const ev = managerFAbi.find((x) => x.type === "event" && x.name === "PoolCreated");
|
|
1343
881
|
if (!ev)
|
|
@@ -1348,7 +886,6 @@ export async function discoverFPools(c, opts = {}) {
|
|
|
1348
886
|
getEventLogs(c, { ...range, event: ev }),
|
|
1349
887
|
deployEv ? getEventLogs(c, { ...range, event: deployEv }) : Promise.resolve({ logs: [] }),
|
|
1350
888
|
]);
|
|
1351
|
-
// the pool's first deployment (generation 0) names its allocation, cap and opening bid
|
|
1352
889
|
const first = new Map();
|
|
1353
890
|
for (const l of deploys) {
|
|
1354
891
|
const a = l.args;
|
|
@@ -1359,7 +896,7 @@ export async function discoverFPools(c, opts = {}) {
|
|
|
1359
896
|
return Promise.all(logs.map(async (l) => {
|
|
1360
897
|
const a = l.args;
|
|
1361
898
|
const g0 = first.get(a.poolId.toLowerCase());
|
|
1362
|
-
const kind = await fPoolKindOfPolicy(c, a.policy);
|
|
899
|
+
const kind = await fPoolKindOfPolicy(c, a.policy);
|
|
1363
900
|
const swapFeeIdx = Number(a.swapFeeIdx);
|
|
1364
901
|
return {
|
|
1365
902
|
poolId: a.poolId,
|
|
@@ -1377,14 +914,10 @@ export async function discoverFPools(c, opts = {}) {
|
|
|
1377
914
|
block: l.blockNumber,
|
|
1378
915
|
seeded: g0 !== undefined,
|
|
1379
916
|
q0: g0?.q0 ?? 0n,
|
|
1380
|
-
shape: kind === "pad" ? "launch" : "basket",
|
|
917
|
+
shape: kind === "pad" ? "launch" : "basket",
|
|
1381
918
|
};
|
|
1382
919
|
}));
|
|
1383
920
|
}
|
|
1384
|
-
/**
|
|
1385
|
-
* Every F pool `who` runs (its operator) or sponsors (the authority of its policy) — the policy page's list. `roles` tells
|
|
1386
|
-
* which. `pools` may be passed (from the indexer, say) to skip the log scan.
|
|
1387
|
-
*/
|
|
1388
921
|
export async function fPoolsControlledBy(c, who, opts = {}) {
|
|
1389
922
|
const pools = opts.pools ?? (await discoverFPools(c, { fromBlock: opts.fromBlock }));
|
|
1390
923
|
const states = await Promise.all(pools.map((p) => getFPool(c, p.poolId)));
|
|
@@ -1400,13 +933,6 @@ export async function fPoolsControlledBy(c, who, opts = {}) {
|
|
|
1400
933
|
}
|
|
1401
934
|
return out;
|
|
1402
935
|
}
|
|
1403
|
-
/**
|
|
1404
|
-
* Every holder of a pool's shares, from the ERC-6909 Transfer stream — the id is an indexed
|
|
1405
|
-
* topic, so one filtered log query aggregates the whole ledger. The 0xdead entry is the
|
|
1406
|
-
* MIN_SHARES lock from seeding; callers usually label rather than hide it. Pass `indexer`: the Transfer rows come from
|
|
1407
|
-
* its tables — a node prunes its logs (anvil keeps about a day), and a ledger rebuilt from a pruned stream loses every
|
|
1408
|
-
* holder minted before the cut. (The indexer's derived views are read by the app's `@logswap/base`, not here.)
|
|
1409
|
-
*/
|
|
1410
936
|
export async function fPoolShareHolders(c, poolIdHex, opts = {}) {
|
|
1411
937
|
const ev = managerFAbi.find((x) => x.type === "event" && x.name === "Transfer");
|
|
1412
938
|
if (!ev)
|
|
@@ -1427,12 +953,10 @@ export async function fPoolShareHolders(c, poolIdHex, opts = {}) {
|
|
|
1427
953
|
.map(([holder, shares]) => ({ holder: holder, shares }))
|
|
1428
954
|
.sort((a, b) => (b.shares > a.shares ? 1 : -1));
|
|
1429
955
|
}
|
|
1430
|
-
/** Every F pool's raw state in one lens call (the manager's `Pool` struct: quote, swapFee, restructureTime, flags, policy, seeded, gen, n, lnCapOverSeed, Q, realizedVariance, L, shares, refLogFloor, operator, mintFee). */
|
|
1431
956
|
export async function getFPoolsRaw(c, poolIds) {
|
|
1432
957
|
const { lensFAbi } = await import("./generated.js");
|
|
1433
958
|
return (await c.public.readContract({ address: c.addresses.lensF, abi: lensFAbi, functionName: "getPools", args: [poolIds] }));
|
|
1434
959
|
}
|
|
1435
|
-
/** Share value from the lens — (L + Q)/shares, WAD per share — the same figure as `fPoolShareValue`, from one source. */
|
|
1436
960
|
export async function shareValueOnChain(c, poolId) {
|
|
1437
961
|
const { lensFAbi } = await import("./generated.js");
|
|
1438
962
|
return (await c.public.readContract({ address: c.addresses.lensF, abi: lensFAbi, functionName: "shareValue", args: [poolId] }));
|