@logswap/sdk 0.5.90 → 0.5.92
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 +136 -31
- package/dist/actions.js +4 -3
- package/dist/admin.d.ts +96 -925
- package/dist/admin.js +113 -194
- package/dist/chains.d.ts +13 -4
- package/dist/chains.js +22 -9
- package/dist/claims.d.ts +1 -1
- package/dist/claims.js +11 -9
- package/dist/client.d.ts +42 -20
- package/dist/client.js +86 -26
- package/dist/fees.d.ts +1 -1
- package/dist/fees.js +5 -4
- package/dist/fpool.d.ts +327 -1120
- package/dist/fpool.js +408 -475
- package/dist/generated.d.ts +5017 -7631
- package/dist/generated.js +3040 -4879
- package/dist/history.js +12 -14
- package/dist/index.d.ts +5 -7
- package/dist/index.js +5 -7
- package/dist/indexer.d.ts +2 -2
- package/dist/indexer.js +12 -9
- package/dist/keys.d.ts +15 -3
- package/dist/keys.js +5 -1
- package/dist/liquidity.d.ts +1 -1
- package/dist/liquidity.js +16 -9
- package/dist/onboard.d.ts +16 -11
- package/dist/onboard.js +27 -21
- package/dist/pools.d.ts +2 -0
- package/dist/pools.js +21 -13
- package/dist/positions.d.ts +1 -1
- package/dist/positions.js +18 -17
- package/dist/quote.d.ts +15 -0
- package/dist/quote.js +36 -0
- package/dist/swap.d.ts +7 -9
- package/dist/swap.js +40 -25
- package/dist/views.d.ts +1 -1
- package/dist/write.d.ts +7 -2
- package/dist/write.js +10 -7
- package/package.json +3 -3
- package/src/actions.ts +4 -3
- package/src/admin.ts +143 -249
- package/src/chains.ts +32 -13
- package/src/claims.ts +11 -10
- package/src/client.ts +111 -39
- package/src/fees.ts +6 -6
- package/src/fpool.ts +555 -648
- package/src/generated.ts +3063 -4904
- package/src/history.ts +11 -11
- package/src/index.ts +5 -7
- package/src/indexer.ts +13 -11
- package/src/keys.ts +19 -3
- package/src/liquidity.ts +16 -10
- package/src/onboard.ts +29 -21
- package/src/pools.ts +23 -15
- package/src/positions.ts +18 -18
- package/src/quote.ts +36 -0
- package/src/swap.ts +46 -25
- package/src/views.ts +1 -2
- package/src/write.ts +11 -10
package/src/fpool.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* fpool.ts — the `
|
|
2
|
+
* fpool.ts — the `ManagerF` surface: n bases, one quote, one shared floor.
|
|
3
3
|
*
|
|
4
|
-
* The other primitive. `
|
|
5
|
-
* `
|
|
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
6
|
* per-position accounting with it. Reading the two side by side is the fastest way to understand
|
|
7
7
|
* either.
|
|
8
8
|
*
|
|
@@ -18,48 +18,49 @@
|
|
|
18
18
|
* and release) — and nothing in the maths. `describeFPool` below reports
|
|
19
19
|
* which shape a given pool is, because a UI has to decide what to render.
|
|
20
20
|
*
|
|
21
|
-
* **The roles are the policy's
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
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.
|
|
26
31
|
*
|
|
27
|
-
* **Zaps live on the ROUTER, not here.**
|
|
28
|
-
*
|
|
29
|
-
*
|
|
30
|
-
* `
|
|
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)`.
|
|
31
36
|
*/
|
|
32
37
|
|
|
33
38
|
import { decodeAbiParameters, encodeAbiParameters, encodeFunctionData, erc20Abi, keccak256, toFunctionSelector, type Address, type Hash, type Hex } from "viem";
|
|
34
|
-
import {
|
|
39
|
+
import { managerFAbi, lensFAbi, routerFAbi, policyFAbi, policyRegistryAbi } from "./generated.js";
|
|
35
40
|
|
|
36
41
|
/**
|
|
37
|
-
* One contract, one ABI (F version 12): `harvest`, `claim`, `
|
|
38
|
-
*
|
|
39
|
-
*
|
|
40
|
-
* {@link privatePolicyAbi} the desk's, {@link padPolicyAbi} / {@link polPolicyAbi} / {@link publicPolicyAbi}
|
|
41
|
-
* the kinds'.
|
|
42
|
+
* One contract, one ABI (F version 12): `harvest`, `claim`, `close`, `deployLiquidity`, the fee list are `ManagerF`'s own
|
|
43
|
+
* code. The roles left it for the policy in F version 15; since F 41 there is one policy contract, {@link policyFAbi}
|
|
44
|
+
* (`PolicyF`, policy.md): every F pool's operator, gate modes and lists.
|
|
42
45
|
*/
|
|
43
|
-
export {
|
|
44
|
-
/**
|
|
45
|
-
* What every protocol policy shares (`FPolicyBase`): the roles and their handover and the
|
|
46
|
-
* `maxHarvest` readout (a harvest has no cut, decisions 056). `polPolicyAbi` is a superset of it and carries nothing that collides, so it stands
|
|
47
|
-
* in for the base — a call through it to any of the four policies decodes the base's functions.
|
|
48
|
-
*/
|
|
49
|
-
export const fPolicyBaseAbi = polPolicyAbi;
|
|
46
|
+
export { managerFAbi, policyFAbi };
|
|
50
47
|
import { clientChainId, type LogswapClient } from "./client.js";
|
|
48
|
+
import { findQuoteResult } from "./quote.js";
|
|
51
49
|
import { fallBackUnlessRejected, signerFor } from "./write.js";
|
|
52
50
|
import { getEventLogs } from "./history.js";
|
|
53
51
|
import { poolHolders } from "./views.js";
|
|
54
|
-
import { presetMintFee } from "./positions.js";
|
|
55
|
-
import { isValidMintFee, MINT_FEE_MAX } from "./keys.js";
|
|
56
52
|
|
|
57
53
|
const WAD = 10n ** 18n;
|
|
58
54
|
const ZERO_ADDRESS = "0x0000000000000000000000000000000000000000" as const;
|
|
59
55
|
|
|
60
|
-
/**
|
|
61
|
-
|
|
62
|
-
|
|
56
|
+
/**
|
|
57
|
+
* The bits a policy declares at birth, in `Pool.flags` (decision 098; `ASK_SWAP` / `ASK_MINT` before): with a gate bit off nothing is
|
|
58
|
+
* asked; with it on the manager admits the cached operator with no policy call and asks the policy about everyone else.
|
|
59
|
+
*/
|
|
60
|
+
export const GATE_SWAP = 1;
|
|
61
|
+
export const GATE_MINT = 2;
|
|
62
|
+
/** `GATE_SWAP | GATE_MINT`: the bits `setGates` carries (`SEED_TO_DEAD` is the birth's alone). */
|
|
63
|
+
export const GATES = GATE_SWAP | GATE_MINT;
|
|
63
64
|
|
|
64
65
|
/** Everything scalar about a basket pool, in one round trip's worth of reads. */
|
|
65
66
|
export interface FPoolState {
|
|
@@ -75,9 +76,9 @@ export interface FPoolState {
|
|
|
75
76
|
Q: bigint;
|
|
76
77
|
/** Total exposure. Grows on mint, shrinks on burn; never moves on a swap. */
|
|
77
78
|
L: bigint;
|
|
78
|
-
/** The swap fee, WAD
|
|
79
|
+
/** The swap fee, WAD: `F_FEE_LIST[key.swapFeeIdx]`, resolved by the manager at the birth (policy.md §6). Never 0: the list has no zero. */
|
|
79
80
|
swapFee: bigint;
|
|
80
|
-
/** The
|
|
81
|
+
/** The mint fee, WAD of newly-minted L: the list's next entry after the swap fee (the same at the top), resolved at the birth — nothing was chosen ({@link fMintFeeOf}). */
|
|
81
82
|
mintFee: bigint;
|
|
82
83
|
/** The reference log floor (`refLogFloor`): 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. */
|
|
83
84
|
refLogFloor: bigint;
|
|
@@ -96,29 +97,32 @@ export interface FPoolState {
|
|
|
96
97
|
/** Σ = ∫ Σ_j w_j (dx_j)², accrued even though the fee is fixed — the kernel stays calculable. */
|
|
97
98
|
realizedVariance: bigint;
|
|
98
99
|
/**
|
|
99
|
-
* The pool's policy: the contract the key names, holding the pool's roles
|
|
100
|
-
*
|
|
101
|
-
*
|
|
100
|
+
* The pool's policy for life: the contract the key names, holding the pool's roles and answering every question the
|
|
101
|
+
* manager does not decide itself. Read its roles with {@link getFPoolRoles}, its terms with {@link fPolicyTermsOf}; one
|
|
102
|
+
* of the deployment's four ({@link fPoolPolicyFor}) on every protocol pool.
|
|
102
103
|
*/
|
|
103
104
|
policy: Address;
|
|
104
|
-
/**
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
105
|
+
/**
|
|
106
|
+
* What the policy declared for the pool (`Pool.flags`, decision 098): the gate bits {@link GATE_SWAP} and {@link GATE_MINT} (set by the
|
|
107
|
+
* policy's `setGates` as the operator changes the modes) and the birth bit {@link SEED_TO_DEAD} (a pad's, the pool's for life).
|
|
108
|
+
*/
|
|
109
|
+
flags: number;
|
|
110
|
+
/**
|
|
111
|
+
* The operator the manager caches (`Pool.operator`): the one account that funds, harvests and closes the pool, admitted by a gated swap or
|
|
112
|
+
* mint with no policy call. The policy's `operator(poolId)`, synced at every appointment ({@link getFPoolRoles}).
|
|
113
|
+
*/
|
|
114
|
+
operator: Address;
|
|
108
115
|
/** The time (unix seconds) of the last harvest / composition action: no swap runs at that timestamp (F version 29; a block number before). */
|
|
109
116
|
restructureTime: number;
|
|
110
|
-
/** What the pool is — its POLICY's
|
|
117
|
+
/** What the pool is — a label read off its POLICY's immutables; see {@link FPoolKind}. */
|
|
111
118
|
kind: FPoolKind;
|
|
112
|
-
/** False before the first `deployLiquidity` — and between a `close` and the next one. */
|
|
119
|
+
/** False before the first `deployLiquidity` — and between a `close` and the next one (the pool is INACTIVE: listed, or closed). */
|
|
113
120
|
seeded: boolean;
|
|
114
121
|
/**
|
|
115
|
-
* The live GENERATION.
|
|
116
|
-
* ({@link fPoolRedeem}) and
|
|
117
|
-
*
|
|
118
|
-
* ({@link
|
|
119
|
-
* as `gen + 1`, every other holder of `gen` is frozen out into its bundle. The share id carries
|
|
120
|
-
* it ({@link fPoolShareId}), so generations `0 … gen-1` are claims ({@link fPoolClaimsOf}) and
|
|
121
|
-
* `gen` is the pool. On a pad, `gen` is the graduation count — the rung.
|
|
122
|
+
* The live GENERATION (policy.md §10). The first is 0. A `close` freezes it into a bundle its shares redeem
|
|
123
|
+
* ({@link fPoolRedeem}) and moves the counter to `gen + 1`, the generation the next {@link fPoolDeploy} opens — so an
|
|
124
|
+
* inactive pool after a close already reads the number its next deploy will carry. The share id carries it
|
|
125
|
+
* ({@link fPoolShareId}): generations `0 … gen-1` are claims ({@link fPoolClaimsOf}) and `gen` is the pool.
|
|
122
126
|
*/
|
|
123
127
|
gen: number;
|
|
124
128
|
totalSupply: bigint;
|
|
@@ -136,21 +140,21 @@ export interface FPoolState {
|
|
|
136
140
|
*/
|
|
137
141
|
async function rawFPool(c: LogswapClient, poolId: Hex) {
|
|
138
142
|
const [p] = await c.public.readContract({
|
|
139
|
-
address: c.addresses.
|
|
140
|
-
abi:
|
|
141
|
-
functionName: "
|
|
143
|
+
address: c.addresses.lensF,
|
|
144
|
+
abi: lensFAbi,
|
|
145
|
+
functionName: "getPools",
|
|
142
146
|
args: [[poolId]],
|
|
143
147
|
});
|
|
144
148
|
if (!p || /^0x0{40}$/i.test(p.quote)) throw new Error(`logswap: no F pool with id ${poolId}`);
|
|
145
149
|
return p;
|
|
146
150
|
}
|
|
147
151
|
|
|
148
|
-
/** Read a basket pool whole: one lens call (`
|
|
152
|
+
/** 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}. */
|
|
149
153
|
export async function getFPool(c: LogswapClient, poolId: Hex): Promise<FPoolState> {
|
|
150
154
|
const v = await c.public.readContract({
|
|
151
|
-
address: c.addresses.
|
|
152
|
-
abi:
|
|
153
|
-
functionName: "
|
|
155
|
+
address: c.addresses.lensF,
|
|
156
|
+
abi: lensFAbi,
|
|
157
|
+
functionName: "pool",
|
|
154
158
|
args: [poolId],
|
|
155
159
|
});
|
|
156
160
|
const p = v.pool;
|
|
@@ -160,7 +164,7 @@ export async function getFPool(c: LogswapClient, poolId: Hex): Promise<FPoolStat
|
|
|
160
164
|
// flow's resumability turns on: an initialized-but-unseeded pool MUST still read, so this
|
|
161
165
|
// cannot be a check on `seeded`.
|
|
162
166
|
if (/^0x0{40}$/i.test(p.quote)) throw new Error(`logswap: no F pool with id ${poolId}`);
|
|
163
|
-
const
|
|
167
|
+
const kind = await fPoolKindOfPolicy(c, p.policy);
|
|
164
168
|
return {
|
|
165
169
|
poolId,
|
|
166
170
|
quote: p.quote,
|
|
@@ -178,8 +182,8 @@ export async function getFPool(c: LogswapClient, poolId: Hex): Promise<FPoolStat
|
|
|
178
182
|
lnCapOverSeed: Number(p.lnCapOverSeed),
|
|
179
183
|
realizedVariance: p.realizedVariance,
|
|
180
184
|
policy: p.policy,
|
|
181
|
-
|
|
182
|
-
|
|
185
|
+
flags: Number(p.flags),
|
|
186
|
+
operator: p.operator,
|
|
183
187
|
restructureTime: Number(p.restructureTime),
|
|
184
188
|
kind,
|
|
185
189
|
seeded: p.seeded,
|
|
@@ -192,55 +196,131 @@ export async function getFPool(c: LogswapClient, poolId: Hex): Promise<FPoolStat
|
|
|
192
196
|
}
|
|
193
197
|
|
|
194
198
|
/**
|
|
195
|
-
* The kind of pool —
|
|
196
|
-
*
|
|
197
|
-
*
|
|
198
|
-
*
|
|
199
|
-
*
|
|
200
|
-
*
|
|
201
|
-
* its seed the pool's at birth (`SEED_TO_DEAD`) — open to all. private → pol → pad is the ladder
|
|
202
|
-
* of rigidity; public is a pol held by the protocol. Every rate, role and gate is the policy's.
|
|
199
|
+
* The kind of pool — a LABEL read off its policy's immutables (policy.md §4.1; the manager knows no kind, and the policy's
|
|
200
|
+
* `kind()` says `"f"` for every instance). `public`: an `open` policy — anyone creates at salt zero, no gate ever, the
|
|
201
|
+
* LOG runs the pool. `pad`: `seedToDead` — the deploy's shares are the pool's, a harvest takes income only, the pool never
|
|
202
|
+
* closes. `pol`: a closed policy keeping a bid under its pools (`quoteBuffer`), a treasury's. `desk`: any other closed
|
|
203
|
+
* policy — a sponsor's, gates by pool. The LOG's four instances are one of each ({@link fPoolPolicyFor}); a third
|
|
204
|
+
* party's policy is whatever its terms say ({@link fPolicyKindOf}).
|
|
203
205
|
*/
|
|
204
|
-
export type FPoolKind = "public" | "
|
|
205
|
-
|
|
206
|
-
/** The policy's birth-time declaration that the seed's shares are the pool's (a pad's), in `asks`. */
|
|
206
|
+
export type FPoolKind = "public" | "desk" | "pol" | "pad";
|
|
207
|
+
/** The policy's birth-time declaration that the deploy's shares are the pool's (`seedToDead`, a pad's), in `flags`. */
|
|
207
208
|
export const SEED_TO_DEAD = 4;
|
|
208
209
|
|
|
209
|
-
|
|
210
|
+
/** A policy's parameters — `PolicyF`'s immutables (policy.md §4.1), set at its deployment and never changed. */
|
|
211
|
+
export interface FPolicyTerms {
|
|
212
|
+
policy: Address;
|
|
213
|
+
/** The authority as deployed; zero defers to the LOG Authority of the day — {@link getFPoolRoles} reads the live answer (`authority()`). */
|
|
214
|
+
fixedAuthority: Address;
|
|
215
|
+
/** Anyone initializes; the salt must be zero; no gate is ever set on its pools. */
|
|
216
|
+
open: boolean;
|
|
217
|
+
/** The deploy's shares go to 0xdead: a pad. The pool never closes and a harvest takes income only (the manager's rule as well). */
|
|
218
|
+
seedToDead: boolean;
|
|
219
|
+
/** A harvest takes income and never capital. */
|
|
220
|
+
incomeHarvestOnly: boolean;
|
|
221
|
+
/** WAD, at most the manager's `INCOME_TAX_MAX`: the tax on the payer's slice of each harvest's income (§8). */
|
|
222
|
+
incomeTaxRate: bigint;
|
|
223
|
+
/** The entries of {@link F_FEE_LIST} a pool may be born with, a bit per index; 0 lists all eight ({@link fFeesAllowed}). */
|
|
224
|
+
feeMask: number;
|
|
225
|
+
/** Legs per pool, 1..8. */
|
|
226
|
+
lenMax: number;
|
|
227
|
+
/** Millionths of ln(cap / seed price): the least distance a cap may sit above the seed price; 0 allows any cap, none included (§7). */
|
|
228
|
+
lnCapMin: number;
|
|
229
|
+
/** WAD, a multiple of L: the bid a deploy must bring and a harvest must leave. */
|
|
230
|
+
quoteBuffer: bigint;
|
|
231
|
+
/** The policy lists the quotes a pool may be born on (`quoteListed`); false: any quote. */
|
|
232
|
+
quoteCurated: boolean;
|
|
233
|
+
/** The policy lists the bases a pool may hold (`baseListed`); false: any base. */
|
|
234
|
+
baseCurated: boolean;
|
|
235
|
+
/** The label the terms spell: {@link fPolicyKindOf}. */
|
|
236
|
+
kind: FPoolKind;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
const termsCache = new Map<string, Promise<FPolicyTerms>>();
|
|
240
|
+
|
|
241
|
+
/** The label a policy's terms spell (see {@link FPoolKind}). Pure. */
|
|
242
|
+
export function fPolicyKindOf(t: Pick<FPolicyTerms, "open" | "seedToDead" | "quoteBuffer">): FPoolKind {
|
|
243
|
+
if (t.open) return "public";
|
|
244
|
+
if (t.seedToDead) return "pad";
|
|
245
|
+
if (t.quoteBuffer > 0n) return "pol";
|
|
246
|
+
return "desk";
|
|
247
|
+
}
|
|
210
248
|
|
|
211
249
|
/**
|
|
212
|
-
*
|
|
213
|
-
* chain:
|
|
214
|
-
* (a policy that is not one of the protocol's four shapes) throws; the app has no screen for it.
|
|
250
|
+
* A policy's terms, read once per policy address and cached for the client's chain (the policies sit at one address on
|
|
251
|
+
* every release chain): every field is an immutable, so the first read is the last. A failed read is not cached.
|
|
215
252
|
*/
|
|
216
|
-
export async function
|
|
217
|
-
// the chain id is part of the key: the policies sit at one address on every release chain
|
|
253
|
+
export async function fPolicyTermsOf(c: LogswapClient, policy: Address): Promise<FPolicyTerms> {
|
|
218
254
|
const key = `${await clientChainId(c)}:${policy.toLowerCase()}`;
|
|
219
|
-
let hit =
|
|
255
|
+
let hit = termsCache.get(key);
|
|
220
256
|
if (!hit) {
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
257
|
+
const rd = <T>(functionName: string) => c.public.readContract({ address: policy, abi: policyFAbi, functionName } as never) as Promise<T>;
|
|
258
|
+
hit = Promise.all([
|
|
259
|
+
rd<Address>("fixedAuthority"),
|
|
260
|
+
rd<boolean>("open"),
|
|
261
|
+
rd<boolean>("seedToDead"),
|
|
262
|
+
rd<boolean>("incomeHarvestOnly"),
|
|
263
|
+
rd<bigint>("incomeTaxRate"),
|
|
264
|
+
rd<number | bigint>("feeMask"),
|
|
265
|
+
rd<number | bigint>("lenMax"),
|
|
266
|
+
rd<number | bigint>("lnCapMin"),
|
|
267
|
+
rd<bigint>("quoteBuffer"),
|
|
268
|
+
rd<boolean>("quoteCurated"),
|
|
269
|
+
rd<boolean>("baseCurated"),
|
|
270
|
+
]).then(([fixedAuthority, open, seedToDead, incomeHarvestOnly, incomeTaxRate, feeMask, lenMax, lnCapMin, quoteBuffer, quoteCurated, baseCurated]) => {
|
|
271
|
+
const t = {
|
|
272
|
+
policy,
|
|
273
|
+
fixedAuthority,
|
|
274
|
+
open,
|
|
275
|
+
seedToDead,
|
|
276
|
+
incomeHarvestOnly,
|
|
277
|
+
incomeTaxRate,
|
|
278
|
+
feeMask: Number(feeMask),
|
|
279
|
+
lenMax: Number(lenMax),
|
|
280
|
+
lnCapMin: Number(lnCapMin),
|
|
281
|
+
quoteBuffer,
|
|
282
|
+
quoteCurated,
|
|
283
|
+
baseCurated,
|
|
284
|
+
};
|
|
285
|
+
return { ...t, kind: fPolicyKindOf(t) };
|
|
225
286
|
});
|
|
226
|
-
|
|
227
|
-
hit.catch(() =>
|
|
287
|
+
termsCache.set(key, hit);
|
|
288
|
+
hit.catch(() => termsCache.delete(key)); // a failed read is not a fact
|
|
228
289
|
}
|
|
229
290
|
return hit;
|
|
230
291
|
}
|
|
231
292
|
|
|
232
|
-
/**
|
|
233
|
-
export async function
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
293
|
+
/** What a policy IS, as a label: {@link fPolicyTermsOf}'s `kind`. One read per policy address, cached. */
|
|
294
|
+
export async function fPoolKindOfPolicy(c: LogswapClient, policy: Address): Promise<FPoolKind> {
|
|
295
|
+
return (await fPolicyTermsOf(c, policy)).kind;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* The pool's label — the last `NameSet` its policy emitted for it: the operator's word, mutable, never identity. Nothing is
|
|
300
|
+
* stored on chain (policy.md §4.3), so this is a log query — pass `indexer`, or set the client's. "" when never named.
|
|
301
|
+
*/
|
|
302
|
+
export async function fPoolNameOf(c: LogswapClient, poolId: Hex, opts: { policy?: Address; fromBlock?: bigint; indexer?: string } = {}): Promise<string> {
|
|
303
|
+
const policy = opts.policy ?? (await fPoolPolicyOf(c, poolId));
|
|
304
|
+
type Ev = Extract<(typeof policyFAbi)[number], { type: "event"; name: "NameSet" }>;
|
|
305
|
+
const ev = policyFAbi.find((x): x is Ev => x.type === "event" && x.name === "NameSet");
|
|
306
|
+
if (!ev) throw new Error("logswap: NameSet event missing from the generated ABI");
|
|
307
|
+
const { logs } = await getEventLogs<{ poolId: Hex; name: Hex }>(c, { indexer: opts.indexer, address: policy, event: ev, args: { poolId }, fromBlock: opts.fromBlock });
|
|
308
|
+
const last = logs[logs.length - 1];
|
|
309
|
+
return last ? bytes32ToText(last.args.name) : "";
|
|
237
310
|
}
|
|
238
311
|
|
|
239
|
-
/**
|
|
240
|
-
|
|
312
|
+
/**
|
|
313
|
+
* The deployment's named policies (its artifact keys): the LOG's four `PolicyF` instances — `public` (open: anyone creates at
|
|
314
|
+
* salt zero, no gate ever), `private` (the LOG's desk: closed, gates by pool), `pol`, `pad`. The keys predate the one-contract
|
|
315
|
+
* policy and are kept.
|
|
316
|
+
*/
|
|
317
|
+
export type FPolicySlot = "public" | "private" | "pol" | "pad";
|
|
318
|
+
|
|
319
|
+
/** The deployment's policy for a slot — the one a key names when no `policy` is given. */
|
|
320
|
+
export function fPoolPolicyFor(c: LogswapClient, slot: FPolicySlot): Address {
|
|
241
321
|
const a = c.addresses;
|
|
242
|
-
const policy =
|
|
243
|
-
if (!policy) throw new Error(`logswap: this deployment carries no ${
|
|
322
|
+
const policy = slot === "public" ? a.publicPolicy : slot === "private" ? a.privatePolicy : slot === "pol" ? a.polPolicy : a.padPolicy;
|
|
323
|
+
if (!policy) throw new Error(`logswap: this deployment carries no ${slot} policy`);
|
|
244
324
|
return policy;
|
|
245
325
|
}
|
|
246
326
|
|
|
@@ -250,58 +330,49 @@ export async function fPoolPolicyOf(c: LogswapClient, poolId: Hex): Promise<Addr
|
|
|
250
330
|
}
|
|
251
331
|
|
|
252
332
|
/**
|
|
253
|
-
* A pool's roles, as its POLICY holds them.
|
|
254
|
-
*
|
|
255
|
-
*
|
|
256
|
-
*
|
|
257
|
-
* operator and no gate: those fields read zero / false.
|
|
333
|
+
* A pool's roles, as its POLICY holds them (policy.md §2). The AUTHORITY is the policy's — one address per policy, immutable,
|
|
334
|
+
* the LOG Authority of the day on the LOG's own instances — and appoints the pool's OPERATOR (zero resets it to the authority),
|
|
335
|
+
* who runs the pool: `deployLiquidity`, `harvest`, `close`, the two gate modes, the name; the operator pays the seed and holds
|
|
336
|
+
* its shares. The modes are the pool's; the lists they consult are the policy's ({@link fPolicyRightsOf}).
|
|
258
337
|
*/
|
|
259
338
|
export interface FPoolRoles {
|
|
260
339
|
policy: Address;
|
|
261
|
-
|
|
340
|
+
/** The policy's authority now (`authority()`): its immutable, or the registry's LOG Authority when that is zero. */
|
|
262
341
|
authority: Address;
|
|
263
|
-
/** The
|
|
264
|
-
pendingAuthority: Address;
|
|
265
|
-
/** The desk's optional pool operator (decision 073): one delegate besides the authority, zero when none. */
|
|
342
|
+
/** The pool's operator (`operator(poolId)`): the authority at birth until re-appointed. Zero: the policy never held this pool. */
|
|
266
343
|
operator: Address;
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
/** `
|
|
277
|
-
export
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
const
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
rdPolicy<bigint>(fPolicyBaseAbi, "maxHarvest"),
|
|
344
|
+
/** Swap admission: everyone (`open`), the policy's swap list (`listed`; the operator always passes) or the operator alone. Always `open` under an open policy. */
|
|
345
|
+
swapMode: FPoolMode;
|
|
346
|
+
/** Mint admission, at least as restrictive as the swap mode (`ModeOrder`): the same three, the mint list in `listed`. */
|
|
347
|
+
mintMode: FPoolMode;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/** `IPolicyF.Mode`: Open = 0, Listed = 1, Operator = 2 — the order `open < listed < operator` is what `mintMode ≥ swapMode` compares. */
|
|
351
|
+
export type FPoolMode = "open" | "listed" | "operator";
|
|
352
|
+
const MODES: readonly FPoolMode[] = ["open", "listed", "operator"];
|
|
353
|
+
/** The gate modes in `IPolicyF.Mode` order — the index is the on-chain ordinal. */
|
|
354
|
+
export const fPoolModes: readonly FPoolMode[] = MODES;
|
|
355
|
+
|
|
356
|
+
/** Read a pool's roles from its policy. `state` saves the `getPool` round trip when the policy is already in hand. */
|
|
357
|
+
export async function getFPoolRoles(c: LogswapClient, poolId: Hex, state?: Pick<FPoolState, "policy">): Promise<FPoolRoles> {
|
|
358
|
+
const policy = state?.policy ?? (await fPoolPolicyOf(c, poolId));
|
|
359
|
+
const rd = <T>(functionName: string, args: readonly unknown[] = []) =>
|
|
360
|
+
c.public.readContract({ address: policy, abi: policyFAbi, functionName, args } as never) as Promise<T>;
|
|
361
|
+
const [authority, operator, swap, mint] = await Promise.all([
|
|
362
|
+
rd<Address>("authority"),
|
|
363
|
+
rd<Address>("operator", [poolId]),
|
|
364
|
+
rd<number | bigint>("swapMode", [poolId]),
|
|
365
|
+
rd<number | bigint>("mintMode", [poolId]),
|
|
290
366
|
]);
|
|
291
|
-
|
|
292
|
-
const permissions = desk
|
|
293
|
-
? ((await c.public.readContract({ address: s.policy, abi: privatePolicyAbi, functionName: "permissionsOf", args: [poolId] } as never)) as readonly [number, Address, boolean, Address, Address])
|
|
294
|
-
: undefined;
|
|
295
|
-
const [mode, swapExecutor, gateMint, , operator] = permissions ?? [0, ZERO_ADDRESS, false, ZERO_ADDRESS, ZERO_ADDRESS];
|
|
296
|
-
return { policy: s.policy, creator, authority, pendingAuthority, operator, gateMint, swapMode: SWAP_MODES[Number(mode)] ?? "open", swapExecutor, maxHarvest };
|
|
367
|
+
return { policy, authority, operator, swapMode: MODES[Number(swap)] ?? "open", mintMode: MODES[Number(mint)] ?? "open" };
|
|
297
368
|
}
|
|
298
369
|
|
|
299
370
|
/** Which of the two products a pool is configured as — a pad is a launch, anything else a basket/pool. A UI has to choose what to render. */
|
|
300
371
|
export type FPoolShape = "launch" | "basket";
|
|
301
372
|
|
|
302
373
|
export interface FPoolDescription {
|
|
303
|
-
shape: FPoolShape;
|
|
304
374
|
/** The pad is the launch shape, by the kind. */
|
|
375
|
+
shape: FPoolShape;
|
|
305
376
|
legs: number;
|
|
306
377
|
/** True when the pool holds no quote: an all-base resting ask. base→quote is the one blocked path. */
|
|
307
378
|
atFloor: boolean;
|
|
@@ -311,30 +382,42 @@ export interface FPoolDescription {
|
|
|
311
382
|
* from the first wei after it.
|
|
312
383
|
*/
|
|
313
384
|
unharvested: bigint;
|
|
314
|
-
/**
|
|
315
|
-
* The most a harvest may take now by the MANAGER's rule: the bid, `Q` once seeded (0 before).
|
|
316
|
-
* The manager's `harvestable()` getter was cut in F version 21; this is the same number, read
|
|
317
|
-
* off `getPool`. The policy may allow less (a pad: the income; a POL: above `minQuoteRatio`·L) —
|
|
318
|
-
* {@link FPoolRoles.maxHarvest}.
|
|
319
|
-
*/
|
|
320
|
-
harvestable: bigint;
|
|
321
|
-
/** The dead shares' banked dividend — a pad's income, the creator's until a rung is climbed (decision 085: formerly the pot). */
|
|
385
|
+
/** What a harvest takes with `extra` 0: the income, at most the bid. */
|
|
322
386
|
income: bigint;
|
|
387
|
+
/** The most capital a harvest may take beside the income (`extra`): `Q − income − quoteBuffer·L`; 0 under an income-only policy and on a pad ({@link fPoolHarvestRoom}). */
|
|
388
|
+
capitalRoom: bigint;
|
|
389
|
+
/** The most a harvest may take now, income and capital: `income + capitalRoom`. */
|
|
390
|
+
harvestable: bigint;
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
/**
|
|
394
|
+
* What a harvest may take now (policy.md §9): the income `I = min(unharvested, Q)` always; capital on top of it up to
|
|
395
|
+
* `Q − I − quoteBuffer·L` (`QuoteTooThin` past it), none where the policy is income-only (`IncomeOnly`) or the pool a pad
|
|
396
|
+
* (`SEED_TO_DEAD`: the manager's own rule, `HarvestLimit`). Nothing on an unfunded pool.
|
|
397
|
+
*/
|
|
398
|
+
export function fPoolHarvestRoom(
|
|
399
|
+
s: Pick<FPoolState, "Q" | "L" | "unharvested" | "flags">,
|
|
400
|
+
t: Pick<FPolicyTerms, "incomeHarvestOnly" | "quoteBuffer">,
|
|
401
|
+
): { income: bigint; capital: bigint } {
|
|
402
|
+
if (s.L === 0n) return { income: 0n, capital: 0n };
|
|
403
|
+
const income = s.unharvested < s.Q ? s.unharvested : s.Q;
|
|
404
|
+
if (t.incomeHarvestOnly || (s.flags & SEED_TO_DEAD) !== 0) return { income, capital: 0n };
|
|
405
|
+
const keep = income + (s.L * t.quoteBuffer + WAD - 1n) / WAD; // `mulWadUp`, as the policy rounds
|
|
406
|
+
return { income, capital: s.Q > keep ? s.Q - keep : 0n };
|
|
323
407
|
}
|
|
324
408
|
|
|
325
409
|
export async function describeFPool(c: LogswapClient, s: FPoolState): Promise<FPoolDescription> {
|
|
326
|
-
// an unfunded pool has no L: nothing earned, nothing to harvest
|
|
327
|
-
|
|
328
|
-
const
|
|
329
|
-
const unharvested = s.L > 0n ? s.unharvested : 0n;
|
|
330
|
-
const income = s.L > 0n ? await fPoolDividendOf(c, s.poolId, DEAD_ADDRESS, s.gen) : 0n;
|
|
410
|
+
// an unfunded pool has no L: nothing earned, nothing to harvest
|
|
411
|
+
const terms = await fPolicyTermsOf(c, s.policy);
|
|
412
|
+
const { income, capital } = fPoolHarvestRoom(s, terms);
|
|
331
413
|
return {
|
|
332
|
-
shape: s.kind === "pad" ? "launch": "basket", // the kind, not n = 1
|
|
414
|
+
shape: s.kind === "pad" ? "launch" : "basket", // the kind, not n = 1
|
|
333
415
|
legs: s.bases.length,
|
|
334
416
|
atFloor: s.Q === 0n,
|
|
335
|
-
unharvested,
|
|
336
|
-
harvestable,
|
|
417
|
+
unharvested: s.L > 0n ? s.unharvested : 0n,
|
|
337
418
|
income,
|
|
419
|
+
capitalRoom: capital,
|
|
420
|
+
harvestable: income + capital,
|
|
338
421
|
};
|
|
339
422
|
}
|
|
340
423
|
|
|
@@ -467,11 +550,11 @@ export function fPoolPreviewMintQuote(st: Pick<FPoolState, "Q" | "L">, dL: bigin
|
|
|
467
550
|
* and expect change back — do not treat it as exact.
|
|
468
551
|
*/
|
|
469
552
|
export async function fPoolPreviewZapIn(c: LogswapClient, poolId: Hex, dL: bigint): Promise<bigint> {
|
|
470
|
-
// read-only lives on the LENS (the
|
|
471
|
-
const {
|
|
553
|
+
// read-only lives on the LENS (LensF: the previews)
|
|
554
|
+
const { lensFAbi } = await import("./generated.js");
|
|
472
555
|
return c.public.readContract({
|
|
473
|
-
address: c.addresses.
|
|
474
|
-
abi:
|
|
556
|
+
address: c.addresses.lensF,
|
|
557
|
+
abi: lensFAbi,
|
|
475
558
|
functionName: "previewZapIn",
|
|
476
559
|
args: [poolId, dL],
|
|
477
560
|
} as never) as Promise<bigint>;
|
|
@@ -531,8 +614,8 @@ export async function fPoolPreviewZapOut(
|
|
|
531
614
|
a: { poolId: Hex; shares: bigint; tokenOut: Address; account: Address },
|
|
532
615
|
): Promise<bigint> {
|
|
533
616
|
const { result } = await c.public.simulateContract({
|
|
534
|
-
address: c.addresses.
|
|
535
|
-
abi:
|
|
617
|
+
address: c.addresses.routerF,
|
|
618
|
+
abi: routerFAbi,
|
|
536
619
|
functionName: "zapOut",
|
|
537
620
|
args: [a.poolId, a.shares, a.tokenOut, 0n, a.account, defaultDeadline()],
|
|
538
621
|
account: a.account,
|
|
@@ -588,28 +671,30 @@ export async function fPoolPreviewRollIn(
|
|
|
588
671
|
holder: Address,
|
|
589
672
|
shares: bigint,
|
|
590
673
|
): Promise<{ dL: bigint; quoteShort: bigint; quoteExcess: bigint }> {
|
|
591
|
-
const {
|
|
674
|
+
const { lensFAbi } = await import("./generated.js");
|
|
592
675
|
const [dL, quoteShort, quoteExcess] = (await c.public.readContract({
|
|
593
|
-
address: c.addresses.
|
|
594
|
-
abi:
|
|
676
|
+
address: c.addresses.lensF,
|
|
677
|
+
abi: lensFAbi,
|
|
595
678
|
functionName: "previewRollIn",
|
|
596
679
|
args: [poolId, BigInt(gen), holder, shares],
|
|
597
680
|
} as never)) as readonly [bigint, bigint, bigint];
|
|
598
681
|
return { dL, quoteShort, quoteExcess };
|
|
599
682
|
}
|
|
600
683
|
|
|
601
|
-
// ─── the floor lever (
|
|
684
|
+
// ─── the floor lever (the operator's) ─────────────────────────────────────────
|
|
602
685
|
|
|
603
686
|
/**
|
|
604
|
-
*
|
|
605
|
-
*
|
|
606
|
-
*
|
|
607
|
-
*
|
|
608
|
-
*
|
|
609
|
-
*
|
|
687
|
+
* Harvest (policy.md §9): take this generation's income — `L·(refLogFloor − logFloor)`, the fees since the floor was last
|
|
688
|
+
* referenced — and `extra` of capital on top of it, out of the bid; price-neutral, no base moves. Both accrue as a DIVIDEND to
|
|
689
|
+
* every share, settled lazily on each holder's next transfer, mint or burn or pulled with {@link fPoolClaim}; the income is taxed
|
|
690
|
+
* 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`.
|
|
691
|
+
* The operator's own settled dividend — this harvest's and anything pending — is paid to `to` in the same call: one transaction,
|
|
692
|
+
* and the operator (usually a contract) routes the payout through `to`. The operator's alone (`NotOperator`). `extra` must fit the
|
|
693
|
+
* room ({@link fPoolHarvestRoom}): 0 on a pad (`HarvestLimit`) and under an income-only policy (`IncomeOnly`), within the buffer
|
|
694
|
+
* otherwise (`QuoteTooThin`).
|
|
610
695
|
*/
|
|
611
|
-
export async function fPoolHarvest(c: LogswapClient, a: { poolId: Hex;
|
|
612
|
-
return writeFPool(c, a.poolId, "harvest", [a.
|
|
696
|
+
export async function fPoolHarvest(c: LogswapClient, a: { poolId: Hex; extra?: bigint; to?: Address; account: Address }) {
|
|
697
|
+
return writeFPool(c, a.poolId, "harvest", [a.extra ?? 0n, a.to ?? a.account], a.account);
|
|
613
698
|
}
|
|
614
699
|
|
|
615
700
|
/**
|
|
@@ -630,9 +715,9 @@ export async function fPoolClaim(c: LogswapClient, a: { poolId: Hex; gen?: bigin
|
|
|
630
715
|
export async function fPoolDividendOf(c: LogswapClient, poolId: Hex, holder: Address, gen?: bigint | number): Promise<bigint> {
|
|
631
716
|
const g = gen ?? (await fPoolGen(c, poolId));
|
|
632
717
|
return c.public.readContract({
|
|
633
|
-
address: c.addresses.
|
|
634
|
-
abi:
|
|
635
|
-
functionName: "
|
|
718
|
+
address: c.addresses.lensF,
|
|
719
|
+
abi: lensFAbi,
|
|
720
|
+
functionName: "dividendOf",
|
|
636
721
|
args: [poolId, BigInt(g), holder],
|
|
637
722
|
});
|
|
638
723
|
}
|
|
@@ -641,7 +726,7 @@ export async function fPoolDividendOf(c: LogswapClient, poolId: Hex, holder: Add
|
|
|
641
726
|
// A lending contract — the LOCKER — locks part of an owner's shares in place: no transfer, burn or
|
|
642
727
|
// redeem past the free balance. The dividend the locked amount earns is HELD BY THE LIEN, claimable
|
|
643
728
|
// by nobody while it stands; lifted, it goes with the lifted part — to the owner on a release (a
|
|
644
|
-
// repaid loan gets it back), to the seizer on a seizure. A borrower frozen
|
|
729
|
+
// repaid loan gets it back), to the seizer on a seizure. A borrower frozen into a bundle by `close` keeps
|
|
645
730
|
// its lien on the old generation's id.
|
|
646
731
|
|
|
647
732
|
/** A lien on one share id: the locker, the amount locked, and the dividend the lien holds (banked). */
|
|
@@ -659,9 +744,9 @@ export interface FPoolLien {
|
|
|
659
744
|
export async function fPoolLienOf(c: LogswapClient, poolId: Hex, owner: Address, gen?: bigint | number): Promise<FPoolLien> {
|
|
660
745
|
const g = gen ?? (await fPoolGen(c, poolId));
|
|
661
746
|
const [locker, amount, owed] = await c.public.readContract({
|
|
662
|
-
address: c.addresses.
|
|
663
|
-
abi:
|
|
664
|
-
functionName: "
|
|
747
|
+
address: c.addresses.lensF,
|
|
748
|
+
abi: lensFAbi,
|
|
749
|
+
functionName: "lienOf",
|
|
665
750
|
args: [fPoolShareId(poolId, g), owner],
|
|
666
751
|
});
|
|
667
752
|
return { locker, amount, owed };
|
|
@@ -716,8 +801,8 @@ function requireWallet(c: LogswapClient) {
|
|
|
716
801
|
async function writeFPool(c: LogswapClient, poolId: Hex, functionName: string, args: unknown[], account: Address) {
|
|
717
802
|
const wallet = requireWallet(c);
|
|
718
803
|
const { request } = await c.public.simulateContract({
|
|
719
|
-
address: c.addresses.
|
|
720
|
-
abi:
|
|
804
|
+
address: c.addresses.managerF,
|
|
805
|
+
abi: managerFAbi,
|
|
721
806
|
functionName,
|
|
722
807
|
// Every manager write is keyed by poolId as its FIRST parameter; prepending it here, in the
|
|
723
808
|
// one place all seven helpers share, is what keeps a caller from ever omitting it. The `as
|
|
@@ -732,8 +817,8 @@ async function writeFPool(c: LogswapClient, poolId: Hex, functionName: string, a
|
|
|
732
817
|
async function writeFPool0(c: LogswapClient, functionName: string, args: unknown[], account: Address) {
|
|
733
818
|
const wallet = requireWallet(c);
|
|
734
819
|
const { request } = await c.public.simulateContract({
|
|
735
|
-
address: c.addresses.
|
|
736
|
-
abi:
|
|
820
|
+
address: c.addresses.managerF,
|
|
821
|
+
abi: managerFAbi,
|
|
737
822
|
functionName,
|
|
738
823
|
args,
|
|
739
824
|
account: signerFor(c, account),
|
|
@@ -754,17 +839,17 @@ async function writeRouter(
|
|
|
754
839
|
let sendArgs: unknown[] = args;
|
|
755
840
|
if (pullTokens.length) {
|
|
756
841
|
const { permit2SigCalls } = await import("./onboard.js");
|
|
757
|
-
const sigCalls = await permit2SigCalls(c, pullTokens).catch(fallBackUnlessRejected);
|
|
842
|
+
const sigCalls = await permit2SigCalls(c, "F", pullTokens).catch(fallBackUnlessRejected);
|
|
758
843
|
if (sigCalls.length) {
|
|
759
844
|
const { encodeFunctionData } = await import("viem");
|
|
760
|
-
const inner = encodeFunctionData({ abi:
|
|
845
|
+
const inner = encodeFunctionData({ abi: routerFAbi, functionName, args } as never);
|
|
761
846
|
fn = "multicall";
|
|
762
847
|
sendArgs = [[...sigCalls, inner]];
|
|
763
848
|
}
|
|
764
849
|
}
|
|
765
850
|
const { request } = await c.public.simulateContract({
|
|
766
|
-
address: c.addresses.
|
|
767
|
-
abi:
|
|
851
|
+
address: c.addresses.routerF,
|
|
852
|
+
abi: routerFAbi,
|
|
768
853
|
functionName: fn,
|
|
769
854
|
args: sendArgs,
|
|
770
855
|
account: signerFor(c, account),
|
|
@@ -787,7 +872,7 @@ export async function approveTokenForFPoolManager(c: LogswapClient, token: Addre
|
|
|
787
872
|
address: token,
|
|
788
873
|
abi: [{ type: "function", name: "approve", stateMutability: "nonpayable", inputs: [{ name: "s", type: "address" }, { name: "a", type: "uint256" }], outputs: [{ type: "bool" }] }],
|
|
789
874
|
functionName: "approve",
|
|
790
|
-
args: [c.addresses.
|
|
875
|
+
args: [c.addresses.managerF, (1n << 256n) - 1n],
|
|
791
876
|
account: wallet.account,
|
|
792
877
|
chain: c.wallet!.chain,
|
|
793
878
|
} as never);
|
|
@@ -799,7 +884,7 @@ export async function fPoolManagerAllowanceOk(c: LogswapClient, token: Address,
|
|
|
799
884
|
address: token,
|
|
800
885
|
abi: [{ type: "function", name: "allowance", stateMutability: "view", inputs: [{ name: "o", type: "address" }, { name: "s", type: "address" }], outputs: [{ type: "uint256" }] }],
|
|
801
886
|
functionName: "allowance",
|
|
802
|
-
args: [owner, c.addresses.
|
|
887
|
+
args: [owner, c.addresses.managerF],
|
|
803
888
|
} as never)) as bigint;
|
|
804
889
|
return allowance >= need;
|
|
805
890
|
}
|
|
@@ -813,10 +898,10 @@ export async function fPoolManagerAllowanceOk(c: LogswapClient, token: Address,
|
|
|
813
898
|
|
|
814
899
|
export async function isRouterOperatorForFPool(c: LogswapClient, owner: Address): Promise<boolean> {
|
|
815
900
|
return c.public.readContract({
|
|
816
|
-
address: c.addresses.
|
|
817
|
-
abi:
|
|
901
|
+
address: c.addresses.managerF,
|
|
902
|
+
abi: managerFAbi,
|
|
818
903
|
functionName: "isOperator",
|
|
819
|
-
args: [owner, c.addresses.
|
|
904
|
+
args: [owner, c.addresses.routerF],
|
|
820
905
|
} as never) as Promise<boolean>;
|
|
821
906
|
}
|
|
822
907
|
|
|
@@ -824,10 +909,10 @@ export async function isRouterOperatorForFPool(c: LogswapClient, owner: Address)
|
|
|
824
909
|
export async function approveRouterForFPool(c: LogswapClient, account: Address) {
|
|
825
910
|
const wallet = requireWallet(c);
|
|
826
911
|
const { request } = await c.public.simulateContract({
|
|
827
|
-
address: c.addresses.
|
|
828
|
-
abi:
|
|
912
|
+
address: c.addresses.managerF,
|
|
913
|
+
abi: managerFAbi,
|
|
829
914
|
functionName: "setOperator",
|
|
830
|
-
args: [c.addresses.
|
|
915
|
+
args: [c.addresses.routerF, true],
|
|
831
916
|
account: signerFor(c, account),
|
|
832
917
|
} as never);
|
|
833
918
|
return wallet.writeContract(request as never);
|
|
@@ -867,8 +952,8 @@ export function fPoolClaimId(token: Address): bigint {
|
|
|
867
952
|
export async function fPoolShareBalance(c: LogswapClient, poolId: Hex, owner: Address, gen?: bigint | number): Promise<bigint> {
|
|
868
953
|
const g = gen ?? (await fPoolGen(c, poolId));
|
|
869
954
|
return c.public.readContract({
|
|
870
|
-
address: c.addresses.
|
|
871
|
-
abi:
|
|
955
|
+
address: c.addresses.managerF,
|
|
956
|
+
abi: managerFAbi,
|
|
872
957
|
functionName: "balanceOf",
|
|
873
958
|
args: [owner, fPoolShareId(poolId, g)],
|
|
874
959
|
} as never) as Promise<bigint>;
|
|
@@ -881,9 +966,9 @@ export async function fPoolBundleOf(
|
|
|
881
966
|
gen: bigint | number,
|
|
882
967
|
): Promise<{ supply: bigint; quote: bigint; base: bigint[] }> {
|
|
883
968
|
const [supply, quote, base] = await c.public.readContract({
|
|
884
|
-
address: c.addresses.
|
|
885
|
-
abi:
|
|
886
|
-
functionName: "
|
|
969
|
+
address: c.addresses.lensF,
|
|
970
|
+
abi: lensFAbi,
|
|
971
|
+
functionName: "bundleOf",
|
|
887
972
|
args: [poolId, BigInt(gen)],
|
|
888
973
|
});
|
|
889
974
|
return { supply, quote, base: [...base] };
|
|
@@ -900,11 +985,11 @@ export interface FPoolClaimRow {
|
|
|
900
985
|
|
|
901
986
|
/** A holder's claims on a pool's retired generations — one row per generation still held. */
|
|
902
987
|
export async function fPoolClaimsOf(c: LogswapClient, poolId: Hex, owner: Address): Promise<FPoolClaimRow[]> {
|
|
903
|
-
const {
|
|
988
|
+
const { lensFAbi } = await import("./generated.js");
|
|
904
989
|
const rows = (await c.public.readContract({
|
|
905
|
-
address: c.addresses.
|
|
906
|
-
abi:
|
|
907
|
-
functionName: "
|
|
990
|
+
address: c.addresses.lensF,
|
|
991
|
+
abi: lensFAbi,
|
|
992
|
+
functionName: "claimsOf",
|
|
908
993
|
args: [poolId, owner],
|
|
909
994
|
} as never)) as readonly { gen: bigint; shares: bigint; base: readonly bigint[]; quote: bigint; dividend: bigint }[];
|
|
910
995
|
return rows.map((r) => ({ gen: Number(r.gen), shares: r.shares, base: [...r.base], quote: r.quote, dividend: r.dividend }));
|
|
@@ -924,8 +1009,8 @@ export async function fPoolRedeem(
|
|
|
924
1009
|
|
|
925
1010
|
export async function fPoolClaimBalance(c: LogswapClient, token: Address, owner: Address): Promise<bigint> {
|
|
926
1011
|
return c.public.readContract({
|
|
927
|
-
address: c.addresses.
|
|
928
|
-
abi:
|
|
1012
|
+
address: c.addresses.managerF,
|
|
1013
|
+
abi: managerFAbi,
|
|
929
1014
|
functionName: "balanceOf",
|
|
930
1015
|
args: [owner, fPoolClaimId(token)],
|
|
931
1016
|
} as never) as Promise<bigint>;
|
|
@@ -953,8 +1038,8 @@ export async function fPoolQuoteSwap(
|
|
|
953
1038
|
): Promise<bigint> {
|
|
954
1039
|
try {
|
|
955
1040
|
await c.public.simulateContract({
|
|
956
|
-
address: c.addresses.
|
|
957
|
-
abi:
|
|
1041
|
+
address: c.addresses.routerF,
|
|
1042
|
+
abi: routerFAbi,
|
|
958
1043
|
functionName: "quoteSwap",
|
|
959
1044
|
// the taker matters only on a gated pool: the connected account, or the zero address
|
|
960
1045
|
args: [a.poolId, a.kind, BigInt(a.j), BigInt(a.k ?? 0), a.amountIn, a.taker ?? c.wallet?.account?.address ?? ZERO_ADDRESS],
|
|
@@ -967,32 +1052,6 @@ export async function fPoolQuoteSwap(
|
|
|
967
1052
|
throw new Error("logswap: quoteSwap returned without reverting, which it must never do");
|
|
968
1053
|
}
|
|
969
1054
|
|
|
970
|
-
/**
|
|
971
|
-
* `QuoteResult(uint256)` — selector then one word. viem nests the revert data several layers deep
|
|
972
|
-
* depending on the transport, so walk for it rather than guessing the shape.
|
|
973
|
-
*
|
|
974
|
-
* The selector is DERIVED, not written down. A hardcoded one is wrong silently: the decode simply
|
|
975
|
-
* never matches and every quote rethrows as if the swap had failed.
|
|
976
|
-
*/
|
|
977
|
-
function findQuoteResult(err: unknown): bigint | null {
|
|
978
|
-
const SELECTOR = toFunctionSelector("QuoteResult(uint256)");
|
|
979
|
-
const seen = new Set<unknown>();
|
|
980
|
-
const walk = (e: unknown): bigint | null => {
|
|
981
|
-
if (!e || typeof e !== "object" || seen.has(e)) return null;
|
|
982
|
-
seen.add(e);
|
|
983
|
-
const anyE = e as Record<string, unknown>;
|
|
984
|
-
const data = anyE.data;
|
|
985
|
-
if (typeof data === "string" && data.startsWith(SELECTOR) && data.length >= 10 + 64) {
|
|
986
|
-
return BigInt("0x" + data.slice(10, 10 + 64));
|
|
987
|
-
}
|
|
988
|
-
for (const k of ["cause", "walk", "error", "details"]) {
|
|
989
|
-
const found = walk(anyE[k]);
|
|
990
|
-
if (found !== null) return found;
|
|
991
|
-
}
|
|
992
|
-
return null;
|
|
993
|
-
};
|
|
994
|
-
return walk(err);
|
|
995
|
-
}
|
|
996
1055
|
|
|
997
1056
|
// ─── the pool lifecycle (creation to dissolution) ─────────────────────────────
|
|
998
1057
|
//
|
|
@@ -1004,33 +1063,26 @@ export interface FPoolCreateArgs {
|
|
|
1004
1063
|
quote: Address;
|
|
1005
1064
|
/** 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. */
|
|
1006
1065
|
bases: Address[];
|
|
1007
|
-
/** The swap fee
|
|
1008
|
-
|
|
1066
|
+
/** The swap fee as its index into {@link F_FEE_LIST} (policy.md §6); the mint fee is the list's next entry, nothing to choose. One of this or `swapFee`. */
|
|
1067
|
+
swapFeeIdx?: number;
|
|
1068
|
+
/** The swap fee, WAD — one of the list's eight values ({@link fFeeIndexOf} throws otherwise); the index is what the key carries. */
|
|
1069
|
+
swapFee?: bigint;
|
|
1009
1070
|
/**
|
|
1010
|
-
*
|
|
1011
|
-
*
|
|
1012
|
-
* {@link presetMintFee}: twice the swap fee.
|
|
1071
|
+
* Which of the deployment's policies the key names when `policy` is not given ({@link fPoolPolicyFor}). NOT a key
|
|
1072
|
+
* field (decisions 049: the manager knows no kind): the policy is, and its terms say what it is ({@link FPoolKind}).
|
|
1013
1073
|
*/
|
|
1014
|
-
|
|
1015
|
-
/**
|
|
1016
|
-
* Which of the protocol's four the pool is — see {@link FPoolKind}. NOT a key field (decisions
|
|
1017
|
-
* 049: the manager knows no kind): it selects the deployment's policy of that kind when `policy`
|
|
1018
|
-
* is not named ({@link fPoolPolicyFor}), and it is what the policy will say it is.
|
|
1019
|
-
*/
|
|
1020
|
-
kind: FPoolKind;
|
|
1074
|
+
kind: FPolicySlot;
|
|
1021
1075
|
/**
|
|
1022
|
-
* The pool's policy: the contract the key names, approved by the
|
|
1023
|
-
*
|
|
1024
|
-
*
|
|
1076
|
+
* The pool's policy for life: the contract the key names, approved by the registry (`PolicyNotApproved`). Defaults to the
|
|
1077
|
+
* deployment's policy for `kind`. An open policy admits anyone; a closed one its authority alone (`Refused`). The policy's
|
|
1078
|
+
* authority is the pool's operator at birth: the one account that then funds it ({@link fPoolDeploy}).
|
|
1025
1079
|
*/
|
|
1026
1080
|
policy?: Address;
|
|
1027
|
-
/** Who is born holding the pool: immutable identity, the pool's first authority (the policy records it). */
|
|
1028
|
-
creator: Address;
|
|
1029
1081
|
/**
|
|
1030
|
-
* The differentiator, and nothing else. Identity is the key's hash, so
|
|
1031
|
-
*
|
|
1032
|
-
*
|
|
1033
|
-
*
|
|
1082
|
+
* The differentiator, and nothing else. Identity is the key's hash, so a sponsor cannot run two pools of the same shape
|
|
1083
|
+
* without varying it — the second `initialize` would land on the first pool's id. Zero under an open policy (`NotCanonical`):
|
|
1084
|
+
* one public pool per shape and swap fee. Defaults to zero. A pool's NAME is not this: names are events on the policy
|
|
1085
|
+
* ({@link fPoolSetName}), so a rename forks nothing.
|
|
1034
1086
|
*/
|
|
1035
1087
|
salt?: Hex;
|
|
1036
1088
|
account: Address;
|
|
@@ -1038,6 +1090,59 @@ export interface FPoolCreateArgs {
|
|
|
1038
1090
|
|
|
1039
1091
|
const ZERO_SALT = `0x${"0".repeat(64)}` as const;
|
|
1040
1092
|
|
|
1093
|
+
// ─── the fee list (policy.md §6) ──────────────────────────────────────────────
|
|
1094
|
+
|
|
1095
|
+
/** `FeeParams.FEE_LIST` in bp: the eight swap fees an F pool may be born with. The key carries the index. */
|
|
1096
|
+
export const F_FEE_LIST_BP = [1, 2, 5, 10, 20, 50, 100, 200] as const;
|
|
1097
|
+
/** The list in WAD (1 bp = 1e14). No zero: the fee-free pool cannot be born. */
|
|
1098
|
+
export const F_FEE_LIST: readonly bigint[] = F_FEE_LIST_BP.map((bp) => BigInt(bp) * 10n ** 14n);
|
|
1099
|
+
|
|
1100
|
+
/** The fee at `idx` of the list, WAD. Throws off the list. */
|
|
1101
|
+
export function fFeeOf(idx: number): bigint {
|
|
1102
|
+
const fee = Number.isInteger(idx) ? F_FEE_LIST[idx] : undefined;
|
|
1103
|
+
if (fee === undefined) throw new Error(`logswap: swap fee index ${idx} is off the F fee list (0..${F_FEE_LIST.length - 1})`);
|
|
1104
|
+
return fee;
|
|
1105
|
+
}
|
|
1106
|
+
|
|
1107
|
+
/** 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). */
|
|
1108
|
+
export function fMintFeeIdxOf(swapFeeIdx: number): number {
|
|
1109
|
+
fFeeOf(swapFeeIdx);
|
|
1110
|
+
return Math.min(swapFeeIdx + 1, F_FEE_LIST.length - 1);
|
|
1111
|
+
}
|
|
1112
|
+
|
|
1113
|
+
/** The mint fee, WAD of newly-minted L, a pool born at `swapFeeIdx` charges on outside mints. */
|
|
1114
|
+
export function fMintFeeOf(swapFeeIdx: number): bigint {
|
|
1115
|
+
return fFeeOf(fMintFeeIdxOf(swapFeeIdx));
|
|
1116
|
+
}
|
|
1117
|
+
|
|
1118
|
+
/** 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. */
|
|
1119
|
+
export function fFeeIndexOf(fee: bigint): number {
|
|
1120
|
+
const idx = F_FEE_LIST.indexOf(fee);
|
|
1121
|
+
if (idx < 0) throw new Error(`logswap: swap fee ${fee} is not on the F fee list (${F_FEE_LIST_BP.join(", ")} bp)`);
|
|
1122
|
+
return idx;
|
|
1123
|
+
}
|
|
1124
|
+
|
|
1125
|
+
/** Whether a policy's `feeMask` admits `idx`: a bit per index, an empty mask admitting all eight. */
|
|
1126
|
+
export function fFeeListed(feeMask: number, idx: number): boolean {
|
|
1127
|
+
return Number.isInteger(idx) && idx >= 0 && idx < F_FEE_LIST.length && (feeMask === 0 || ((feeMask >> idx) & 1) === 1);
|
|
1128
|
+
}
|
|
1129
|
+
|
|
1130
|
+
/** The indices a policy's `feeMask` admits, ascending. */
|
|
1131
|
+
export function fFeesAllowed(feeMask: number): number[] {
|
|
1132
|
+
return F_FEE_LIST.map((_, i) => i).filter((i) => fFeeListed(feeMask, i));
|
|
1133
|
+
}
|
|
1134
|
+
|
|
1135
|
+
/** The swap fee index of create arguments given either way; both given must agree. */
|
|
1136
|
+
export function fPoolSwapFeeIdxOf(a: { swapFeeIdx?: number; swapFee?: bigint }): number {
|
|
1137
|
+
if (a.swapFeeIdx !== undefined) {
|
|
1138
|
+
const fee = fFeeOf(a.swapFeeIdx);
|
|
1139
|
+
if (a.swapFee !== undefined && a.swapFee !== fee) throw new Error(`logswap: swap fee ${a.swapFee} is not the F fee list's entry ${a.swapFeeIdx} (${fee})`);
|
|
1140
|
+
return a.swapFeeIdx;
|
|
1141
|
+
}
|
|
1142
|
+
if (a.swapFee !== undefined) return fFeeIndexOf(a.swapFee);
|
|
1143
|
+
throw new Error("logswap: an F pool needs its swap fee — `swapFeeIdx` (into the list) or `swapFee` (WAD, on the list)");
|
|
1144
|
+
}
|
|
1145
|
+
|
|
1041
1146
|
/** `bytes32` ⇄ short UTF-8 text, for the pool and sponsor labels. */
|
|
1042
1147
|
export function textToBytes32(text: string): Hex {
|
|
1043
1148
|
const b = new TextEncoder().encode(text);
|
|
@@ -1060,73 +1165,64 @@ export function sortFPoolLegs<T>(bases: Address[], ...companions: T[][]): { base
|
|
|
1060
1165
|
}
|
|
1061
1166
|
|
|
1062
1167
|
/**
|
|
1063
|
-
* The tuple an F pool's id hashes — `src/types/
|
|
1064
|
-
*
|
|
1065
|
-
*
|
|
1066
|
-
* cap: those belong to a generation's `deployLiquidity` (decision 075), and the mint fee is part of identity (078).
|
|
1168
|
+
* The tuple an F pool's id hashes — `src/types/PoolKeyF.sol`, field order load-bearing (it is the ABI encoding order).
|
|
1169
|
+
* Stored by the manager at `initialize` and never in calldata again. No creator, no mint fee, no weights and no cap
|
|
1170
|
+
* (policy.md §5): both fees follow from `swapFeeIdx`, the book belongs to a generation's `deployLiquidity`.
|
|
1067
1171
|
*/
|
|
1068
1172
|
export interface FPoolKey {
|
|
1069
1173
|
quote: Address;
|
|
1070
|
-
/** Sorted ascending, unique; fixed for the pool's life. */
|
|
1174
|
+
/** Sorted ascending, unique, 1..8; fixed for the pool's life. */
|
|
1071
1175
|
bases: Address[];
|
|
1072
|
-
|
|
1073
|
-
|
|
1176
|
+
/** Into {@link F_FEE_LIST}; the mint fee is the next entry ({@link fMintFeeIdxOf}). */
|
|
1177
|
+
swapFeeIdx: number;
|
|
1178
|
+
/** The pool's policy for life. */
|
|
1074
1179
|
policy: Address;
|
|
1075
|
-
|
|
1180
|
+
/** Zero under an open policy. */
|
|
1076
1181
|
salt: Hex;
|
|
1077
|
-
/** The creator-selected mint fee, WAD, fixed for life: `2 * swapFee <= mintFee <= MINT_FEE_MAX`. */
|
|
1078
|
-
mintFee: bigint;
|
|
1079
1182
|
}
|
|
1080
1183
|
|
|
1081
|
-
|
|
1184
|
+
/** The key's ABI as `abi.encode(key)` lays it out: what {@link fPoolIdOfKey} hashes. */
|
|
1185
|
+
export const F_POOL_KEY_ABI = [
|
|
1082
1186
|
{
|
|
1083
1187
|
type: "tuple",
|
|
1084
1188
|
components: [
|
|
1085
1189
|
{ name: "quote", type: "address" },
|
|
1086
1190
|
{ name: "bases", type: "address[]" },
|
|
1087
|
-
{ name: "
|
|
1191
|
+
{ name: "swapFeeIdx", type: "uint8" },
|
|
1088
1192
|
{ name: "policy", type: "address" },
|
|
1089
|
-
{ name: "creator", type: "address" },
|
|
1090
1193
|
{ name: "salt", type: "bytes32" },
|
|
1091
|
-
{ name: "mintFee", type: "uint256" },
|
|
1092
1194
|
],
|
|
1093
1195
|
},
|
|
1094
1196
|
] as const;
|
|
1095
1197
|
|
|
1096
1198
|
/**
|
|
1097
1199
|
* An F pool's id: `keccak256(abi.encode(key))`, offline — what `initialize` computes inline. The
|
|
1098
|
-
* manager's `idOf
|
|
1099
|
-
*
|
|
1100
|
-
* one the pool was initialized with: bases sorted ({@link fPoolKeyOf} sorts them), the birth policy.
|
|
1200
|
+
* manager's `idOf` getter was cut in F version 21; this is the same hash (checked against Foundry's encoder in the
|
|
1201
|
+
* tests). The key must be the one the pool was initialized with: bases sorted ({@link fPoolKeyOf} sorts them).
|
|
1101
1202
|
*/
|
|
1102
1203
|
export function fPoolIdOfKey(key: FPoolKey): Hex {
|
|
1103
1204
|
return keccak256(encodeAbiParameters(F_POOL_KEY_ABI, [key]));
|
|
1104
1205
|
}
|
|
1105
1206
|
|
|
1106
|
-
/** The key as the manager hashes it: bases sorted, the
|
|
1207
|
+
/** 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). */
|
|
1107
1208
|
export function fPoolKeyOf(c: LogswapClient, a: Omit<FPoolCreateArgs, "account">): FPoolKey {
|
|
1108
1209
|
const { bases } = sortFPoolLegs(a.bases);
|
|
1109
|
-
return {
|
|
1110
|
-
quote: a.quote,
|
|
1111
|
-
bases,
|
|
1112
|
-
swapFee: a.swapFee,
|
|
1113
|
-
policy: a.policy ?? fPoolPolicyFor(c, a.kind),
|
|
1114
|
-
creator: a.creator,
|
|
1115
|
-
salt: a.salt ?? ZERO_SALT,
|
|
1116
|
-
mintFee: a.mintFee ?? presetMintFee(a.swapFee),
|
|
1117
|
-
};
|
|
1210
|
+
return { quote: a.quote, bases, swapFeeIdx: fPoolSwapFeeIdxOf(a), policy: a.policy ?? fPoolPolicyFor(c, a.kind), salt: a.salt ?? ZERO_SALT };
|
|
1118
1211
|
}
|
|
1119
1212
|
|
|
1120
|
-
/**
|
|
1213
|
+
/**
|
|
1214
|
+
* List the pool — `initialize(key)` (policy.md §9): no funds move; the pool is inactive until its operator funds it
|
|
1215
|
+
* ({@link fPoolDeploy}). Anyone under an open policy (salt zero), the policy's authority alone under a closed one
|
|
1216
|
+
* (`Refused`); refused past the policy's sunset (`PolicyNotApproved`), off the policy's fee mask (`FeeNotListed`), quote or
|
|
1217
|
+
* base list (`QuoteNotListed`, `BaseNotListed`), or with more legs than it allows (`TooManyLegs`). Returns the tx hash;
|
|
1218
|
+
* read the id with {@link fPoolIdOf}.
|
|
1219
|
+
*/
|
|
1121
1220
|
export async function fPoolInitialize(c: LogswapClient, a: FPoolCreateArgs) {
|
|
1122
1221
|
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
|
-
}
|
|
1126
1222
|
const wallet = requireWallet(c);
|
|
1127
1223
|
const { request } = await c.public.simulateContract({
|
|
1128
|
-
address: c.addresses.
|
|
1129
|
-
abi:
|
|
1224
|
+
address: c.addresses.managerF,
|
|
1225
|
+
abi: managerFAbi,
|
|
1130
1226
|
functionName: "initialize",
|
|
1131
1227
|
args: [key],
|
|
1132
1228
|
account: wallet.account,
|
|
@@ -1144,39 +1240,19 @@ export async function fPoolIdOf(c: LogswapClient, a: Omit<FPoolCreateArgs, "acco
|
|
|
1144
1240
|
}
|
|
1145
1241
|
|
|
1146
1242
|
/**
|
|
1147
|
-
* Rebuild a live pool's KEY from its id: the `PoolCreated` log carries every field
|
|
1148
|
-
*
|
|
1149
|
-
* without naming one; a pad's carries its split, so it is rebuilt from the policy's record with nonce 0 — pass `opts.salt` for another nonce). The result is checked against the id, so a wrong salt throws rather than
|
|
1150
|
-
* returning a key that names another pool. What {@link fPoolMigrate} needs when handed an id.
|
|
1243
|
+
* Rebuild a live pool's KEY from its id: the `PoolCreated` log carries every field, the salt included (F 41). The result
|
|
1244
|
+
* is checked against the id.
|
|
1151
1245
|
*/
|
|
1152
|
-
export async function fPoolKeyOfPool(c: LogswapClient, poolId: Hex, opts: {
|
|
1153
|
-
type Ev = Extract<(typeof
|
|
1154
|
-
const ev =
|
|
1155
|
-
const { logs } = await getEventLogs(c, { indexer: opts.indexer, address: c.addresses.
|
|
1246
|
+
export async function fPoolKeyOfPool(c: LogswapClient, poolId: Hex, opts: { fromBlock?: bigint; /** The rindexer GraphQL endpoint: `PoolCreated` from there, the node otherwise. */ indexer?: string } = {}): Promise<FPoolKey> {
|
|
1247
|
+
type Ev = Extract<(typeof managerFAbi)[number], { type: "event"; name: "PoolCreated" }>;
|
|
1248
|
+
const ev = managerFAbi.find((x): x is Ev => x.type === "event" && x.name === "PoolCreated")!;
|
|
1249
|
+
const { logs } = await getEventLogs(c, { indexer: opts.indexer, address: c.addresses.managerF, event: ev as never, args: { poolId }, fromBlock: opts.fromBlock });
|
|
1156
1250
|
const l = logs[0];
|
|
1157
1251
|
if (!l) throw new Error(`logswap: no PoolCreated for F pool ${poolId}`);
|
|
1158
|
-
const a = l.args as unknown as { quote: Address;
|
|
1159
|
-
const key: FPoolKey = {
|
|
1160
|
-
quote: a.quote,
|
|
1161
|
-
bases: [...a.bases],
|
|
1162
|
-
swapFee: a.swapFee,
|
|
1163
|
-
policy: a.policy,
|
|
1164
|
-
creator: a.creator,
|
|
1165
|
-
salt: opts.salt ?? ZERO_SALT,
|
|
1166
|
-
mintFee: a.mintFee,
|
|
1167
|
-
};
|
|
1168
|
-
if (fPoolIdOfKey(key).toLowerCase() !== poolId.toLowerCase() && opts.salt === undefined) {
|
|
1169
|
-
// a pad's salt carries its split (decisions 056): rebuild it from the policy's record with the default nonce
|
|
1170
|
-
try {
|
|
1171
|
-
const creatorShare = BigInt((await c.public.readContract({ address: a.policy, abi: padPolicyAbi, functionName: "creatorShareOf", args: [poolId] } as never)) as bigint | number);
|
|
1172
|
-
const padKey = { ...key, salt: padSalt({ creatorShare }) };
|
|
1173
|
-
if (fPoolIdOfKey(padKey).toLowerCase() === poolId.toLowerCase()) return padKey;
|
|
1174
|
-
} catch {
|
|
1175
|
-
/* not a pad: fall through to the error */
|
|
1176
|
-
}
|
|
1177
|
-
}
|
|
1252
|
+
const a = l.args as unknown as { quote: Address; policy: Address; bases: readonly Address[]; swapFeeIdx: number | bigint; salt: Hex };
|
|
1253
|
+
const key: FPoolKey = { quote: a.quote, bases: [...a.bases], swapFeeIdx: Number(a.swapFeeIdx), policy: a.policy, salt: a.salt };
|
|
1178
1254
|
if (fPoolIdOfKey(key).toLowerCase() !== poolId.toLowerCase()) {
|
|
1179
|
-
throw new Error(`logswap: F pool ${poolId}
|
|
1255
|
+
throw new Error(`logswap: the PoolCreated log of F pool ${poolId} does not hash to it — a wrong manager, or a log from before F 41`);
|
|
1180
1256
|
}
|
|
1181
1257
|
return key;
|
|
1182
1258
|
}
|
|
@@ -1346,86 +1422,75 @@ export function fPoolBookL(baseAssets: readonly BaseAsset[], lnCapOverSeed: numb
|
|
|
1346
1422
|
* carried holder, every other holder is frozen into the closing generation's bundle ({@link fPoolRedeem}), and the
|
|
1347
1423
|
* carried book becomes the one named, at the supplied prices. A pad is forward-only ({@link fPoolRegenerate}).
|
|
1348
1424
|
*/
|
|
1425
|
+
/**
|
|
1426
|
+
* Fund the pool — `deployLiquidity(poolId, baseAssets, quoteAmount, lnCapOverSeed)` (policy.md §9): the book of this generation,
|
|
1427
|
+
* on an INACTIVE pool — listed and never funded, or closed (`PoolActive` otherwise). The operator's alone (`NotOperator`): it pays
|
|
1428
|
+
* every leg's amount and `quoteAmount` by plain allowance to the manager ({@link approveTokenForFPoolManager}) and holds the shares —
|
|
1429
|
+
* all but `MIN_SHARES`, which go to 0xdead; every share does on a pad. Refused past the policy's sunset (`PolicyNotApproved`),
|
|
1430
|
+
* under its buffer (`QuoteTooThin`), with a cap under its `lnCapMin` (`CapTooClose`). An amount of 0 leaves a leg dormant. Pass the
|
|
1431
|
+
* book raw (`baseAssets` + `lnCapOverSeed`) or as a {@link FPoolBookSpec}.
|
|
1432
|
+
*/
|
|
1349
1433
|
export async function fPoolDeploy(
|
|
1350
1434
|
c: LogswapClient,
|
|
1351
|
-
a: { poolId: Hex; quoteAmount: bigint;
|
|
1352
|
-
| { baseAssets: BaseAsset[]; lnCapOverSeed: number }
|
|
1353
|
-
| FPoolBookSpec
|
|
1354
|
-
),
|
|
1435
|
+
a: { poolId: Hex; quoteAmount: bigint; account: Address } & ({ baseAssets: BaseAsset[]; lnCapOverSeed: number } | FPoolBookSpec),
|
|
1355
1436
|
) {
|
|
1356
1437
|
const { baseAssets, lnCapOverSeed } = "baseAssets" in a ? a : fPoolBook(a);
|
|
1357
|
-
return writeFPool(c, a.poolId, "deployLiquidity", [baseAssets, a.quoteAmount, lnCapOverSeed
|
|
1438
|
+
return writeFPool(c, a.poolId, "deployLiquidity", [baseAssets, a.quoteAmount, lnCapOverSeed], a.account);
|
|
1358
1439
|
}
|
|
1359
1440
|
|
|
1360
1441
|
/**
|
|
1361
|
-
* Close the pool
|
|
1362
|
-
*
|
|
1363
|
-
*
|
|
1364
|
-
*
|
|
1365
|
-
* `
|
|
1442
|
+
* Close the pool (policy.md §9) — at any bid. The manager harvests the income first (a dividend to every share, the operator's
|
|
1443
|
+
* paid to `to`), freezes every reserve and the bid into generation `gen`'s bundle — every share of it redeems pro rata
|
|
1444
|
+
* ({@link fPoolRedeem}), forever — and moves the counter to `gen + 1`, the generation the next {@link fPoolDeploy} opens under
|
|
1445
|
+
* the same id, policy, roles and gates. The operator's alone. Throws before sending on a pad: a pad never closes
|
|
1446
|
+
* (`PadNeverCloses`). Pass `flags` when in hand to save the read.
|
|
1366
1447
|
*/
|
|
1367
|
-
export async function
|
|
1448
|
+
export async function fPoolClose(c: LogswapClient, a: { poolId: Hex; to?: Address; account: Address; flags?: number }) {
|
|
1449
|
+
const flags = a.flags ?? (await getFPool(c, a.poolId)).flags;
|
|
1450
|
+
if ((flags & SEED_TO_DEAD) !== 0) throw new Error("logswap: a pad never closes (PadNeverCloses) — a fresh start is a new pad");
|
|
1368
1451
|
return writeFPool(c, a.poolId, "close", [a.to ?? a.account], a.account);
|
|
1369
1452
|
}
|
|
1370
1453
|
|
|
1371
1454
|
/**
|
|
1372
|
-
*
|
|
1373
|
-
* (
|
|
1374
|
-
*
|
|
1375
|
-
* should call. Throws before sending on a pad: a pad never closes.
|
|
1455
|
+
* The relaunch's calls — what `regenerate` was (policy.md §9): `close(poolId, to)`, `redeem(poolId, gen, operator, shares)` for the
|
|
1456
|
+
* operator's own shares of the generation closed (left out at 0), then `deployLiquidity` with the next book. Pure, so a form can show
|
|
1457
|
+
* what it is about to send; {@link fPoolRelaunch} sends them as one `multicall`.
|
|
1376
1458
|
*/
|
|
1377
|
-
export
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
}
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
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.
|
|
1392
|
-
*/
|
|
1393
|
-
export async function fPoolEmptyingHarvests(c: LogswapClient, poolId: Hex): Promise<bigint[]> {
|
|
1394
|
-
const s = await getFPool(c, poolId);
|
|
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");
|
|
1397
|
-
if (s.Q === 0n) return [];
|
|
1398
|
-
const { maxHarvest } = await getFPoolRoles(c, poolId, s);
|
|
1399
|
-
if (maxHarvest < s.Q) throw new Error("logswap: the pool's policy keeps a floor on the bid — it cannot be harvested empty");
|
|
1400
|
-
return [s.Q];
|
|
1459
|
+
export function fPoolRelaunchCalls(
|
|
1460
|
+
a: { poolId: Hex; gen: number | bigint; shares: bigint; quoteAmount: bigint; to?: Address; account: Address } & (
|
|
1461
|
+
| { baseAssets: BaseAsset[]; lnCapOverSeed: number }
|
|
1462
|
+
| FPoolBookSpec
|
|
1463
|
+
),
|
|
1464
|
+
): Hex[] {
|
|
1465
|
+
const { baseAssets, lnCapOverSeed } = "baseAssets" in a ? a : fPoolBook(a);
|
|
1466
|
+
const enc = (functionName: string, args: unknown[]) => encodeFunctionData({ abi: managerFAbi, functionName, args } as never) as Hex;
|
|
1467
|
+
const calls = [enc("close", [a.poolId, a.to ?? a.account])];
|
|
1468
|
+
if (a.shares > 0n) calls.push(enc("redeem", [a.poolId, BigInt(a.gen), a.account, a.shares]));
|
|
1469
|
+
calls.push(enc("deployLiquidity", [a.poolId, baseAssets, a.quoteAmount, lnCapOverSeed]));
|
|
1470
|
+
return calls;
|
|
1401
1471
|
}
|
|
1402
1472
|
|
|
1403
1473
|
/**
|
|
1404
|
-
*
|
|
1405
|
-
*
|
|
1406
|
-
*
|
|
1407
|
-
*
|
|
1408
|
-
*
|
|
1409
|
-
* - the carried holder's and the dead shares' `g` shares are re-minted 1:1 as `g + 1`: they go on
|
|
1410
|
-
* as the pool;
|
|
1411
|
-
* - every OTHER holder of `g` is frozen out pro rata into generation `g`'s bundle (`GenerationRetired`)
|
|
1412
|
-
* and redeems it with {@link fPoolRedeem} / rolls it with {@link fPoolRollIn} (`gen: g`); their
|
|
1413
|
-
* dividends on `g` stay claimable ({@link fPoolClaim} with `gen: g`). {@link fPoolClaimsOf}
|
|
1414
|
-
* lists them;
|
|
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.
|
|
1417
|
-
*
|
|
1418
|
-
* A pad's gate is `threshold(poolId, gen)`, in its quote (`PadPolicy.NotGraduated` below it); POL and private carry the
|
|
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}.
|
|
1474
|
+
* Relaunch the pool as ONE transaction: close generation `gen`, redeem the operator's own shares of it (its funds come back),
|
|
1475
|
+
* fund `gen + 1` with the book given — the manager's `multicall`, the operator as sender. Every other holder is frozen into the
|
|
1476
|
+
* bundle and redeems it ({@link fPoolRedeem}); the new book may re-weight any of the key's bases and pick its own cap. The
|
|
1477
|
+
* deploy pulls its amounts and `quoteAmount` from the operator in the same transaction the redeem pays it, so the allowances
|
|
1478
|
+
* must cover the pull. Not on a pad (a pad never closes); not on an inactive pool (fund it with {@link fPoolDeploy}).
|
|
1421
1479
|
*/
|
|
1422
|
-
export async function
|
|
1423
|
-
|
|
1480
|
+
export async function fPoolRelaunch(
|
|
1481
|
+
c: LogswapClient,
|
|
1482
|
+
a: { poolId: Hex; quoteAmount: bigint; to?: Address; account: Address } & ({ baseAssets: BaseAsset[]; lnCapOverSeed: number } | FPoolBookSpec),
|
|
1483
|
+
) {
|
|
1484
|
+
const s = await getFPool(c, a.poolId);
|
|
1485
|
+
if ((s.flags & SEED_TO_DEAD) !== 0) throw new Error("logswap: a pad never closes (PadNeverCloses) — a fresh start is a new pad");
|
|
1486
|
+
if (!s.seeded) throw new Error("logswap: the pool is inactive — nothing to close; fund it with fPoolDeploy");
|
|
1487
|
+
const shares = await fPoolShareBalance(c, a.poolId, a.account, s.gen);
|
|
1488
|
+
return writeFPool0(c, "multicall", [fPoolRelaunchCalls({ ...a, gen: s.gen, shares })], a.account);
|
|
1424
1489
|
}
|
|
1425
1490
|
|
|
1426
|
-
/** Where a pad's seed lives: `
|
|
1491
|
+
/** Where a pad's seed lives: `deployLiquidity` mints every share of a pad here itself. */
|
|
1427
1492
|
export const DEAD_ADDRESS: Address = "0x000000000000000000000000000000000000dEaD";
|
|
1428
|
-
/** The manager's `MIN_SHARES`: the
|
|
1493
|
+
/** 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. */
|
|
1429
1494
|
export const F_MIN_SHARES = 1000n;
|
|
1430
1495
|
|
|
1431
1496
|
/**
|
|
@@ -1481,7 +1546,7 @@ export interface FPoolLaunchArgs extends Omit<FPoolCreateArgs, "account"> {
|
|
|
1481
1546
|
* `followup`: always left to it. Ignored when no row names a recipient.
|
|
1482
1547
|
*/
|
|
1483
1548
|
deliver?: "auto" | "followup";
|
|
1484
|
-
/** The pool's label (≤ 31 bytes of UTF-8) — the policy's
|
|
1549
|
+
/** The pool's label (≤ 31 bytes of UTF-8) — a `NameSet` event on the policy, the operator's (049), written right after the batch by {@link fPoolLaunch}; not in the batch. */
|
|
1485
1550
|
name?: string;
|
|
1486
1551
|
/**
|
|
1487
1552
|
* The pool already exists (a previous launch got as far as `initialize` and no further — a seed
|
|
@@ -1489,7 +1554,7 @@ export interface FPoolLaunchArgs extends Omit<FPoolCreateArgs, "account"> {
|
|
|
1489
1554
|
* out: the key is a pure function of the arguments and a second `initialize` can only revert.
|
|
1490
1555
|
*/
|
|
1491
1556
|
initialized?: boolean;
|
|
1492
|
-
/** Anything else, pre-encoded against {@link
|
|
1557
|
+
/** Anything else, pre-encoded against {@link managerFAbi}, appended after the above. */
|
|
1493
1558
|
extra?: Hex[];
|
|
1494
1559
|
account: Address;
|
|
1495
1560
|
}
|
|
@@ -1507,30 +1572,21 @@ export function fPoolLaunchCalls(
|
|
|
1507
1572
|
if (!a.policy) throw new Error("logswap: fPoolLaunchCalls needs the key's policy — fPoolLaunch fills it from the deployment");
|
|
1508
1573
|
const { baseAssets, lnCapOverSeed } = fPoolBook(a);
|
|
1509
1574
|
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
|
-
};
|
|
1575
|
+
const key: FPoolKey = { quote: a.quote, bases, swapFeeIdx: fPoolSwapFeeIdxOf(a), policy: a.policy, salt: a.salt ?? ZERO_SALT };
|
|
1519
1576
|
const enc = (functionName: string, args: unknown[]) =>
|
|
1520
|
-
encodeFunctionData({ abi:
|
|
1577
|
+
encodeFunctionData({ abi: managerFAbi, functionName, args } as never) as Hex;
|
|
1521
1578
|
const calls: Hex[] = [];
|
|
1522
1579
|
if (!a.initialized) calls.push(enc("initialize", [key]));
|
|
1523
|
-
calls.push(enc("deployLiquidity", [poolId, baseAssets, a.quoteAmount, lnCapOverSeed
|
|
1524
|
-
// gen 0 by construction: a launch is the pool's FIRST deployment — a later one is `fPoolDeploy` on the
|
|
1580
|
+
calls.push(enc("deployLiquidity", [poolId, baseAssets, a.quoteAmount, lnCapOverSeed]));
|
|
1581
|
+
// gen 0 by construction: a launch is the pool's FIRST deployment — a later one is `fPoolDeploy` on the closed pool.
|
|
1525
1582
|
// No transfer to 0xdead: on a pad `deployLiquidity` mints every share there itself.
|
|
1526
1583
|
for (const row of fPoolGenesisRows(a)) {
|
|
1527
1584
|
const j = bases.indexOf(a.bases[row.j]!);
|
|
1528
1585
|
if (j < 0) throw new Error(`logswap: genesis row j = ${row.j} is not a leg`);
|
|
1529
1586
|
calls.push(enc(row.side === "buy" ? "swapQuoteIn" : "swapBaseIn", [poolId, BigInt(j), row.amountIn, row.minOut ?? 0n, a.account]));
|
|
1530
1587
|
}
|
|
1531
|
-
// the name
|
|
1532
|
-
//
|
|
1533
|
-
// right after, as the same creator
|
|
1588
|
+
// the name and the gate modes are the POLICY's, not the manager's: they cannot ride in this batch — `fPoolLaunch`
|
|
1589
|
+
// sends the name right after, as the same operator; the modes are `fPoolSetSwapMode` / `fPoolSetMintMode`
|
|
1534
1590
|
calls.push(...(a.extra ?? []));
|
|
1535
1591
|
return calls;
|
|
1536
1592
|
}
|
|
@@ -1555,8 +1611,8 @@ export async function fPoolGenesisOutputs(
|
|
|
1555
1611
|
if (rows.length === 0) return [];
|
|
1556
1612
|
const calls = fPoolLaunchCalls(poolId, a);
|
|
1557
1613
|
const { result } = await c.public.simulateContract({
|
|
1558
|
-
address: c.addresses.
|
|
1559
|
-
abi:
|
|
1614
|
+
address: c.addresses.managerF,
|
|
1615
|
+
abi: managerFAbi,
|
|
1560
1616
|
functionName: "multicall",
|
|
1561
1617
|
args: [calls],
|
|
1562
1618
|
account: signerFor(c, a.account),
|
|
@@ -1617,34 +1673,21 @@ export async function fPoolWalletBatchesAtomically(c: LogswapClient, account: Ad
|
|
|
1617
1673
|
}
|
|
1618
1674
|
|
|
1619
1675
|
/**
|
|
1620
|
-
*
|
|
1621
|
-
*
|
|
1622
|
-
*
|
|
1623
|
-
|
|
1624
|
-
|
|
1625
|
-
const policy = a.policy ?? fPoolPolicyFor(c, "private");
|
|
1626
|
-
return [
|
|
1627
|
-
await fPoolSetMintGate(c, { poolId: a.poolId, gated: true, account: a.account, policy }),
|
|
1628
|
-
await fPoolSetMinters(c, { poolId: a.poolId, who: [a.account], allowed: true, account: a.account, policy }),
|
|
1629
|
-
];
|
|
1630
|
-
}
|
|
1631
|
-
|
|
1632
|
-
/**
|
|
1633
|
-
* Create a pool as ONE transaction: `initialize`, `seed`, the seed lock, the opening buy, the
|
|
1634
|
-
* name, the private-pool gates — the manager's `multicall`, the creator as sender throughout.
|
|
1635
|
-
* Either every call lands or none does; there is no half-built pool to resume.
|
|
1676
|
+
* Create a pool as ONE transaction: `initialize`, `deployLiquidity`, the opening buys — the manager's `multicall`, one sender
|
|
1677
|
+
* throughout. Either every call lands or none does; there is no half-built pool to resume. The sender must be the policy's
|
|
1678
|
+
* AUTHORITY: it is the pool's operator at birth, and `deployLiquidity` is the operator's (`NotOperator`). Under an open
|
|
1679
|
+
* policy anyone may list a pool ({@link fPoolInitialize}) but only the LOG — its authority — funds it, so a launch under the
|
|
1680
|
+
* public policy is the LOG's; a sponsor launches under its own policy.
|
|
1636
1681
|
*
|
|
1637
|
-
* Why the manager and not the router: every one of these entries authenticates by `msg.sender
|
|
1638
|
-
*
|
|
1639
|
-
* — the authority, the holder of the seed shares — and the handover back is two-step, so it
|
|
1640
|
-
* could not even close in the same transaction. `multicall` is delegatecall-to-self, so the
|
|
1641
|
-
* sender survives, which is what the manager's own doc says a router cannot do.
|
|
1682
|
+
* Why the manager and not the router: every one of these entries authenticates by `msg.sender`. Routed, the router would be
|
|
1683
|
+
* the sender — the operator, the holder of the seed shares. `multicall` is delegatecall-to-self, so the sender survives.
|
|
1642
1684
|
*
|
|
1643
|
-
* What the batch PULLS, by plain allowance to the manager (never Permit2): `r0[j]` of each base,
|
|
1644
|
-
*
|
|
1645
|
-
*
|
|
1685
|
+
* What the batch PULLS, by plain allowance to the manager (never Permit2): `r0[j]` of each base, `quoteAmount` of quote, plus
|
|
1686
|
+
* each opening buy's `amountIn` of quote. Grant those first — one `approve` per token, once ever
|
|
1687
|
+
* ({@link approveTokenForFPoolManager}, {@link fPoolManagerAllowanceOk}).
|
|
1646
1688
|
*
|
|
1647
|
-
* Returns the hash and the pool's id (the key's hash, {@link fPoolIdOf}).
|
|
1689
|
+
* Returns the hash and the pool's id (the key's hash, {@link fPoolIdOf}). The name, when given, is a second transaction on
|
|
1690
|
+
* the policy ({@link fPoolSetName}); the gate modes are {@link fPoolSetSwapMode} / {@link fPoolSetMintMode} after it.
|
|
1648
1691
|
*/
|
|
1649
1692
|
export async function fPoolLaunch(
|
|
1650
1693
|
c: LogswapClient,
|
|
@@ -1671,7 +1714,7 @@ export async function fPoolLaunch(
|
|
|
1671
1714
|
account: signerFor(c, a.account),
|
|
1672
1715
|
forceAtomic: true,
|
|
1673
1716
|
calls: [
|
|
1674
|
-
{ to: c.addresses.
|
|
1717
|
+
{ to: c.addresses.managerF, data: encodeFunctionData({ abi: managerFAbi, functionName: "multicall", args: [calls] } as never) },
|
|
1675
1718
|
...transfers.map((t) => ({ to: t.token, data: encodeFunctionData({ abi: erc20Abi, functionName: "transfer", args: [t.to, t.amount] }) })),
|
|
1676
1719
|
],
|
|
1677
1720
|
} as never);
|
|
@@ -1689,104 +1732,80 @@ export async function fPoolLaunch(
|
|
|
1689
1732
|
|
|
1690
1733
|
// ─── the roles, on the policy ─────────────────────────────────────────────
|
|
1691
1734
|
//
|
|
1692
|
-
// Every write here goes to the pool's POLICY, not the manager: the manager holds no role. `policy`
|
|
1693
|
-
//
|
|
1735
|
+
// Every write here goes to the pool's POLICY, not the manager: the manager holds no role. `policy` may be passed when in
|
|
1736
|
+
// hand (`FPoolState.policy`, `FPoolRoles.policy`); otherwise it is read once. The policy syncs the manager itself
|
|
1737
|
+
// (`setGates`), which stamps the block: no swap lands in the block of a change (047). Every mode and list write reverts
|
|
1738
|
+
// `GatesUnavailable` on an open policy: a public pool can never be gated.
|
|
1694
1739
|
|
|
1695
|
-
/** A write
|
|
1696
|
-
async function writePolicy(c: LogswapClient,
|
|
1740
|
+
/** A write on a policy. */
|
|
1741
|
+
async function writePolicy(c: LogswapClient, policy: Address, functionName: string, args: unknown[], account: Address) {
|
|
1697
1742
|
const wallet = requireWallet(c);
|
|
1698
|
-
const
|
|
1699
|
-
const { request } = await c.public.simulateContract({
|
|
1700
|
-
address: policy,
|
|
1701
|
-
abi,
|
|
1702
|
-
functionName,
|
|
1703
|
-
args: [a.poolId, ...args],
|
|
1704
|
-
account: signerFor(c, a.account),
|
|
1705
|
-
} as never);
|
|
1743
|
+
const { request } = await c.public.simulateContract({ address: policy, abi: policyFAbi, functionName, args, account: signerFor(c, account) } as never);
|
|
1706
1744
|
return wallet.writeContract(request as never);
|
|
1707
1745
|
}
|
|
1708
1746
|
|
|
1709
|
-
/**
|
|
1710
|
-
|
|
1711
|
-
|
|
1712
|
-
|
|
1713
|
-
*/
|
|
1714
|
-
export async function fPoolProposeAuthority(c: LogswapClient, a: { poolId: Hex; next: Address; account: Address; policy?: Address }) {
|
|
1715
|
-
return writePolicy(c, fPolicyBaseAbi, a, "proposeAuthority", [a.next]);
|
|
1747
|
+
/** A write keyed by poolId, on the pool's policy. */
|
|
1748
|
+
async function writePoolPolicy(c: LogswapClient, a: { poolId: Hex; policy?: Address; account: Address }, functionName: string, args: unknown[]) {
|
|
1749
|
+
const policy = a.policy ?? (await fPoolPolicyOf(c, a.poolId));
|
|
1750
|
+
return writePolicy(c, policy, functionName, [a.poolId, ...args], a.account);
|
|
1716
1751
|
}
|
|
1717
1752
|
|
|
1718
1753
|
/**
|
|
1719
|
-
*
|
|
1720
|
-
*
|
|
1721
|
-
*
|
|
1754
|
+
* Appoint the pool's operator (the AUTHORITY's; zero resets it to the authority): the account that funds, harvests, closes and sets the
|
|
1755
|
+
* 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
|
|
1756
|
+
* a contract (an executor). `InactivePool` on a pool the policy never held.
|
|
1722
1757
|
*/
|
|
1723
|
-
export async function
|
|
1724
|
-
return
|
|
1758
|
+
export async function fPoolAppointOperator(c: LogswapClient, a: { poolId: Hex; operator: Address; account: Address; policy?: Address }) {
|
|
1759
|
+
return writePoolPolicy(c, a, "appointOperator", [a.operator]);
|
|
1725
1760
|
}
|
|
1726
1761
|
|
|
1727
|
-
// ─── the desk's controls (PrivatePolicy) ───────────────────────────────
|
|
1728
|
-
|
|
1729
1762
|
/**
|
|
1730
|
-
* Set the
|
|
1731
|
-
*
|
|
1732
|
-
* and must be omitted otherwise. Preserves mint admission. `burn` is never gated.
|
|
1763
|
+
* Set the pool's swap gate (the OPERATOR's): `open`, `listed` (the policy's swap list, {@link fPolicySetRights}; the operator always
|
|
1764
|
+
* passes) or `operator`. The mint mode must stay at least as restrictive (`ModeOrder`). `burn`, `redeem` and `claim` are never gated.
|
|
1733
1765
|
*/
|
|
1734
|
-
export async function fPoolSetSwapMode(
|
|
1735
|
-
c
|
|
1736
|
-
a: { poolId: Hex; mode: FPoolSwapMode; executor?: Address; account: Address; policy?: Address },
|
|
1737
|
-
) {
|
|
1738
|
-
return writePolicy(c, privatePolicyAbi, a, "setSwapMode", [SWAP_MODES.indexOf(a.mode), a.executor ?? ZERO_ADDRESS]);
|
|
1766
|
+
export async function fPoolSetSwapMode(c: LogswapClient, a: { poolId: Hex; mode: FPoolMode; account: Address; policy?: Address }) {
|
|
1767
|
+
return writePoolPolicy(c, a, "setSwapMode", [MODES.indexOf(a.mode)]);
|
|
1739
1768
|
}
|
|
1740
1769
|
|
|
1741
|
-
/**
|
|
1742
|
-
export async function
|
|
1743
|
-
return
|
|
1770
|
+
/** 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. */
|
|
1771
|
+
export async function fPoolSetMintMode(c: LogswapClient, a: { poolId: Hex; mode: FPoolMode; account: Address; policy?: Address }) {
|
|
1772
|
+
return writePoolPolicy(c, a, "setMintMode", [MODES.indexOf(a.mode)]);
|
|
1744
1773
|
}
|
|
1745
1774
|
|
|
1746
|
-
/**
|
|
1747
|
-
|
|
1748
|
-
|
|
1749
|
-
|
|
1750
|
-
|
|
1751
|
-
*/
|
|
1752
|
-
export async function fPoolSetMinters(
|
|
1753
|
-
c: LogswapClient,
|
|
1754
|
-
a: { poolId: Hex; who: readonly Address[]; allowed: boolean; account: Address; policy?: Address },
|
|
1755
|
-
) {
|
|
1756
|
-
return writePolicy(c, privatePolicyAbi, a, "setMinters", [a.who, a.allowed]);
|
|
1757
|
-
}
|
|
1775
|
+
/** The bits of `PolicyF.rights`: listed for swaps; listed for mints, which implies swaps. */
|
|
1776
|
+
export const RIGHT_SWAP = 1;
|
|
1777
|
+
export const RIGHT_MINT = 2;
|
|
1778
|
+
/** What a policy lists an address for: nothing, swaps, or mints (and so swaps). */
|
|
1779
|
+
export type FPolicyRight = "none" | "swap" | "mint";
|
|
1758
1780
|
|
|
1759
|
-
/**
|
|
1760
|
-
export
|
|
1761
|
-
|
|
1762
|
-
a: { poolId: Hex; who: readonly Address[]; allowed: boolean; account: Address; policy?: Address },
|
|
1763
|
-
) {
|
|
1764
|
-
return writePolicy(c, privatePolicyAbi, a, "setTakers", [a.who, a.allowed]);
|
|
1781
|
+
/** The on-chain bits of a right (`MINT` is written as `MINT | SWAP`, as the policy does). */
|
|
1782
|
+
export function fPolicyRightBits(right: FPolicyRight): number {
|
|
1783
|
+
return right === "none" ? 0 : right === "swap" ? RIGHT_SWAP : RIGHT_SWAP | RIGHT_MINT;
|
|
1765
1784
|
}
|
|
1766
1785
|
|
|
1767
|
-
|
|
1768
|
-
|
|
1769
|
-
|
|
1786
|
+
/** The right the bits spell. */
|
|
1787
|
+
export function fPolicyRightOf(bits: number | bigint): FPolicyRight {
|
|
1788
|
+
const b = Number(bits);
|
|
1789
|
+
return (b & RIGHT_MINT) !== 0 ? "mint" : (b & RIGHT_SWAP) !== 0 ? "swap" : "none";
|
|
1770
1790
|
}
|
|
1771
1791
|
|
|
1772
|
-
/**
|
|
1773
|
-
|
|
1774
|
-
|
|
1775
|
-
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
|
|
1779
|
-
return readDesk<boolean>(c, poolId, who, "isTaker", policy);
|
|
1792
|
+
/**
|
|
1793
|
+
* 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
|
|
1794
|
+
* — 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);
|
|
1795
|
+
* the modes are each pool's. Stamps nothing: an address removed in a block can still swap in that block.
|
|
1796
|
+
*/
|
|
1797
|
+
export async function fPolicySetRights(c: LogswapClient, a: { policy: Address; who: readonly Address[]; right: FPolicyRight; account: Address }) {
|
|
1798
|
+
return writePolicy(c, a.policy, "setRights", [a.who, fPolicyRightBits(a.right)], a.account);
|
|
1780
1799
|
}
|
|
1781
1800
|
|
|
1782
|
-
/**
|
|
1783
|
-
export async function
|
|
1784
|
-
return
|
|
1801
|
+
/** What `policy` lists `who` for now (`rights`). */
|
|
1802
|
+
export async function fPolicyRightsOf(c: LogswapClient, policy: Address, who: Address): Promise<FPolicyRight> {
|
|
1803
|
+
return fPolicyRightOf((await c.public.readContract({ address: policy, abi: policyFAbi, functionName: "rights", args: [who] } as never)) as number | bigint);
|
|
1785
1804
|
}
|
|
1786
1805
|
|
|
1787
|
-
/** Label the pool
|
|
1806
|
+
/** Label the pool (the OPERATOR's): a `NameSet` event on the policy, nothing stored — mutable, never identity. At most 31 bytes of UTF-8. */
|
|
1788
1807
|
export async function fPoolSetName(c: LogswapClient, a: { poolId: Hex; name: string; account: Address; policy?: Address }) {
|
|
1789
|
-
return
|
|
1808
|
+
return writePoolPolicy(c, a, "setName", [textToBytes32(a.name)]);
|
|
1790
1809
|
}
|
|
1791
1810
|
|
|
1792
1811
|
/**
|
|
@@ -1818,7 +1837,7 @@ export async function fPoolSponsorName(c: LogswapClient, who: Address): Promise<
|
|
|
1818
1837
|
/** The registry the manager asks at every birth — `addresses.policyRegistry`, else the manager's word; zero on a bare deployment. */
|
|
1819
1838
|
export async function fPoolRegistryOf(c: LogswapClient): Promise<Address> {
|
|
1820
1839
|
if (c.addresses.policyRegistry) return c.addresses.policyRegistry;
|
|
1821
|
-
return (await c.public.readContract({ address: c.addresses.
|
|
1840
|
+
return (await c.public.readContract({ address: c.addresses.managerF, abi: managerFAbi, functionName: "registry" } as never)) as Address;
|
|
1822
1841
|
}
|
|
1823
1842
|
|
|
1824
1843
|
async function registryAddress(c: LogswapClient): Promise<Address> {
|
|
@@ -1827,18 +1846,9 @@ async function registryAddress(c: LogswapClient): Promise<Address> {
|
|
|
1827
1846
|
return registry;
|
|
1828
1847
|
}
|
|
1829
1848
|
|
|
1830
|
-
/** Who
|
|
1831
|
-
export function fPoolRunners(s: Pick<FPoolRoles, "
|
|
1832
|
-
return s.operator === ZERO_ADDRESS ? [
|
|
1833
|
-
}
|
|
1834
|
-
|
|
1835
|
-
/**
|
|
1836
|
-
* Grant, replace or revoke the pool operator (the authority, on the desk's policy; decision 073): one optional delegate who may
|
|
1837
|
-
* `harvest`, `retire`, `regenerate` and `setLegs` besides the authority. Immediate, with no acceptance step, so check the
|
|
1838
|
-
* address; the zero address revokes. A handover or a policy move clears it.
|
|
1839
|
-
*/
|
|
1840
|
-
export async function fPoolSetPoolOperator(c: LogswapClient, a: { poolId: Hex; operator: Address; account: Address; policy?: Address }) {
|
|
1841
|
-
return writePolicy(c, privatePolicyAbi, a, "setPoolOperator", [a.operator]);
|
|
1849
|
+
/** 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. */
|
|
1850
|
+
export function fPoolRunners(s: Pick<FPoolRoles, "operator">): Address[] {
|
|
1851
|
+
return s.operator === ZERO_ADDRESS ? [] : [s.operator];
|
|
1842
1852
|
}
|
|
1843
1853
|
|
|
1844
1854
|
/**
|
|
@@ -1853,8 +1863,8 @@ export async function fPoolTransferShares(
|
|
|
1853
1863
|
const wallet = requireWallet(c);
|
|
1854
1864
|
const gen = a.gen ?? (await fPoolGen(c, a.poolId));
|
|
1855
1865
|
const { request } = await c.public.simulateContract({
|
|
1856
|
-
address: c.addresses.
|
|
1857
|
-
abi:
|
|
1866
|
+
address: c.addresses.managerF,
|
|
1867
|
+
abi: managerFAbi,
|
|
1858
1868
|
functionName: "transfer",
|
|
1859
1869
|
args: [a.to, fPoolShareId(a.poolId, gen), a.shares],
|
|
1860
1870
|
account: signerFor(c, a.account),
|
|
@@ -1870,16 +1880,19 @@ export interface DiscoveredFPool {
|
|
|
1870
1880
|
bases: Address[];
|
|
1871
1881
|
/** The generation-0 allocation, from the pool's first `LiquidityDeployed` ({@link fPoolBookWeights}); `[]` until it is deployed — F 38 keeps no weights in the key. */
|
|
1872
1882
|
weights: bigint[];
|
|
1883
|
+
/** The key's swap fee index (policy.md §6). */
|
|
1884
|
+
swapFeeIdx: number;
|
|
1885
|
+
/** The swap fee, WAD: `F_FEE_LIST[swapFeeIdx]`. */
|
|
1873
1886
|
swapFee: bigint;
|
|
1874
|
-
/** The
|
|
1887
|
+
/** The mint fee, WAD: the list's next entry ({@link fMintFeeOf}). */
|
|
1875
1888
|
mintFee: bigint;
|
|
1876
1889
|
/** The generation-0 cap as ln(cap price / seed price), in 1e-6 log units; 0 uncapped, cap ∞ (decisions 061); 0 until deployed. */
|
|
1877
1890
|
lnCapOverSeed: number;
|
|
1878
1891
|
kind: FPoolKind;
|
|
1879
|
-
/** The pool's policy
|
|
1892
|
+
/** The pool's policy for life — the contract the key names. */
|
|
1880
1893
|
policy: Address;
|
|
1881
|
-
/**
|
|
1882
|
-
|
|
1894
|
+
/** The key's salt: zero under an open policy. */
|
|
1895
|
+
salt: Hex;
|
|
1883
1896
|
/** The block the pool was initialized in — its age, for annualising realized income. */
|
|
1884
1897
|
block: bigint;
|
|
1885
1898
|
/** Whether `deployLiquidity` has run; an unfunded pool has no floor and no float, so nothing to show. */
|
|
@@ -1896,22 +1909,21 @@ export interface DiscoveredFPool {
|
|
|
1896
1909
|
}
|
|
1897
1910
|
|
|
1898
1911
|
/**
|
|
1899
|
-
* Every F pool ever created, from `PoolCreated` logs alone — plus
|
|
1900
|
-
*
|
|
1901
|
-
*
|
|
1902
|
-
*
|
|
1903
|
-
* a scan from block 0 per call is what made the first load wait on the node.
|
|
1912
|
+
* Every F pool ever created, from `PoolCreated` logs alone — plus the terms of each distinct policy, read once and cached.
|
|
1913
|
+
* Possible only because the event carries the full key (quote, policy, bases, swapFeeIdx, salt) — the poolId is a hash and
|
|
1914
|
+
* could never be inverted; contracts PR #17 exists for exactly this call. With `indexer`, the logs come from it (the node
|
|
1915
|
+
* when it fails): a scan from block 0 per call is what made the first load wait on the node.
|
|
1904
1916
|
*/
|
|
1905
1917
|
export async function discoverFPools(
|
|
1906
1918
|
c: LogswapClient,
|
|
1907
1919
|
opts: { fromBlock?: bigint; toBlock?: bigint; indexer?: string } = {},
|
|
1908
1920
|
): Promise<DiscoveredFPool[]> {
|
|
1909
|
-
type Ev = Extract<(typeof
|
|
1910
|
-
const ev =
|
|
1921
|
+
type Ev = Extract<(typeof managerFAbi)[number], { type: "event"; name: "PoolCreated" }>;
|
|
1922
|
+
const ev = managerFAbi.find((x): x is Ev => x.type === "event" && x.name === "PoolCreated");
|
|
1911
1923
|
if (!ev) throw new Error("logswap: F PoolCreated event missing from the generated ABI");
|
|
1912
|
-
type DeployEv = Extract<(typeof
|
|
1913
|
-
const deployEv =
|
|
1914
|
-
const range = { indexer: opts.indexer, address: c.addresses.
|
|
1924
|
+
type DeployEv = Extract<(typeof managerFAbi)[number], { type: "event"; name: "LiquidityDeployed" }>;
|
|
1925
|
+
const deployEv = managerFAbi.find((x): x is DeployEv => x.type === "event" && x.name === "LiquidityDeployed");
|
|
1926
|
+
const range = { indexer: opts.indexer, address: c.addresses.managerF, fromBlock: opts.fromBlock, toBlock: opts.toBlock };
|
|
1915
1927
|
const [{ logs }, { logs: deploys }] = await Promise.all([
|
|
1916
1928
|
getEventLogs(c, { ...range, event: ev }),
|
|
1917
1929
|
deployEv ? getEventLogs(c, { ...range, event: deployEv }) : Promise.resolve({ logs: [] }),
|
|
@@ -1925,23 +1937,22 @@ export async function discoverFPools(
|
|
|
1925
1937
|
}
|
|
1926
1938
|
return Promise.all(
|
|
1927
1939
|
logs.map(async (l) => {
|
|
1928
|
-
const a = l.args as {
|
|
1929
|
-
poolId: Hex; quote: Address; creator: Address; bases: readonly Address[];
|
|
1930
|
-
swapFee: bigint; policy: Address; mintFee: bigint;
|
|
1931
|
-
};
|
|
1940
|
+
const a = l.args as { poolId: Hex; quote: Address; policy: Address; bases: readonly Address[]; swapFeeIdx: number | bigint; salt: Hex };
|
|
1932
1941
|
const g0 = first.get(a.poolId.toLowerCase());
|
|
1933
1942
|
const kind = await fPoolKindOfPolicy(c, a.policy); // one read per distinct policy, cached
|
|
1943
|
+
const swapFeeIdx = Number(a.swapFeeIdx);
|
|
1934
1944
|
return {
|
|
1935
1945
|
poolId: a.poolId,
|
|
1936
1946
|
quote: a.quote,
|
|
1937
1947
|
bases: [...a.bases],
|
|
1938
1948
|
weights: g0?.weights ?? [],
|
|
1939
|
-
|
|
1940
|
-
|
|
1949
|
+
swapFeeIdx,
|
|
1950
|
+
swapFee: fFeeOf(swapFeeIdx),
|
|
1951
|
+
mintFee: fMintFeeOf(swapFeeIdx),
|
|
1941
1952
|
lnCapOverSeed: g0?.lnCapOverSeed ?? 0,
|
|
1942
1953
|
kind,
|
|
1943
1954
|
policy: a.policy,
|
|
1944
|
-
|
|
1955
|
+
salt: a.salt,
|
|
1945
1956
|
block: l.blockNumber,
|
|
1946
1957
|
seeded: g0 !== undefined,
|
|
1947
1958
|
q0: g0?.q0 ?? 0n,
|
|
@@ -1951,111 +1962,24 @@ export async function discoverFPools(
|
|
|
1951
1962
|
);
|
|
1952
1963
|
}
|
|
1953
1964
|
|
|
1954
|
-
// ─── the policy page: what an
|
|
1965
|
+
// ─── the policy page: what an account runs ────────────────────────
|
|
1955
1966
|
//
|
|
1956
|
-
// One policy serves every pool
|
|
1957
|
-
// every pool
|
|
1958
|
-
// indexer), then
|
|
1967
|
+
// One policy serves every pool under it, so "the pools I run" is not a policy's list: it is every pool whose policy answers
|
|
1968
|
+
// `operator(poolId) == me` — and, for a sponsor, every pool under a policy whose `authority()` is me. Discovery from the log
|
|
1969
|
+
// stream (or the indexer), then the roles per pool on its policy — viem multicalls them.
|
|
1959
1970
|
|
|
1960
|
-
/** A pool an
|
|
1971
|
+
/** A pool an account runs or sponsors, with what the policy page shows of it. */
|
|
1961
1972
|
export interface FPoolControlled {
|
|
1962
1973
|
pool: DiscoveredFPool;
|
|
1963
1974
|
roles: FPoolRoles;
|
|
1964
1975
|
state: FPoolState;
|
|
1965
|
-
/** The policy's
|
|
1966
|
-
|
|
1967
|
-
}
|
|
1968
|
-
|
|
1969
|
-
/** What a pool's policy says about it, by kind: the terms a buyer reads before entering. */
|
|
1970
|
-
export type FPoolRules =
|
|
1971
|
-
| {
|
|
1972
|
-
kind: "pad";
|
|
1973
|
-
/** The pad's graduation count: the pool's generation (F version 21 — `PadPolicy.rung` is gone). */
|
|
1974
|
-
gen: number;
|
|
1975
|
-
/** @deprecated Equal to {@link gen} since F version 21, kept for callers; read `gen`. */
|
|
1976
|
-
rung: number;
|
|
1977
|
-
/** The income the next graduation needs, in the pad's quote: `PadPolicy.threshold(poolId, gen)` (T(0) is per quote, decision 070). */
|
|
1978
|
-
threshold: bigint;
|
|
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). */
|
|
1982
|
-
creatorShare: bigint;
|
|
1983
|
-
/** The income tax the dead shares pay on their own new income dividend (decisions 073, 085), WAD. */
|
|
1984
|
-
incomeTaxRate: bigint;
|
|
1985
|
-
/** The ranges the LOG Authority set on the policy NOW for the pads born after this read: what a new creator may choose. */
|
|
1986
|
-
ranges: PadRanges;
|
|
1987
|
-
}
|
|
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 }
|
|
1989
|
-
| { kind: "public" }
|
|
1990
|
-
| { kind: "private"; gateMint: boolean; swapMode: FPoolSwapMode; swapExecutor: Address; operator: Address };
|
|
1991
|
-
|
|
1992
|
-
/** The LOG Authority's range on a pad's creator choice (`PadPolicy`, decisions 056, 067), WAD fractions of the income released. */
|
|
1993
|
-
export interface PadRanges {
|
|
1994
|
-
creatorShareMin: bigint;
|
|
1995
|
-
/** At most the F manager's `PAYEE_CUT_MAX` (50%), which bounds a pad's payee whatever the policy (067). */
|
|
1996
|
-
creatorShareMax: bigint;
|
|
1997
|
-
}
|
|
1998
|
-
|
|
1999
|
-
const MAX_U64 = (1n << 64n) - 1n;
|
|
2000
|
-
const MAX_U128 = (1n << 128n) - 1n;
|
|
2001
|
-
|
|
2002
|
-
/**
|
|
2003
|
-
* The salt that carries a pad's split (`PadPolicy.pack(creatorShare, nonce)`, decisions 056, 067): `creatorShare` in the top 64
|
|
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
|
|
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
|
|
2006
|
-
* chosen at launch (`FPoolLaunchArgs.salt`) and never changes; the policy refuses a cut outside its range.
|
|
2007
|
-
*/
|
|
2008
|
-
export function padSalt(s: { creatorShare: bigint; nonce?: bigint; /** @deprecated F version 28 has no burn (067): only 0 is accepted. */ burnShare?: bigint }): Hex {
|
|
2009
|
-
const nonce = s.nonce ?? 0n;
|
|
2010
|
-
if (s.burnShare !== undefined && s.burnShare !== 0n) throw new Error("logswap: a pad has no burn share since F version 28 (decision 067)");
|
|
2011
|
-
if (s.creatorShare < 0n || s.creatorShare > MAX_U64) throw new Error("logswap: a pad's creator share is a WAD fraction that fits 64 bits");
|
|
2012
|
-
if (nonce < 0n || nonce > MAX_U128) throw new Error("logswap: a pad salt's nonce fits 128 bits");
|
|
2013
|
-
return `0x${((s.creatorShare << 192n) | nonce).toString(16).padStart(64, "0")}` as Hex;
|
|
2014
|
-
}
|
|
2015
|
-
|
|
2016
|
-
/** The inverse of {@link padSalt}. `burnShare` is the old field's bits, nonzero only on a salt the F version 28 policy refuses. */
|
|
2017
|
-
export function padSplitOfSalt(salt: Hex): { creatorShare: bigint; burnShare: bigint; nonce: bigint } {
|
|
2018
|
-
const v = BigInt(salt);
|
|
2019
|
-
return { creatorShare: v >> 192n, burnShare: (v >> 128n) & MAX_U64, nonce: v & MAX_U128 };
|
|
2020
|
-
}
|
|
2021
|
-
|
|
2022
|
-
/** The policy's terms for one pool, by its kind. */
|
|
2023
|
-
export async function getFPoolRules(c: LogswapClient, s: Pick<FPoolState, "poolId" | "policy" | "kind" | "gen">, roles?: FPoolRoles): Promise<FPoolRules> {
|
|
2024
|
-
const rd = <T>(abi: readonly unknown[], functionName: string, args: readonly unknown[] = []) =>
|
|
2025
|
-
c.public.readContract({ address: s.policy, abi, functionName, args } as never) as Promise<T>;
|
|
2026
|
-
switch (s.kind) {
|
|
2027
|
-
case "pad": {
|
|
2028
|
-
// the rung is the manager's generation (F version 21): a move carries it, nothing to ask the policy
|
|
2029
|
-
const gen = s.gen;
|
|
2030
|
-
const [creatorShare, income, threshold, incomeTaxRate, creatorShareMin, creatorShareMax] = await Promise.all([
|
|
2031
|
-
rd<bigint | number>(padPolicyAbi, "creatorShareOf", [s.poolId]).then(BigInt),
|
|
2032
|
-
fPoolDividendOf(c, s.poolId, DEAD_ADDRESS, gen),
|
|
2033
|
-
rd<bigint>(padPolicyAbi, "threshold", [s.poolId, BigInt(gen)]),
|
|
2034
|
-
rd<bigint>(padPolicyAbi, "incomeTaxRate"),
|
|
2035
|
-
rd<bigint>(padPolicyAbi, "creatorShareMin"),
|
|
2036
|
-
rd<bigint>(padPolicyAbi, "creatorShareMax"),
|
|
2037
|
-
]);
|
|
2038
|
-
const ranges: PadRanges = { creatorShareMin, creatorShareMax };
|
|
2039
|
-
return { kind: "pad", gen, rung: gen, threshold, income, creatorShare, incomeTaxRate, ranges };
|
|
2040
|
-
}
|
|
2041
|
-
case "pol": {
|
|
2042
|
-
const [minQuoteRatio, incomeTaxRate] = await Promise.all([rd<bigint>(polPolicyAbi, "minQuoteRatio"), rd<bigint>(polPolicyAbi, "incomeTaxRate")]);
|
|
2043
|
-
return { kind: "pol", minQuoteRatio, incomeTaxRate };
|
|
2044
|
-
}
|
|
2045
|
-
case "public": {
|
|
2046
|
-
return { kind: "public" };
|
|
2047
|
-
}
|
|
2048
|
-
case "private": {
|
|
2049
|
-
const r = roles ?? (await getFPoolRoles(c, s.poolId, s));
|
|
2050
|
-
return { kind: "private", gateMint: r.gateMint, swapMode: r.swapMode, swapExecutor: r.swapExecutor, operator: r.operator };
|
|
2051
|
-
}
|
|
2052
|
-
}
|
|
1976
|
+
/** The policy's immutables: the terms a holder reads before entering. */
|
|
1977
|
+
terms: FPolicyTerms;
|
|
2053
1978
|
}
|
|
2054
1979
|
|
|
2055
1980
|
/**
|
|
2056
|
-
* Every F pool `who`
|
|
2057
|
-
* `
|
|
2058
|
-
* `who` are. `pools` may be passed (from the indexer, say) to skip the log scan.
|
|
1981
|
+
* Every F pool `who` runs (its operator) or sponsors (the authority of its policy) — the policy page's list. `roles` tells
|
|
1982
|
+
* which. `pools` may be passed (from the indexer, say) to skip the log scan.
|
|
2059
1983
|
*/
|
|
2060
1984
|
export async function fPoolsControlledBy(
|
|
2061
1985
|
c: LogswapClient,
|
|
@@ -2063,20 +1987,15 @@ export async function fPoolsControlledBy(
|
|
|
2063
1987
|
opts: { pools?: DiscoveredFPool[]; fromBlock?: bigint } = {},
|
|
2064
1988
|
): Promise<FPoolControlled[]> {
|
|
2065
1989
|
const pools = opts.pools ?? (await discoverFPools(c, { fromBlock: opts.fromBlock }));
|
|
2066
|
-
// the LIVE policy answers for the authority: a moved pool (046) is on another one than its birth's
|
|
2067
1990
|
const states = await Promise.all(pools.map((p) => getFPool(c, p.poolId)));
|
|
2068
|
-
const
|
|
2069
|
-
|
|
2070
|
-
c.public.readContract({ address: s.policy, abi: fPolicyBaseAbi, functionName: "authority", args: [s.poolId] } as never) as Promise<Address>,
|
|
2071
|
-
),
|
|
2072
|
-
);
|
|
1991
|
+
const roles = await Promise.all(states.map((s) => getFPoolRoles(c, s.poolId, s)));
|
|
1992
|
+
const me = who.toLowerCase();
|
|
2073
1993
|
const out: FPoolControlled[] = [];
|
|
2074
1994
|
for (let i = 0; i < pools.length; ++i) {
|
|
2075
|
-
|
|
1995
|
+
const r = roles[i]!;
|
|
1996
|
+
if (r.operator.toLowerCase() !== me && r.authority.toLowerCase() !== me) continue;
|
|
2076
1997
|
const state = states[i]!;
|
|
2077
|
-
|
|
2078
|
-
const rules = await getFPoolRules(c, state, roles);
|
|
2079
|
-
out.push({ pool: pools[i]!, roles, state, rules });
|
|
1998
|
+
out.push({ pool: pools[i]!, roles: r, state, terms: await fPolicyTermsOf(c, state.policy) });
|
|
2080
1999
|
}
|
|
2081
2000
|
return out;
|
|
2082
2001
|
}
|
|
@@ -2094,14 +2013,14 @@ export async function fPoolShareHolders(
|
|
|
2094
2013
|
poolIdHex: Hex,
|
|
2095
2014
|
opts: { fromBlock?: bigint; gen?: bigint | number; indexer?: string } = {},
|
|
2096
2015
|
): Promise<Array<{ holder: Address; shares: bigint }>> {
|
|
2097
|
-
type Ev = Extract<(typeof
|
|
2098
|
-
const ev =
|
|
2016
|
+
type Ev = Extract<(typeof managerFAbi)[number], { type: "event"; name: "Transfer" }>;
|
|
2017
|
+
const ev = managerFAbi.find((x): x is Ev => x.type === "event" && x.name === "Transfer");
|
|
2099
2018
|
if (!ev) throw new Error("logswap: 6909 Transfer event missing from the generated ABI");
|
|
2100
2019
|
const gen = opts.gen ?? (await fPoolGen(c, poolIdHex));
|
|
2101
2020
|
const indexer = opts.indexer ?? c.indexerUrl;
|
|
2102
2021
|
if (indexer) {
|
|
2103
2022
|
try {
|
|
2104
|
-
const rows = await poolHolders(indexer, { condition: { side: "F", poolId: poolIdHex.toLowerCase(), gen: Number(gen), manager: c.addresses.
|
|
2023
|
+
const rows = await poolHolders(indexer, { condition: { side: "F", poolId: poolIdHex.toLowerCase(), gen: Number(gen), manager: c.addresses.managerF.toLowerCase() } });
|
|
2105
2024
|
return rows
|
|
2106
2025
|
.filter((r) => r.balance > 0n)
|
|
2107
2026
|
.map((r) => ({ holder: r.holder, shares: r.balance }))
|
|
@@ -2111,7 +2030,7 @@ export async function fPoolShareHolders(
|
|
|
2111
2030
|
}
|
|
2112
2031
|
}
|
|
2113
2032
|
const id = fPoolShareId(poolIdHex, gen);
|
|
2114
|
-
const { logs } = await getEventLogs(c, { indexer: opts.indexer, address: c.addresses.
|
|
2033
|
+
const { logs } = await getEventLogs(c, { indexer: opts.indexer, address: c.addresses.managerF, event: ev, args: { id }, fromBlock: opts.fromBlock });
|
|
2115
2034
|
const bal = new Map<string, bigint>();
|
|
2116
2035
|
for (const l of logs) {
|
|
2117
2036
|
const a = l.args as { from: Address; to: Address; amount: bigint };
|
|
@@ -2124,26 +2043,14 @@ export async function fPoolShareHolders(
|
|
|
2124
2043
|
.sort((a, b) => (b.shares > a.shares ? 1 : -1));
|
|
2125
2044
|
}
|
|
2126
2045
|
|
|
2127
|
-
/**
|
|
2128
|
-
* What a policy answers `onRegenerate` with: `IFPolicy.Terms` — four words, exactly 128 bytes since F version 28 (decision 067
|
|
2129
|
-
* removed `burn`). `carried` is the holder the next generation carries beside the dead shares; on a pad the manager requires
|
|
2130
|
-
* `0xdead` and caps `toPayee` at `PAYEE_CUT_MAX` of the income.
|
|
2131
|
-
*/
|
|
2132
|
-
export interface FPolicyTerms {
|
|
2133
|
-
payee: Address;
|
|
2134
|
-
toPayee: bigint;
|
|
2135
|
-
protocolCut: bigint;
|
|
2136
|
-
carried: Address;
|
|
2137
|
-
}
|
|
2138
|
-
|
|
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). */
|
|
2046
|
+
/** 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). */
|
|
2140
2047
|
export async function getFPoolsRaw(c: LogswapClient, poolIds: Hex[]): Promise<readonly unknown[]> {
|
|
2141
|
-
const {
|
|
2142
|
-
return (await c.public.readContract({ address: c.addresses.
|
|
2048
|
+
const { lensFAbi } = await import("./generated.js");
|
|
2049
|
+
return (await c.public.readContract({ address: c.addresses.lensF, abi: lensFAbi, functionName: "getPools", args: [poolIds] } as never)) as readonly unknown[];
|
|
2143
2050
|
}
|
|
2144
2051
|
|
|
2145
2052
|
/** Share value from the lens — (L + Q)/shares, WAD per share — the same figure as `fPoolShareValue`, from one source. */
|
|
2146
2053
|
export async function shareValueOnChain(c: LogswapClient, poolId: Hex): Promise<bigint> {
|
|
2147
|
-
const {
|
|
2148
|
-
return (await c.public.readContract({ address: c.addresses.
|
|
2054
|
+
const { lensFAbi } = await import("./generated.js");
|
|
2055
|
+
return (await c.public.readContract({ address: c.addresses.lensF, abi: lensFAbi, functionName: "shareValue", args: [poolId] } as never)) as bigint;
|
|
2149
2056
|
}
|