@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/dist/fpool.js
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,65 +18,66 @@
|
|
|
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
|
-
import { decodeAbiParameters, encodeAbiParameters, encodeFunctionData, erc20Abi, keccak256
|
|
33
|
-
import {
|
|
37
|
+
import { decodeAbiParameters, encodeAbiParameters, encodeFunctionData, erc20Abi, keccak256 } from "viem";
|
|
38
|
+
import { managerFAbi, lensFAbi, routerFAbi, policyFAbi, policyRegistryAbi } from "./generated.js";
|
|
34
39
|
/**
|
|
35
|
-
* One contract, one ABI (F version 12): `harvest`, `claim`, `
|
|
36
|
-
*
|
|
37
|
-
*
|
|
38
|
-
* {@link privatePolicyAbi} the desk's, {@link padPolicyAbi} / {@link polPolicyAbi} / {@link publicPolicyAbi}
|
|
39
|
-
* the kinds'.
|
|
40
|
+
* One contract, one ABI (F version 12): `harvest`, `claim`, `close`, `deployLiquidity`, the fee list are `ManagerF`'s own
|
|
41
|
+
* code. The roles left it for the policy in F version 15; since F 41 there is one policy contract, {@link policyFAbi}
|
|
42
|
+
* (`PolicyF`, policy.md): every F pool's operator, gate modes and lists.
|
|
40
43
|
*/
|
|
41
|
-
export {
|
|
42
|
-
/**
|
|
43
|
-
* What every protocol policy shares (`FPolicyBase`): the roles and their handover and the
|
|
44
|
-
* `maxHarvest` readout (a harvest has no cut, decisions 056). `polPolicyAbi` is a superset of it and carries nothing that collides, so it stands
|
|
45
|
-
* in for the base — a call through it to any of the four policies decodes the base's functions.
|
|
46
|
-
*/
|
|
47
|
-
export const fPolicyBaseAbi = polPolicyAbi;
|
|
44
|
+
export { managerFAbi, policyFAbi };
|
|
48
45
|
import { clientChainId } from "./client.js";
|
|
46
|
+
import { findQuoteResult } from "./quote.js";
|
|
49
47
|
import { fallBackUnlessRejected, signerFor } from "./write.js";
|
|
50
48
|
import { getEventLogs } from "./history.js";
|
|
51
49
|
import { poolHolders } from "./views.js";
|
|
52
|
-
import { presetMintFee } from "./positions.js";
|
|
53
|
-
import { isValidMintFee, MINT_FEE_MAX } from "./keys.js";
|
|
54
50
|
const WAD = 10n ** 18n;
|
|
55
51
|
const ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";
|
|
56
|
-
/**
|
|
57
|
-
|
|
58
|
-
|
|
52
|
+
/**
|
|
53
|
+
* The bits a policy declares at birth, in `Pool.flags` (decision 098; `ASK_SWAP` / `ASK_MINT` before): with a gate bit off nothing is
|
|
54
|
+
* asked; with it on the manager admits the cached operator with no policy call and asks the policy about everyone else.
|
|
55
|
+
*/
|
|
56
|
+
export const GATE_SWAP = 1;
|
|
57
|
+
export const GATE_MINT = 2;
|
|
58
|
+
/** `GATE_SWAP | GATE_MINT`: the bits `setGates` carries (`SEED_TO_DEAD` is the birth's alone). */
|
|
59
|
+
export const GATES = GATE_SWAP | GATE_MINT;
|
|
59
60
|
/**
|
|
60
61
|
* The lens's raw F pool struct — what the manager's `getPool` returned. Since F version 25 the
|
|
61
62
|
* manager's typed views are behind `extsload` (decisions 062) and the lens reads them; one call.
|
|
62
63
|
*/
|
|
63
64
|
async function rawFPool(c, poolId) {
|
|
64
65
|
const [p] = await c.public.readContract({
|
|
65
|
-
address: c.addresses.
|
|
66
|
-
abi:
|
|
67
|
-
functionName: "
|
|
66
|
+
address: c.addresses.lensF,
|
|
67
|
+
abi: lensFAbi,
|
|
68
|
+
functionName: "getPools",
|
|
68
69
|
args: [[poolId]],
|
|
69
70
|
});
|
|
70
71
|
if (!p || /^0x0{40}$/i.test(p.quote))
|
|
71
72
|
throw new Error(`logswap: no F pool with id ${poolId}`);
|
|
72
73
|
return p;
|
|
73
74
|
}
|
|
74
|
-
/** Read a basket pool whole: one lens call (`
|
|
75
|
+
/** Read a basket pool whole: one lens call (`pool`, F version 25) plus the policy's terms (cached per policy). The name is a log query apart: {@link fPoolNameOf}. */
|
|
75
76
|
export async function getFPool(c, poolId) {
|
|
76
77
|
const v = await c.public.readContract({
|
|
77
|
-
address: c.addresses.
|
|
78
|
-
abi:
|
|
79
|
-
functionName: "
|
|
78
|
+
address: c.addresses.lensF,
|
|
79
|
+
abi: lensFAbi,
|
|
80
|
+
functionName: "pool",
|
|
80
81
|
args: [poolId],
|
|
81
82
|
});
|
|
82
83
|
const p = v.pool;
|
|
@@ -87,7 +88,7 @@ export async function getFPool(c, poolId) {
|
|
|
87
88
|
// cannot be a check on `seeded`.
|
|
88
89
|
if (/^0x0{40}$/i.test(p.quote))
|
|
89
90
|
throw new Error(`logswap: no F pool with id ${poolId}`);
|
|
90
|
-
const
|
|
91
|
+
const kind = await fPoolKindOfPolicy(c, p.policy);
|
|
91
92
|
return {
|
|
92
93
|
poolId,
|
|
93
94
|
quote: p.quote,
|
|
@@ -105,8 +106,8 @@ export async function getFPool(c, poolId) {
|
|
|
105
106
|
lnCapOverSeed: Number(p.lnCapOverSeed),
|
|
106
107
|
realizedVariance: p.realizedVariance,
|
|
107
108
|
policy: p.policy,
|
|
108
|
-
|
|
109
|
-
|
|
109
|
+
flags: Number(p.flags),
|
|
110
|
+
operator: p.operator,
|
|
110
111
|
restructureTime: Number(p.restructureTime),
|
|
111
112
|
kind,
|
|
112
113
|
seeded: p.seeded,
|
|
@@ -117,80 +118,132 @@ export async function getFPool(c, poolId) {
|
|
|
117
118
|
kappa: v.baseAssets.map((l) => l.kappa),
|
|
118
119
|
};
|
|
119
120
|
}
|
|
120
|
-
|
|
121
|
-
/** The policy's birth-time declaration that the seed's shares are the pool's (a pad's), in `asks`. */
|
|
121
|
+
/** The policy's birth-time declaration that the deploy's shares are the pool's (`seedToDead`, a pad's), in `flags`. */
|
|
122
122
|
export const SEED_TO_DEAD = 4;
|
|
123
|
-
const
|
|
123
|
+
const termsCache = new Map();
|
|
124
|
+
/** The label a policy's terms spell (see {@link FPoolKind}). Pure. */
|
|
125
|
+
export function fPolicyKindOf(t) {
|
|
126
|
+
if (t.open)
|
|
127
|
+
return "public";
|
|
128
|
+
if (t.seedToDead)
|
|
129
|
+
return "pad";
|
|
130
|
+
if (t.quoteBuffer > 0n)
|
|
131
|
+
return "pol";
|
|
132
|
+
return "desk";
|
|
133
|
+
}
|
|
124
134
|
/**
|
|
125
|
-
*
|
|
126
|
-
* chain:
|
|
127
|
-
* (a policy that is not one of the protocol's four shapes) throws; the app has no screen for it.
|
|
135
|
+
* A policy's terms, read once per policy address and cached for the client's chain (the policies sit at one address on
|
|
136
|
+
* every release chain): every field is an immutable, so the first read is the last. A failed read is not cached.
|
|
128
137
|
*/
|
|
129
|
-
export async function
|
|
130
|
-
// the chain id is part of the key: the policies sit at one address on every release chain
|
|
138
|
+
export async function fPolicyTermsOf(c, policy) {
|
|
131
139
|
const key = `${await clientChainId(c)}:${policy.toLowerCase()}`;
|
|
132
|
-
let hit =
|
|
140
|
+
let hit = termsCache.get(key);
|
|
133
141
|
if (!hit) {
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
142
|
+
const rd = (functionName) => c.public.readContract({ address: policy, abi: policyFAbi, functionName });
|
|
143
|
+
hit = Promise.all([
|
|
144
|
+
rd("fixedAuthority"),
|
|
145
|
+
rd("open"),
|
|
146
|
+
rd("seedToDead"),
|
|
147
|
+
rd("incomeHarvestOnly"),
|
|
148
|
+
rd("incomeTaxRate"),
|
|
149
|
+
rd("feeMask"),
|
|
150
|
+
rd("lenMax"),
|
|
151
|
+
rd("lnCapMin"),
|
|
152
|
+
rd("quoteBuffer"),
|
|
153
|
+
rd("quoteCurated"),
|
|
154
|
+
rd("baseCurated"),
|
|
155
|
+
]).then(([fixedAuthority, open, seedToDead, incomeHarvestOnly, incomeTaxRate, feeMask, lenMax, lnCapMin, quoteBuffer, quoteCurated, baseCurated]) => {
|
|
156
|
+
const t = {
|
|
157
|
+
policy,
|
|
158
|
+
fixedAuthority,
|
|
159
|
+
open,
|
|
160
|
+
seedToDead,
|
|
161
|
+
incomeHarvestOnly,
|
|
162
|
+
incomeTaxRate,
|
|
163
|
+
feeMask: Number(feeMask),
|
|
164
|
+
lenMax: Number(lenMax),
|
|
165
|
+
lnCapMin: Number(lnCapMin),
|
|
166
|
+
quoteBuffer,
|
|
167
|
+
quoteCurated,
|
|
168
|
+
baseCurated,
|
|
169
|
+
};
|
|
170
|
+
return { ...t, kind: fPolicyKindOf(t) };
|
|
139
171
|
});
|
|
140
|
-
|
|
141
|
-
hit.catch(() =>
|
|
172
|
+
termsCache.set(key, hit);
|
|
173
|
+
hit.catch(() => termsCache.delete(key)); // a failed read is not a fact
|
|
142
174
|
}
|
|
143
175
|
return hit;
|
|
144
176
|
}
|
|
145
|
-
/**
|
|
146
|
-
export async function
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
177
|
+
/** What a policy IS, as a label: {@link fPolicyTermsOf}'s `kind`. One read per policy address, cached. */
|
|
178
|
+
export async function fPoolKindOfPolicy(c, policy) {
|
|
179
|
+
return (await fPolicyTermsOf(c, policy)).kind;
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* The pool's label — the last `NameSet` its policy emitted for it: the operator's word, mutable, never identity. Nothing is
|
|
183
|
+
* stored on chain (policy.md §4.3), so this is a log query — pass `indexer`, or set the client's. "" when never named.
|
|
184
|
+
*/
|
|
185
|
+
export async function fPoolNameOf(c, poolId, opts = {}) {
|
|
186
|
+
const policy = opts.policy ?? (await fPoolPolicyOf(c, poolId));
|
|
187
|
+
const ev = policyFAbi.find((x) => x.type === "event" && x.name === "NameSet");
|
|
188
|
+
if (!ev)
|
|
189
|
+
throw new Error("logswap: NameSet event missing from the generated ABI");
|
|
190
|
+
const { logs } = await getEventLogs(c, { indexer: opts.indexer, address: policy, event: ev, args: { poolId }, fromBlock: opts.fromBlock });
|
|
191
|
+
const last = logs[logs.length - 1];
|
|
192
|
+
return last ? bytes32ToText(last.args.name) : "";
|
|
150
193
|
}
|
|
151
|
-
/** The deployment's policy for a
|
|
152
|
-
export function fPoolPolicyFor(c,
|
|
194
|
+
/** The deployment's policy for a slot — the one a key names when no `policy` is given. */
|
|
195
|
+
export function fPoolPolicyFor(c, slot) {
|
|
153
196
|
const a = c.addresses;
|
|
154
|
-
const policy =
|
|
197
|
+
const policy = slot === "public" ? a.publicPolicy : slot === "private" ? a.privatePolicy : slot === "pol" ? a.polPolicy : a.padPolicy;
|
|
155
198
|
if (!policy)
|
|
156
|
-
throw new Error(`logswap: this deployment carries no ${
|
|
199
|
+
throw new Error(`logswap: this deployment carries no ${slot} policy`);
|
|
157
200
|
return policy;
|
|
158
201
|
}
|
|
159
202
|
/** The policy a pool named in its key — one read; {@link getFPool} carries it too. */
|
|
160
203
|
export async function fPoolPolicyOf(c, poolId) {
|
|
161
204
|
return (await rawFPool(c, poolId)).policy;
|
|
162
205
|
}
|
|
163
|
-
const
|
|
164
|
-
/**
|
|
206
|
+
const MODES = ["open", "listed", "operator"];
|
|
207
|
+
/** The gate modes in `IPolicyF.Mode` order — the index is the on-chain ordinal. */
|
|
208
|
+
export const fPoolModes = MODES;
|
|
209
|
+
/** Read a pool's roles from its policy. `state` saves the `getPool` round trip when the policy is already in hand. */
|
|
165
210
|
export async function getFPoolRoles(c, poolId, state) {
|
|
166
|
-
const
|
|
167
|
-
const
|
|
168
|
-
const [
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
211
|
+
const policy = state?.policy ?? (await fPoolPolicyOf(c, poolId));
|
|
212
|
+
const rd = (functionName, args = []) => c.public.readContract({ address: policy, abi: policyFAbi, functionName, args });
|
|
213
|
+
const [authority, operator, swap, mint] = await Promise.all([
|
|
214
|
+
rd("authority"),
|
|
215
|
+
rd("operator", [poolId]),
|
|
216
|
+
rd("swapMode", [poolId]),
|
|
217
|
+
rd("mintMode", [poolId]),
|
|
173
218
|
]);
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
219
|
+
return { policy, authority, operator, swapMode: MODES[Number(swap)] ?? "open", mintMode: MODES[Number(mint)] ?? "open" };
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* What a harvest may take now (policy.md §9): the income `I = min(unharvested, Q)` always; capital on top of it up to
|
|
223
|
+
* `Q − I − quoteBuffer·L` (`QuoteTooThin` past it), none where the policy is income-only (`IncomeOnly`) or the pool a pad
|
|
224
|
+
* (`SEED_TO_DEAD`: the manager's own rule, `HarvestLimit`). Nothing on an unfunded pool.
|
|
225
|
+
*/
|
|
226
|
+
export function fPoolHarvestRoom(s, t) {
|
|
227
|
+
if (s.L === 0n)
|
|
228
|
+
return { income: 0n, capital: 0n };
|
|
229
|
+
const income = s.unharvested < s.Q ? s.unharvested : s.Q;
|
|
230
|
+
if (t.incomeHarvestOnly || (s.flags & SEED_TO_DEAD) !== 0)
|
|
231
|
+
return { income, capital: 0n };
|
|
232
|
+
const keep = income + (s.L * t.quoteBuffer + WAD - 1n) / WAD; // `mulWadUp`, as the policy rounds
|
|
233
|
+
return { income, capital: s.Q > keep ? s.Q - keep : 0n };
|
|
180
234
|
}
|
|
181
235
|
export async function describeFPool(c, s) {
|
|
182
|
-
// an unfunded pool has no L: nothing earned, nothing to harvest
|
|
183
|
-
|
|
184
|
-
const
|
|
185
|
-
const unharvested = s.L > 0n ? s.unharvested : 0n;
|
|
186
|
-
const income = s.L > 0n ? await fPoolDividendOf(c, s.poolId, DEAD_ADDRESS, s.gen) : 0n;
|
|
236
|
+
// an unfunded pool has no L: nothing earned, nothing to harvest
|
|
237
|
+
const terms = await fPolicyTermsOf(c, s.policy);
|
|
238
|
+
const { income, capital } = fPoolHarvestRoom(s, terms);
|
|
187
239
|
return {
|
|
188
|
-
shape: s.kind === "pad" ? "launch" : "basket", // the kind, not n = 1
|
|
240
|
+
shape: s.kind === "pad" ? "launch" : "basket", // the kind, not n = 1
|
|
189
241
|
legs: s.bases.length,
|
|
190
242
|
atFloor: s.Q === 0n,
|
|
191
|
-
unharvested,
|
|
192
|
-
harvestable,
|
|
243
|
+
unharvested: s.L > 0n ? s.unharvested : 0n,
|
|
193
244
|
income,
|
|
245
|
+
capitalRoom: capital,
|
|
246
|
+
harvestable: income + capital,
|
|
194
247
|
};
|
|
195
248
|
}
|
|
196
249
|
/** `p_j = e^{x_j}`, lossy the way any float conversion is. Compare in log space when it matters. */
|
|
@@ -282,11 +335,11 @@ export function fPoolPreviewMintQuote(st, dL) {
|
|
|
282
335
|
* and expect change back — do not treat it as exact.
|
|
283
336
|
*/
|
|
284
337
|
export async function fPoolPreviewZapIn(c, poolId, dL) {
|
|
285
|
-
// read-only lives on the LENS (the
|
|
286
|
-
const {
|
|
338
|
+
// read-only lives on the LENS (LensF: the previews)
|
|
339
|
+
const { lensFAbi } = await import("./generated.js");
|
|
287
340
|
return c.public.readContract({
|
|
288
|
-
address: c.addresses.
|
|
289
|
-
abi:
|
|
341
|
+
address: c.addresses.lensF,
|
|
342
|
+
abi: lensFAbi,
|
|
290
343
|
functionName: "previewZapIn",
|
|
291
344
|
args: [poolId, dL],
|
|
292
345
|
});
|
|
@@ -324,8 +377,8 @@ a) {
|
|
|
324
377
|
*/
|
|
325
378
|
export async function fPoolPreviewZapOut(c, a) {
|
|
326
379
|
const { result } = await c.public.simulateContract({
|
|
327
|
-
address: c.addresses.
|
|
328
|
-
abi:
|
|
380
|
+
address: c.addresses.routerF,
|
|
381
|
+
abi: routerFAbi,
|
|
329
382
|
functionName: "zapOut",
|
|
330
383
|
args: [a.poolId, a.shares, a.tokenOut, 0n, a.account, defaultDeadline()],
|
|
331
384
|
account: a.account,
|
|
@@ -354,26 +407,28 @@ export async function fPoolRollIn(c, a) {
|
|
|
354
407
|
* seed.
|
|
355
408
|
*/
|
|
356
409
|
export async function fPoolPreviewRollIn(c, poolId, gen, holder, shares) {
|
|
357
|
-
const {
|
|
410
|
+
const { lensFAbi } = await import("./generated.js");
|
|
358
411
|
const [dL, quoteShort, quoteExcess] = (await c.public.readContract({
|
|
359
|
-
address: c.addresses.
|
|
360
|
-
abi:
|
|
412
|
+
address: c.addresses.lensF,
|
|
413
|
+
abi: lensFAbi,
|
|
361
414
|
functionName: "previewRollIn",
|
|
362
415
|
args: [poolId, BigInt(gen), holder, shares],
|
|
363
416
|
}));
|
|
364
417
|
return { dL, quoteShort, quoteExcess };
|
|
365
418
|
}
|
|
366
|
-
// ─── the floor lever (
|
|
419
|
+
// ─── the floor lever (the operator's) ─────────────────────────────────────────
|
|
367
420
|
/**
|
|
368
|
-
*
|
|
369
|
-
*
|
|
370
|
-
*
|
|
371
|
-
*
|
|
372
|
-
*
|
|
373
|
-
*
|
|
421
|
+
* Harvest (policy.md §9): take this generation's income — `L·(refLogFloor − logFloor)`, the fees since the floor was last
|
|
422
|
+
* referenced — and `extra` of capital on top of it, out of the bid; price-neutral, no base moves. Both accrue as a DIVIDEND to
|
|
423
|
+
* every share, settled lazily on each holder's next transfer, mint or burn or pulled with {@link fPoolClaim}; the income is taxed
|
|
424
|
+
* 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`.
|
|
425
|
+
* The operator's own settled dividend — this harvest's and anything pending — is paid to `to` in the same call: one transaction,
|
|
426
|
+
* and the operator (usually a contract) routes the payout through `to`. The operator's alone (`NotOperator`). `extra` must fit the
|
|
427
|
+
* room ({@link fPoolHarvestRoom}): 0 on a pad (`HarvestLimit`) and under an income-only policy (`IncomeOnly`), within the buffer
|
|
428
|
+
* otherwise (`QuoteTooThin`).
|
|
374
429
|
*/
|
|
375
430
|
export async function fPoolHarvest(c, a) {
|
|
376
|
-
return writeFPool(c, a.poolId, "harvest", [a.
|
|
431
|
+
return writeFPool(c, a.poolId, "harvest", [a.extra ?? 0n, a.to ?? a.account], a.account);
|
|
377
432
|
}
|
|
378
433
|
/**
|
|
379
434
|
* Pull one's settled dividend on a generation's shares without moving them;
|
|
@@ -392,9 +447,9 @@ export async function fPoolClaim(c, a) {
|
|
|
392
447
|
export async function fPoolDividendOf(c, poolId, holder, gen) {
|
|
393
448
|
const g = gen ?? (await fPoolGen(c, poolId));
|
|
394
449
|
return c.public.readContract({
|
|
395
|
-
address: c.addresses.
|
|
396
|
-
abi:
|
|
397
|
-
functionName: "
|
|
450
|
+
address: c.addresses.lensF,
|
|
451
|
+
abi: lensFAbi,
|
|
452
|
+
functionName: "dividendOf",
|
|
398
453
|
args: [poolId, BigInt(g), holder],
|
|
399
454
|
});
|
|
400
455
|
}
|
|
@@ -406,9 +461,9 @@ export async function fPoolDividendOf(c, poolId, holder, gen) {
|
|
|
406
461
|
export async function fPoolLienOf(c, poolId, owner, gen) {
|
|
407
462
|
const g = gen ?? (await fPoolGen(c, poolId));
|
|
408
463
|
const [locker, amount, owed] = await c.public.readContract({
|
|
409
|
-
address: c.addresses.
|
|
410
|
-
abi:
|
|
411
|
-
functionName: "
|
|
464
|
+
address: c.addresses.lensF,
|
|
465
|
+
abi: lensFAbi,
|
|
466
|
+
functionName: "lienOf",
|
|
412
467
|
args: [fPoolShareId(poolId, g), owner],
|
|
413
468
|
});
|
|
414
469
|
return { locker, amount, owed };
|
|
@@ -453,8 +508,8 @@ function requireWallet(c) {
|
|
|
453
508
|
async function writeFPool(c, poolId, functionName, args, account) {
|
|
454
509
|
const wallet = requireWallet(c);
|
|
455
510
|
const { request } = await c.public.simulateContract({
|
|
456
|
-
address: c.addresses.
|
|
457
|
-
abi:
|
|
511
|
+
address: c.addresses.managerF,
|
|
512
|
+
abi: managerFAbi,
|
|
458
513
|
functionName,
|
|
459
514
|
// Every manager write is keyed by poolId as its FIRST parameter; prepending it here, in the
|
|
460
515
|
// one place all seven helpers share, is what keeps a caller from ever omitting it. The `as
|
|
@@ -468,8 +523,8 @@ async function writeFPool(c, poolId, functionName, args, account) {
|
|
|
468
523
|
async function writeFPool0(c, functionName, args, account) {
|
|
469
524
|
const wallet = requireWallet(c);
|
|
470
525
|
const { request } = await c.public.simulateContract({
|
|
471
|
-
address: c.addresses.
|
|
472
|
-
abi:
|
|
526
|
+
address: c.addresses.managerF,
|
|
527
|
+
abi: managerFAbi,
|
|
473
528
|
functionName,
|
|
474
529
|
args,
|
|
475
530
|
account: signerFor(c, account),
|
|
@@ -484,17 +539,17 @@ pullTokens = []) {
|
|
|
484
539
|
let sendArgs = args;
|
|
485
540
|
if (pullTokens.length) {
|
|
486
541
|
const { permit2SigCalls } = await import("./onboard.js");
|
|
487
|
-
const sigCalls = await permit2SigCalls(c, pullTokens).catch(fallBackUnlessRejected);
|
|
542
|
+
const sigCalls = await permit2SigCalls(c, "F", pullTokens).catch(fallBackUnlessRejected);
|
|
488
543
|
if (sigCalls.length) {
|
|
489
544
|
const { encodeFunctionData } = await import("viem");
|
|
490
|
-
const inner = encodeFunctionData({ abi:
|
|
545
|
+
const inner = encodeFunctionData({ abi: routerFAbi, functionName, args });
|
|
491
546
|
fn = "multicall";
|
|
492
547
|
sendArgs = [[...sigCalls, inner]];
|
|
493
548
|
}
|
|
494
549
|
}
|
|
495
550
|
const { request } = await c.public.simulateContract({
|
|
496
|
-
address: c.addresses.
|
|
497
|
-
abi:
|
|
551
|
+
address: c.addresses.routerF,
|
|
552
|
+
abi: routerFAbi,
|
|
498
553
|
functionName: fn,
|
|
499
554
|
args: sendArgs,
|
|
500
555
|
account: signerFor(c, account),
|
|
@@ -515,7 +570,7 @@ export async function approveTokenForFPoolManager(c, token) {
|
|
|
515
570
|
address: token,
|
|
516
571
|
abi: [{ type: "function", name: "approve", stateMutability: "nonpayable", inputs: [{ name: "s", type: "address" }, { name: "a", type: "uint256" }], outputs: [{ type: "bool" }] }],
|
|
517
572
|
functionName: "approve",
|
|
518
|
-
args: [c.addresses.
|
|
573
|
+
args: [c.addresses.managerF, (1n << 256n) - 1n],
|
|
519
574
|
account: wallet.account,
|
|
520
575
|
chain: c.wallet.chain,
|
|
521
576
|
});
|
|
@@ -526,7 +581,7 @@ export async function fPoolManagerAllowanceOk(c, token, owner, need) {
|
|
|
526
581
|
address: token,
|
|
527
582
|
abi: [{ type: "function", name: "allowance", stateMutability: "view", inputs: [{ name: "o", type: "address" }, { name: "s", type: "address" }], outputs: [{ type: "uint256" }] }],
|
|
528
583
|
functionName: "allowance",
|
|
529
|
-
args: [owner, c.addresses.
|
|
584
|
+
args: [owner, c.addresses.managerF],
|
|
530
585
|
}));
|
|
531
586
|
return allowance >= need;
|
|
532
587
|
}
|
|
@@ -538,20 +593,20 @@ export async function fPoolManagerAllowanceOk(c, token, owner, need) {
|
|
|
538
593
|
// first `fPoolZapOut` revert with something unreadable.
|
|
539
594
|
export async function isRouterOperatorForFPool(c, owner) {
|
|
540
595
|
return c.public.readContract({
|
|
541
|
-
address: c.addresses.
|
|
542
|
-
abi:
|
|
596
|
+
address: c.addresses.managerF,
|
|
597
|
+
abi: managerFAbi,
|
|
543
598
|
functionName: "isOperator",
|
|
544
|
-
args: [owner, c.addresses.
|
|
599
|
+
args: [owner, c.addresses.routerF],
|
|
545
600
|
});
|
|
546
601
|
}
|
|
547
602
|
/** Approve the router to move this account's F-pool shares. Needed once, before any `fPoolZapOut`. */
|
|
548
603
|
export async function approveRouterForFPool(c, account) {
|
|
549
604
|
const wallet = requireWallet(c);
|
|
550
605
|
const { request } = await c.public.simulateContract({
|
|
551
|
-
address: c.addresses.
|
|
552
|
-
abi:
|
|
606
|
+
address: c.addresses.managerF,
|
|
607
|
+
abi: managerFAbi,
|
|
553
608
|
functionName: "setOperator",
|
|
554
|
-
args: [c.addresses.
|
|
609
|
+
args: [c.addresses.routerF, true],
|
|
555
610
|
account: signerFor(c, account),
|
|
556
611
|
});
|
|
557
612
|
return wallet.writeContract(request);
|
|
@@ -585,8 +640,8 @@ export function fPoolClaimId(token) {
|
|
|
585
640
|
export async function fPoolShareBalance(c, poolId, owner, gen) {
|
|
586
641
|
const g = gen ?? (await fPoolGen(c, poolId));
|
|
587
642
|
return c.public.readContract({
|
|
588
|
-
address: c.addresses.
|
|
589
|
-
abi:
|
|
643
|
+
address: c.addresses.managerF,
|
|
644
|
+
abi: managerFAbi,
|
|
590
645
|
functionName: "balanceOf",
|
|
591
646
|
args: [owner, fPoolShareId(poolId, g)],
|
|
592
647
|
});
|
|
@@ -594,20 +649,20 @@ export async function fPoolShareBalance(c, poolId, owner, gen) {
|
|
|
594
649
|
/** A retired generation's bundle: what is left to redeem — supply, quote, base per leg index. */
|
|
595
650
|
export async function fPoolBundleOf(c, poolId, gen) {
|
|
596
651
|
const [supply, quote, base] = await c.public.readContract({
|
|
597
|
-
address: c.addresses.
|
|
598
|
-
abi:
|
|
599
|
-
functionName: "
|
|
652
|
+
address: c.addresses.lensF,
|
|
653
|
+
abi: lensFAbi,
|
|
654
|
+
functionName: "bundleOf",
|
|
600
655
|
args: [poolId, BigInt(gen)],
|
|
601
656
|
});
|
|
602
657
|
return { supply, quote, base: [...base] };
|
|
603
658
|
}
|
|
604
659
|
/** A holder's claims on a pool's retired generations — one row per generation still held. */
|
|
605
660
|
export async function fPoolClaimsOf(c, poolId, owner) {
|
|
606
|
-
const {
|
|
661
|
+
const { lensFAbi } = await import("./generated.js");
|
|
607
662
|
const rows = (await c.public.readContract({
|
|
608
|
-
address: c.addresses.
|
|
609
|
-
abi:
|
|
610
|
-
functionName: "
|
|
663
|
+
address: c.addresses.lensF,
|
|
664
|
+
abi: lensFAbi,
|
|
665
|
+
functionName: "claimsOf",
|
|
611
666
|
args: [poolId, owner],
|
|
612
667
|
}));
|
|
613
668
|
return rows.map((r) => ({ gen: Number(r.gen), shares: r.shares, base: [...r.base], quote: r.quote, dividend: r.dividend }));
|
|
@@ -622,8 +677,8 @@ export async function fPoolRedeem(c, a) {
|
|
|
622
677
|
}
|
|
623
678
|
export async function fPoolClaimBalance(c, token, owner) {
|
|
624
679
|
return c.public.readContract({
|
|
625
|
-
address: c.addresses.
|
|
626
|
-
abi:
|
|
680
|
+
address: c.addresses.managerF,
|
|
681
|
+
abi: managerFAbi,
|
|
627
682
|
functionName: "balanceOf",
|
|
628
683
|
args: [owner, fPoolClaimId(token)],
|
|
629
684
|
});
|
|
@@ -646,8 +701,8 @@ export var FPoolQuoteKind;
|
|
|
646
701
|
export async function fPoolQuoteSwap(c, a) {
|
|
647
702
|
try {
|
|
648
703
|
await c.public.simulateContract({
|
|
649
|
-
address: c.addresses.
|
|
650
|
-
abi:
|
|
704
|
+
address: c.addresses.routerF,
|
|
705
|
+
abi: routerFAbi,
|
|
651
706
|
functionName: "quoteSwap",
|
|
652
707
|
// the taker matters only on a gated pool: the connected account, or the zero address
|
|
653
708
|
args: [a.poolId, a.kind, BigInt(a.j), BigInt(a.k ?? 0), a.amountIn, a.taker ?? c.wallet?.account?.address ?? ZERO_ADDRESS],
|
|
@@ -661,35 +716,55 @@ export async function fPoolQuoteSwap(c, a) {
|
|
|
661
716
|
}
|
|
662
717
|
throw new Error("logswap: quoteSwap returned without reverting, which it must never do");
|
|
663
718
|
}
|
|
664
|
-
/**
|
|
665
|
-
* `QuoteResult(uint256)` — selector then one word. viem nests the revert data several layers deep
|
|
666
|
-
* depending on the transport, so walk for it rather than guessing the shape.
|
|
667
|
-
*
|
|
668
|
-
* The selector is DERIVED, not written down. A hardcoded one is wrong silently: the decode simply
|
|
669
|
-
* never matches and every quote rethrows as if the swap had failed.
|
|
670
|
-
*/
|
|
671
|
-
function findQuoteResult(err) {
|
|
672
|
-
const SELECTOR = toFunctionSelector("QuoteResult(uint256)");
|
|
673
|
-
const seen = new Set();
|
|
674
|
-
const walk = (e) => {
|
|
675
|
-
if (!e || typeof e !== "object" || seen.has(e))
|
|
676
|
-
return null;
|
|
677
|
-
seen.add(e);
|
|
678
|
-
const anyE = e;
|
|
679
|
-
const data = anyE.data;
|
|
680
|
-
if (typeof data === "string" && data.startsWith(SELECTOR) && data.length >= 10 + 64) {
|
|
681
|
-
return BigInt("0x" + data.slice(10, 10 + 64));
|
|
682
|
-
}
|
|
683
|
-
for (const k of ["cause", "walk", "error", "details"]) {
|
|
684
|
-
const found = walk(anyE[k]);
|
|
685
|
-
if (found !== null)
|
|
686
|
-
return found;
|
|
687
|
-
}
|
|
688
|
-
return null;
|
|
689
|
-
};
|
|
690
|
-
return walk(err);
|
|
691
|
-
}
|
|
692
719
|
const ZERO_SALT = `0x${"0".repeat(64)}`;
|
|
720
|
+
// ─── the fee list (policy.md §6) ──────────────────────────────────────────────
|
|
721
|
+
/** `FeeParams.FEE_LIST` in bp: the eight swap fees an F pool may be born with. The key carries the index. */
|
|
722
|
+
export const F_FEE_LIST_BP = [1, 2, 5, 10, 20, 50, 100, 200];
|
|
723
|
+
/** The list in WAD (1 bp = 1e14). No zero: the fee-free pool cannot be born. */
|
|
724
|
+
export const F_FEE_LIST = F_FEE_LIST_BP.map((bp) => BigInt(bp) * 10n ** 14n);
|
|
725
|
+
/** The fee at `idx` of the list, WAD. Throws off the list. */
|
|
726
|
+
export function fFeeOf(idx) {
|
|
727
|
+
const fee = Number.isInteger(idx) ? F_FEE_LIST[idx] : undefined;
|
|
728
|
+
if (fee === undefined)
|
|
729
|
+
throw new Error(`logswap: swap fee index ${idx} is off the F fee list (0..${F_FEE_LIST.length - 1})`);
|
|
730
|
+
return fee;
|
|
731
|
+
}
|
|
732
|
+
/** 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). */
|
|
733
|
+
export function fMintFeeIdxOf(swapFeeIdx) {
|
|
734
|
+
fFeeOf(swapFeeIdx);
|
|
735
|
+
return Math.min(swapFeeIdx + 1, F_FEE_LIST.length - 1);
|
|
736
|
+
}
|
|
737
|
+
/** The mint fee, WAD of newly-minted L, a pool born at `swapFeeIdx` charges on outside mints. */
|
|
738
|
+
export function fMintFeeOf(swapFeeIdx) {
|
|
739
|
+
return fFeeOf(fMintFeeIdxOf(swapFeeIdx));
|
|
740
|
+
}
|
|
741
|
+
/** 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. */
|
|
742
|
+
export function fFeeIndexOf(fee) {
|
|
743
|
+
const idx = F_FEE_LIST.indexOf(fee);
|
|
744
|
+
if (idx < 0)
|
|
745
|
+
throw new Error(`logswap: swap fee ${fee} is not on the F fee list (${F_FEE_LIST_BP.join(", ")} bp)`);
|
|
746
|
+
return idx;
|
|
747
|
+
}
|
|
748
|
+
/** Whether a policy's `feeMask` admits `idx`: a bit per index, an empty mask admitting all eight. */
|
|
749
|
+
export function fFeeListed(feeMask, idx) {
|
|
750
|
+
return Number.isInteger(idx) && idx >= 0 && idx < F_FEE_LIST.length && (feeMask === 0 || ((feeMask >> idx) & 1) === 1);
|
|
751
|
+
}
|
|
752
|
+
/** The indices a policy's `feeMask` admits, ascending. */
|
|
753
|
+
export function fFeesAllowed(feeMask) {
|
|
754
|
+
return F_FEE_LIST.map((_, i) => i).filter((i) => fFeeListed(feeMask, i));
|
|
755
|
+
}
|
|
756
|
+
/** The swap fee index of create arguments given either way; both given must agree. */
|
|
757
|
+
export function fPoolSwapFeeIdxOf(a) {
|
|
758
|
+
if (a.swapFeeIdx !== undefined) {
|
|
759
|
+
const fee = fFeeOf(a.swapFeeIdx);
|
|
760
|
+
if (a.swapFee !== undefined && a.swapFee !== fee)
|
|
761
|
+
throw new Error(`logswap: swap fee ${a.swapFee} is not the F fee list's entry ${a.swapFeeIdx} (${fee})`);
|
|
762
|
+
return a.swapFeeIdx;
|
|
763
|
+
}
|
|
764
|
+
if (a.swapFee !== undefined)
|
|
765
|
+
return fFeeIndexOf(a.swapFee);
|
|
766
|
+
throw new Error("logswap: an F pool needs its swap fee — `swapFeeIdx` (into the list) or `swapFee` (WAD, on the list)");
|
|
767
|
+
}
|
|
693
768
|
/** `bytes32` ⇄ short UTF-8 text, for the pool and sponsor labels. */
|
|
694
769
|
export function textToBytes32(text) {
|
|
695
770
|
const b = new TextEncoder().encode(text);
|
|
@@ -711,52 +786,45 @@ export function sortFPoolLegs(bases, ...companions) {
|
|
|
711
786
|
const idx = bases.map((_, i) => i).sort((a, b) => (bases[a].toLowerCase() < bases[b].toLowerCase() ? -1 : 1));
|
|
712
787
|
return { bases: idx.map((i) => bases[i]), companions: companions.map((arr) => idx.map((i) => arr[i])) };
|
|
713
788
|
}
|
|
714
|
-
|
|
789
|
+
/** The key's ABI as `abi.encode(key)` lays it out: what {@link fPoolIdOfKey} hashes. */
|
|
790
|
+
export const F_POOL_KEY_ABI = [
|
|
715
791
|
{
|
|
716
792
|
type: "tuple",
|
|
717
793
|
components: [
|
|
718
794
|
{ name: "quote", type: "address" },
|
|
719
795
|
{ name: "bases", type: "address[]" },
|
|
720
|
-
{ name: "
|
|
796
|
+
{ name: "swapFeeIdx", type: "uint8" },
|
|
721
797
|
{ name: "policy", type: "address" },
|
|
722
|
-
{ name: "creator", type: "address" },
|
|
723
798
|
{ name: "salt", type: "bytes32" },
|
|
724
|
-
{ name: "mintFee", type: "uint256" },
|
|
725
799
|
],
|
|
726
800
|
},
|
|
727
801
|
];
|
|
728
802
|
/**
|
|
729
803
|
* An F pool's id: `keccak256(abi.encode(key))`, offline — what `initialize` computes inline. The
|
|
730
|
-
* manager's `idOf
|
|
731
|
-
*
|
|
732
|
-
* one the pool was initialized with: bases sorted ({@link fPoolKeyOf} sorts them), the birth policy.
|
|
804
|
+
* manager's `idOf` getter was cut in F version 21; this is the same hash (checked against Foundry's encoder in the
|
|
805
|
+
* tests). The key must be the one the pool was initialized with: bases sorted ({@link fPoolKeyOf} sorts them).
|
|
733
806
|
*/
|
|
734
807
|
export function fPoolIdOfKey(key) {
|
|
735
808
|
return keccak256(encodeAbiParameters(F_POOL_KEY_ABI, [key]));
|
|
736
809
|
}
|
|
737
|
-
/** The key as the manager hashes it: bases sorted, the
|
|
810
|
+
/** 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). */
|
|
738
811
|
export function fPoolKeyOf(c, a) {
|
|
739
812
|
const { bases } = sortFPoolLegs(a.bases);
|
|
740
|
-
return {
|
|
741
|
-
quote: a.quote,
|
|
742
|
-
bases,
|
|
743
|
-
swapFee: a.swapFee,
|
|
744
|
-
policy: a.policy ?? fPoolPolicyFor(c, a.kind),
|
|
745
|
-
creator: a.creator,
|
|
746
|
-
salt: a.salt ?? ZERO_SALT,
|
|
747
|
-
mintFee: a.mintFee ?? presetMintFee(a.swapFee),
|
|
748
|
-
};
|
|
813
|
+
return { quote: a.quote, bases, swapFeeIdx: fPoolSwapFeeIdxOf(a), policy: a.policy ?? fPoolPolicyFor(c, a.kind), salt: a.salt ?? ZERO_SALT };
|
|
749
814
|
}
|
|
750
|
-
/**
|
|
815
|
+
/**
|
|
816
|
+
* List the pool — `initialize(key)` (policy.md §9): no funds move; the pool is inactive until its operator funds it
|
|
817
|
+
* ({@link fPoolDeploy}). Anyone under an open policy (salt zero), the policy's authority alone under a closed one
|
|
818
|
+
* (`Refused`); refused past the policy's sunset (`PolicyNotApproved`), off the policy's fee mask (`FeeNotListed`), quote or
|
|
819
|
+
* base list (`QuoteNotListed`, `BaseNotListed`), or with more legs than it allows (`TooManyLegs`). Returns the tx hash;
|
|
820
|
+
* read the id with {@link fPoolIdOf}.
|
|
821
|
+
*/
|
|
751
822
|
export async function fPoolInitialize(c, a) {
|
|
752
823
|
const key = fPoolKeyOf(c, a);
|
|
753
|
-
if (!isValidMintFee(key.swapFee, key.mintFee)) {
|
|
754
|
-
throw new Error(`logswap: mint fee ${key.mintFee} is outside 2 × the swap fee (${2n * key.swapFee}) … ${MINT_FEE_MAX}`);
|
|
755
|
-
}
|
|
756
824
|
const wallet = requireWallet(c);
|
|
757
825
|
const { request } = await c.public.simulateContract({
|
|
758
|
-
address: c.addresses.
|
|
759
|
-
abi:
|
|
826
|
+
address: c.addresses.managerF,
|
|
827
|
+
abi: managerFAbi,
|
|
760
828
|
functionName: "initialize",
|
|
761
829
|
args: [key],
|
|
762
830
|
account: wallet.account,
|
|
@@ -772,41 +840,19 @@ export async function fPoolIdOf(c, a) {
|
|
|
772
840
|
return fPoolIdOfKey(fPoolKeyOf(c, a));
|
|
773
841
|
}
|
|
774
842
|
/**
|
|
775
|
-
* Rebuild a live pool's KEY from its id: the `PoolCreated` log carries every field
|
|
776
|
-
*
|
|
777
|
-
* 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
|
|
778
|
-
* returning a key that names another pool. What {@link fPoolMigrate} needs when handed an id.
|
|
843
|
+
* Rebuild a live pool's KEY from its id: the `PoolCreated` log carries every field, the salt included (F 41). The result
|
|
844
|
+
* is checked against the id.
|
|
779
845
|
*/
|
|
780
846
|
export async function fPoolKeyOfPool(c, poolId, opts = {}) {
|
|
781
|
-
const ev =
|
|
782
|
-
const { logs } = await getEventLogs(c, { indexer: opts.indexer, address: c.addresses.
|
|
847
|
+
const ev = managerFAbi.find((x) => x.type === "event" && x.name === "PoolCreated");
|
|
848
|
+
const { logs } = await getEventLogs(c, { indexer: opts.indexer, address: c.addresses.managerF, event: ev, args: { poolId }, fromBlock: opts.fromBlock });
|
|
783
849
|
const l = logs[0];
|
|
784
850
|
if (!l)
|
|
785
851
|
throw new Error(`logswap: no PoolCreated for F pool ${poolId}`);
|
|
786
852
|
const a = l.args;
|
|
787
|
-
const key = {
|
|
788
|
-
quote: a.quote,
|
|
789
|
-
bases: [...a.bases],
|
|
790
|
-
swapFee: a.swapFee,
|
|
791
|
-
policy: a.policy,
|
|
792
|
-
creator: a.creator,
|
|
793
|
-
salt: opts.salt ?? ZERO_SALT,
|
|
794
|
-
mintFee: a.mintFee,
|
|
795
|
-
};
|
|
796
|
-
if (fPoolIdOfKey(key).toLowerCase() !== poolId.toLowerCase() && opts.salt === undefined) {
|
|
797
|
-
// a pad's salt carries its split (decisions 056): rebuild it from the policy's record with the default nonce
|
|
798
|
-
try {
|
|
799
|
-
const creatorShare = BigInt((await c.public.readContract({ address: a.policy, abi: padPolicyAbi, functionName: "creatorShareOf", args: [poolId] })));
|
|
800
|
-
const padKey = { ...key, salt: padSalt({ creatorShare }) };
|
|
801
|
-
if (fPoolIdOfKey(padKey).toLowerCase() === poolId.toLowerCase())
|
|
802
|
-
return padKey;
|
|
803
|
-
}
|
|
804
|
-
catch {
|
|
805
|
-
/* not a pad: fall through to the error */
|
|
806
|
-
}
|
|
807
|
-
}
|
|
853
|
+
const key = { quote: a.quote, bases: [...a.bases], swapFeeIdx: Number(a.swapFeeIdx), policy: a.policy, salt: a.salt };
|
|
808
854
|
if (fPoolIdOfKey(key).toLowerCase() !== poolId.toLowerCase()) {
|
|
809
|
-
throw new Error(`logswap: F pool ${poolId}
|
|
855
|
+
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`);
|
|
810
856
|
}
|
|
811
857
|
return key;
|
|
812
858
|
}
|
|
@@ -942,78 +988,64 @@ export function fPoolBookL(baseAssets, lnCapOverSeed) {
|
|
|
942
988
|
* carried holder, every other holder is frozen into the closing generation's bundle ({@link fPoolRedeem}), and the
|
|
943
989
|
* carried book becomes the one named, at the supplied prices. A pad is forward-only ({@link fPoolRegenerate}).
|
|
944
990
|
*/
|
|
945
|
-
export async function fPoolDeploy(c, a) {
|
|
946
|
-
const { baseAssets, lnCapOverSeed } = "baseAssets" in a ? a : fPoolBook(a);
|
|
947
|
-
return writeFPool(c, a.poolId, "deployLiquidity", [baseAssets, a.quoteAmount, lnCapOverSeed, a.to ?? a.account], a.account);
|
|
948
|
-
}
|
|
949
991
|
/**
|
|
950
|
-
*
|
|
951
|
-
*
|
|
952
|
-
*
|
|
953
|
-
*
|
|
954
|
-
*
|
|
992
|
+
* Fund the pool — `deployLiquidity(poolId, baseAssets, quoteAmount, lnCapOverSeed)` (policy.md §9): the book of this generation,
|
|
993
|
+
* on an INACTIVE pool — listed and never funded, or closed (`PoolActive` otherwise). The operator's alone (`NotOperator`): it pays
|
|
994
|
+
* every leg's amount and `quoteAmount` by plain allowance to the manager ({@link approveTokenForFPoolManager}) and holds the shares —
|
|
995
|
+
* all but `MIN_SHARES`, which go to 0xdead; every share does on a pad. Refused past the policy's sunset (`PolicyNotApproved`),
|
|
996
|
+
* under its buffer (`QuoteTooThin`), with a cap under its `lnCapMin` (`CapTooClose`). An amount of 0 leaves a leg dormant. Pass the
|
|
997
|
+
* book raw (`baseAssets` + `lnCapOverSeed`) or as a {@link FPoolBookSpec}.
|
|
955
998
|
*/
|
|
956
|
-
export async function
|
|
957
|
-
|
|
999
|
+
export async function fPoolDeploy(c, a) {
|
|
1000
|
+
const { baseAssets, lnCapOverSeed } = "baseAssets" in a ? a : fPoolBook(a);
|
|
1001
|
+
return writeFPool(c, a.poolId, "deployLiquidity", [baseAssets, a.quoteAmount, lnCapOverSeed], a.account);
|
|
958
1002
|
}
|
|
959
1003
|
/**
|
|
960
|
-
* Close the pool
|
|
961
|
-
*
|
|
962
|
-
*
|
|
963
|
-
*
|
|
1004
|
+
* Close the pool (policy.md §9) — at any bid. The manager harvests the income first (a dividend to every share, the operator's
|
|
1005
|
+
* paid to `to`), freezes every reserve and the bid into generation `gen`'s bundle — every share of it redeems pro rata
|
|
1006
|
+
* ({@link fPoolRedeem}), forever — and moves the counter to `gen + 1`, the generation the next {@link fPoolDeploy} opens under
|
|
1007
|
+
* the same id, policy, roles and gates. The operator's alone. Throws before sending on a pad: a pad never closes
|
|
1008
|
+
* (`PadNeverCloses`). Pass `flags` when in hand to save the read.
|
|
964
1009
|
*/
|
|
965
1010
|
export async function fPoolClose(c, a) {
|
|
966
|
-
const
|
|
967
|
-
if (
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
const calls = [...harvests.map((amount) => enc("harvest", [a.poolId, amount, a.account])), enc("close", [a.poolId, a.to ?? a.account])];
|
|
971
|
-
return writeFPool0(c, "multicall", [calls], a.account);
|
|
1011
|
+
const flags = a.flags ?? (await getFPool(c, a.poolId)).flags;
|
|
1012
|
+
if ((flags & SEED_TO_DEAD) !== 0)
|
|
1013
|
+
throw new Error("logswap: a pad never closes (PadNeverCloses) — a fresh start is a new pad");
|
|
1014
|
+
return writeFPool(c, a.poolId, "close", [a.to ?? a.account], a.account);
|
|
972
1015
|
}
|
|
973
1016
|
/**
|
|
974
|
-
* The
|
|
975
|
-
*
|
|
976
|
-
*
|
|
977
|
-
* never closes, whatever its bid), and when the pool's policy keeps a floor on the bid
|
|
978
|
-
* (`PolPolicy.minQuoteRatio`): a `close` under that policy waits for the market.
|
|
1017
|
+
* The relaunch's calls — what `regenerate` was (policy.md §9): `close(poolId, to)`, `redeem(poolId, gen, operator, shares)` for the
|
|
1018
|
+
* operator's own shares of the generation closed (left out at 0), then `deployLiquidity` with the next book. Pure, so a form can show
|
|
1019
|
+
* what it is about to send; {@link fPoolRelaunch} sends them as one `multicall`.
|
|
979
1020
|
*/
|
|
980
|
-
export
|
|
981
|
-
const
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
if (maxHarvest < s.Q)
|
|
989
|
-
throw new Error("logswap: the pool's policy keeps a floor on the bid — it cannot be harvested empty");
|
|
990
|
-
return [s.Q];
|
|
1021
|
+
export function fPoolRelaunchCalls(a) {
|
|
1022
|
+
const { baseAssets, lnCapOverSeed } = "baseAssets" in a ? a : fPoolBook(a);
|
|
1023
|
+
const enc = (functionName, args) => encodeFunctionData({ abi: managerFAbi, functionName, args });
|
|
1024
|
+
const calls = [enc("close", [a.poolId, a.to ?? a.account])];
|
|
1025
|
+
if (a.shares > 0n)
|
|
1026
|
+
calls.push(enc("redeem", [a.poolId, BigInt(a.gen), a.account, a.shares]));
|
|
1027
|
+
calls.push(enc("deployLiquidity", [a.poolId, baseAssets, a.quoteAmount, lnCapOverSeed]));
|
|
1028
|
+
return calls;
|
|
991
1029
|
}
|
|
992
1030
|
/**
|
|
993
|
-
*
|
|
994
|
-
*
|
|
995
|
-
*
|
|
996
|
-
*
|
|
997
|
-
*
|
|
998
|
-
* - the carried holder's and the dead shares' `g` shares are re-minted 1:1 as `g + 1`: they go on
|
|
999
|
-
* as the pool;
|
|
1000
|
-
* - every OTHER holder of `g` is frozen out pro rata into generation `g`'s bundle (`GenerationRetired`)
|
|
1001
|
-
* and redeems it with {@link fPoolRedeem} / rolls it with {@link fPoolRollIn} (`gen: g`); their
|
|
1002
|
-
* dividends on `g` stay claimable ({@link fPoolClaim} with `gen: g`). {@link fPoolClaimsOf}
|
|
1003
|
-
* lists them;
|
|
1004
|
-
* - the income released (`IncomeReleased`), all in quote: `toPayee` to the payee and the rest into the bid
|
|
1005
|
-
* (the floor down). No share is minted; L does not move. The book keeps its reserves, marks and cap.
|
|
1006
|
-
*
|
|
1007
|
-
* A pad's gate is `threshold(poolId, gen)`, in its quote (`PadPolicy.NotGraduated` below it); POL and private carry the
|
|
1008
|
-
* authority and send it the whole income; a public pool refuses (`Refused`). A carried holder with no
|
|
1009
|
-
* share is `BadTerms`. Whoever runs the pool. To change the book (reserves, prices, cap) use {@link fPoolDeploy}.
|
|
1031
|
+
* Relaunch the pool as ONE transaction: close generation `gen`, redeem the operator's own shares of it (its funds come back),
|
|
1032
|
+
* fund `gen + 1` with the book given — the manager's `multicall`, the operator as sender. Every other holder is frozen into the
|
|
1033
|
+
* bundle and redeems it ({@link fPoolRedeem}); the new book may re-weight any of the key's bases and pick its own cap. The
|
|
1034
|
+
* deploy pulls its amounts and `quoteAmount` from the operator in the same transaction the redeem pays it, so the allowances
|
|
1035
|
+
* must cover the pull. Not on a pad (a pad never closes); not on an inactive pool (fund it with {@link fPoolDeploy}).
|
|
1010
1036
|
*/
|
|
1011
|
-
export async function
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1037
|
+
export async function fPoolRelaunch(c, a) {
|
|
1038
|
+
const s = await getFPool(c, a.poolId);
|
|
1039
|
+
if ((s.flags & SEED_TO_DEAD) !== 0)
|
|
1040
|
+
throw new Error("logswap: a pad never closes (PadNeverCloses) — a fresh start is a new pad");
|
|
1041
|
+
if (!s.seeded)
|
|
1042
|
+
throw new Error("logswap: the pool is inactive — nothing to close; fund it with fPoolDeploy");
|
|
1043
|
+
const shares = await fPoolShareBalance(c, a.poolId, a.account, s.gen);
|
|
1044
|
+
return writeFPool0(c, "multicall", [fPoolRelaunchCalls({ ...a, gen: s.gen, shares })], a.account);
|
|
1045
|
+
}
|
|
1046
|
+
/** Where a pad's seed lives: `deployLiquidity` mints every share of a pad here itself. */
|
|
1015
1047
|
export const DEAD_ADDRESS = "0x000000000000000000000000000000000000dEaD";
|
|
1016
|
-
/** The manager's `MIN_SHARES`: the
|
|
1048
|
+
/** 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. */
|
|
1017
1049
|
export const F_MIN_SHARES = 1000n;
|
|
1018
1050
|
/**
|
|
1019
1051
|
* The launch's calls, in order — the batch {@link fPoolLaunch} sends. Pure, so a form can show
|
|
@@ -1026,21 +1058,13 @@ export function fPoolLaunchCalls(poolId, a) {
|
|
|
1026
1058
|
throw new Error("logswap: fPoolLaunchCalls needs the key's policy — fPoolLaunch fills it from the deployment");
|
|
1027
1059
|
const { baseAssets, lnCapOverSeed } = fPoolBook(a);
|
|
1028
1060
|
const bases = baseAssets.map((x) => x.base);
|
|
1029
|
-
const key = {
|
|
1030
|
-
|
|
1031
|
-
bases,
|
|
1032
|
-
swapFee: a.swapFee,
|
|
1033
|
-
policy: a.policy,
|
|
1034
|
-
creator: a.creator,
|
|
1035
|
-
salt: a.salt ?? ZERO_SALT,
|
|
1036
|
-
mintFee: a.mintFee ?? presetMintFee(a.swapFee),
|
|
1037
|
-
};
|
|
1038
|
-
const enc = (functionName, args) => encodeFunctionData({ abi: fPoolManagerAbi, functionName, args });
|
|
1061
|
+
const key = { quote: a.quote, bases, swapFeeIdx: fPoolSwapFeeIdxOf(a), policy: a.policy, salt: a.salt ?? ZERO_SALT };
|
|
1062
|
+
const enc = (functionName, args) => encodeFunctionData({ abi: managerFAbi, functionName, args });
|
|
1039
1063
|
const calls = [];
|
|
1040
1064
|
if (!a.initialized)
|
|
1041
1065
|
calls.push(enc("initialize", [key]));
|
|
1042
|
-
calls.push(enc("deployLiquidity", [poolId, baseAssets, a.quoteAmount, lnCapOverSeed
|
|
1043
|
-
// gen 0 by construction: a launch is the pool's FIRST deployment — a later one is `fPoolDeploy` on the
|
|
1066
|
+
calls.push(enc("deployLiquidity", [poolId, baseAssets, a.quoteAmount, lnCapOverSeed]));
|
|
1067
|
+
// gen 0 by construction: a launch is the pool's FIRST deployment — a later one is `fPoolDeploy` on the closed pool.
|
|
1044
1068
|
// No transfer to 0xdead: on a pad `deployLiquidity` mints every share there itself.
|
|
1045
1069
|
for (const row of fPoolGenesisRows(a)) {
|
|
1046
1070
|
const j = bases.indexOf(a.bases[row.j]);
|
|
@@ -1048,9 +1072,8 @@ export function fPoolLaunchCalls(poolId, a) {
|
|
|
1048
1072
|
throw new Error(`logswap: genesis row j = ${row.j} is not a leg`);
|
|
1049
1073
|
calls.push(enc(row.side === "buy" ? "swapQuoteIn" : "swapBaseIn", [poolId, BigInt(j), row.amountIn, row.minOut ?? 0n, a.account]));
|
|
1050
1074
|
}
|
|
1051
|
-
// the name
|
|
1052
|
-
//
|
|
1053
|
-
// right after, as the same creator
|
|
1075
|
+
// the name and the gate modes are the POLICY's, not the manager's: they cannot ride in this batch — `fPoolLaunch`
|
|
1076
|
+
// sends the name right after, as the same operator; the modes are `fPoolSetSwapMode` / `fPoolSetMintMode`
|
|
1054
1077
|
calls.push(...(a.extra ?? []));
|
|
1055
1078
|
return calls;
|
|
1056
1079
|
}
|
|
@@ -1070,8 +1093,8 @@ export async function fPoolGenesisOutputs(c, poolId, a) {
|
|
|
1070
1093
|
return [];
|
|
1071
1094
|
const calls = fPoolLaunchCalls(poolId, a);
|
|
1072
1095
|
const { result } = await c.public.simulateContract({
|
|
1073
|
-
address: c.addresses.
|
|
1074
|
-
abi:
|
|
1096
|
+
address: c.addresses.managerF,
|
|
1097
|
+
abi: managerFAbi,
|
|
1075
1098
|
functionName: "multicall",
|
|
1076
1099
|
args: [calls],
|
|
1077
1100
|
account: signerFor(c, a.account),
|
|
@@ -1129,33 +1152,21 @@ export async function fPoolWalletBatchesAtomically(c, account) {
|
|
|
1129
1152
|
}
|
|
1130
1153
|
}
|
|
1131
1154
|
/**
|
|
1132
|
-
*
|
|
1133
|
-
*
|
|
1134
|
-
*
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
const policy = a.policy ?? fPoolPolicyFor(c, "private");
|
|
1138
|
-
return [
|
|
1139
|
-
await fPoolSetMintGate(c, { poolId: a.poolId, gated: true, account: a.account, policy }),
|
|
1140
|
-
await fPoolSetMinters(c, { poolId: a.poolId, who: [a.account], allowed: true, account: a.account, policy }),
|
|
1141
|
-
];
|
|
1142
|
-
}
|
|
1143
|
-
/**
|
|
1144
|
-
* Create a pool as ONE transaction: `initialize`, `seed`, the seed lock, the opening buy, the
|
|
1145
|
-
* name, the private-pool gates — the manager's `multicall`, the creator as sender throughout.
|
|
1146
|
-
* Either every call lands or none does; there is no half-built pool to resume.
|
|
1155
|
+
* Create a pool as ONE transaction: `initialize`, `deployLiquidity`, the opening buys — the manager's `multicall`, one sender
|
|
1156
|
+
* throughout. Either every call lands or none does; there is no half-built pool to resume. The sender must be the policy's
|
|
1157
|
+
* AUTHORITY: it is the pool's operator at birth, and `deployLiquidity` is the operator's (`NotOperator`). Under an open
|
|
1158
|
+
* policy anyone may list a pool ({@link fPoolInitialize}) but only the LOG — its authority — funds it, so a launch under the
|
|
1159
|
+
* public policy is the LOG's; a sponsor launches under its own policy.
|
|
1147
1160
|
*
|
|
1148
|
-
* Why the manager and not the router: every one of these entries authenticates by `msg.sender
|
|
1149
|
-
*
|
|
1150
|
-
* — the authority, the holder of the seed shares — and the handover back is two-step, so it
|
|
1151
|
-
* could not even close in the same transaction. `multicall` is delegatecall-to-self, so the
|
|
1152
|
-
* sender survives, which is what the manager's own doc says a router cannot do.
|
|
1161
|
+
* Why the manager and not the router: every one of these entries authenticates by `msg.sender`. Routed, the router would be
|
|
1162
|
+
* the sender — the operator, the holder of the seed shares. `multicall` is delegatecall-to-self, so the sender survives.
|
|
1153
1163
|
*
|
|
1154
|
-
* What the batch PULLS, by plain allowance to the manager (never Permit2): `r0[j]` of each base,
|
|
1155
|
-
*
|
|
1156
|
-
*
|
|
1164
|
+
* What the batch PULLS, by plain allowance to the manager (never Permit2): `r0[j]` of each base, `quoteAmount` of quote, plus
|
|
1165
|
+
* each opening buy's `amountIn` of quote. Grant those first — one `approve` per token, once ever
|
|
1166
|
+
* ({@link approveTokenForFPoolManager}, {@link fPoolManagerAllowanceOk}).
|
|
1157
1167
|
*
|
|
1158
|
-
* Returns the hash and the pool's id (the key's hash, {@link fPoolIdOf}).
|
|
1168
|
+
* Returns the hash and the pool's id (the key's hash, {@link fPoolIdOf}). The name, when given, is a second transaction on
|
|
1169
|
+
* the policy ({@link fPoolSetName}); the gate modes are {@link fPoolSetSwapMode} / {@link fPoolSetMintMode} after it.
|
|
1159
1170
|
*/
|
|
1160
1171
|
export async function fPoolLaunch(c, a) {
|
|
1161
1172
|
const poolId = await fPoolIdOf(c, a);
|
|
@@ -1179,7 +1190,7 @@ export async function fPoolLaunch(c, a) {
|
|
|
1179
1190
|
account: signerFor(c, a.account),
|
|
1180
1191
|
forceAtomic: true,
|
|
1181
1192
|
calls: [
|
|
1182
|
-
{ to: c.addresses.
|
|
1193
|
+
{ to: c.addresses.managerF, data: encodeFunctionData({ abi: managerFAbi, functionName: "multicall", args: [calls] }) },
|
|
1183
1194
|
...transfers.map((t) => ({ to: t.token, data: encodeFunctionData({ abi: erc20Abi, functionName: "transfer", args: [t.to, t.amount] }) })),
|
|
1184
1195
|
],
|
|
1185
1196
|
});
|
|
@@ -1199,82 +1210,67 @@ export async function fPoolLaunch(c, a) {
|
|
|
1199
1210
|
}
|
|
1200
1211
|
// ─── the roles, on the policy ─────────────────────────────────────────────
|
|
1201
1212
|
//
|
|
1202
|
-
// Every write here goes to the pool's POLICY, not the manager: the manager holds no role. `policy`
|
|
1203
|
-
//
|
|
1204
|
-
|
|
1205
|
-
|
|
1213
|
+
// Every write here goes to the pool's POLICY, not the manager: the manager holds no role. `policy` may be passed when in
|
|
1214
|
+
// hand (`FPoolState.policy`, `FPoolRoles.policy`); otherwise it is read once. The policy syncs the manager itself
|
|
1215
|
+
// (`setGates`), which stamps the block: no swap lands in the block of a change (047). Every mode and list write reverts
|
|
1216
|
+
// `GatesUnavailable` on an open policy: a public pool can never be gated.
|
|
1217
|
+
/** A write on a policy. */
|
|
1218
|
+
async function writePolicy(c, policy, functionName, args, account) {
|
|
1206
1219
|
const wallet = requireWallet(c);
|
|
1207
|
-
const
|
|
1208
|
-
const { request } = await c.public.simulateContract({
|
|
1209
|
-
address: policy,
|
|
1210
|
-
abi,
|
|
1211
|
-
functionName,
|
|
1212
|
-
args: [a.poolId, ...args],
|
|
1213
|
-
account: signerFor(c, a.account),
|
|
1214
|
-
});
|
|
1220
|
+
const { request } = await c.public.simulateContract({ address: policy, abi: policyFAbi, functionName, args, account: signerFor(c, account) });
|
|
1215
1221
|
return wallet.writeContract(request);
|
|
1216
1222
|
}
|
|
1217
|
-
/**
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
*/
|
|
1222
|
-
export async function fPoolProposeAuthority(c, a) {
|
|
1223
|
-
return writePolicy(c, fPolicyBaseAbi, a, "proposeAuthority", [a.next]);
|
|
1223
|
+
/** A write keyed by poolId, on the pool's policy. */
|
|
1224
|
+
async function writePoolPolicy(c, a, functionName, args) {
|
|
1225
|
+
const policy = a.policy ?? (await fPoolPolicyOf(c, a.poolId));
|
|
1226
|
+
return writePolicy(c, policy, functionName, [a.poolId, ...args], a.account);
|
|
1224
1227
|
}
|
|
1225
1228
|
/**
|
|
1226
|
-
*
|
|
1227
|
-
*
|
|
1228
|
-
*
|
|
1229
|
+
* Appoint the pool's operator (the AUTHORITY's; zero resets it to the authority): the account that funds, harvests, closes and sets the
|
|
1230
|
+
* 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
|
|
1231
|
+
* a contract (an executor). `InactivePool` on a pool the policy never held.
|
|
1229
1232
|
*/
|
|
1230
|
-
export async function
|
|
1231
|
-
return
|
|
1233
|
+
export async function fPoolAppointOperator(c, a) {
|
|
1234
|
+
return writePoolPolicy(c, a, "appointOperator", [a.operator]);
|
|
1232
1235
|
}
|
|
1233
|
-
// ─── the desk's controls (PrivatePolicy) ───────────────────────────────
|
|
1234
1236
|
/**
|
|
1235
|
-
* Set the
|
|
1236
|
-
*
|
|
1237
|
-
* and must be omitted otherwise. Preserves mint admission. `burn` is never gated.
|
|
1237
|
+
* Set the pool's swap gate (the OPERATOR's): `open`, `listed` (the policy's swap list, {@link fPolicySetRights}; the operator always
|
|
1238
|
+
* passes) or `operator`. The mint mode must stay at least as restrictive (`ModeOrder`). `burn`, `redeem` and `claim` are never gated.
|
|
1238
1239
|
*/
|
|
1239
1240
|
export async function fPoolSetSwapMode(c, a) {
|
|
1240
|
-
return
|
|
1241
|
-
}
|
|
1242
|
-
/** Turn mint admission on or off (the authority, on the desk's policy), preserving the swap mode and its executor. */
|
|
1243
|
-
export async function fPoolSetMintGate(c, a) {
|
|
1244
|
-
return writePolicy(c, privatePolicyAbi, a, "setMintGate", [a.gated]);
|
|
1245
|
-
}
|
|
1246
|
-
/**
|
|
1247
|
-
* Add to or remove from the pool's MINTERS — who may mint, and swap (a zap in is both under one
|
|
1248
|
-
* lock) — in one call (the authority, on the desk's policy). The list is keyed by
|
|
1249
|
-
* the authority that granted it: a handover starts the buyer with an empty one. Stamps the
|
|
1250
|
-
* block: no swap lands in it (047).
|
|
1251
|
-
*/
|
|
1252
|
-
export async function fPoolSetMinters(c, a) {
|
|
1253
|
-
return writePolicy(c, privatePolicyAbi, a, "setMinters", [a.who, a.allowed]);
|
|
1241
|
+
return writePoolPolicy(c, a, "setSwapMode", [MODES.indexOf(a.mode)]);
|
|
1254
1242
|
}
|
|
1255
|
-
/**
|
|
1256
|
-
export async function
|
|
1257
|
-
return
|
|
1243
|
+
/** 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. */
|
|
1244
|
+
export async function fPoolSetMintMode(c, a) {
|
|
1245
|
+
return writePoolPolicy(c, a, "setMintMode", [MODES.indexOf(a.mode)]);
|
|
1258
1246
|
}
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1247
|
+
/** The bits of `PolicyF.rights`: listed for swaps; listed for mints, which implies swaps. */
|
|
1248
|
+
export const RIGHT_SWAP = 1;
|
|
1249
|
+
export const RIGHT_MINT = 2;
|
|
1250
|
+
/** The on-chain bits of a right (`MINT` is written as `MINT | SWAP`, as the policy does). */
|
|
1251
|
+
export function fPolicyRightBits(right) {
|
|
1252
|
+
return right === "none" ? 0 : right === "swap" ? RIGHT_SWAP : RIGHT_SWAP | RIGHT_MINT;
|
|
1262
1253
|
}
|
|
1263
|
-
/**
|
|
1264
|
-
export
|
|
1265
|
-
|
|
1254
|
+
/** The right the bits spell. */
|
|
1255
|
+
export function fPolicyRightOf(bits) {
|
|
1256
|
+
const b = Number(bits);
|
|
1257
|
+
return (b & RIGHT_MINT) !== 0 ? "mint" : (b & RIGHT_SWAP) !== 0 ? "swap" : "none";
|
|
1266
1258
|
}
|
|
1267
|
-
/**
|
|
1268
|
-
|
|
1269
|
-
|
|
1259
|
+
/**
|
|
1260
|
+
* 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
|
|
1261
|
+
* — 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);
|
|
1262
|
+
* the modes are each pool's. Stamps nothing: an address removed in a block can still swap in that block.
|
|
1263
|
+
*/
|
|
1264
|
+
export async function fPolicySetRights(c, a) {
|
|
1265
|
+
return writePolicy(c, a.policy, "setRights", [a.who, fPolicyRightBits(a.right)], a.account);
|
|
1270
1266
|
}
|
|
1271
|
-
/**
|
|
1272
|
-
export async function
|
|
1273
|
-
return
|
|
1267
|
+
/** What `policy` lists `who` for now (`rights`). */
|
|
1268
|
+
export async function fPolicyRightsOf(c, policy, who) {
|
|
1269
|
+
return fPolicyRightOf((await c.public.readContract({ address: policy, abi: policyFAbi, functionName: "rights", args: [who] })));
|
|
1274
1270
|
}
|
|
1275
|
-
/** Label the pool
|
|
1271
|
+
/** Label the pool (the OPERATOR's): a `NameSet` event on the policy, nothing stored — mutable, never identity. At most 31 bytes of UTF-8. */
|
|
1276
1272
|
export async function fPoolSetName(c, a) {
|
|
1277
|
-
return
|
|
1273
|
+
return writePoolPolicy(c, a, "setName", [textToBytes32(a.name)]);
|
|
1278
1274
|
}
|
|
1279
1275
|
/**
|
|
1280
1276
|
* What the PROTOCOL says an address is — "Keyrock" — on the REGISTRY. Only its
|
|
@@ -1305,7 +1301,7 @@ export async function fPoolSponsorName(c, who) {
|
|
|
1305
1301
|
export async function fPoolRegistryOf(c) {
|
|
1306
1302
|
if (c.addresses.policyRegistry)
|
|
1307
1303
|
return c.addresses.policyRegistry;
|
|
1308
|
-
return (await c.public.readContract({ address: c.addresses.
|
|
1304
|
+
return (await c.public.readContract({ address: c.addresses.managerF, abi: managerFAbi, functionName: "registry" }));
|
|
1309
1305
|
}
|
|
1310
1306
|
async function registryAddress(c) {
|
|
1311
1307
|
const registry = await fPoolRegistryOf(c);
|
|
@@ -1313,17 +1309,9 @@ async function registryAddress(c) {
|
|
|
1313
1309
|
throw new Error("logswap: this deployment carries no policy registry");
|
|
1314
1310
|
return registry;
|
|
1315
1311
|
}
|
|
1316
|
-
/** Who
|
|
1312
|
+
/** 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. */
|
|
1317
1313
|
export function fPoolRunners(s) {
|
|
1318
|
-
return s.operator === ZERO_ADDRESS ? [
|
|
1319
|
-
}
|
|
1320
|
-
/**
|
|
1321
|
-
* Grant, replace or revoke the pool operator (the authority, on the desk's policy; decision 073): one optional delegate who may
|
|
1322
|
-
* `harvest`, `retire`, `regenerate` and `setLegs` besides the authority. Immediate, with no acceptance step, so check the
|
|
1323
|
-
* address; the zero address revokes. A handover or a policy move clears it.
|
|
1324
|
-
*/
|
|
1325
|
-
export async function fPoolSetPoolOperator(c, a) {
|
|
1326
|
-
return writePolicy(c, privatePolicyAbi, a, "setPoolOperator", [a.operator]);
|
|
1314
|
+
return s.operator === ZERO_ADDRESS ? [] : [s.operator];
|
|
1327
1315
|
}
|
|
1328
1316
|
/**
|
|
1329
1317
|
* Move shares (ERC-6909 `transfer`) — to another holder, or to `0xdead` to lock them for good.
|
|
@@ -1334,8 +1322,8 @@ export async function fPoolTransferShares(c, a) {
|
|
|
1334
1322
|
const wallet = requireWallet(c);
|
|
1335
1323
|
const gen = a.gen ?? (await fPoolGen(c, a.poolId));
|
|
1336
1324
|
const { request } = await c.public.simulateContract({
|
|
1337
|
-
address: c.addresses.
|
|
1338
|
-
abi:
|
|
1325
|
+
address: c.addresses.managerF,
|
|
1326
|
+
abi: managerFAbi,
|
|
1339
1327
|
functionName: "transfer",
|
|
1340
1328
|
args: [a.to, fPoolShareId(a.poolId, gen), a.shares],
|
|
1341
1329
|
account: signerFor(c, a.account),
|
|
@@ -1343,18 +1331,17 @@ export async function fPoolTransferShares(c, a) {
|
|
|
1343
1331
|
return wallet.writeContract(request);
|
|
1344
1332
|
}
|
|
1345
1333
|
/**
|
|
1346
|
-
* Every F pool ever created, from `PoolCreated` logs alone — plus
|
|
1347
|
-
*
|
|
1348
|
-
*
|
|
1349
|
-
*
|
|
1350
|
-
* a scan from block 0 per call is what made the first load wait on the node.
|
|
1334
|
+
* Every F pool ever created, from `PoolCreated` logs alone — plus the terms of each distinct policy, read once and cached.
|
|
1335
|
+
* Possible only because the event carries the full key (quote, policy, bases, swapFeeIdx, salt) — the poolId is a hash and
|
|
1336
|
+
* could never be inverted; contracts PR #17 exists for exactly this call. With `indexer`, the logs come from it (the node
|
|
1337
|
+
* when it fails): a scan from block 0 per call is what made the first load wait on the node.
|
|
1351
1338
|
*/
|
|
1352
1339
|
export async function discoverFPools(c, opts = {}) {
|
|
1353
|
-
const ev =
|
|
1340
|
+
const ev = managerFAbi.find((x) => x.type === "event" && x.name === "PoolCreated");
|
|
1354
1341
|
if (!ev)
|
|
1355
1342
|
throw new Error("logswap: F PoolCreated event missing from the generated ABI");
|
|
1356
|
-
const deployEv =
|
|
1357
|
-
const range = { indexer: opts.indexer, address: c.addresses.
|
|
1343
|
+
const deployEv = managerFAbi.find((x) => x.type === "event" && x.name === "LiquidityDeployed");
|
|
1344
|
+
const range = { indexer: opts.indexer, address: c.addresses.managerF, fromBlock: opts.fromBlock, toBlock: opts.toBlock };
|
|
1358
1345
|
const [{ logs }, { logs: deploys }] = await Promise.all([
|
|
1359
1346
|
getEventLogs(c, { ...range, event: ev }),
|
|
1360
1347
|
deployEv ? getEventLogs(c, { ...range, event: deployEv }) : Promise.resolve({ logs: [] }),
|
|
@@ -1371,17 +1358,19 @@ export async function discoverFPools(c, opts = {}) {
|
|
|
1371
1358
|
const a = l.args;
|
|
1372
1359
|
const g0 = first.get(a.poolId.toLowerCase());
|
|
1373
1360
|
const kind = await fPoolKindOfPolicy(c, a.policy); // one read per distinct policy, cached
|
|
1361
|
+
const swapFeeIdx = Number(a.swapFeeIdx);
|
|
1374
1362
|
return {
|
|
1375
1363
|
poolId: a.poolId,
|
|
1376
1364
|
quote: a.quote,
|
|
1377
1365
|
bases: [...a.bases],
|
|
1378
1366
|
weights: g0?.weights ?? [],
|
|
1379
|
-
|
|
1380
|
-
|
|
1367
|
+
swapFeeIdx,
|
|
1368
|
+
swapFee: fFeeOf(swapFeeIdx),
|
|
1369
|
+
mintFee: fMintFeeOf(swapFeeIdx),
|
|
1381
1370
|
lnCapOverSeed: g0?.lnCapOverSeed ?? 0,
|
|
1382
1371
|
kind,
|
|
1383
1372
|
policy: a.policy,
|
|
1384
|
-
|
|
1373
|
+
salt: a.salt,
|
|
1385
1374
|
block: l.blockNumber,
|
|
1386
1375
|
seeded: g0 !== undefined,
|
|
1387
1376
|
q0: g0?.q0 ?? 0n,
|
|
@@ -1389,78 +1378,22 @@ export async function discoverFPools(c, opts = {}) {
|
|
|
1389
1378
|
};
|
|
1390
1379
|
}));
|
|
1391
1380
|
}
|
|
1392
|
-
const MAX_U64 = (1n << 64n) - 1n;
|
|
1393
|
-
const MAX_U128 = (1n << 128n) - 1n;
|
|
1394
|
-
/**
|
|
1395
|
-
* The salt that carries a pad's split (`PadPolicy.pack(creatorShare, nonce)`, decisions 056, 067): `creatorShare` in the top 64
|
|
1396
|
-
* bits (a WAD fraction of the income), zero in the next 64 — the burn share's place before F version 28, refused by the policy if
|
|
1397
|
-
* set — and a nonce in the low 128 that tells two otherwise identical pads apart. It is part of the pool's identity, so it is
|
|
1398
|
-
* chosen at launch (`FPoolLaunchArgs.salt`) and never changes; the policy refuses a cut outside its range.
|
|
1399
|
-
*/
|
|
1400
|
-
export function padSalt(s) {
|
|
1401
|
-
const nonce = s.nonce ?? 0n;
|
|
1402
|
-
if (s.burnShare !== undefined && s.burnShare !== 0n)
|
|
1403
|
-
throw new Error("logswap: a pad has no burn share since F version 28 (decision 067)");
|
|
1404
|
-
if (s.creatorShare < 0n || s.creatorShare > MAX_U64)
|
|
1405
|
-
throw new Error("logswap: a pad's creator share is a WAD fraction that fits 64 bits");
|
|
1406
|
-
if (nonce < 0n || nonce > MAX_U128)
|
|
1407
|
-
throw new Error("logswap: a pad salt's nonce fits 128 bits");
|
|
1408
|
-
return `0x${((s.creatorShare << 192n) | nonce).toString(16).padStart(64, "0")}`;
|
|
1409
|
-
}
|
|
1410
|
-
/** The inverse of {@link padSalt}. `burnShare` is the old field's bits, nonzero only on a salt the F version 28 policy refuses. */
|
|
1411
|
-
export function padSplitOfSalt(salt) {
|
|
1412
|
-
const v = BigInt(salt);
|
|
1413
|
-
return { creatorShare: v >> 192n, burnShare: (v >> 128n) & MAX_U64, nonce: v & MAX_U128 };
|
|
1414
|
-
}
|
|
1415
|
-
/** The policy's terms for one pool, by its kind. */
|
|
1416
|
-
export async function getFPoolRules(c, s, roles) {
|
|
1417
|
-
const rd = (abi, functionName, args = []) => c.public.readContract({ address: s.policy, abi, functionName, args });
|
|
1418
|
-
switch (s.kind) {
|
|
1419
|
-
case "pad": {
|
|
1420
|
-
// the rung is the manager's generation (F version 21): a move carries it, nothing to ask the policy
|
|
1421
|
-
const gen = s.gen;
|
|
1422
|
-
const [creatorShare, income, threshold, incomeTaxRate, creatorShareMin, creatorShareMax] = await Promise.all([
|
|
1423
|
-
rd(padPolicyAbi, "creatorShareOf", [s.poolId]).then(BigInt),
|
|
1424
|
-
fPoolDividendOf(c, s.poolId, DEAD_ADDRESS, gen),
|
|
1425
|
-
rd(padPolicyAbi, "threshold", [s.poolId, BigInt(gen)]),
|
|
1426
|
-
rd(padPolicyAbi, "incomeTaxRate"),
|
|
1427
|
-
rd(padPolicyAbi, "creatorShareMin"),
|
|
1428
|
-
rd(padPolicyAbi, "creatorShareMax"),
|
|
1429
|
-
]);
|
|
1430
|
-
const ranges = { creatorShareMin, creatorShareMax };
|
|
1431
|
-
return { kind: "pad", gen, rung: gen, threshold, income, creatorShare, incomeTaxRate, ranges };
|
|
1432
|
-
}
|
|
1433
|
-
case "pol": {
|
|
1434
|
-
const [minQuoteRatio, incomeTaxRate] = await Promise.all([rd(polPolicyAbi, "minQuoteRatio"), rd(polPolicyAbi, "incomeTaxRate")]);
|
|
1435
|
-
return { kind: "pol", minQuoteRatio, incomeTaxRate };
|
|
1436
|
-
}
|
|
1437
|
-
case "public": {
|
|
1438
|
-
return { kind: "public" };
|
|
1439
|
-
}
|
|
1440
|
-
case "private": {
|
|
1441
|
-
const r = roles ?? (await getFPoolRoles(c, s.poolId, s));
|
|
1442
|
-
return { kind: "private", gateMint: r.gateMint, swapMode: r.swapMode, swapExecutor: r.swapExecutor, operator: r.operator };
|
|
1443
|
-
}
|
|
1444
|
-
}
|
|
1445
|
-
}
|
|
1446
1381
|
/**
|
|
1447
|
-
* Every F pool `who`
|
|
1448
|
-
* `
|
|
1449
|
-
* `who` are. `pools` may be passed (from the indexer, say) to skip the log scan.
|
|
1382
|
+
* Every F pool `who` runs (its operator) or sponsors (the authority of its policy) — the policy page's list. `roles` tells
|
|
1383
|
+
* which. `pools` may be passed (from the indexer, say) to skip the log scan.
|
|
1450
1384
|
*/
|
|
1451
1385
|
export async function fPoolsControlledBy(c, who, opts = {}) {
|
|
1452
1386
|
const pools = opts.pools ?? (await discoverFPools(c, { fromBlock: opts.fromBlock }));
|
|
1453
|
-
// the LIVE policy answers for the authority: a moved pool (046) is on another one than its birth's
|
|
1454
1387
|
const states = await Promise.all(pools.map((p) => getFPool(c, p.poolId)));
|
|
1455
|
-
const
|
|
1388
|
+
const roles = await Promise.all(states.map((s) => getFPoolRoles(c, s.poolId, s)));
|
|
1389
|
+
const me = who.toLowerCase();
|
|
1456
1390
|
const out = [];
|
|
1457
1391
|
for (let i = 0; i < pools.length; ++i) {
|
|
1458
|
-
|
|
1392
|
+
const r = roles[i];
|
|
1393
|
+
if (r.operator.toLowerCase() !== me && r.authority.toLowerCase() !== me)
|
|
1459
1394
|
continue;
|
|
1460
1395
|
const state = states[i];
|
|
1461
|
-
|
|
1462
|
-
const rules = await getFPoolRules(c, state, roles);
|
|
1463
|
-
out.push({ pool: pools[i], roles, state, rules });
|
|
1396
|
+
out.push({ pool: pools[i], roles: r, state, terms: await fPolicyTermsOf(c, state.policy) });
|
|
1464
1397
|
}
|
|
1465
1398
|
return out;
|
|
1466
1399
|
}
|
|
@@ -1472,14 +1405,14 @@ export async function fPoolsControlledBy(c, who, opts = {}) {
|
|
|
1472
1405
|
* holder minted before the cut.
|
|
1473
1406
|
*/
|
|
1474
1407
|
export async function fPoolShareHolders(c, poolIdHex, opts = {}) {
|
|
1475
|
-
const ev =
|
|
1408
|
+
const ev = managerFAbi.find((x) => x.type === "event" && x.name === "Transfer");
|
|
1476
1409
|
if (!ev)
|
|
1477
1410
|
throw new Error("logswap: 6909 Transfer event missing from the generated ABI");
|
|
1478
1411
|
const gen = opts.gen ?? (await fPoolGen(c, poolIdHex));
|
|
1479
1412
|
const indexer = opts.indexer ?? c.indexerUrl;
|
|
1480
1413
|
if (indexer) {
|
|
1481
1414
|
try {
|
|
1482
|
-
const rows = await poolHolders(indexer, { condition: { side: "F", poolId: poolIdHex.toLowerCase(), gen: Number(gen), manager: c.addresses.
|
|
1415
|
+
const rows = await poolHolders(indexer, { condition: { side: "F", poolId: poolIdHex.toLowerCase(), gen: Number(gen), manager: c.addresses.managerF.toLowerCase() } });
|
|
1483
1416
|
return rows
|
|
1484
1417
|
.filter((r) => r.balance > 0n)
|
|
1485
1418
|
.map((r) => ({ holder: r.holder, shares: r.balance }))
|
|
@@ -1490,7 +1423,7 @@ export async function fPoolShareHolders(c, poolIdHex, opts = {}) {
|
|
|
1490
1423
|
}
|
|
1491
1424
|
}
|
|
1492
1425
|
const id = fPoolShareId(poolIdHex, gen);
|
|
1493
|
-
const { logs } = await getEventLogs(c, { indexer: opts.indexer, address: c.addresses.
|
|
1426
|
+
const { logs } = await getEventLogs(c, { indexer: opts.indexer, address: c.addresses.managerF, event: ev, args: { id }, fromBlock: opts.fromBlock });
|
|
1494
1427
|
const bal = new Map();
|
|
1495
1428
|
for (const l of logs) {
|
|
1496
1429
|
const a = l.args;
|
|
@@ -1504,13 +1437,13 @@ export async function fPoolShareHolders(c, poolIdHex, opts = {}) {
|
|
|
1504
1437
|
.map(([holder, shares]) => ({ holder: holder, shares }))
|
|
1505
1438
|
.sort((a, b) => (b.shares > a.shares ? 1 : -1));
|
|
1506
1439
|
}
|
|
1507
|
-
/** Every F pool's raw state in one lens call (the manager's `Pool` struct: quote, swapFee, policy, seeded, gen, n,
|
|
1440
|
+
/** 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). */
|
|
1508
1441
|
export async function getFPoolsRaw(c, poolIds) {
|
|
1509
|
-
const {
|
|
1510
|
-
return (await c.public.readContract({ address: c.addresses.
|
|
1442
|
+
const { lensFAbi } = await import("./generated.js");
|
|
1443
|
+
return (await c.public.readContract({ address: c.addresses.lensF, abi: lensFAbi, functionName: "getPools", args: [poolIds] }));
|
|
1511
1444
|
}
|
|
1512
1445
|
/** Share value from the lens — (L + Q)/shares, WAD per share — the same figure as `fPoolShareValue`, from one source. */
|
|
1513
1446
|
export async function shareValueOnChain(c, poolId) {
|
|
1514
|
-
const {
|
|
1515
|
-
return (await c.public.readContract({ address: c.addresses.
|
|
1447
|
+
const { lensFAbi } = await import("./generated.js");
|
|
1448
|
+
return (await c.public.readContract({ address: c.addresses.lensF, abi: lensFAbi, functionName: "shareValue", args: [poolId] }));
|
|
1516
1449
|
}
|