@omnipair/dusk-sdk 2.0.2 → 2.18.0-next.20261106
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 +863 -42
- package/dist/amounts.d.ts +9 -0
- package/dist/amounts.d.ts.map +1 -0
- package/dist/amounts.js +10 -0
- package/dist/amounts.js.map +1 -0
- package/dist/constants.d.ts +68 -27
- package/dist/constants.d.ts.map +1 -1
- package/dist/constants.js +153 -41
- package/dist/constants.js.map +1 -1
- package/dist/delegate.d.ts +97 -0
- package/dist/delegate.d.ts.map +1 -0
- package/dist/delegate.js +152 -0
- package/dist/delegate.js.map +1 -0
- package/dist/dusk.d.ts +14 -0
- package/dist/dusk.d.ts.map +1 -1
- package/dist/dusk.js +22 -0
- package/dist/dusk.js.map +1 -1
- package/dist/get.d.ts +3033 -385
- package/dist/get.d.ts.map +1 -1
- package/dist/get.js +109 -72
- package/dist/get.js.map +1 -1
- package/dist/hash.d.ts +9 -0
- package/dist/hash.d.ts.map +1 -0
- package/dist/hash.js +16 -0
- package/dist/hash.js.map +1 -0
- package/dist/hlp-liquidation-client.d.ts +104 -0
- package/dist/hlp-liquidation-client.d.ts.map +1 -0
- package/dist/hlp-liquidation-client.js +146 -0
- package/dist/hlp-liquidation-client.js.map +1 -0
- package/dist/idl_delegate.d.ts +3 -0
- package/dist/idl_delegate.d.ts.map +1 -0
- package/dist/idl_delegate.js +3 -0
- package/dist/idl_delegate.js.map +1 -0
- package/dist/idl_delegate.json +6268 -0
- package/dist/idl_v2.json +16746 -6676
- package/dist/index.d.ts +23 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +23 -0
- package/dist/index.js.map +1 -1
- package/dist/interest-accounting.d.ts +45 -0
- package/dist/interest-accounting.d.ts.map +1 -0
- package/dist/interest-accounting.js +59 -0
- package/dist/interest-accounting.js.map +1 -0
- package/dist/leverage-actions.d.ts +122 -0
- package/dist/leverage-actions.d.ts.map +1 -0
- package/dist/leverage-actions.js +228 -0
- package/dist/leverage-actions.js.map +1 -0
- package/dist/leverage-margins.d.ts +12 -0
- package/dist/leverage-margins.d.ts.map +1 -0
- package/dist/leverage-margins.js +45 -0
- package/dist/leverage-margins.js.map +1 -0
- package/dist/leverage-preview.d.ts +598 -0
- package/dist/leverage-preview.d.ts.map +1 -0
- package/dist/leverage-preview.js +89 -0
- package/dist/leverage-preview.js.map +1 -0
- package/dist/liquidation-client.d.ts +226 -0
- package/dist/liquidation-client.d.ts.map +1 -0
- package/dist/liquidation-client.js +237 -0
- package/dist/liquidation-client.js.map +1 -0
- package/dist/liquidation.d.ts +72 -0
- package/dist/liquidation.d.ts.map +1 -0
- package/dist/liquidation.js +104 -0
- package/dist/liquidation.js.map +1 -0
- package/dist/lp-naming.d.ts +43 -0
- package/dist/lp-naming.d.ts.map +1 -0
- package/dist/lp-naming.js +81 -0
- package/dist/lp-naming.js.map +1 -0
- package/dist/lp-vanity.d.ts +33 -0
- package/dist/lp-vanity.d.ts.map +1 -0
- package/dist/lp-vanity.js +94 -0
- package/dist/lp-vanity.js.map +1 -0
- package/dist/market-bootstrap.d.ts +109 -0
- package/dist/market-bootstrap.d.ts.map +1 -0
- package/dist/market-bootstrap.js +156 -0
- package/dist/market-bootstrap.js.map +1 -0
- package/dist/market-launch.d.ts +45 -0
- package/dist/market-launch.d.ts.map +1 -0
- package/dist/market-launch.js +76 -0
- package/dist/market-launch.js.map +1 -0
- package/dist/operator-client.d.ts +99 -0
- package/dist/operator-client.d.ts.map +1 -0
- package/dist/operator-client.js +153 -0
- package/dist/operator-client.js.map +1 -0
- package/dist/oracle.d.ts +46 -0
- package/dist/oracle.d.ts.map +1 -0
- package/dist/oracle.js +103 -0
- package/dist/oracle.js.map +1 -0
- package/dist/parameters.d.ts +231 -0
- package/dist/parameters.d.ts.map +1 -0
- package/dist/parameters.js +683 -0
- package/dist/parameters.js.map +1 -0
- package/dist/preview.d.ts +39 -1
- package/dist/preview.d.ts.map +1 -1
- package/dist/preview.js +12 -0
- package/dist/preview.js.map +1 -1
- package/dist/protection.d.ts +48 -0
- package/dist/protection.d.ts.map +1 -0
- package/dist/protection.js +88 -0
- package/dist/protection.js.map +1 -0
- package/dist/risk-pricing.d.ts +12 -0
- package/dist/risk-pricing.d.ts.map +1 -0
- package/dist/risk-pricing.js +23 -0
- package/dist/risk-pricing.js.map +1 -0
- package/dist/simulation.d.ts +45 -0
- package/dist/simulation.d.ts.map +1 -0
- package/dist/simulation.js +106 -0
- package/dist/simulation.js.map +1 -0
- package/dist/tranche-client.d.ts +121 -0
- package/dist/tranche-client.d.ts.map +1 -0
- package/dist/tranche-client.js +185 -0
- package/dist/tranche-client.js.map +1 -0
- package/dist/transfer-fees.d.ts +46 -0
- package/dist/transfer-fees.d.ts.map +1 -0
- package/dist/transfer-fees.js +76 -0
- package/dist/transfer-fees.js.map +1 -0
- package/dist/type-aliases.d.ts +265 -31
- package/dist/type-aliases.d.ts.map +1 -1
- package/dist/types_delegate.d.ts +6275 -0
- package/dist/types_delegate.d.ts.map +1 -0
- package/dist/types_delegate.js +2 -0
- package/dist/types_delegate.js.map +1 -0
- package/dist/types_v2.d.ts +16654 -6584
- package/dist/types_v2.d.ts.map +1 -1
- package/dist/virtual-book/index.d.ts +4 -0
- package/dist/virtual-book/index.d.ts.map +1 -0
- package/dist/virtual-book/index.js +4 -0
- package/dist/virtual-book/index.js.map +1 -0
- package/dist/virtual-book/market.d.ts +619 -0
- package/dist/virtual-book/market.d.ts.map +1 -0
- package/dist/virtual-book/market.js +59 -0
- package/dist/virtual-book/market.js.map +1 -0
- package/dist/virtual-book/projection.d.ts +44 -0
- package/dist/virtual-book/projection.d.ts.map +1 -0
- package/dist/virtual-book/projection.js +229 -0
- package/dist/virtual-book/projection.js.map +1 -0
- package/dist/virtual-book/quotes.d.ts +1263 -0
- package/dist/virtual-book/quotes.d.ts.map +1 -0
- package/dist/virtual-book/quotes.js +233 -0
- package/dist/virtual-book/quotes.js.map +1 -0
- package/dist/write.d.ts +427 -0
- package/dist/write.d.ts.map +1 -1
- package/dist/write.js +970 -26
- package/dist/write.js.map +1 -1
- package/dist/yield-client.d.ts +51 -0
- package/dist/yield-client.d.ts.map +1 -0
- package/dist/yield-client.js +98 -0
- package/dist/yield-client.js.map +1 -0
- package/package.json +11 -4
- package/src/amounts.ts +13 -0
- package/src/constants.ts +220 -46
- package/src/delegate.ts +259 -0
- package/src/dusk.ts +28 -0
- package/src/get.ts +201 -86
- package/src/hash.ts +15 -0
- package/src/hlp-liquidation-client.ts +189 -0
- package/src/idl_delegate.json +6268 -0
- package/src/idl_delegate.ts +3 -0
- package/src/idl_v2.json +16746 -6676
- package/src/index.ts +31 -0
- package/src/interest-accounting.ts +73 -0
- package/src/leverage-actions.ts +216 -0
- package/src/leverage-margins.ts +48 -0
- package/src/leverage-preview.ts +86 -0
- package/src/liquidation-client.ts +295 -0
- package/src/liquidation.ts +119 -0
- package/src/lp-naming.ts +127 -0
- package/src/lp-vanity.ts +135 -0
- package/src/market-bootstrap.ts +271 -0
- package/src/market-launch.ts +103 -0
- package/src/operator-client.ts +169 -0
- package/src/oracle.ts +120 -0
- package/src/parameters.ts +1019 -0
- package/src/preview.ts +53 -1
- package/src/protection.ts +112 -0
- package/src/risk-pricing.ts +26 -0
- package/src/simulation.ts +169 -0
- package/src/tranche-client.ts +187 -0
- package/src/transfer-fees.ts +99 -0
- package/src/type-aliases.ts +294 -32
- package/src/types_delegate.ts +6274 -0
- package/src/types_v2.ts +16745 -6675
- package/src/virtual-book/index.ts +3 -0
- package/src/virtual-book/market.ts +76 -0
- package/src/virtual-book/projection.ts +265 -0
- package/src/virtual-book/quotes.ts +308 -0
- package/src/write.ts +1650 -28
- package/src/yield-client.ts +117 -0
|
@@ -0,0 +1,1019 @@
|
|
|
1
|
+
import * as anchorNamespace from "@coral-xyz/anchor";
|
|
2
|
+
import { type BN } from "@coral-xyz/anchor";
|
|
3
|
+
|
|
4
|
+
import {
|
|
5
|
+
MAX_PROPOSAL_DESCRIPTION_BYTES,
|
|
6
|
+
MAX_PROPOSAL_DESCRIPTION_URI_BYTES,
|
|
7
|
+
MAX_PROPOSAL_TITLE_BYTES,
|
|
8
|
+
PROPOSAL_METADATA_VERSION,
|
|
9
|
+
} from "./constants.js";
|
|
10
|
+
import { sha256 } from "./hash.js";
|
|
11
|
+
|
|
12
|
+
import type { IntegerLike } from "./referral.js";
|
|
13
|
+
export type { IntegerLike } from "./referral.js";
|
|
14
|
+
const BPS_DENOMINATOR = 10_000;
|
|
15
|
+
|
|
16
|
+
export const NAD = 1_000_000_000n;
|
|
17
|
+
export const MIN_PARAMETER_HALF_LIFE_MS = 60_000n;
|
|
18
|
+
export const MAX_PARAMETER_HALF_LIFE_MS = 12n * 60n * 60n * 1_000n;
|
|
19
|
+
export const MAX_PARAMETER_FEE_BPS = 5_000;
|
|
20
|
+
export const MAX_CONCENTRATION_AMPLIFICATION_NAD = 2_000n * NAD;
|
|
21
|
+
export const MAX_FEE_COEFFICIENT_NAD = 100n * NAD;
|
|
22
|
+
export const MAX_VOLATILITY_ACCUMULATOR_NAD = 10n * NAD;
|
|
23
|
+
export const MAX_DAILY_BORROW_BPS = 3_000;
|
|
24
|
+
export const MIN_CENTER_ADJUSTMENT_NAD = NAD / 1_000_000n;
|
|
25
|
+
export const MAX_CENTER_ADJUSTMENT_NAD = NAD / 10n;
|
|
26
|
+
export const MAX_LAUNCH_FEE_DURATION_SECONDS = 30n * 24n * 60n * 60n;
|
|
27
|
+
export const LAUNCH_FEE_DECAY_DISABLED = 0;
|
|
28
|
+
export const LAUNCH_FEE_DECAY_LINEAR = 1;
|
|
29
|
+
export const LAUNCH_FEE_DECAY_EXPONENTIAL = 2;
|
|
30
|
+
export const LAUNCH_RATE_LIMIT_ASSET_DISABLED = 0;
|
|
31
|
+
export const LAUNCH_RATE_LIMIT_ASSET_BASE = 1;
|
|
32
|
+
export const LAUNCH_RATE_LIMIT_ASSET_QUOTE = 2;
|
|
33
|
+
export const SWAP_FEE_COLLECT_INPUT_ASSET = 0;
|
|
34
|
+
export const SWAP_FEE_COLLECT_BASE_ONLY = 1;
|
|
35
|
+
export const SWAP_FEE_COLLECT_QUOTE_ONLY = 2;
|
|
36
|
+
export const MAX_LAUNCH_MARKET_FEE_PERIODS = 64;
|
|
37
|
+
export const MIN_JUNIOR_INCOME_SHARE_BPS = 1_000;
|
|
38
|
+
export const MAX_JUNIOR_INCOME_SHARE_BPS = 9_000;
|
|
39
|
+
/** Operator parameter families, and the length of a market's revision list. */
|
|
40
|
+
export const PARAMETER_FAMILY_COUNT = 7;
|
|
41
|
+
export const JUNIOR_EXIT_REQUEST_FEE_BPS = 50;
|
|
42
|
+
export const LIQUIDATION_FEE_BPS = 300;
|
|
43
|
+
/** A proposal changes one to seven families, each at most once. */
|
|
44
|
+
export const MAX_PARAMETER_UPDATES_PER_PROPOSAL = PARAMETER_FAMILY_COUNT;
|
|
45
|
+
|
|
46
|
+
const U64_MAX = 0xffff_ffff_ffff_ffffn;
|
|
47
|
+
|
|
48
|
+
// `@coral-xyz/anchor` ships both a CommonJS and an ESM build, and they disagree
|
|
49
|
+
// about how `BN` is reachable: bundlers resolve the ESM build, which has no
|
|
50
|
+
// default export, while Node's CJS interop exposes `BN` only through `default`.
|
|
51
|
+
// Reading both keeps this module importable from a browser bundle and from Node.
|
|
52
|
+
type AnchorBNConstructor = new (value: string) => BN;
|
|
53
|
+
const anchorExports = anchorNamespace as unknown as {
|
|
54
|
+
BN?: AnchorBNConstructor;
|
|
55
|
+
default?: { BN?: AnchorBNConstructor };
|
|
56
|
+
};
|
|
57
|
+
const AnchorBN = (anchorExports.BN ?? anchorExports.default?.BN) as AnchorBNConstructor;
|
|
58
|
+
|
|
59
|
+
export interface FeeProfileInput {
|
|
60
|
+
baseFeeBps: number;
|
|
61
|
+
divergenceFeeShareCapBps: number;
|
|
62
|
+
volatilityFeeShareCapBps: number;
|
|
63
|
+
divergenceFeeCoefficientNad: IntegerLike;
|
|
64
|
+
volatilityFeeCoefficientNad: IntegerLike;
|
|
65
|
+
volatilityHalfLifeMs: IntegerLike;
|
|
66
|
+
volatilityShockCapNad: IntegerLike;
|
|
67
|
+
volatilityAccumulatorCapNad: IntegerLike;
|
|
68
|
+
swapFeeCollectMode?: number;
|
|
69
|
+
/** LP-owned swap-fee share compounded into reserve principal, in bps. */
|
|
70
|
+
compoundingFeeBps?: number;
|
|
71
|
+
launchFeeStartBps?: number;
|
|
72
|
+
launchFeeDurationSeconds?: IntegerLike;
|
|
73
|
+
launchFeeDecayMode?: number;
|
|
74
|
+
launchMarketPriceStepBps?: number;
|
|
75
|
+
launchMarketNumberOfPeriods?: number;
|
|
76
|
+
launchMarketReductionFactorBps?: number;
|
|
77
|
+
launchRateLimitAsset?: number;
|
|
78
|
+
launchRateLimitReferenceNad?: IntegerLike;
|
|
79
|
+
launchRateLimitIncrementBps?: number;
|
|
80
|
+
launchRateLimitMaxFeeBps?: number;
|
|
81
|
+
launchRateLimitDurationSeconds?: IntegerLike;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export interface FeeProfile {
|
|
85
|
+
baseFeeBps: number;
|
|
86
|
+
divergenceFeeShareCapBps: number;
|
|
87
|
+
volatilityFeeShareCapBps: number;
|
|
88
|
+
divergenceFeeCoefficientNad: BN;
|
|
89
|
+
volatilityFeeCoefficientNad: BN;
|
|
90
|
+
volatilityHalfLifeMs: BN;
|
|
91
|
+
volatilityShockCapNad: BN;
|
|
92
|
+
volatilityAccumulatorCapNad: BN;
|
|
93
|
+
swapFeeCollectMode: number;
|
|
94
|
+
compoundingFeeBps: number;
|
|
95
|
+
launchFeeStartBps: number;
|
|
96
|
+
launchFeeDurationSeconds: BN;
|
|
97
|
+
launchFeeDecayMode: number;
|
|
98
|
+
launchMarketPriceStepBps: number;
|
|
99
|
+
launchMarketNumberOfPeriods: number;
|
|
100
|
+
launchMarketReductionFactorBps: number;
|
|
101
|
+
launchRateLimitAsset: number;
|
|
102
|
+
launchRateLimitReferenceNad: BN;
|
|
103
|
+
launchRateLimitIncrementBps: number;
|
|
104
|
+
launchRateLimitMaxFeeBps: number;
|
|
105
|
+
launchRateLimitDurationSeconds: BN;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export interface IrmUpdateInput {
|
|
109
|
+
lowerSignalNad: IntegerLike;
|
|
110
|
+
upperSignalNad: IntegerLike;
|
|
111
|
+
halfLifeMs: IntegerLike;
|
|
112
|
+
borrowUtilizationLimitBps: number;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export interface IrmUpdate {
|
|
116
|
+
lowerSignalNad: BN;
|
|
117
|
+
upperSignalNad: BN;
|
|
118
|
+
halfLifeMs: BN;
|
|
119
|
+
borrowUtilizationLimitBps: number;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export type ParameterUpdate =
|
|
123
|
+
| { kind: "fee"; profile: FeeProfile }
|
|
124
|
+
| {
|
|
125
|
+
kind: "concentration";
|
|
126
|
+
peakAmplificationNad: BN;
|
|
127
|
+
coreHalfWidthBps: number;
|
|
128
|
+
fadeWidthBps: number;
|
|
129
|
+
rampDurationSlots: BN;
|
|
130
|
+
}
|
|
131
|
+
| { kind: "irm"; config: IrmUpdate }
|
|
132
|
+
| {
|
|
133
|
+
kind: "emaHalfLives";
|
|
134
|
+
priceMs: BN;
|
|
135
|
+
directionalPriceMs: BN;
|
|
136
|
+
curveDepthMs: BN;
|
|
137
|
+
centerPriceMs: BN;
|
|
138
|
+
}
|
|
139
|
+
| { kind: "dailyBorrowLimit"; maxDailyBorrowBps: number }
|
|
140
|
+
| {
|
|
141
|
+
kind: "centerController";
|
|
142
|
+
adjustmentStepNad: BN;
|
|
143
|
+
}
|
|
144
|
+
| {
|
|
145
|
+
kind: "tranche";
|
|
146
|
+
juniorIncomeShareBps: number;
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
export type ParameterFamilyName = ParameterUpdate["kind"];
|
|
150
|
+
export type ParameterFamilyCode = 0 | 1 | 2 | 3 | 4 | 5 | 6;
|
|
151
|
+
|
|
152
|
+
export interface ProposalMetadataV1 {
|
|
153
|
+
version: number;
|
|
154
|
+
title: string;
|
|
155
|
+
descriptionUri: string;
|
|
156
|
+
descriptionSha256: number[];
|
|
157
|
+
descriptionLen: number;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
export type ProposalMarkdown = string | Uint8Array;
|
|
161
|
+
|
|
162
|
+
export interface ProposalDescriptionUploadContext {
|
|
163
|
+
readonly title: string;
|
|
164
|
+
readonly contentType: "text/markdown; charset=utf-8";
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
export type ProposalDescriptionUploader = (
|
|
168
|
+
exactMarkdownBytes: Uint8Array,
|
|
169
|
+
context: ProposalDescriptionUploadContext
|
|
170
|
+
) => Promise<string | { uri: string }>;
|
|
171
|
+
|
|
172
|
+
export type ProposalFetch = (input: string | URL, init?: RequestInit) => Promise<Response>;
|
|
173
|
+
export type ProposalUriResolver = (uri: string) => string | URL | Promise<string | URL>;
|
|
174
|
+
|
|
175
|
+
export interface ProposalDescriptionFetchOptions {
|
|
176
|
+
fetch?: ProposalFetch;
|
|
177
|
+
resolveUri?: ProposalUriResolver;
|
|
178
|
+
signal?: AbortSignal;
|
|
179
|
+
ipfsGateway?: string;
|
|
180
|
+
arweaveGateway?: string;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
export interface VerifiedProposalDescription {
|
|
184
|
+
verified: true;
|
|
185
|
+
uri: string;
|
|
186
|
+
markdown: string;
|
|
187
|
+
bytes: Uint8Array;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
export type ProposalDescriptionResult =
|
|
191
|
+
| VerifiedProposalDescription
|
|
192
|
+
| {
|
|
193
|
+
verified: false;
|
|
194
|
+
uri: string;
|
|
195
|
+
warning: string;
|
|
196
|
+
error: unknown;
|
|
197
|
+
};
|
|
198
|
+
|
|
199
|
+
export interface CreateProposalMetadataInput extends ProposalDescriptionFetchOptions {
|
|
200
|
+
title: string;
|
|
201
|
+
markdown: ProposalMarkdown;
|
|
202
|
+
descriptionUri: string;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
export interface UploadProposalMetadataInput extends ProposalDescriptionFetchOptions {
|
|
206
|
+
title: string;
|
|
207
|
+
markdown: ProposalMarkdown;
|
|
208
|
+
upload: ProposalDescriptionUploader;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
export function feeParameterUpdate(input: FeeProfileInput): ParameterUpdate {
|
|
212
|
+
assertBps(input.baseFeeBps, "baseFeeBps", MAX_PARAMETER_FEE_BPS);
|
|
213
|
+
assertBps(
|
|
214
|
+
input.divergenceFeeShareCapBps,
|
|
215
|
+
"divergenceFeeShareCapBps",
|
|
216
|
+
MAX_PARAMETER_FEE_BPS
|
|
217
|
+
);
|
|
218
|
+
assertBps(
|
|
219
|
+
input.volatilityFeeShareCapBps,
|
|
220
|
+
"volatilityFeeShareCapBps",
|
|
221
|
+
MAX_PARAMETER_FEE_BPS
|
|
222
|
+
);
|
|
223
|
+
if (
|
|
224
|
+
input.baseFeeBps +
|
|
225
|
+
input.divergenceFeeShareCapBps +
|
|
226
|
+
input.volatilityFeeShareCapBps >
|
|
227
|
+
MAX_PARAMETER_FEE_BPS
|
|
228
|
+
) {
|
|
229
|
+
throw new Error(`fee component caps must sum to at most ${MAX_PARAMETER_FEE_BPS} bps`);
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
const divergenceFeeCoefficientNad = toU64BigInt(
|
|
233
|
+
input.divergenceFeeCoefficientNad,
|
|
234
|
+
"divergenceFeeCoefficientNad"
|
|
235
|
+
);
|
|
236
|
+
const volatilityFeeCoefficientNad = toU64BigInt(
|
|
237
|
+
input.volatilityFeeCoefficientNad,
|
|
238
|
+
"volatilityFeeCoefficientNad"
|
|
239
|
+
);
|
|
240
|
+
const volatilityHalfLifeMs = assertRange(
|
|
241
|
+
toU64BigInt(input.volatilityHalfLifeMs, "volatilityHalfLifeMs"),
|
|
242
|
+
MIN_PARAMETER_HALF_LIFE_MS,
|
|
243
|
+
MAX_PARAMETER_HALF_LIFE_MS,
|
|
244
|
+
"volatilityHalfLifeMs"
|
|
245
|
+
);
|
|
246
|
+
const volatilityShockCapNad = toU64BigInt(
|
|
247
|
+
input.volatilityShockCapNad,
|
|
248
|
+
"volatilityShockCapNad"
|
|
249
|
+
);
|
|
250
|
+
const volatilityAccumulatorCapNad = toU64BigInt(
|
|
251
|
+
input.volatilityAccumulatorCapNad,
|
|
252
|
+
"volatilityAccumulatorCapNad"
|
|
253
|
+
);
|
|
254
|
+
assertRange(
|
|
255
|
+
divergenceFeeCoefficientNad,
|
|
256
|
+
0n,
|
|
257
|
+
MAX_FEE_COEFFICIENT_NAD,
|
|
258
|
+
"divergenceFeeCoefficientNad"
|
|
259
|
+
);
|
|
260
|
+
assertRange(
|
|
261
|
+
volatilityFeeCoefficientNad,
|
|
262
|
+
0n,
|
|
263
|
+
MAX_FEE_COEFFICIENT_NAD,
|
|
264
|
+
"volatilityFeeCoefficientNad"
|
|
265
|
+
);
|
|
266
|
+
const signalDisabled = volatilityShockCapNad === 0n && volatilityAccumulatorCapNad === 0n;
|
|
267
|
+
const signalValid =
|
|
268
|
+
volatilityShockCapNad > 0n &&
|
|
269
|
+
volatilityShockCapNad <= volatilityAccumulatorCapNad &&
|
|
270
|
+
volatilityAccumulatorCapNad <= MAX_VOLATILITY_ACCUMULATOR_NAD;
|
|
271
|
+
if (!signalDisabled && !signalValid) {
|
|
272
|
+
throw new Error(
|
|
273
|
+
"volatility caps must both be zero, or shock > 0, shock <= accumulator, and accumulator <= 10 NAD"
|
|
274
|
+
);
|
|
275
|
+
}
|
|
276
|
+
if (volatilityFeeCoefficientNad !== 0n && !signalValid) {
|
|
277
|
+
throw new Error("a nonzero volatility fee coefficient requires an enabled volatility signal");
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
const swapFeeCollectMode =
|
|
281
|
+
input.swapFeeCollectMode ?? SWAP_FEE_COLLECT_INPUT_ASSET;
|
|
282
|
+
if (
|
|
283
|
+
![
|
|
284
|
+
SWAP_FEE_COLLECT_INPUT_ASSET,
|
|
285
|
+
SWAP_FEE_COLLECT_BASE_ONLY,
|
|
286
|
+
SWAP_FEE_COLLECT_QUOTE_ONLY,
|
|
287
|
+
].includes(swapFeeCollectMode)
|
|
288
|
+
) {
|
|
289
|
+
throw new Error("invalid swap fee collection mode");
|
|
290
|
+
}
|
|
291
|
+
const compoundingFeeBps = input.compoundingFeeBps ?? 0;
|
|
292
|
+
assertBps(
|
|
293
|
+
compoundingFeeBps,
|
|
294
|
+
"compoundingFeeBps",
|
|
295
|
+
BPS_DENOMINATOR
|
|
296
|
+
);
|
|
297
|
+
|
|
298
|
+
const launchFeeStartBps = input.launchFeeStartBps ?? 0;
|
|
299
|
+
const launchFeeDurationSeconds = toU64BigInt(
|
|
300
|
+
input.launchFeeDurationSeconds ?? 0,
|
|
301
|
+
"launchFeeDurationSeconds"
|
|
302
|
+
);
|
|
303
|
+
const launchFeeDecayMode = input.launchFeeDecayMode ?? LAUNCH_FEE_DECAY_DISABLED;
|
|
304
|
+
const launchMarketPriceStepBps = input.launchMarketPriceStepBps ?? 0;
|
|
305
|
+
const launchMarketNumberOfPeriods = input.launchMarketNumberOfPeriods ?? 0;
|
|
306
|
+
const launchMarketReductionFactorBps = input.launchMarketReductionFactorBps ?? 0;
|
|
307
|
+
const marketScheduleDisabled =
|
|
308
|
+
launchMarketPriceStepBps === 0 &&
|
|
309
|
+
launchMarketNumberOfPeriods === 0 &&
|
|
310
|
+
launchMarketReductionFactorBps === 0;
|
|
311
|
+
const marketScheduleEnabled =
|
|
312
|
+
launchMarketPriceStepBps > 0 &&
|
|
313
|
+
launchMarketNumberOfPeriods > 0 &&
|
|
314
|
+
launchMarketNumberOfPeriods <= MAX_LAUNCH_MARKET_FEE_PERIODS &&
|
|
315
|
+
launchMarketReductionFactorBps > 0 &&
|
|
316
|
+
launchMarketReductionFactorBps < BPS_DENOMINATOR;
|
|
317
|
+
const launchFeeDisabled =
|
|
318
|
+
launchFeeStartBps === 0 &&
|
|
319
|
+
launchFeeDurationSeconds === 0n &&
|
|
320
|
+
launchFeeDecayMode === LAUNCH_FEE_DECAY_DISABLED &&
|
|
321
|
+
marketScheduleDisabled;
|
|
322
|
+
if (
|
|
323
|
+
!launchFeeDisabled &&
|
|
324
|
+
(launchFeeStartBps <= input.baseFeeBps ||
|
|
325
|
+
launchFeeStartBps > MAX_PARAMETER_FEE_BPS ||
|
|
326
|
+
launchFeeDurationSeconds < 1n ||
|
|
327
|
+
launchFeeDurationSeconds > MAX_LAUNCH_FEE_DURATION_SECONDS ||
|
|
328
|
+
![LAUNCH_FEE_DECAY_LINEAR, LAUNCH_FEE_DECAY_EXPONENTIAL].includes(
|
|
329
|
+
launchFeeDecayMode
|
|
330
|
+
))
|
|
331
|
+
) {
|
|
332
|
+
throw new Error("invalid launch fee start, duration, or decay mode");
|
|
333
|
+
}
|
|
334
|
+
if (!launchFeeDisabled && !marketScheduleDisabled && !marketScheduleEnabled) {
|
|
335
|
+
throw new Error("invalid launch market-cap fee schedule");
|
|
336
|
+
}
|
|
337
|
+
if (
|
|
338
|
+
marketScheduleEnabled &&
|
|
339
|
+
![SWAP_FEE_COLLECT_BASE_ONLY, SWAP_FEE_COLLECT_QUOTE_ONLY].includes(
|
|
340
|
+
swapFeeCollectMode
|
|
341
|
+
)
|
|
342
|
+
) {
|
|
343
|
+
throw new Error("a market-cap fee schedule requires a fixed fee asset");
|
|
344
|
+
}
|
|
345
|
+
if (
|
|
346
|
+
!launchFeeDisabled &&
|
|
347
|
+
launchFeeStartBps + input.divergenceFeeShareCapBps + input.volatilityFeeShareCapBps >
|
|
348
|
+
MAX_PARAMETER_FEE_BPS
|
|
349
|
+
) {
|
|
350
|
+
throw new Error(`launch fee component caps must sum to at most ${MAX_PARAMETER_FEE_BPS} bps`);
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
const launchRateLimitAsset =
|
|
354
|
+
input.launchRateLimitAsset ?? LAUNCH_RATE_LIMIT_ASSET_DISABLED;
|
|
355
|
+
const launchRateLimitReferenceNad = toU64BigInt(
|
|
356
|
+
input.launchRateLimitReferenceNad ?? 0,
|
|
357
|
+
"launchRateLimitReferenceNad"
|
|
358
|
+
);
|
|
359
|
+
const launchRateLimitIncrementBps = input.launchRateLimitIncrementBps ?? 0;
|
|
360
|
+
const launchRateLimitMaxFeeBps = input.launchRateLimitMaxFeeBps ?? 0;
|
|
361
|
+
const launchRateLimitDurationSeconds = toU64BigInt(
|
|
362
|
+
input.launchRateLimitDurationSeconds ?? 0,
|
|
363
|
+
"launchRateLimitDurationSeconds"
|
|
364
|
+
);
|
|
365
|
+
const rateLimitDisabled =
|
|
366
|
+
launchRateLimitAsset === LAUNCH_RATE_LIMIT_ASSET_DISABLED &&
|
|
367
|
+
launchRateLimitReferenceNad === 0n &&
|
|
368
|
+
launchRateLimitIncrementBps === 0 &&
|
|
369
|
+
launchRateLimitMaxFeeBps === 0 &&
|
|
370
|
+
launchRateLimitDurationSeconds === 0n;
|
|
371
|
+
const scheduledPeak = launchFeeDisabled ? input.baseFeeBps : launchFeeStartBps;
|
|
372
|
+
if (
|
|
373
|
+
!rateLimitDisabled &&
|
|
374
|
+
(![LAUNCH_RATE_LIMIT_ASSET_BASE, LAUNCH_RATE_LIMIT_ASSET_QUOTE].includes(
|
|
375
|
+
launchRateLimitAsset
|
|
376
|
+
) ||
|
|
377
|
+
launchRateLimitReferenceNad === 0n ||
|
|
378
|
+
launchRateLimitIncrementBps <= 0 ||
|
|
379
|
+
launchRateLimitMaxFeeBps <= input.baseFeeBps ||
|
|
380
|
+
launchRateLimitMaxFeeBps < scheduledPeak ||
|
|
381
|
+
launchRateLimitDurationSeconds < 1n ||
|
|
382
|
+
launchRateLimitDurationSeconds > MAX_LAUNCH_FEE_DURATION_SECONDS)
|
|
383
|
+
) {
|
|
384
|
+
throw new Error("invalid launch buy-size limiter configuration");
|
|
385
|
+
}
|
|
386
|
+
if (!rateLimitDisabled) {
|
|
387
|
+
assertBps(
|
|
388
|
+
launchRateLimitIncrementBps,
|
|
389
|
+
"launchRateLimitIncrementBps",
|
|
390
|
+
MAX_PARAMETER_FEE_BPS,
|
|
391
|
+
1
|
|
392
|
+
);
|
|
393
|
+
assertBps(
|
|
394
|
+
launchRateLimitMaxFeeBps,
|
|
395
|
+
"launchRateLimitMaxFeeBps",
|
|
396
|
+
MAX_PARAMETER_FEE_BPS,
|
|
397
|
+
1
|
|
398
|
+
);
|
|
399
|
+
if (
|
|
400
|
+
launchRateLimitMaxFeeBps +
|
|
401
|
+
input.divergenceFeeShareCapBps +
|
|
402
|
+
input.volatilityFeeShareCapBps >
|
|
403
|
+
MAX_PARAMETER_FEE_BPS
|
|
404
|
+
) {
|
|
405
|
+
throw new Error(
|
|
406
|
+
`rate-limit fee component caps must sum to at most ${MAX_PARAMETER_FEE_BPS} bps`
|
|
407
|
+
);
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
return {
|
|
412
|
+
kind: "fee",
|
|
413
|
+
profile: {
|
|
414
|
+
baseFeeBps: input.baseFeeBps,
|
|
415
|
+
divergenceFeeShareCapBps: input.divergenceFeeShareCapBps,
|
|
416
|
+
volatilityFeeShareCapBps: input.volatilityFeeShareCapBps,
|
|
417
|
+
divergenceFeeCoefficientNad: toBN(divergenceFeeCoefficientNad),
|
|
418
|
+
volatilityFeeCoefficientNad: toBN(volatilityFeeCoefficientNad),
|
|
419
|
+
volatilityHalfLifeMs: toBN(volatilityHalfLifeMs),
|
|
420
|
+
volatilityShockCapNad: toBN(volatilityShockCapNad),
|
|
421
|
+
volatilityAccumulatorCapNad: toBN(volatilityAccumulatorCapNad),
|
|
422
|
+
swapFeeCollectMode,
|
|
423
|
+
compoundingFeeBps,
|
|
424
|
+
launchFeeStartBps,
|
|
425
|
+
launchFeeDurationSeconds: toBN(launchFeeDurationSeconds),
|
|
426
|
+
launchFeeDecayMode,
|
|
427
|
+
launchMarketPriceStepBps,
|
|
428
|
+
launchMarketNumberOfPeriods,
|
|
429
|
+
launchMarketReductionFactorBps,
|
|
430
|
+
launchRateLimitAsset,
|
|
431
|
+
launchRateLimitReferenceNad: toBN(launchRateLimitReferenceNad),
|
|
432
|
+
launchRateLimitIncrementBps,
|
|
433
|
+
launchRateLimitMaxFeeBps,
|
|
434
|
+
launchRateLimitDurationSeconds: toBN(launchRateLimitDurationSeconds),
|
|
435
|
+
},
|
|
436
|
+
};
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
/** Standard launch-token fee template: Base is sold and all swap revenue is Quote. */
|
|
440
|
+
export function standardLaunchFeeParameterUpdate(
|
|
441
|
+
input: Omit<FeeProfileInput, "swapFeeCollectMode" | "launchRateLimitAsset">
|
|
442
|
+
): ParameterUpdate {
|
|
443
|
+
return feeParameterUpdate({
|
|
444
|
+
...input,
|
|
445
|
+
swapFeeCollectMode: SWAP_FEE_COLLECT_QUOTE_ONLY,
|
|
446
|
+
launchRateLimitAsset: LAUNCH_RATE_LIMIT_ASSET_BASE,
|
|
447
|
+
});
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
/** Build an atomic, protected concentration update. */
|
|
451
|
+
export function concentrationParameterUpdate(input: {
|
|
452
|
+
peakAmplificationNad: IntegerLike;
|
|
453
|
+
coreHalfWidthBps: number;
|
|
454
|
+
fadeWidthBps: number;
|
|
455
|
+
rampDurationSlots?: IntegerLike;
|
|
456
|
+
}): ParameterUpdate {
|
|
457
|
+
const rampDurationSlots = toU64BigInt(input.rampDurationSlots ?? 432_000n, "rampDurationSlots");
|
|
458
|
+
if (rampDurationSlots < 432_000n) throw new Error("concentration ramps require at least one protocol day");
|
|
459
|
+
const peakAmplificationNad = toU64BigInt(input.peakAmplificationNad, "peakAmplificationNad");
|
|
460
|
+
assertBps(input.coreHalfWidthBps, "coreHalfWidthBps", 0xffff);
|
|
461
|
+
assertBps(input.fadeWidthBps, "fadeWidthBps", 0xffff);
|
|
462
|
+
if (input.coreHalfWidthBps + input.fadeWidthBps > 0xffff) {
|
|
463
|
+
throw new Error("coreHalfWidthBps + fadeWidthBps must fit in u16");
|
|
464
|
+
}
|
|
465
|
+
if (peakAmplificationNad === NAD) {
|
|
466
|
+
if (input.coreHalfWidthBps !== 0 || input.fadeWidthBps !== 0) {
|
|
467
|
+
throw new Error("CPMM concentration must use zero core and fade widths");
|
|
468
|
+
}
|
|
469
|
+
} else {
|
|
470
|
+
if (peakAmplificationNad <= NAD || peakAmplificationNad > MAX_CONCENTRATION_AMPLIFICATION_NAD) {
|
|
471
|
+
throw new Error("peakAmplificationNad is outside the amplification policy");
|
|
472
|
+
}
|
|
473
|
+
if (input.coreHalfWidthBps === 0) {
|
|
474
|
+
throw new Error("concentrated curves require a nonzero coreHalfWidthBps");
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
return {
|
|
479
|
+
kind: "concentration",
|
|
480
|
+
peakAmplificationNad: toBN(peakAmplificationNad),
|
|
481
|
+
coreHalfWidthBps: input.coreHalfWidthBps,
|
|
482
|
+
fadeWidthBps: input.fadeWidthBps,
|
|
483
|
+
rampDurationSlots: toBN(rampDurationSlots),
|
|
484
|
+
};
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
export const MINIMUM_BORROW_APR_NAD = NAD / 100n;
|
|
488
|
+
export const MIN_BORROW_HALF_LIFE_MS = 43_200_000n;
|
|
489
|
+
export const MAX_BORROW_HALF_LIFE_MS = 30n * 86_400_000n;
|
|
490
|
+
export function irmParameterUpdate(input: IrmUpdateInput): ParameterUpdate {
|
|
491
|
+
assertBps(input.borrowUtilizationLimitBps, "borrowUtilizationLimitBps", 8_000, 1);
|
|
492
|
+
const lowerSignalNad = toU64BigInt(input.lowerSignalNad, "lowerSignalNad");
|
|
493
|
+
const upperSignalNad = toU64BigInt(input.upperSignalNad, "upperSignalNad");
|
|
494
|
+
const halfLifeMs = toU64BigInt(input.halfLifeMs, "halfLifeMs");
|
|
495
|
+
if (lowerSignalNad === 0n || upperSignalNad <= lowerSignalNad) throw new Error("Invalid coverage target band");
|
|
496
|
+
assertRange(halfLifeMs, MIN_BORROW_HALF_LIFE_MS, MAX_BORROW_HALF_LIFE_MS, "halfLifeMs");
|
|
497
|
+
for (const field of Object.keys(input)) {
|
|
498
|
+
if (!["lowerSignalNad", "upperSignalNad", "halfLifeMs", "borrowUtilizationLimitBps"].includes(field)) throw new Error(`Unknown IRM update field: ${field}`);
|
|
499
|
+
}
|
|
500
|
+
return { kind: "irm", config: { lowerSignalNad: toBN(lowerSignalNad), upperSignalNad: toBN(upperSignalNad),
|
|
501
|
+
halfLifeMs: toBN(halfLifeMs), borrowUtilizationLimitBps: input.borrowUtilizationLimitBps } };
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
export function emaHalfLivesParameterUpdate(input: {
|
|
505
|
+
priceMs: IntegerLike;
|
|
506
|
+
directionalPriceMs: IntegerLike;
|
|
507
|
+
curveDepthMs: IntegerLike;
|
|
508
|
+
centerPriceMs: IntegerLike;
|
|
509
|
+
}): ParameterUpdate {
|
|
510
|
+
const normalize = (value: IntegerLike, label: string) =>
|
|
511
|
+
toBN(
|
|
512
|
+
assertRange(
|
|
513
|
+
toU64BigInt(value, label),
|
|
514
|
+
MIN_PARAMETER_HALF_LIFE_MS,
|
|
515
|
+
MAX_PARAMETER_HALF_LIFE_MS,
|
|
516
|
+
label
|
|
517
|
+
)
|
|
518
|
+
);
|
|
519
|
+
return {
|
|
520
|
+
kind: "emaHalfLives",
|
|
521
|
+
priceMs: normalize(input.priceMs, "priceMs"),
|
|
522
|
+
directionalPriceMs: normalize(input.directionalPriceMs, "directionalPriceMs"),
|
|
523
|
+
curveDepthMs: normalize(input.curveDepthMs, "curveDepthMs"),
|
|
524
|
+
centerPriceMs: normalize(input.centerPriceMs, "centerPriceMs"),
|
|
525
|
+
};
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
export function dailyBorrowLimitParameterUpdate(maxDailyBorrowBps: number): ParameterUpdate {
|
|
529
|
+
assertBps(maxDailyBorrowBps, "maxDailyBorrowBps", MAX_DAILY_BORROW_BPS);
|
|
530
|
+
return { kind: "dailyBorrowLimit", maxDailyBorrowBps };
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
export function centerControllerParameterUpdate(input: { adjustmentStepNad: IntegerLike }): ParameterUpdate {
|
|
534
|
+
const step = toU64BigInt(input.adjustmentStepNad, "adjustmentStepNad");
|
|
535
|
+
assertRange(step, MIN_CENTER_ADJUSTMENT_NAD, MAX_CENTER_ADJUSTMENT_NAD, "adjustmentStepNad");
|
|
536
|
+
return { kind: "centerController", adjustmentStepNad: toBN(step) };
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
export function trancheParameterUpdate(input: {
|
|
540
|
+
juniorIncomeShareBps: number;
|
|
541
|
+
}): ParameterUpdate {
|
|
542
|
+
assertBps(
|
|
543
|
+
input.juniorIncomeShareBps,
|
|
544
|
+
"juniorIncomeShareBps",
|
|
545
|
+
MAX_JUNIOR_INCOME_SHARE_BPS,
|
|
546
|
+
MIN_JUNIOR_INCOME_SHARE_BPS
|
|
547
|
+
);
|
|
548
|
+
for (const key of Object.keys(input)) {
|
|
549
|
+
if (key !== "kind" && key !== "juniorIncomeShareBps") throw new Error(`Unknown tranche update field: ${key}`);
|
|
550
|
+
}
|
|
551
|
+
return { kind: "tranche", juniorIncomeShareBps: input.juniorIncomeShareBps };
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
export const parameterUpdate = {
|
|
555
|
+
fee: feeParameterUpdate,
|
|
556
|
+
concentration: concentrationParameterUpdate,
|
|
557
|
+
irm: irmParameterUpdate,
|
|
558
|
+
emaHalfLives: emaHalfLivesParameterUpdate,
|
|
559
|
+
dailyBorrowLimit: dailyBorrowLimitParameterUpdate,
|
|
560
|
+
centerController: centerControllerParameterUpdate,
|
|
561
|
+
tranche: trancheParameterUpdate,
|
|
562
|
+
} as const;
|
|
563
|
+
|
|
564
|
+
export function assertParameterUpdate(update: ParameterUpdate): void {
|
|
565
|
+
switch (update.kind) {
|
|
566
|
+
case "fee":
|
|
567
|
+
feeParameterUpdate(update.profile);
|
|
568
|
+
return;
|
|
569
|
+
case "concentration":
|
|
570
|
+
concentrationParameterUpdate(update);
|
|
571
|
+
return;
|
|
572
|
+
case "irm":
|
|
573
|
+
irmParameterUpdate(update.config);
|
|
574
|
+
return;
|
|
575
|
+
case "emaHalfLives":
|
|
576
|
+
emaHalfLivesParameterUpdate(update);
|
|
577
|
+
return;
|
|
578
|
+
case "dailyBorrowLimit":
|
|
579
|
+
dailyBorrowLimitParameterUpdate(update.maxDailyBorrowBps);
|
|
580
|
+
return;
|
|
581
|
+
case "centerController":
|
|
582
|
+
centerControllerParameterUpdate(update);
|
|
583
|
+
return;
|
|
584
|
+
case "tranche":
|
|
585
|
+
trancheParameterUpdate(update);
|
|
586
|
+
return;
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
export function parameterFamilyCode(update: ParameterUpdate): ParameterFamilyCode {
|
|
591
|
+
switch (update.kind) {
|
|
592
|
+
case "fee":
|
|
593
|
+
return 0;
|
|
594
|
+
case "concentration":
|
|
595
|
+
return 1;
|
|
596
|
+
case "irm":
|
|
597
|
+
return 2;
|
|
598
|
+
case "emaHalfLives":
|
|
599
|
+
return 3;
|
|
600
|
+
case "dailyBorrowLimit":
|
|
601
|
+
return 4;
|
|
602
|
+
case "centerController":
|
|
603
|
+
return 5;
|
|
604
|
+
case "tranche":
|
|
605
|
+
return 6;
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
/**
|
|
610
|
+
* The one encoding a proposal accepts for a set of updates: one to seven,
|
|
611
|
+
* each family at most once, in ascending family order. Throws on an empty
|
|
612
|
+
* set or a repeated family.
|
|
613
|
+
*/
|
|
614
|
+
export function canonicalParameterUpdates(updates: readonly ParameterUpdate[]): ParameterUpdate[] {
|
|
615
|
+
if (updates.length === 0) throw new Error("a proposal must change at least one parameter family");
|
|
616
|
+
if (updates.length > MAX_PARAMETER_UPDATES_PER_PROPOSAL) {
|
|
617
|
+
throw new Error(`a proposal changes at most ${MAX_PARAMETER_UPDATES_PER_PROPOSAL} parameter families`);
|
|
618
|
+
}
|
|
619
|
+
const sorted = [...updates].sort((left, right) => parameterFamilyCode(left) - parameterFamilyCode(right));
|
|
620
|
+
for (let index = 1; index < sorted.length; index += 1) {
|
|
621
|
+
if (parameterFamilyCode(sorted[index - 1]!) === parameterFamilyCode(sorted[index]!)) {
|
|
622
|
+
throw new Error(`a proposal changes the ${sorted[index]!.kind} family more than once`);
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
sorted.forEach(assertParameterUpdate);
|
|
626
|
+
return sorted;
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
/** Convert the readable SDK union to Anchor's generated Rust-enum object. */
|
|
630
|
+
export function anchorParameterUpdate(update: ParameterUpdate): Record<string, unknown> {
|
|
631
|
+
assertParameterUpdate(update);
|
|
632
|
+
switch (update.kind) {
|
|
633
|
+
case "fee":
|
|
634
|
+
// Fee is a Rust tuple variant, so its one field is keyed by tuple index.
|
|
635
|
+
return { fee: { 0: update.profile } };
|
|
636
|
+
case "concentration":
|
|
637
|
+
return {
|
|
638
|
+
concentration: {
|
|
639
|
+
peakAmplificationNad: update.peakAmplificationNad,
|
|
640
|
+
coreHalfWidthBps: update.coreHalfWidthBps,
|
|
641
|
+
fadeWidthBps: update.fadeWidthBps,
|
|
642
|
+
rampDurationSlots: update.rampDurationSlots,
|
|
643
|
+
},
|
|
644
|
+
};
|
|
645
|
+
case "irm":
|
|
646
|
+
return { irm: { 0: update.config } };
|
|
647
|
+
case "emaHalfLives":
|
|
648
|
+
return {
|
|
649
|
+
emaHalfLives: {
|
|
650
|
+
priceMs: update.priceMs,
|
|
651
|
+
directionalPriceMs: update.directionalPriceMs,
|
|
652
|
+
curveDepthMs: update.curveDepthMs,
|
|
653
|
+
centerPriceMs: update.centerPriceMs,
|
|
654
|
+
},
|
|
655
|
+
};
|
|
656
|
+
case "dailyBorrowLimit":
|
|
657
|
+
return { dailyBorrowLimit: { maxDailyBorrowBps: update.maxDailyBorrowBps } };
|
|
658
|
+
case "centerController":
|
|
659
|
+
return {
|
|
660
|
+
centerController: {
|
|
661
|
+
adjustmentStepNad: update.adjustmentStepNad,
|
|
662
|
+
},
|
|
663
|
+
};
|
|
664
|
+
case "tranche":
|
|
665
|
+
return {
|
|
666
|
+
tranche: {
|
|
667
|
+
juniorIncomeShareBps: update.juniorIncomeShareBps,
|
|
668
|
+
},
|
|
669
|
+
};
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
/** Convert a decoded Anchor enum (including tuple-field objects) to the readable SDK union. */
|
|
674
|
+
export function parameterUpdateFromAnchor(value: unknown): ParameterUpdate {
|
|
675
|
+
const update = objectValue(value, "market parameter update");
|
|
676
|
+
if (update.fee !== undefined) {
|
|
677
|
+
const profile = tupleField(update.fee, "fee");
|
|
678
|
+
return feeParameterUpdate(objectValue(profile, "fee profile") as unknown as FeeProfileInput);
|
|
679
|
+
}
|
|
680
|
+
if (update.concentration !== undefined) {
|
|
681
|
+
const fields = objectValue(update.concentration, "concentration update");
|
|
682
|
+
return concentrationParameterUpdate({
|
|
683
|
+
peakAmplificationNad: integerField(fields, "peakAmplificationNad"),
|
|
684
|
+
coreHalfWidthBps: numberField(fields, "coreHalfWidthBps"),
|
|
685
|
+
fadeWidthBps: numberField(fields, "fadeWidthBps"),
|
|
686
|
+
rampDurationSlots: integerField(fields, "rampDurationSlots"),
|
|
687
|
+
});
|
|
688
|
+
}
|
|
689
|
+
if (update.irm !== undefined) {
|
|
690
|
+
const config = objectValue(tupleField(update.irm, "irm"), "IRM config");
|
|
691
|
+
return irmParameterUpdate({
|
|
692
|
+
lowerSignalNad: integerField(config, "lowerSignalNad"),
|
|
693
|
+
upperSignalNad: integerField(config, "upperSignalNad"),
|
|
694
|
+
halfLifeMs: integerField(config, "halfLifeMs"),
|
|
695
|
+
borrowUtilizationLimitBps: numberField(config, "borrowUtilizationLimitBps"),
|
|
696
|
+
});
|
|
697
|
+
}
|
|
698
|
+
if (update.emaHalfLives !== undefined) {
|
|
699
|
+
const fields = objectValue(update.emaHalfLives, "EMA half-lives update");
|
|
700
|
+
return emaHalfLivesParameterUpdate({
|
|
701
|
+
priceMs: integerField(fields, "priceMs"),
|
|
702
|
+
directionalPriceMs: integerField(fields, "directionalPriceMs"),
|
|
703
|
+
curveDepthMs: integerField(fields, "curveDepthMs"),
|
|
704
|
+
centerPriceMs: integerField(fields, "centerPriceMs"),
|
|
705
|
+
});
|
|
706
|
+
}
|
|
707
|
+
if (update.dailyBorrowLimit !== undefined) {
|
|
708
|
+
const fields = objectValue(update.dailyBorrowLimit, "daily borrow-limit update");
|
|
709
|
+
return dailyBorrowLimitParameterUpdate(numberField(fields, "maxDailyBorrowBps"));
|
|
710
|
+
}
|
|
711
|
+
if (update.centerController !== undefined) {
|
|
712
|
+
const fields = objectValue(update.centerController, "center-controller update");
|
|
713
|
+
return centerControllerParameterUpdate({
|
|
714
|
+
adjustmentStepNad: integerField(fields, "adjustmentStepNad"),
|
|
715
|
+
});
|
|
716
|
+
}
|
|
717
|
+
if (update.tranche !== undefined) {
|
|
718
|
+
const fields = objectValue(update.tranche, "tranche update");
|
|
719
|
+
return trancheParameterUpdate({
|
|
720
|
+
juniorIncomeShareBps: numberField(fields, "juniorIncomeShareBps"),
|
|
721
|
+
});
|
|
722
|
+
}
|
|
723
|
+
throw new Error("unknown market parameter update variant");
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
/** Create metadata from already-uploaded bytes, then retrieve and verify the URI. */
|
|
727
|
+
export async function createProposalMetadata(
|
|
728
|
+
input: CreateProposalMetadataInput
|
|
729
|
+
): Promise<ProposalMetadataV1> {
|
|
730
|
+
const bytes = markdownBytes(input.markdown);
|
|
731
|
+
const metadata: ProposalMetadataV1 = {
|
|
732
|
+
version: PROPOSAL_METADATA_VERSION,
|
|
733
|
+
title: input.title,
|
|
734
|
+
descriptionUri: input.descriptionUri,
|
|
735
|
+
descriptionSha256: [...(await sha256(bytes))],
|
|
736
|
+
descriptionLen: bytes.byteLength,
|
|
737
|
+
};
|
|
738
|
+
assertProposalMetadata(metadata);
|
|
739
|
+
await fetchAndVerifyProposalDescription(metadata, input);
|
|
740
|
+
return metadata;
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
/** Upload the exact Markdown bytes, fetch the returned URI, and verify length + SHA-256. */
|
|
744
|
+
export async function uploadProposalMetadata(
|
|
745
|
+
input: UploadProposalMetadataInput
|
|
746
|
+
): Promise<ProposalMetadataV1> {
|
|
747
|
+
assertProposalTitle(input.title);
|
|
748
|
+
const bytes = markdownBytes(input.markdown);
|
|
749
|
+
assertDescriptionLength(bytes.byteLength);
|
|
750
|
+
const uploaded = await input.upload(bytes.slice(), {
|
|
751
|
+
title: input.title,
|
|
752
|
+
contentType: "text/markdown; charset=utf-8",
|
|
753
|
+
});
|
|
754
|
+
const descriptionUri = typeof uploaded === "string" ? uploaded : uploaded.uri;
|
|
755
|
+
return createProposalMetadata({ ...input, descriptionUri, markdown: bytes });
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
export function assertProposalMetadata(metadata: ProposalMetadataV1): void {
|
|
759
|
+
if (metadata.version !== PROPOSAL_METADATA_VERSION) {
|
|
760
|
+
throw new Error(`proposal metadata version must be ${PROPOSAL_METADATA_VERSION}`);
|
|
761
|
+
}
|
|
762
|
+
assertProposalTitle(metadata.title);
|
|
763
|
+
assertProposalUri(metadata.descriptionUri);
|
|
764
|
+
assertDescriptionLength(metadata.descriptionLen);
|
|
765
|
+
if (!Number.isInteger(metadata.descriptionLen)) {
|
|
766
|
+
throw new Error("descriptionLen must be an integer byte length");
|
|
767
|
+
}
|
|
768
|
+
if (metadata.descriptionSha256.length !== 32) {
|
|
769
|
+
throw new Error("descriptionSha256 must contain exactly 32 bytes");
|
|
770
|
+
}
|
|
771
|
+
for (const byte of metadata.descriptionSha256) {
|
|
772
|
+
if (!Number.isInteger(byte) || byte < 0 || byte > 255) {
|
|
773
|
+
throw new Error("descriptionSha256 must contain only bytes");
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
if (metadata.descriptionSha256.every((byte) => byte === 0)) {
|
|
777
|
+
throw new Error("descriptionSha256 must be nonzero");
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
export function assertProposalTitle(title: string): void {
|
|
782
|
+
const byteLength = new TextEncoder().encode(title).byteLength;
|
|
783
|
+
if (
|
|
784
|
+
byteLength < 1 ||
|
|
785
|
+
byteLength > MAX_PROPOSAL_TITLE_BYTES ||
|
|
786
|
+
title !== title.trim() ||
|
|
787
|
+
/\p{Cc}/u.test(title)
|
|
788
|
+
) {
|
|
789
|
+
throw new Error(
|
|
790
|
+
`title must be trimmed, control-free UTF-8 occupying 1-${MAX_PROPOSAL_TITLE_BYTES} bytes`
|
|
791
|
+
);
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
export function assertProposalUri(uri: string): void {
|
|
796
|
+
const ascii = /^[\x00-\x7f]*$/.test(uri);
|
|
797
|
+
const validScheme = ["ipfs://", "ar://", "https://"].some(
|
|
798
|
+
(prefix) => uri.startsWith(prefix) && uri.length > prefix.length
|
|
799
|
+
);
|
|
800
|
+
if (
|
|
801
|
+
uri.length < 1 ||
|
|
802
|
+
uri.length > MAX_PROPOSAL_DESCRIPTION_URI_BYTES ||
|
|
803
|
+
!ascii ||
|
|
804
|
+
/[\x00-\x20\x7f]/.test(uri) ||
|
|
805
|
+
!validScheme
|
|
806
|
+
) {
|
|
807
|
+
throw new Error(
|
|
808
|
+
`description URI must be a whitespace-free ipfs://, ar://, or https:// URI of at most ${MAX_PROPOSAL_DESCRIPTION_URI_BYTES} ASCII bytes`
|
|
809
|
+
);
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
/** Fetch no unbounded body, verify the exact byte count/hash, then decode strict UTF-8. */
|
|
814
|
+
export async function fetchAndVerifyProposalDescription(
|
|
815
|
+
metadata: ProposalMetadataV1,
|
|
816
|
+
options: ProposalDescriptionFetchOptions = {}
|
|
817
|
+
): Promise<VerifiedProposalDescription> {
|
|
818
|
+
assertProposalMetadata(metadata);
|
|
819
|
+
const fetchImpl = options.fetch ?? globalThis.fetch?.bind(globalThis);
|
|
820
|
+
if (!fetchImpl) throw new Error("fetch is unavailable; supply ProposalDescriptionFetchOptions.fetch");
|
|
821
|
+
const resolved = options.resolveUri
|
|
822
|
+
? await options.resolveUri(metadata.descriptionUri)
|
|
823
|
+
: resolveProposalDescriptionUri(metadata.descriptionUri, options);
|
|
824
|
+
const response = await fetchImpl(resolved, {
|
|
825
|
+
signal: options.signal,
|
|
826
|
+
headers: {
|
|
827
|
+
accept: "text/markdown, text/plain;q=0.9, application/octet-stream;q=0.8",
|
|
828
|
+
range: `bytes=0-${metadata.descriptionLen - 1}`,
|
|
829
|
+
},
|
|
830
|
+
});
|
|
831
|
+
if (!response.ok) {
|
|
832
|
+
throw new Error(`proposal description fetch failed with HTTP ${response.status}`);
|
|
833
|
+
}
|
|
834
|
+
const bytes = await readExactBody(response, metadata.descriptionLen);
|
|
835
|
+
const actualHash = await sha256(bytes);
|
|
836
|
+
if (!equalBytes(actualHash, metadata.descriptionSha256)) {
|
|
837
|
+
throw new Error("proposal description SHA-256 does not match its on-chain metadata");
|
|
838
|
+
}
|
|
839
|
+
let markdown: string;
|
|
840
|
+
try {
|
|
841
|
+
markdown = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
|
|
842
|
+
} catch {
|
|
843
|
+
throw new Error("verified proposal description is not valid UTF-8");
|
|
844
|
+
}
|
|
845
|
+
return { verified: true, uri: metadata.descriptionUri, markdown, bytes };
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
/** UI-friendly verification: failure is data, so callers can show title + typed diff. */
|
|
849
|
+
export async function tryFetchProposalDescription(
|
|
850
|
+
metadata: ProposalMetadataV1,
|
|
851
|
+
options: ProposalDescriptionFetchOptions = {}
|
|
852
|
+
): Promise<ProposalDescriptionResult> {
|
|
853
|
+
try {
|
|
854
|
+
return await fetchAndVerifyProposalDescription(metadata, options);
|
|
855
|
+
} catch (error) {
|
|
856
|
+
return {
|
|
857
|
+
verified: false,
|
|
858
|
+
uri: metadata.descriptionUri,
|
|
859
|
+
warning: "Proposal rationale is unavailable or failed on-chain length/hash verification.",
|
|
860
|
+
error,
|
|
861
|
+
};
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
export function resolveProposalDescriptionUri(
|
|
866
|
+
uri: string,
|
|
867
|
+
options: Pick<ProposalDescriptionFetchOptions, "ipfsGateway" | "arweaveGateway"> = {}
|
|
868
|
+
): string {
|
|
869
|
+
assertProposalUri(uri);
|
|
870
|
+
if (uri.startsWith("https://")) return uri;
|
|
871
|
+
if (uri.startsWith("ipfs://")) {
|
|
872
|
+
const payload = uri.slice("ipfs://".length).replace(/^ipfs\//, "");
|
|
873
|
+
const gateway = (options.ipfsGateway ?? "https://ipfs.io/ipfs/").replace(/\/*$/, "/");
|
|
874
|
+
return `${gateway}${payload}`;
|
|
875
|
+
}
|
|
876
|
+
const gateway = (options.arweaveGateway ?? "https://arweave.net/").replace(/\/*$/, "/");
|
|
877
|
+
return `${gateway}${uri.slice("ar://".length)}`;
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
/** Reproduce the immutable on-chain proposal digest over canonical Borsh bytes. */
|
|
881
|
+
export function integerBN(value: IntegerLike, label = "value"): BN {
|
|
882
|
+
return toBN(toU64BigInt(value, label));
|
|
883
|
+
}
|
|
884
|
+
|
|
885
|
+
function markdownBytes(markdown: ProposalMarkdown): Uint8Array {
|
|
886
|
+
const bytes = typeof markdown === "string" ? new TextEncoder().encode(markdown) : markdown.slice();
|
|
887
|
+
assertDescriptionLength(bytes.byteLength);
|
|
888
|
+
try {
|
|
889
|
+
new TextDecoder("utf-8", { fatal: true }).decode(bytes);
|
|
890
|
+
} catch {
|
|
891
|
+
throw new Error("proposal Markdown must contain valid UTF-8 bytes");
|
|
892
|
+
}
|
|
893
|
+
return bytes;
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
function assertDescriptionLength(length: number): void {
|
|
897
|
+
if (!Number.isInteger(length) || length < 1 || length > MAX_PROPOSAL_DESCRIPTION_BYTES) {
|
|
898
|
+
throw new Error(`proposal Markdown must occupy 1-${MAX_PROPOSAL_DESCRIPTION_BYTES} bytes`);
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
|
|
902
|
+
function objectValue(value: unknown, label: string): Record<string, unknown> {
|
|
903
|
+
if (value === null || typeof value !== "object") throw new Error(`${label} must be an object`);
|
|
904
|
+
return value as Record<string, unknown>;
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
function tupleField(value: unknown, label: string): unknown {
|
|
908
|
+
const tuple = objectValue(value, `${label} tuple`);
|
|
909
|
+
if (!("0" in tuple)) throw new Error(`${label} tuple is missing field 0`);
|
|
910
|
+
return tuple["0"];
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
function integerField(value: Record<string, unknown>, field: string): IntegerLike {
|
|
914
|
+
const candidate = value[field];
|
|
915
|
+
if (
|
|
916
|
+
typeof candidate !== "bigint" &&
|
|
917
|
+
typeof candidate !== "number" &&
|
|
918
|
+
typeof candidate !== "string" &&
|
|
919
|
+
(candidate === null || typeof candidate !== "object" || !("toString" in candidate))
|
|
920
|
+
) {
|
|
921
|
+
throw new Error(`${field} is missing or is not integer-like`);
|
|
922
|
+
}
|
|
923
|
+
return candidate as IntegerLike;
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
function numberField(value: Record<string, unknown>, field: string): number {
|
|
927
|
+
const candidate = value[field];
|
|
928
|
+
if (typeof candidate !== "number") throw new Error(`${field} is missing or is not a number`);
|
|
929
|
+
return candidate;
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
function assertBps(value: number, label: string, max: number, min = 0): void {
|
|
933
|
+
if (!Number.isInteger(value) || value < min || value > max) {
|
|
934
|
+
throw new Error(`${label} must be an integer from ${min} to ${max} bps`);
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
|
|
938
|
+
function assertRange(value: bigint, min: bigint, max: bigint, label: string): bigint {
|
|
939
|
+
if (value < min || value > max) {
|
|
940
|
+
throw new Error(`${label} must be between ${min} and ${max}`);
|
|
941
|
+
}
|
|
942
|
+
return value;
|
|
943
|
+
}
|
|
944
|
+
|
|
945
|
+
function toU64BigInt(value: IntegerLike, label: string): bigint {
|
|
946
|
+
if (typeof value === "number" && !Number.isSafeInteger(value)) {
|
|
947
|
+
throw new Error(`${label} must be a safe integer when supplied as a number`);
|
|
948
|
+
}
|
|
949
|
+
let normalized: bigint;
|
|
950
|
+
try {
|
|
951
|
+
normalized = BigInt(value.toString());
|
|
952
|
+
} catch {
|
|
953
|
+
throw new Error(`${label} must be an unsigned 64-bit integer`);
|
|
954
|
+
}
|
|
955
|
+
if (normalized < 0n || normalized > U64_MAX) {
|
|
956
|
+
throw new Error(`${label} must be an unsigned 64-bit integer`);
|
|
957
|
+
}
|
|
958
|
+
return normalized;
|
|
959
|
+
}
|
|
960
|
+
|
|
961
|
+
export function toBN(value: bigint): BN {
|
|
962
|
+
return new AnchorBN(value.toString());
|
|
963
|
+
}
|
|
964
|
+
|
|
965
|
+
function equalBytes(left: Uint8Array | readonly number[], right: Uint8Array | readonly number[]): boolean {
|
|
966
|
+
if (left.length !== right.length) return false;
|
|
967
|
+
let difference = 0;
|
|
968
|
+
for (let index = 0; index < left.length; index += 1) {
|
|
969
|
+
difference |= left[index]! ^ right[index]!;
|
|
970
|
+
}
|
|
971
|
+
return difference === 0;
|
|
972
|
+
}
|
|
973
|
+
|
|
974
|
+
async function readExactBody(response: Response, expectedLength: number): Promise<Uint8Array> {
|
|
975
|
+
const contentRange = response.headers.get("content-range");
|
|
976
|
+
if (response.status === 206) {
|
|
977
|
+
const match = /^bytes\s+(\d+)-(\d+)\/(\d+|\*)$/i.exec(contentRange ?? "");
|
|
978
|
+
if (!match) throw new Error("partial proposal response is missing a valid Content-Range");
|
|
979
|
+
const start = Number(match[1]);
|
|
980
|
+
const end = Number(match[2]);
|
|
981
|
+
const total = match[3] === "*" ? null : Number(match[3]);
|
|
982
|
+
if (start !== 0 || end + 1 !== expectedLength || total !== expectedLength) {
|
|
983
|
+
throw new Error("proposal description response does not have the exact on-chain byte length");
|
|
984
|
+
}
|
|
985
|
+
} else {
|
|
986
|
+
const contentLength = response.headers.get("content-length");
|
|
987
|
+
const contentEncoding = response.headers.get("content-encoding");
|
|
988
|
+
if (contentLength !== null && !contentEncoding && Number(contentLength) !== expectedLength) {
|
|
989
|
+
throw new Error("proposal description Content-Length does not match on-chain metadata");
|
|
990
|
+
}
|
|
991
|
+
}
|
|
992
|
+
|
|
993
|
+
if (!response.body) {
|
|
994
|
+
const bytes = new Uint8Array(await response.arrayBuffer());
|
|
995
|
+
if (bytes.byteLength !== expectedLength) {
|
|
996
|
+
throw new Error("proposal description byte length does not match on-chain metadata");
|
|
997
|
+
}
|
|
998
|
+
return bytes;
|
|
999
|
+
}
|
|
1000
|
+
|
|
1001
|
+
const output = new Uint8Array(expectedLength);
|
|
1002
|
+
const reader = response.body.getReader();
|
|
1003
|
+
let offset = 0;
|
|
1004
|
+
while (true) {
|
|
1005
|
+
const { value, done } = await reader.read();
|
|
1006
|
+
if (done) break;
|
|
1007
|
+
if (!value) continue;
|
|
1008
|
+
if (offset + value.byteLength > expectedLength) {
|
|
1009
|
+
await reader.cancel();
|
|
1010
|
+
throw new Error("proposal description exceeds its on-chain byte length");
|
|
1011
|
+
}
|
|
1012
|
+
output.set(value, offset);
|
|
1013
|
+
offset += value.byteLength;
|
|
1014
|
+
}
|
|
1015
|
+
if (offset !== expectedLength) {
|
|
1016
|
+
throw new Error("proposal description byte length does not match on-chain metadata");
|
|
1017
|
+
}
|
|
1018
|
+
return output;
|
|
1019
|
+
}
|