@omnipair/dusk-sdk 2.0.1 → 2.16.0-next.20261102

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.
Files changed (192) hide show
  1. package/README.md +1085 -26
  2. package/dist/amounts.d.ts +9 -0
  3. package/dist/amounts.d.ts.map +1 -0
  4. package/dist/amounts.js +10 -0
  5. package/dist/amounts.js.map +1 -0
  6. package/dist/constants.d.ts +80 -33
  7. package/dist/constants.d.ts.map +1 -1
  8. package/dist/constants.js +175 -64
  9. package/dist/constants.js.map +1 -1
  10. package/dist/delegate.d.ts +94 -0
  11. package/dist/delegate.d.ts.map +1 -0
  12. package/dist/delegate.js +131 -0
  13. package/dist/delegate.js.map +1 -0
  14. package/dist/dusk.d.ts +14 -0
  15. package/dist/dusk.d.ts.map +1 -1
  16. package/dist/dusk.js +22 -0
  17. package/dist/dusk.js.map +1 -1
  18. package/dist/get.d.ts +3285 -237
  19. package/dist/get.d.ts.map +1 -1
  20. package/dist/get.js +140 -71
  21. package/dist/get.js.map +1 -1
  22. package/dist/governance-client.d.ts +169 -0
  23. package/dist/governance-client.d.ts.map +1 -0
  24. package/dist/governance-client.js +146 -0
  25. package/dist/governance-client.js.map +1 -0
  26. package/dist/governance.d.ts +313 -0
  27. package/dist/governance.d.ts.map +1 -0
  28. package/dist/governance.js +902 -0
  29. package/dist/governance.js.map +1 -0
  30. package/dist/hash.d.ts +9 -0
  31. package/dist/hash.d.ts.map +1 -0
  32. package/dist/hash.js +16 -0
  33. package/dist/hash.js.map +1 -0
  34. package/dist/hlp-liquidation-client.d.ts +106 -0
  35. package/dist/hlp-liquidation-client.d.ts.map +1 -0
  36. package/dist/hlp-liquidation-client.js +150 -0
  37. package/dist/hlp-liquidation-client.js.map +1 -0
  38. package/dist/idl_delegate.d.ts +3 -0
  39. package/dist/idl_delegate.d.ts.map +1 -0
  40. package/dist/idl_delegate.js +3 -0
  41. package/dist/idl_delegate.js.map +1 -0
  42. package/dist/idl_delegate.json +6119 -0
  43. package/dist/idl_v2.json +18372 -6121
  44. package/dist/index.d.ts +23 -0
  45. package/dist/index.d.ts.map +1 -1
  46. package/dist/index.js +23 -0
  47. package/dist/index.js.map +1 -1
  48. package/dist/interest-accounting.d.ts +49 -0
  49. package/dist/interest-accounting.d.ts.map +1 -0
  50. package/dist/interest-accounting.js +72 -0
  51. package/dist/interest-accounting.js.map +1 -0
  52. package/dist/leverage-actions.d.ts +122 -0
  53. package/dist/leverage-actions.d.ts.map +1 -0
  54. package/dist/leverage-actions.js +228 -0
  55. package/dist/leverage-actions.js.map +1 -0
  56. package/dist/leverage-margins.d.ts +12 -0
  57. package/dist/leverage-margins.d.ts.map +1 -0
  58. package/dist/leverage-margins.js +45 -0
  59. package/dist/leverage-margins.js.map +1 -0
  60. package/dist/leverage-preview.d.ts +587 -0
  61. package/dist/leverage-preview.d.ts.map +1 -0
  62. package/dist/leverage-preview.js +89 -0
  63. package/dist/leverage-preview.js.map +1 -0
  64. package/dist/liquidation-client.d.ts +230 -0
  65. package/dist/liquidation-client.d.ts.map +1 -0
  66. package/dist/liquidation-client.js +239 -0
  67. package/dist/liquidation-client.js.map +1 -0
  68. package/dist/liquidation.d.ts +78 -0
  69. package/dist/liquidation.d.ts.map +1 -0
  70. package/dist/liquidation.js +122 -0
  71. package/dist/liquidation.js.map +1 -0
  72. package/dist/lp-naming.d.ts +43 -0
  73. package/dist/lp-naming.d.ts.map +1 -0
  74. package/dist/lp-naming.js +81 -0
  75. package/dist/lp-naming.js.map +1 -0
  76. package/dist/lp-vanity.d.ts +33 -0
  77. package/dist/lp-vanity.d.ts.map +1 -0
  78. package/dist/lp-vanity.js +94 -0
  79. package/dist/lp-vanity.js.map +1 -0
  80. package/dist/market-bootstrap.d.ts +109 -0
  81. package/dist/market-bootstrap.d.ts.map +1 -0
  82. package/dist/market-bootstrap.js +158 -0
  83. package/dist/market-bootstrap.js.map +1 -0
  84. package/dist/market-launch.d.ts +45 -0
  85. package/dist/market-launch.d.ts.map +1 -0
  86. package/dist/market-launch.js +76 -0
  87. package/dist/market-launch.js.map +1 -0
  88. package/dist/oracle.d.ts +46 -0
  89. package/dist/oracle.d.ts.map +1 -0
  90. package/dist/oracle.js +103 -0
  91. package/dist/oracle.js.map +1 -0
  92. package/dist/preview.d.ts +39 -1
  93. package/dist/preview.d.ts.map +1 -1
  94. package/dist/preview.js +12 -0
  95. package/dist/preview.js.map +1 -1
  96. package/dist/protection.d.ts +48 -0
  97. package/dist/protection.d.ts.map +1 -0
  98. package/dist/protection.js +88 -0
  99. package/dist/protection.js.map +1 -0
  100. package/dist/referral.d.ts +28 -28
  101. package/dist/referral.d.ts.map +1 -1
  102. package/dist/referral.js +41 -33
  103. package/dist/referral.js.map +1 -1
  104. package/dist/risk-pricing.d.ts +14 -0
  105. package/dist/risk-pricing.d.ts.map +1 -0
  106. package/dist/risk-pricing.js +25 -0
  107. package/dist/risk-pricing.js.map +1 -0
  108. package/dist/simulation.d.ts +45 -0
  109. package/dist/simulation.d.ts.map +1 -0
  110. package/dist/simulation.js +106 -0
  111. package/dist/simulation.js.map +1 -0
  112. package/dist/tranche-client.d.ts +121 -0
  113. package/dist/tranche-client.d.ts.map +1 -0
  114. package/dist/tranche-client.js +185 -0
  115. package/dist/tranche-client.js.map +1 -0
  116. package/dist/transfer-fees.d.ts +46 -0
  117. package/dist/transfer-fees.d.ts.map +1 -0
  118. package/dist/transfer-fees.js +76 -0
  119. package/dist/transfer-fees.js.map +1 -0
  120. package/dist/type-aliases.d.ts +271 -30
  121. package/dist/type-aliases.d.ts.map +1 -1
  122. package/dist/types_delegate.d.ts +6126 -0
  123. package/dist/types_delegate.d.ts.map +1 -0
  124. package/dist/types_delegate.js +2 -0
  125. package/dist/types_delegate.js.map +1 -0
  126. package/dist/types_v2.d.ts +18105 -5854
  127. package/dist/types_v2.d.ts.map +1 -1
  128. package/dist/virtual-book/index.d.ts +4 -0
  129. package/dist/virtual-book/index.d.ts.map +1 -0
  130. package/dist/virtual-book/index.js +4 -0
  131. package/dist/virtual-book/index.js.map +1 -0
  132. package/dist/virtual-book/market.d.ts +608 -0
  133. package/dist/virtual-book/market.d.ts.map +1 -0
  134. package/dist/virtual-book/market.js +59 -0
  135. package/dist/virtual-book/market.js.map +1 -0
  136. package/dist/virtual-book/projection.d.ts +44 -0
  137. package/dist/virtual-book/projection.d.ts.map +1 -0
  138. package/dist/virtual-book/projection.js +229 -0
  139. package/dist/virtual-book/projection.js.map +1 -0
  140. package/dist/virtual-book/quotes.d.ts +1241 -0
  141. package/dist/virtual-book/quotes.d.ts.map +1 -0
  142. package/dist/virtual-book/quotes.js +233 -0
  143. package/dist/virtual-book/quotes.js.map +1 -0
  144. package/dist/write.d.ts +584 -14
  145. package/dist/write.d.ts.map +1 -1
  146. package/dist/write.js +1371 -47
  147. package/dist/write.js.map +1 -1
  148. package/dist/yield-client.d.ts +51 -0
  149. package/dist/yield-client.d.ts.map +1 -0
  150. package/dist/yield-client.js +98 -0
  151. package/dist/yield-client.js.map +1 -0
  152. package/package.json +9 -2
  153. package/src/amounts.ts +13 -0
  154. package/src/constants.ts +276 -111
  155. package/src/delegate.ts +238 -0
  156. package/src/dusk.ts +28 -0
  157. package/src/get.ts +267 -90
  158. package/src/governance-client.ts +234 -0
  159. package/src/governance.ts +1422 -0
  160. package/src/hash.ts +15 -0
  161. package/src/hlp-liquidation-client.ts +195 -0
  162. package/src/idl_delegate.json +6119 -0
  163. package/src/idl_delegate.ts +3 -0
  164. package/src/idl_v2.json +18372 -6121
  165. package/src/index.ts +31 -0
  166. package/src/interest-accounting.ts +85 -0
  167. package/src/leverage-actions.ts +216 -0
  168. package/src/leverage-margins.ts +48 -0
  169. package/src/leverage-preview.ts +86 -0
  170. package/src/liquidation-client.ts +297 -0
  171. package/src/liquidation.ts +137 -0
  172. package/src/lp-naming.ts +127 -0
  173. package/src/lp-vanity.ts +135 -0
  174. package/src/market-bootstrap.ts +273 -0
  175. package/src/market-launch.ts +103 -0
  176. package/src/oracle.ts +120 -0
  177. package/src/preview.ts +53 -1
  178. package/src/protection.ts +112 -0
  179. package/src/referral.ts +71 -71
  180. package/src/risk-pricing.ts +28 -0
  181. package/src/simulation.ts +169 -0
  182. package/src/tranche-client.ts +187 -0
  183. package/src/transfer-fees.ts +99 -0
  184. package/src/type-aliases.ts +280 -30
  185. package/src/types_delegate.ts +6125 -0
  186. package/src/types_v2.ts +18372 -6121
  187. package/src/virtual-book/index.ts +3 -0
  188. package/src/virtual-book/market.ts +76 -0
  189. package/src/virtual-book/projection.ts +265 -0
  190. package/src/virtual-book/quotes.ts +308 -0
  191. package/src/write.ts +2394 -67
  192. package/src/yield-client.ts +117 -0
@@ -0,0 +1,1422 @@
1
+ import { oraclePolicy, encodeOraclePolicy, type OraclePolicy, type OraclePolicyInput } from "./oracle.js";
2
+ import * as anchorNamespace from "@coral-xyz/anchor";
3
+ import { type BN } from "@coral-xyz/anchor";
4
+
5
+ import { address, type AddressLike } from "./address.js";
6
+ import {
7
+ GOVERNANCE_BPS_DENOMINATOR,
8
+ MAX_PROPOSAL_DESCRIPTION_BYTES,
9
+ MAX_PROPOSAL_DESCRIPTION_URI_BYTES,
10
+ MAX_PROPOSAL_TITLE_BYTES,
11
+ PARAMETER_PROPOSAL_SPONSOR_BPS,
12
+ PARAMETER_PROPOSAL_SUPPORT_BPS,
13
+ PROPOSAL_METADATA_VERSION,
14
+ } from "./constants.js";
15
+ import { sha256 } from "./hash.js";
16
+
17
+ export type GovernanceIntegerLike = bigint | number | string | BN | { toString(): string };
18
+
19
+ export const NAD = 1_000_000_000n;
20
+ export const MIN_PARAMETER_HALF_LIFE_MS = 60_000n;
21
+ export const MAX_PARAMETER_HALF_LIFE_MS = 12n * 60n * 60n * 1_000n;
22
+ export const MAX_PARAMETER_FEE_BPS = 5_000;
23
+ export const MIN_IRM_TARGET_UTILIZATION_BPS = 6_000;
24
+ export const MAX_IRM_TARGET_UTILIZATION_BPS = 7_500;
25
+ export const MIN_IRM_CURVE_STEEPNESS_NAD = 2n * NAD;
26
+ export const MAX_IRM_CURVE_STEEPNESS_NAD = 8n * NAD;
27
+ export const MIN_IRM_ADJUSTMENT_SPEED_PER_YEAR = 1n;
28
+ export const MAX_IRM_ADJUSTMENT_SPEED_PER_YEAR = 50n;
29
+ export const MAX_CONCENTRATION_AMPLIFICATION_NAD = 2_000n * NAD;
30
+ export const MAX_FEE_COEFFICIENT_NAD = 100n * NAD;
31
+ export const MAX_VOLATILITY_ACCUMULATOR_NAD = 10n * NAD;
32
+ export const MAX_DAILY_BORROW_BPS = 3_000;
33
+ export const MIN_CENTER_ADJUSTMENT_NAD = NAD / 1_000_000n;
34
+ export const MAX_CENTER_ADJUSTMENT_NAD = NAD / 10n;
35
+ // One nominal day of scheduled 200 ms slots, matching the program cap.
36
+ export const MAX_CENTER_ADJUSTMENT_INTERVAL_SLOTS = 432_000n;
37
+ export const MAX_LAUNCH_FEE_DURATION_SECONDS = 30n * 24n * 60n * 60n;
38
+ export const LAUNCH_FEE_DECAY_DISABLED = 0;
39
+ export const LAUNCH_FEE_DECAY_LINEAR = 1;
40
+ export const LAUNCH_FEE_DECAY_EXPONENTIAL = 2;
41
+ export const LAUNCH_RATE_LIMIT_ASSET_DISABLED = 0;
42
+ export const LAUNCH_RATE_LIMIT_ASSET_BASE = 1;
43
+ export const LAUNCH_RATE_LIMIT_ASSET_QUOTE = 2;
44
+ export const SWAP_FEE_COLLECT_INPUT_ASSET = 0;
45
+ export const SWAP_FEE_COLLECT_BASE_ONLY = 1;
46
+ export const SWAP_FEE_COLLECT_QUOTE_ONLY = 2;
47
+ export const MAX_LAUNCH_MARKET_FEE_PERIODS = 64;
48
+ export const MAX_INSURANCE_PRINCIPAL_COVERAGE_BPS = 7_500;
49
+ export const MAX_INSURANCE_DRAW_PER_DAY_BPS = 5_000;
50
+ export const MIN_JUNIOR_INCOME_SHARE_BPS = 1_000;
51
+ export const MAX_JUNIOR_INCOME_SHARE_BPS = 9_000;
52
+ export const MIN_JUNIOR_EXIT_REQUEST_FEE_BPS = 1;
53
+ export const MAX_JUNIOR_EXIT_REQUEST_FEE_BPS = 50;
54
+ export const MIN_LIQUIDATION_FEE_BPS = 25;
55
+ export const MAX_LIQUIDATION_FEE_BPS = 300;
56
+ /** Governed parameter families, and the length of a market's revision list. */
57
+ export const PARAMETER_FAMILY_COUNT = 9;
58
+ /** A proposal changes one to nine families, each at most once. */
59
+ export const MAX_PARAMETER_UPDATES_PER_PROPOSAL = PARAMETER_FAMILY_COUNT;
60
+ export const PARAMETER_PROPOSAL_DIGEST_DOMAIN = "DUSK_PARAMETER_PROPOSAL_V2";
61
+
62
+ const U64_MAX = 0xffff_ffff_ffff_ffffn;
63
+ const PROPOSAL_DIGEST_DOMAIN = new TextEncoder().encode(PARAMETER_PROPOSAL_DIGEST_DOMAIN);
64
+
65
+ // `@coral-xyz/anchor` ships both a CommonJS and an ESM build, and they disagree
66
+ // about how `BN` is reachable: bundlers resolve the ESM build, which has no
67
+ // default export, while Node's CJS interop exposes `BN` only through `default`.
68
+ // Reading both keeps this module importable from a browser bundle and from Node.
69
+ type AnchorBNConstructor = new (value: string) => BN;
70
+ const anchorExports = anchorNamespace as unknown as {
71
+ BN?: AnchorBNConstructor;
72
+ default?: { BN?: AnchorBNConstructor };
73
+ };
74
+ const AnchorBN = (anchorExports.BN ?? anchorExports.default?.BN) as AnchorBNConstructor;
75
+
76
+ export interface FeeProfileInput {
77
+ baseFeeBps: number;
78
+ divergenceFeeShareCapBps: number;
79
+ volatilityFeeShareCapBps: number;
80
+ divergenceFeeCoefficientNad: GovernanceIntegerLike;
81
+ volatilityFeeCoefficientNad: GovernanceIntegerLike;
82
+ volatilityHalfLifeMs: GovernanceIntegerLike;
83
+ volatilityShockCapNad: GovernanceIntegerLike;
84
+ volatilityAccumulatorCapNad: GovernanceIntegerLike;
85
+ swapFeeCollectMode?: number;
86
+ /** LP-owned swap-fee share compounded into reserve principal, in bps. */
87
+ compoundingFeeBps?: number;
88
+ launchFeeStartBps?: number;
89
+ launchFeeDurationSeconds?: GovernanceIntegerLike;
90
+ launchFeeDecayMode?: number;
91
+ launchMarketPriceStepBps?: number;
92
+ launchMarketNumberOfPeriods?: number;
93
+ launchMarketReductionFactorBps?: number;
94
+ launchRateLimitAsset?: number;
95
+ launchRateLimitReferenceNad?: GovernanceIntegerLike;
96
+ launchRateLimitIncrementBps?: number;
97
+ launchRateLimitMaxFeeBps?: number;
98
+ launchRateLimitDurationSeconds?: GovernanceIntegerLike;
99
+ }
100
+
101
+ export interface FeeProfile {
102
+ baseFeeBps: number;
103
+ divergenceFeeShareCapBps: number;
104
+ volatilityFeeShareCapBps: number;
105
+ divergenceFeeCoefficientNad: BN;
106
+ volatilityFeeCoefficientNad: BN;
107
+ volatilityHalfLifeMs: BN;
108
+ volatilityShockCapNad: BN;
109
+ volatilityAccumulatorCapNad: BN;
110
+ swapFeeCollectMode: number;
111
+ compoundingFeeBps: number;
112
+ launchFeeStartBps: number;
113
+ launchFeeDurationSeconds: BN;
114
+ launchFeeDecayMode: number;
115
+ launchMarketPriceStepBps: number;
116
+ launchMarketNumberOfPeriods: number;
117
+ launchMarketReductionFactorBps: number;
118
+ launchRateLimitAsset: number;
119
+ launchRateLimitReferenceNad: BN;
120
+ launchRateLimitIncrementBps: number;
121
+ launchRateLimitMaxFeeBps: number;
122
+ launchRateLimitDurationSeconds: BN;
123
+ }
124
+
125
+ export interface IrmConfigInput {
126
+ lowerSignalNad: GovernanceIntegerLike;
127
+ upperSignalNad: GovernanceIntegerLike;
128
+ halfLifeMs: GovernanceIntegerLike;
129
+ initialAprNad: GovernanceIntegerLike;
130
+ minimumAprNad: GovernanceIntegerLike;
131
+ maximumAprNad: GovernanceIntegerLike;
132
+ borrowUtilizationLimitBps: number;
133
+ }
134
+
135
+ export interface IrmConfig {
136
+ lowerSignalNad: BN;
137
+ upperSignalNad: BN;
138
+ halfLifeMs: BN;
139
+ initialAprNad: BN;
140
+ minimumAprNad: BN;
141
+ maximumAprNad: BN;
142
+ borrowUtilizationLimitBps: number;
143
+ }
144
+
145
+ export type ParameterUpdate =
146
+ | { kind: "fee"; profile: FeeProfile }
147
+ | {
148
+ kind: "concentration";
149
+ peakAmplificationNad: BN;
150
+ coreHalfWidthBps: number;
151
+ fadeWidthBps: number;
152
+ }
153
+ | { kind: "irm"; config: IrmConfig }
154
+ | {
155
+ kind: "emaHalfLives";
156
+ priceMs: BN;
157
+ directionalPriceMs: BN;
158
+ curveDepthMs: BN;
159
+ centerPriceMs: BN;
160
+ }
161
+ | { kind: "dailyBorrowLimit"; maxDailyBorrowBps: number }
162
+ | {
163
+ kind: "centerController";
164
+ adjustmentThresholdNad: BN;
165
+ adjustmentStepNad: BN;
166
+ minAdjustmentIntervalSlots: BN;
167
+ }
168
+ | { kind: "insuranceDrawCaps"; principalCoverageBps: number; perDayBps: number }
169
+ | { kind: "oracle"; policy: OraclePolicy }
170
+ | {
171
+ kind: "tranche";
172
+ juniorIncomeShareBps: number;
173
+ requestFeeBps: number;
174
+ liquidationFeeBps: number;
175
+ };
176
+
177
+ export type ParameterFamilyName = ParameterUpdate["kind"];
178
+ export type ParameterFamilyCode = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8;
179
+
180
+ export interface ProposalMetadataV1 {
181
+ version: number;
182
+ title: string;
183
+ descriptionUri: string;
184
+ descriptionSha256: number[];
185
+ descriptionLen: number;
186
+ }
187
+
188
+ export type ProposalMarkdown = string | Uint8Array;
189
+
190
+ export interface ProposalDescriptionUploadContext {
191
+ readonly title: string;
192
+ readonly contentType: "text/markdown; charset=utf-8";
193
+ }
194
+
195
+ export type ProposalDescriptionUploader = (
196
+ exactMarkdownBytes: Uint8Array,
197
+ context: ProposalDescriptionUploadContext
198
+ ) => Promise<string | { uri: string }>;
199
+
200
+ export type ProposalFetch = (input: string | URL, init?: RequestInit) => Promise<Response>;
201
+ export type ProposalUriResolver = (uri: string) => string | URL | Promise<string | URL>;
202
+
203
+ export interface ProposalDescriptionFetchOptions {
204
+ fetch?: ProposalFetch;
205
+ resolveUri?: ProposalUriResolver;
206
+ signal?: AbortSignal;
207
+ ipfsGateway?: string;
208
+ arweaveGateway?: string;
209
+ }
210
+
211
+ export interface VerifiedProposalDescription {
212
+ verified: true;
213
+ uri: string;
214
+ markdown: string;
215
+ bytes: Uint8Array;
216
+ }
217
+
218
+ export type ProposalDescriptionResult =
219
+ | VerifiedProposalDescription
220
+ | {
221
+ verified: false;
222
+ uri: string;
223
+ warning: string;
224
+ error: unknown;
225
+ };
226
+
227
+ export interface CreateProposalMetadataInput extends ProposalDescriptionFetchOptions {
228
+ title: string;
229
+ markdown: ProposalMarkdown;
230
+ descriptionUri: string;
231
+ }
232
+
233
+ export interface UploadProposalMetadataInput extends ProposalDescriptionFetchOptions {
234
+ title: string;
235
+ markdown: ProposalMarkdown;
236
+ upload: ProposalDescriptionUploader;
237
+ }
238
+
239
+ export interface ParameterProposalDigestInput {
240
+ programId: AddressLike;
241
+ market: AddressLike;
242
+ proposer: AddressLike;
243
+ nonce: GovernanceIntegerLike;
244
+ /**
245
+ * One revision per family, as the proposal stores them: an updated family's
246
+ * market revision at creation, zero for every family left alone. Build it
247
+ * with `updatedFamilyRevisions`.
248
+ */
249
+ familyRevisions: readonly GovernanceIntegerLike[];
250
+ /** One to seven updates, at most one per family, in any order. */
251
+ updates: readonly ParameterUpdate[];
252
+ metadata: ProposalMetadataV1;
253
+ }
254
+
255
+ export interface DecodedParameterProposalForDigest {
256
+ market: AddressLike;
257
+ proposer: AddressLike;
258
+ nonce: GovernanceIntegerLike;
259
+ familyRevisions: readonly GovernanceIntegerLike[];
260
+ updates: readonly unknown[];
261
+ metadata: ProposalMetadataV1;
262
+ digest?: Uint8Array | number[];
263
+ }
264
+
265
+ /** Normalize and validate the complete mutable fee family. */
266
+ export function feeParameterUpdate(input: FeeProfileInput): ParameterUpdate {
267
+ assertBps(input.baseFeeBps, "baseFeeBps", MAX_PARAMETER_FEE_BPS);
268
+ assertBps(
269
+ input.divergenceFeeShareCapBps,
270
+ "divergenceFeeShareCapBps",
271
+ MAX_PARAMETER_FEE_BPS
272
+ );
273
+ assertBps(
274
+ input.volatilityFeeShareCapBps,
275
+ "volatilityFeeShareCapBps",
276
+ MAX_PARAMETER_FEE_BPS
277
+ );
278
+ if (
279
+ input.baseFeeBps +
280
+ input.divergenceFeeShareCapBps +
281
+ input.volatilityFeeShareCapBps >
282
+ MAX_PARAMETER_FEE_BPS
283
+ ) {
284
+ throw new Error(`fee component caps must sum to at most ${MAX_PARAMETER_FEE_BPS} bps`);
285
+ }
286
+
287
+ const divergenceFeeCoefficientNad = toU64BigInt(
288
+ input.divergenceFeeCoefficientNad,
289
+ "divergenceFeeCoefficientNad"
290
+ );
291
+ const volatilityFeeCoefficientNad = toU64BigInt(
292
+ input.volatilityFeeCoefficientNad,
293
+ "volatilityFeeCoefficientNad"
294
+ );
295
+ const volatilityHalfLifeMs = assertRange(
296
+ toU64BigInt(input.volatilityHalfLifeMs, "volatilityHalfLifeMs"),
297
+ MIN_PARAMETER_HALF_LIFE_MS,
298
+ MAX_PARAMETER_HALF_LIFE_MS,
299
+ "volatilityHalfLifeMs"
300
+ );
301
+ const volatilityShockCapNad = toU64BigInt(
302
+ input.volatilityShockCapNad,
303
+ "volatilityShockCapNad"
304
+ );
305
+ const volatilityAccumulatorCapNad = toU64BigInt(
306
+ input.volatilityAccumulatorCapNad,
307
+ "volatilityAccumulatorCapNad"
308
+ );
309
+ assertRange(
310
+ divergenceFeeCoefficientNad,
311
+ 0n,
312
+ MAX_FEE_COEFFICIENT_NAD,
313
+ "divergenceFeeCoefficientNad"
314
+ );
315
+ assertRange(
316
+ volatilityFeeCoefficientNad,
317
+ 0n,
318
+ MAX_FEE_COEFFICIENT_NAD,
319
+ "volatilityFeeCoefficientNad"
320
+ );
321
+ const signalDisabled = volatilityShockCapNad === 0n && volatilityAccumulatorCapNad === 0n;
322
+ const signalValid =
323
+ volatilityShockCapNad > 0n &&
324
+ volatilityShockCapNad <= volatilityAccumulatorCapNad &&
325
+ volatilityAccumulatorCapNad <= MAX_VOLATILITY_ACCUMULATOR_NAD;
326
+ if (!signalDisabled && !signalValid) {
327
+ throw new Error(
328
+ "volatility caps must both be zero, or shock > 0, shock <= accumulator, and accumulator <= 10 NAD"
329
+ );
330
+ }
331
+ if (volatilityFeeCoefficientNad !== 0n && !signalValid) {
332
+ throw new Error("a nonzero volatility fee coefficient requires an enabled volatility signal");
333
+ }
334
+
335
+ const swapFeeCollectMode =
336
+ input.swapFeeCollectMode ?? SWAP_FEE_COLLECT_INPUT_ASSET;
337
+ if (
338
+ ![
339
+ SWAP_FEE_COLLECT_INPUT_ASSET,
340
+ SWAP_FEE_COLLECT_BASE_ONLY,
341
+ SWAP_FEE_COLLECT_QUOTE_ONLY,
342
+ ].includes(swapFeeCollectMode)
343
+ ) {
344
+ throw new Error("invalid swap fee collection mode");
345
+ }
346
+ const compoundingFeeBps = input.compoundingFeeBps ?? 0;
347
+ assertBps(
348
+ compoundingFeeBps,
349
+ "compoundingFeeBps",
350
+ GOVERNANCE_BPS_DENOMINATOR
351
+ );
352
+
353
+ const launchFeeStartBps = input.launchFeeStartBps ?? 0;
354
+ const launchFeeDurationSeconds = toU64BigInt(
355
+ input.launchFeeDurationSeconds ?? 0,
356
+ "launchFeeDurationSeconds"
357
+ );
358
+ const launchFeeDecayMode = input.launchFeeDecayMode ?? LAUNCH_FEE_DECAY_DISABLED;
359
+ const launchMarketPriceStepBps = input.launchMarketPriceStepBps ?? 0;
360
+ const launchMarketNumberOfPeriods = input.launchMarketNumberOfPeriods ?? 0;
361
+ const launchMarketReductionFactorBps = input.launchMarketReductionFactorBps ?? 0;
362
+ const marketScheduleDisabled =
363
+ launchMarketPriceStepBps === 0 &&
364
+ launchMarketNumberOfPeriods === 0 &&
365
+ launchMarketReductionFactorBps === 0;
366
+ const marketScheduleEnabled =
367
+ launchMarketPriceStepBps > 0 &&
368
+ launchMarketNumberOfPeriods > 0 &&
369
+ launchMarketNumberOfPeriods <= MAX_LAUNCH_MARKET_FEE_PERIODS &&
370
+ launchMarketReductionFactorBps > 0 &&
371
+ launchMarketReductionFactorBps < GOVERNANCE_BPS_DENOMINATOR;
372
+ const launchFeeDisabled =
373
+ launchFeeStartBps === 0 &&
374
+ launchFeeDurationSeconds === 0n &&
375
+ launchFeeDecayMode === LAUNCH_FEE_DECAY_DISABLED &&
376
+ marketScheduleDisabled;
377
+ if (
378
+ !launchFeeDisabled &&
379
+ (launchFeeStartBps <= input.baseFeeBps ||
380
+ launchFeeStartBps > MAX_PARAMETER_FEE_BPS ||
381
+ launchFeeDurationSeconds < 1n ||
382
+ launchFeeDurationSeconds > MAX_LAUNCH_FEE_DURATION_SECONDS ||
383
+ ![LAUNCH_FEE_DECAY_LINEAR, LAUNCH_FEE_DECAY_EXPONENTIAL].includes(
384
+ launchFeeDecayMode
385
+ ))
386
+ ) {
387
+ throw new Error("invalid launch fee start, duration, or decay mode");
388
+ }
389
+ if (!launchFeeDisabled && !marketScheduleDisabled && !marketScheduleEnabled) {
390
+ throw new Error("invalid launch market-cap fee schedule");
391
+ }
392
+ if (
393
+ marketScheduleEnabled &&
394
+ ![SWAP_FEE_COLLECT_BASE_ONLY, SWAP_FEE_COLLECT_QUOTE_ONLY].includes(
395
+ swapFeeCollectMode
396
+ )
397
+ ) {
398
+ throw new Error("a market-cap fee schedule requires a fixed fee asset");
399
+ }
400
+ if (
401
+ !launchFeeDisabled &&
402
+ launchFeeStartBps + input.divergenceFeeShareCapBps + input.volatilityFeeShareCapBps >
403
+ MAX_PARAMETER_FEE_BPS
404
+ ) {
405
+ throw new Error(`launch fee component caps must sum to at most ${MAX_PARAMETER_FEE_BPS} bps`);
406
+ }
407
+
408
+ const launchRateLimitAsset =
409
+ input.launchRateLimitAsset ?? LAUNCH_RATE_LIMIT_ASSET_DISABLED;
410
+ const launchRateLimitReferenceNad = toU64BigInt(
411
+ input.launchRateLimitReferenceNad ?? 0,
412
+ "launchRateLimitReferenceNad"
413
+ );
414
+ const launchRateLimitIncrementBps = input.launchRateLimitIncrementBps ?? 0;
415
+ const launchRateLimitMaxFeeBps = input.launchRateLimitMaxFeeBps ?? 0;
416
+ const launchRateLimitDurationSeconds = toU64BigInt(
417
+ input.launchRateLimitDurationSeconds ?? 0,
418
+ "launchRateLimitDurationSeconds"
419
+ );
420
+ const rateLimitDisabled =
421
+ launchRateLimitAsset === LAUNCH_RATE_LIMIT_ASSET_DISABLED &&
422
+ launchRateLimitReferenceNad === 0n &&
423
+ launchRateLimitIncrementBps === 0 &&
424
+ launchRateLimitMaxFeeBps === 0 &&
425
+ launchRateLimitDurationSeconds === 0n;
426
+ const scheduledPeak = launchFeeDisabled ? input.baseFeeBps : launchFeeStartBps;
427
+ if (
428
+ !rateLimitDisabled &&
429
+ (![LAUNCH_RATE_LIMIT_ASSET_BASE, LAUNCH_RATE_LIMIT_ASSET_QUOTE].includes(
430
+ launchRateLimitAsset
431
+ ) ||
432
+ launchRateLimitReferenceNad === 0n ||
433
+ launchRateLimitIncrementBps <= 0 ||
434
+ launchRateLimitMaxFeeBps <= input.baseFeeBps ||
435
+ launchRateLimitMaxFeeBps < scheduledPeak ||
436
+ launchRateLimitDurationSeconds < 1n ||
437
+ launchRateLimitDurationSeconds > MAX_LAUNCH_FEE_DURATION_SECONDS)
438
+ ) {
439
+ throw new Error("invalid launch buy-size limiter configuration");
440
+ }
441
+ if (!rateLimitDisabled) {
442
+ assertBps(
443
+ launchRateLimitIncrementBps,
444
+ "launchRateLimitIncrementBps",
445
+ MAX_PARAMETER_FEE_BPS,
446
+ 1
447
+ );
448
+ assertBps(
449
+ launchRateLimitMaxFeeBps,
450
+ "launchRateLimitMaxFeeBps",
451
+ MAX_PARAMETER_FEE_BPS,
452
+ 1
453
+ );
454
+ if (
455
+ launchRateLimitMaxFeeBps +
456
+ input.divergenceFeeShareCapBps +
457
+ input.volatilityFeeShareCapBps >
458
+ MAX_PARAMETER_FEE_BPS
459
+ ) {
460
+ throw new Error(
461
+ `rate-limit fee component caps must sum to at most ${MAX_PARAMETER_FEE_BPS} bps`
462
+ );
463
+ }
464
+ }
465
+
466
+ return {
467
+ kind: "fee",
468
+ profile: {
469
+ baseFeeBps: input.baseFeeBps,
470
+ divergenceFeeShareCapBps: input.divergenceFeeShareCapBps,
471
+ volatilityFeeShareCapBps: input.volatilityFeeShareCapBps,
472
+ divergenceFeeCoefficientNad: toBN(divergenceFeeCoefficientNad),
473
+ volatilityFeeCoefficientNad: toBN(volatilityFeeCoefficientNad),
474
+ volatilityHalfLifeMs: toBN(volatilityHalfLifeMs),
475
+ volatilityShockCapNad: toBN(volatilityShockCapNad),
476
+ volatilityAccumulatorCapNad: toBN(volatilityAccumulatorCapNad),
477
+ swapFeeCollectMode,
478
+ compoundingFeeBps,
479
+ launchFeeStartBps,
480
+ launchFeeDurationSeconds: toBN(launchFeeDurationSeconds),
481
+ launchFeeDecayMode,
482
+ launchMarketPriceStepBps,
483
+ launchMarketNumberOfPeriods,
484
+ launchMarketReductionFactorBps,
485
+ launchRateLimitAsset,
486
+ launchRateLimitReferenceNad: toBN(launchRateLimitReferenceNad),
487
+ launchRateLimitIncrementBps,
488
+ launchRateLimitMaxFeeBps,
489
+ launchRateLimitDurationSeconds: toBN(launchRateLimitDurationSeconds),
490
+ },
491
+ };
492
+ }
493
+
494
+ /** Standard launch-token fee template: Base is sold and all swap revenue is Quote. */
495
+ export function standardLaunchFeeParameterUpdate(
496
+ input: Omit<FeeProfileInput, "swapFeeCollectMode" | "launchRateLimitAsset">
497
+ ): ParameterUpdate {
498
+ return feeParameterUpdate({
499
+ ...input,
500
+ swapFeeCollectMode: SWAP_FEE_COLLECT_QUOTE_ONLY,
501
+ launchRateLimitAsset: LAUNCH_RATE_LIMIT_ASSET_BASE,
502
+ });
503
+ }
504
+
505
+ /** Build an atomic, protected concentration update. */
506
+ export function concentrationParameterUpdate(input: {
507
+ peakAmplificationNad: GovernanceIntegerLike;
508
+ coreHalfWidthBps: number;
509
+ fadeWidthBps: number;
510
+ }): ParameterUpdate {
511
+ const peakAmplificationNad = toU64BigInt(input.peakAmplificationNad, "peakAmplificationNad");
512
+ assertBps(input.coreHalfWidthBps, "coreHalfWidthBps", 0xffff);
513
+ assertBps(input.fadeWidthBps, "fadeWidthBps", 0xffff);
514
+ if (input.coreHalfWidthBps + input.fadeWidthBps > 0xffff) {
515
+ throw new Error("coreHalfWidthBps + fadeWidthBps must fit in u16");
516
+ }
517
+ if (peakAmplificationNad === NAD) {
518
+ if (input.coreHalfWidthBps !== 0 || input.fadeWidthBps !== 0) {
519
+ throw new Error("CPMM concentration must use zero core and fade widths");
520
+ }
521
+ } else {
522
+ if (peakAmplificationNad <= NAD || peakAmplificationNad > MAX_CONCENTRATION_AMPLIFICATION_NAD) {
523
+ throw new Error("peakAmplificationNad is outside the amplification policy");
524
+ }
525
+ if (input.coreHalfWidthBps === 0) {
526
+ throw new Error("concentrated curves require a nonzero coreHalfWidthBps");
527
+ }
528
+ }
529
+
530
+ return {
531
+ kind: "concentration",
532
+ peakAmplificationNad: toBN(peakAmplificationNad),
533
+ coreHalfWidthBps: input.coreHalfWidthBps,
534
+ fadeWidthBps: input.fadeWidthBps,
535
+ };
536
+ }
537
+
538
+ export function irmParameterUpdate(input: IrmConfigInput): ParameterUpdate {
539
+ assertBps(input.borrowUtilizationLimitBps, "borrowUtilizationLimitBps", 10_000, 1);
540
+ const lowerSignalNad = toU64BigInt(input.lowerSignalNad, "lowerSignalNad");
541
+ const upperSignalNad = toU64BigInt(input.upperSignalNad, "upperSignalNad");
542
+ const halfLifeMs = toU64BigInt(input.halfLifeMs, "halfLifeMs");
543
+ const initialAprNad = toU64BigInt(input.initialAprNad, "initialAprNad");
544
+ const minimumAprNad = toU64BigInt(input.minimumAprNad, "minimumAprNad");
545
+ const maximumAprNad = toU64BigInt(input.maximumAprNad, "maximumAprNad");
546
+ if (lowerSignalNad === 0n || upperSignalNad <= lowerSignalNad) throw new Error("Invalid coverage target band");
547
+ assertRange(halfLifeMs, 3_600_000n, 30n * 86_400_000n, "halfLifeMs");
548
+ if (initialAprNad === 0n || minimumAprNad > initialAprNad || (maximumAprNad !== 0n && maximumAprNad < initialAprNad)) {
549
+ throw new Error("Invalid initial APR, floor, or ceiling");
550
+ }
551
+ return { kind: "irm", config: {
552
+ lowerSignalNad: toBN(lowerSignalNad),
553
+ upperSignalNad: toBN(upperSignalNad),
554
+ halfLifeMs: toBN(halfLifeMs),
555
+ initialAprNad: toBN(initialAprNad),
556
+ minimumAprNad: toBN(minimumAprNad),
557
+ maximumAprNad: toBN(maximumAprNad),
558
+ borrowUtilizationLimitBps: input.borrowUtilizationLimitBps,
559
+ } };
560
+ }
561
+
562
+ export function emaHalfLivesParameterUpdate(input: {
563
+ priceMs: GovernanceIntegerLike;
564
+ directionalPriceMs: GovernanceIntegerLike;
565
+ curveDepthMs: GovernanceIntegerLike;
566
+ centerPriceMs: GovernanceIntegerLike;
567
+ }): ParameterUpdate {
568
+ const normalize = (value: GovernanceIntegerLike, label: string) =>
569
+ toBN(
570
+ assertRange(
571
+ toU64BigInt(value, label),
572
+ MIN_PARAMETER_HALF_LIFE_MS,
573
+ MAX_PARAMETER_HALF_LIFE_MS,
574
+ label
575
+ )
576
+ );
577
+ return {
578
+ kind: "emaHalfLives",
579
+ priceMs: normalize(input.priceMs, "priceMs"),
580
+ directionalPriceMs: normalize(input.directionalPriceMs, "directionalPriceMs"),
581
+ curveDepthMs: normalize(input.curveDepthMs, "curveDepthMs"),
582
+ centerPriceMs: normalize(input.centerPriceMs, "centerPriceMs"),
583
+ };
584
+ }
585
+
586
+ export function dailyBorrowLimitParameterUpdate(maxDailyBorrowBps: number): ParameterUpdate {
587
+ assertBps(maxDailyBorrowBps, "maxDailyBorrowBps", MAX_DAILY_BORROW_BPS);
588
+ return { kind: "dailyBorrowLimit", maxDailyBorrowBps };
589
+ }
590
+
591
+ export function centerControllerParameterUpdate(input: {
592
+ adjustmentThresholdNad: GovernanceIntegerLike;
593
+ adjustmentStepNad: GovernanceIntegerLike;
594
+ minAdjustmentIntervalSlots: GovernanceIntegerLike;
595
+ }): ParameterUpdate {
596
+ const adjustmentThresholdNad = toU64BigInt(input.adjustmentThresholdNad, "adjustmentThresholdNad");
597
+ const adjustmentStepNad = toU64BigInt(input.adjustmentStepNad, "adjustmentStepNad");
598
+ const minAdjustmentIntervalSlots = toU64BigInt(
599
+ input.minAdjustmentIntervalSlots,
600
+ "minAdjustmentIntervalSlots"
601
+ );
602
+ const disabled =
603
+ adjustmentThresholdNad === 0n && adjustmentStepNad === 0n && minAdjustmentIntervalSlots === 0n;
604
+ if (
605
+ !disabled &&
606
+ (adjustmentStepNad < MIN_CENTER_ADJUSTMENT_NAD ||
607
+ adjustmentStepNad > MAX_CENTER_ADJUSTMENT_NAD ||
608
+ adjustmentThresholdNad < adjustmentStepNad ||
609
+ adjustmentThresholdNad > MAX_CENTER_ADJUSTMENT_NAD ||
610
+ minAdjustmentIntervalSlots < 1n ||
611
+ minAdjustmentIntervalSlots > MAX_CENTER_ADJUSTMENT_INTERVAL_SLOTS)
612
+ ) {
613
+ throw new Error("invalid center-controller threshold, step, or interval");
614
+ }
615
+ return {
616
+ kind: "centerController",
617
+ adjustmentThresholdNad: toBN(adjustmentThresholdNad),
618
+ adjustmentStepNad: toBN(adjustmentStepNad),
619
+ minAdjustmentIntervalSlots: toBN(minAdjustmentIntervalSlots),
620
+ };
621
+ }
622
+
623
+ /** Insurance loss-concentration caps; they may only tighten the protocol ceilings. */
624
+ export function insuranceDrawCapsParameterUpdate(input: {
625
+ principalCoverageBps: number;
626
+ perDayBps: number;
627
+ }): ParameterUpdate {
628
+ assertBps(input.principalCoverageBps, "principalCoverageBps", MAX_INSURANCE_PRINCIPAL_COVERAGE_BPS);
629
+ assertBps(input.perDayBps, "perDayBps", MAX_INSURANCE_DRAW_PER_DAY_BPS);
630
+ return {
631
+ kind: "insuranceDrawCaps",
632
+ principalCoverageBps: input.principalCoverageBps,
633
+ perDayBps: input.perDayBps,
634
+ };
635
+ }
636
+
637
+ export function oracleParameterUpdate(input: OraclePolicyInput): ParameterUpdate {
638
+ return { kind: "oracle", policy: oraclePolicy(input) };
639
+ }
640
+
641
+ export function trancheParameterUpdate(input: {
642
+ juniorIncomeShareBps: number;
643
+ requestFeeBps: number;
644
+ liquidationFeeBps: number;
645
+ }): ParameterUpdate {
646
+ assertBps(
647
+ input.juniorIncomeShareBps,
648
+ "juniorIncomeShareBps",
649
+ MAX_JUNIOR_INCOME_SHARE_BPS,
650
+ MIN_JUNIOR_INCOME_SHARE_BPS
651
+ );
652
+ assertBps(
653
+ input.requestFeeBps,
654
+ "requestFeeBps",
655
+ MAX_JUNIOR_EXIT_REQUEST_FEE_BPS,
656
+ MIN_JUNIOR_EXIT_REQUEST_FEE_BPS
657
+ );
658
+ assertBps(
659
+ input.liquidationFeeBps,
660
+ "liquidationFeeBps",
661
+ MAX_LIQUIDATION_FEE_BPS,
662
+ MIN_LIQUIDATION_FEE_BPS
663
+ );
664
+ return { kind: "tranche", ...input };
665
+ }
666
+
667
+ export const parameterUpdate = {
668
+ oracle: oracleParameterUpdate,
669
+ fee: feeParameterUpdate,
670
+ concentration: concentrationParameterUpdate,
671
+ irm: irmParameterUpdate,
672
+ emaHalfLives: emaHalfLivesParameterUpdate,
673
+ dailyBorrowLimit: dailyBorrowLimitParameterUpdate,
674
+ centerController: centerControllerParameterUpdate,
675
+ insuranceDrawCaps: insuranceDrawCapsParameterUpdate,
676
+ tranche: trancheParameterUpdate,
677
+ } as const;
678
+
679
+ export function assertParameterUpdate(update: ParameterUpdate): void {
680
+ switch (update.kind) {
681
+ case "fee":
682
+ feeParameterUpdate(update.profile);
683
+ return;
684
+ case "concentration":
685
+ concentrationParameterUpdate(update);
686
+ return;
687
+ case "irm":
688
+ irmParameterUpdate(update.config);
689
+ return;
690
+ case "emaHalfLives":
691
+ emaHalfLivesParameterUpdate(update);
692
+ return;
693
+ case "dailyBorrowLimit":
694
+ dailyBorrowLimitParameterUpdate(update.maxDailyBorrowBps);
695
+ return;
696
+ case "centerController":
697
+ centerControllerParameterUpdate(update);
698
+ return;
699
+ case "oracle":
700
+ oraclePolicy(update.policy);
701
+ return;
702
+ case "insuranceDrawCaps":
703
+ insuranceDrawCapsParameterUpdate(update);
704
+ return;
705
+ case "tranche":
706
+ trancheParameterUpdate(update);
707
+ return;
708
+ }
709
+ }
710
+
711
+ export function parameterFamilyCode(update: ParameterUpdate): ParameterFamilyCode {
712
+ switch (update.kind) {
713
+ case "fee":
714
+ return 0;
715
+ case "concentration":
716
+ return 1;
717
+ case "irm":
718
+ return 2;
719
+ case "emaHalfLives":
720
+ return 3;
721
+ case "dailyBorrowLimit":
722
+ return 4;
723
+ case "centerController":
724
+ return 5;
725
+ case "insuranceDrawCaps":
726
+ return 6;
727
+ case "oracle":
728
+ return 7;
729
+ case "tranche":
730
+ return 8;
731
+ }
732
+ }
733
+
734
+ /**
735
+ * The one encoding a proposal accepts for a set of updates: one to eight,
736
+ * each family at most once, in ascending family order. Throws on an empty
737
+ * set or a repeated family.
738
+ */
739
+ export function canonicalParameterUpdates(updates: readonly ParameterUpdate[]): ParameterUpdate[] {
740
+ if (updates.length === 0) throw new Error("a proposal must change at least one parameter family");
741
+ if (updates.length > MAX_PARAMETER_UPDATES_PER_PROPOSAL) {
742
+ throw new Error(`a proposal changes at most ${MAX_PARAMETER_UPDATES_PER_PROPOSAL} parameter families`);
743
+ }
744
+ const sorted = [...updates].sort((left, right) => parameterFamilyCode(left) - parameterFamilyCode(right));
745
+ for (let index = 1; index < sorted.length; index += 1) {
746
+ if (parameterFamilyCode(sorted[index - 1]!) === parameterFamilyCode(sorted[index]!)) {
747
+ throw new Error(`a proposal changes the ${sorted[index]!.kind} family more than once`);
748
+ }
749
+ }
750
+ sorted.forEach(assertParameterUpdate);
751
+ return sorted;
752
+ }
753
+
754
+ /**
755
+ * The revisions a new proposal binds: each updated family's current market
756
+ * revision, and zero for every family the proposal leaves alone.
757
+ */
758
+ export function updatedFamilyRevisions(
759
+ updates: readonly ParameterUpdate[],
760
+ marketRevisions: readonly GovernanceIntegerLike[]
761
+ ): bigint[] {
762
+ assertFamilyRevisionCount(marketRevisions);
763
+ const revisions = new Array<bigint>(PARAMETER_FAMILY_COUNT).fill(0n);
764
+ for (const update of canonicalParameterUpdates(updates)) {
765
+ const code = parameterFamilyCode(update);
766
+ revisions[code] = toU64BigInt(marketRevisions[code]!, `marketRevisions[${code}]`);
767
+ }
768
+ return revisions;
769
+ }
770
+
771
+ /** Convert the readable SDK union to Anchor's generated Rust-enum object. */
772
+ export function anchorParameterUpdate(update: ParameterUpdate): Record<string, unknown> {
773
+ assertParameterUpdate(update);
774
+ switch (update.kind) {
775
+ case "fee":
776
+ // Fee is a Rust tuple variant, so its one field is keyed by tuple index.
777
+ return { fee: { 0: update.profile } };
778
+ case "concentration":
779
+ return {
780
+ concentration: {
781
+ peakAmplificationNad: update.peakAmplificationNad,
782
+ coreHalfWidthBps: update.coreHalfWidthBps,
783
+ fadeWidthBps: update.fadeWidthBps,
784
+ },
785
+ };
786
+ case "irm":
787
+ return { irm: { 0: update.config } };
788
+ case "emaHalfLives":
789
+ return {
790
+ emaHalfLives: {
791
+ priceMs: update.priceMs,
792
+ directionalPriceMs: update.directionalPriceMs,
793
+ curveDepthMs: update.curveDepthMs,
794
+ centerPriceMs: update.centerPriceMs,
795
+ },
796
+ };
797
+ case "dailyBorrowLimit":
798
+ return { dailyBorrowLimit: { maxDailyBorrowBps: update.maxDailyBorrowBps } };
799
+ case "centerController":
800
+ return {
801
+ centerController: {
802
+ adjustmentThresholdNad: update.adjustmentThresholdNad,
803
+ adjustmentStepNad: update.adjustmentStepNad,
804
+ minAdjustmentIntervalSlots: update.minAdjustmentIntervalSlots,
805
+ },
806
+ };
807
+ case "oracle":
808
+ return { oracle: { 0: update.policy } };
809
+ case "insuranceDrawCaps":
810
+ return {
811
+ insuranceDrawCaps: { principalCoverageBps: update.principalCoverageBps, perDayBps: update.perDayBps },
812
+ };
813
+ case "tranche":
814
+ return {
815
+ tranche: {
816
+ juniorIncomeShareBps: update.juniorIncomeShareBps,
817
+ requestFeeBps: update.requestFeeBps,
818
+ liquidationFeeBps: update.liquidationFeeBps,
819
+ },
820
+ };
821
+ }
822
+ }
823
+
824
+ /** Convert a decoded Anchor enum (including tuple-field objects) to the readable SDK union. */
825
+ export function parameterUpdateFromAnchor(value: unknown): ParameterUpdate {
826
+ const update = objectValue(value, "market parameter update");
827
+ if (update.fee !== undefined) {
828
+ const profile = tupleField(update.fee, "fee");
829
+ return feeParameterUpdate(objectValue(profile, "fee profile") as unknown as FeeProfileInput);
830
+ }
831
+ if (update.concentration !== undefined) {
832
+ const fields = objectValue(update.concentration, "concentration update");
833
+ return concentrationParameterUpdate({
834
+ peakAmplificationNad: integerField(fields, "peakAmplificationNad"),
835
+ coreHalfWidthBps: numberField(fields, "coreHalfWidthBps"),
836
+ fadeWidthBps: numberField(fields, "fadeWidthBps"),
837
+ });
838
+ }
839
+ if (update.irm !== undefined) {
840
+ const config = objectValue(tupleField(update.irm, "irm"), "IRM config");
841
+ return irmParameterUpdate({
842
+ lowerSignalNad: integerField(config, "lowerSignalNad"),
843
+ upperSignalNad: integerField(config, "upperSignalNad"),
844
+ halfLifeMs: integerField(config, "halfLifeMs"),
845
+ initialAprNad: integerField(config, "initialAprNad"),
846
+ minimumAprNad: integerField(config, "minimumAprNad"),
847
+ maximumAprNad: integerField(config, "maximumAprNad"),
848
+ borrowUtilizationLimitBps: numberField(config, "borrowUtilizationLimitBps"),
849
+ });
850
+ }
851
+ if (update.emaHalfLives !== undefined) {
852
+ const fields = objectValue(update.emaHalfLives, "EMA half-lives update");
853
+ return emaHalfLivesParameterUpdate({
854
+ priceMs: integerField(fields, "priceMs"),
855
+ directionalPriceMs: integerField(fields, "directionalPriceMs"),
856
+ curveDepthMs: integerField(fields, "curveDepthMs"),
857
+ centerPriceMs: integerField(fields, "centerPriceMs"),
858
+ });
859
+ }
860
+ if (update.dailyBorrowLimit !== undefined) {
861
+ const fields = objectValue(update.dailyBorrowLimit, "daily borrow-limit update");
862
+ return dailyBorrowLimitParameterUpdate(numberField(fields, "maxDailyBorrowBps"));
863
+ }
864
+ if (update.centerController !== undefined) {
865
+ const fields = objectValue(update.centerController, "center-controller update");
866
+ return centerControllerParameterUpdate({
867
+ adjustmentThresholdNad: integerField(fields, "adjustmentThresholdNad"),
868
+ adjustmentStepNad: integerField(fields, "adjustmentStepNad"),
869
+ minAdjustmentIntervalSlots: integerField(fields, "minAdjustmentIntervalSlots"),
870
+ });
871
+ }
872
+ if (update.insuranceDrawCaps !== undefined) {
873
+ const fields = objectValue(update.insuranceDrawCaps, "insurance draw-caps update");
874
+ return insuranceDrawCapsParameterUpdate({
875
+ principalCoverageBps: numberField(fields, "principalCoverageBps"),
876
+ perDayBps: numberField(fields, "perDayBps"),
877
+ });
878
+ }
879
+ if (update.oracle !== undefined) {
880
+ return oracleParameterUpdate(tupleField(update.oracle, "oracle") as OraclePolicyInput);
881
+ }
882
+ if (update.tranche !== undefined) {
883
+ const fields = objectValue(update.tranche, "tranche update");
884
+ return trancheParameterUpdate({
885
+ juniorIncomeShareBps: numberField(fields, "juniorIncomeShareBps"),
886
+ requestFeeBps: numberField(fields, "requestFeeBps"),
887
+ liquidationFeeBps: numberField(fields, "liquidationFeeBps"),
888
+ });
889
+ }
890
+ throw new Error("unknown market parameter update variant");
891
+ }
892
+
893
+ /** Create metadata from already-uploaded bytes, then retrieve and verify the URI. */
894
+ export async function createProposalMetadata(
895
+ input: CreateProposalMetadataInput
896
+ ): Promise<ProposalMetadataV1> {
897
+ const bytes = markdownBytes(input.markdown);
898
+ const metadata: ProposalMetadataV1 = {
899
+ version: PROPOSAL_METADATA_VERSION,
900
+ title: input.title,
901
+ descriptionUri: input.descriptionUri,
902
+ descriptionSha256: [...(await sha256(bytes))],
903
+ descriptionLen: bytes.byteLength,
904
+ };
905
+ assertProposalMetadata(metadata);
906
+ await fetchAndVerifyProposalDescription(metadata, input);
907
+ return metadata;
908
+ }
909
+
910
+ /** Upload the exact Markdown bytes, fetch the returned URI, and verify length + SHA-256. */
911
+ export async function uploadProposalMetadata(
912
+ input: UploadProposalMetadataInput
913
+ ): Promise<ProposalMetadataV1> {
914
+ assertProposalTitle(input.title);
915
+ const bytes = markdownBytes(input.markdown);
916
+ assertDescriptionLength(bytes.byteLength);
917
+ const uploaded = await input.upload(bytes.slice(), {
918
+ title: input.title,
919
+ contentType: "text/markdown; charset=utf-8",
920
+ });
921
+ const descriptionUri = typeof uploaded === "string" ? uploaded : uploaded.uri;
922
+ return createProposalMetadata({ ...input, descriptionUri, markdown: bytes });
923
+ }
924
+
925
+ export function assertProposalMetadata(metadata: ProposalMetadataV1): void {
926
+ if (metadata.version !== PROPOSAL_METADATA_VERSION) {
927
+ throw new Error(`proposal metadata version must be ${PROPOSAL_METADATA_VERSION}`);
928
+ }
929
+ assertProposalTitle(metadata.title);
930
+ assertProposalUri(metadata.descriptionUri);
931
+ assertDescriptionLength(metadata.descriptionLen);
932
+ if (!Number.isInteger(metadata.descriptionLen)) {
933
+ throw new Error("descriptionLen must be an integer byte length");
934
+ }
935
+ if (metadata.descriptionSha256.length !== 32) {
936
+ throw new Error("descriptionSha256 must contain exactly 32 bytes");
937
+ }
938
+ for (const byte of metadata.descriptionSha256) {
939
+ if (!Number.isInteger(byte) || byte < 0 || byte > 255) {
940
+ throw new Error("descriptionSha256 must contain only bytes");
941
+ }
942
+ }
943
+ if (metadata.descriptionSha256.every((byte) => byte === 0)) {
944
+ throw new Error("descriptionSha256 must be nonzero");
945
+ }
946
+ }
947
+
948
+ export function assertProposalTitle(title: string): void {
949
+ const byteLength = new TextEncoder().encode(title).byteLength;
950
+ if (
951
+ byteLength < 1 ||
952
+ byteLength > MAX_PROPOSAL_TITLE_BYTES ||
953
+ title !== title.trim() ||
954
+ /\p{Cc}/u.test(title)
955
+ ) {
956
+ throw new Error(
957
+ `title must be trimmed, control-free UTF-8 occupying 1-${MAX_PROPOSAL_TITLE_BYTES} bytes`
958
+ );
959
+ }
960
+ }
961
+
962
+ export function assertProposalUri(uri: string): void {
963
+ const ascii = /^[\x00-\x7f]*$/.test(uri);
964
+ const validScheme = ["ipfs://", "ar://", "https://"].some(
965
+ (prefix) => uri.startsWith(prefix) && uri.length > prefix.length
966
+ );
967
+ if (
968
+ uri.length < 1 ||
969
+ uri.length > MAX_PROPOSAL_DESCRIPTION_URI_BYTES ||
970
+ !ascii ||
971
+ /[\x00-\x20\x7f]/.test(uri) ||
972
+ !validScheme
973
+ ) {
974
+ throw new Error(
975
+ `description URI must be a whitespace-free ipfs://, ar://, or https:// URI of at most ${MAX_PROPOSAL_DESCRIPTION_URI_BYTES} ASCII bytes`
976
+ );
977
+ }
978
+ }
979
+
980
+ /** Fetch no unbounded body, verify the exact byte count/hash, then decode strict UTF-8. */
981
+ export async function fetchAndVerifyProposalDescription(
982
+ metadata: ProposalMetadataV1,
983
+ options: ProposalDescriptionFetchOptions = {}
984
+ ): Promise<VerifiedProposalDescription> {
985
+ assertProposalMetadata(metadata);
986
+ const fetchImpl = options.fetch ?? globalThis.fetch?.bind(globalThis);
987
+ if (!fetchImpl) throw new Error("fetch is unavailable; supply ProposalDescriptionFetchOptions.fetch");
988
+ const resolved = options.resolveUri
989
+ ? await options.resolveUri(metadata.descriptionUri)
990
+ : resolveProposalDescriptionUri(metadata.descriptionUri, options);
991
+ const response = await fetchImpl(resolved, {
992
+ signal: options.signal,
993
+ headers: {
994
+ accept: "text/markdown, text/plain;q=0.9, application/octet-stream;q=0.8",
995
+ range: `bytes=0-${metadata.descriptionLen - 1}`,
996
+ },
997
+ });
998
+ if (!response.ok) {
999
+ throw new Error(`proposal description fetch failed with HTTP ${response.status}`);
1000
+ }
1001
+ const bytes = await readExactBody(response, metadata.descriptionLen);
1002
+ const actualHash = await sha256(bytes);
1003
+ if (!equalBytes(actualHash, metadata.descriptionSha256)) {
1004
+ throw new Error("proposal description SHA-256 does not match its on-chain metadata");
1005
+ }
1006
+ let markdown: string;
1007
+ try {
1008
+ markdown = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
1009
+ } catch {
1010
+ throw new Error("verified proposal description is not valid UTF-8");
1011
+ }
1012
+ return { verified: true, uri: metadata.descriptionUri, markdown, bytes };
1013
+ }
1014
+
1015
+ /** UI-friendly verification: failure is data, so callers can show title + typed diff. */
1016
+ export async function tryFetchProposalDescription(
1017
+ metadata: ProposalMetadataV1,
1018
+ options: ProposalDescriptionFetchOptions = {}
1019
+ ): Promise<ProposalDescriptionResult> {
1020
+ try {
1021
+ return await fetchAndVerifyProposalDescription(metadata, options);
1022
+ } catch (error) {
1023
+ return {
1024
+ verified: false,
1025
+ uri: metadata.descriptionUri,
1026
+ warning: "Proposal rationale is unavailable or failed on-chain length/hash verification.",
1027
+ error,
1028
+ };
1029
+ }
1030
+ }
1031
+
1032
+ export function resolveProposalDescriptionUri(
1033
+ uri: string,
1034
+ options: Pick<ProposalDescriptionFetchOptions, "ipfsGateway" | "arweaveGateway"> = {}
1035
+ ): string {
1036
+ assertProposalUri(uri);
1037
+ if (uri.startsWith("https://")) return uri;
1038
+ if (uri.startsWith("ipfs://")) {
1039
+ const payload = uri.slice("ipfs://".length).replace(/^ipfs\//, "");
1040
+ const gateway = (options.ipfsGateway ?? "https://ipfs.io/ipfs/").replace(/\/*$/, "/");
1041
+ return `${gateway}${payload}`;
1042
+ }
1043
+ const gateway = (options.arweaveGateway ?? "https://arweave.net/").replace(/\/*$/, "/");
1044
+ return `${gateway}${uri.slice("ar://".length)}`;
1045
+ }
1046
+
1047
+ /** Reproduce the immutable on-chain proposal digest over canonical Borsh bytes. */
1048
+ export async function computeParameterProposalDigest(
1049
+ input: ParameterProposalDigestInput
1050
+ ): Promise<Uint8Array> {
1051
+ assertProposalMetadata(input.metadata);
1052
+ assertFamilyRevisionCount(input.familyRevisions);
1053
+ const updates = canonicalParameterUpdates(input.updates);
1054
+ return sha256(
1055
+ concatBytes(
1056
+ PROPOSAL_DIGEST_DOMAIN,
1057
+ address(input.programId).toBytes(),
1058
+ address(input.market).toBytes(),
1059
+ address(input.proposer).toBytes(),
1060
+ encodeU64(input.nonce, "nonce"),
1061
+ ...input.familyRevisions.map((revision, family) =>
1062
+ encodeU64(revision, `familyRevisions[${family}]`)
1063
+ ),
1064
+ encodeU32(updates.length),
1065
+ ...updates.map(encodeParameterUpdate),
1066
+ encodeProposalMetadata(input.metadata)
1067
+ )
1068
+ );
1069
+ }
1070
+
1071
+ export async function verifyParameterProposalDigest(
1072
+ expected: Uint8Array | number[],
1073
+ input: ParameterProposalDigestInput
1074
+ ): Promise<boolean> {
1075
+ return equalBytes(await computeParameterProposalDigest(input), expected);
1076
+ }
1077
+
1078
+ export function computeDecodedParameterProposalDigest(
1079
+ programId: AddressLike,
1080
+ proposal: DecodedParameterProposalForDigest
1081
+ ): Promise<Uint8Array> {
1082
+ return computeParameterProposalDigest({
1083
+ programId,
1084
+ market: proposal.market,
1085
+ proposer: proposal.proposer,
1086
+ nonce: proposal.nonce,
1087
+ familyRevisions: proposal.familyRevisions,
1088
+ updates: proposal.updates.map(parameterUpdateFromAnchor),
1089
+ metadata: proposal.metadata,
1090
+ });
1091
+ }
1092
+
1093
+ export async function verifyDecodedParameterProposalDigest(
1094
+ programId: AddressLike,
1095
+ proposal: DecodedParameterProposalForDigest
1096
+ ): Promise<boolean> {
1097
+ if (!proposal.digest) throw new Error("decoded proposal is missing its digest");
1098
+ return equalBytes(await computeDecodedParameterProposalDigest(programId, proposal), proposal.digest);
1099
+ }
1100
+
1101
+ export function proposalSponsorshipFloor(eligibleYlp: GovernanceIntegerLike): bigint {
1102
+ const eligible = toU64BigInt(eligibleYlp, "eligibleYlp");
1103
+ if (eligible === 0n) throw new Error("eligibleYlp must be nonzero");
1104
+ return (
1105
+ eligible * BigInt(PARAMETER_PROPOSAL_SPONSOR_BPS) +
1106
+ BigInt(GOVERNANCE_BPS_DENOMINATOR - 1)
1107
+ ) / BigInt(GOVERNANCE_BPS_DENOMINATOR);
1108
+ }
1109
+
1110
+ export function hasStrictProposalMajority(
1111
+ lockedSupport: GovernanceIntegerLike,
1112
+ eligibleYlp: GovernanceIntegerLike
1113
+ ): boolean {
1114
+ const locked = toU64BigInt(lockedSupport, "lockedSupport");
1115
+ const eligible = toU64BigInt(eligibleYlp, "eligibleYlp");
1116
+ return (
1117
+ locked * BigInt(GOVERNANCE_BPS_DENOMINATOR) >
1118
+ eligible * BigInt(PARAMETER_PROPOSAL_SUPPORT_BPS)
1119
+ );
1120
+ }
1121
+
1122
+ export function minimumProposalQueueSupport(eligibleYlp: GovernanceIntegerLike): bigint {
1123
+ const eligible = toU64BigInt(eligibleYlp, "eligibleYlp");
1124
+ if (eligible === 0n) throw new Error("eligibleYlp must be nonzero");
1125
+ return eligible / 2n + 1n;
1126
+ }
1127
+
1128
+ export function eligibleDirectYlp(input: {
1129
+ mintSupply: GovernanceIntegerLike;
1130
+ governanceLockedYlp: GovernanceIntegerLike;
1131
+ baseHlpYlpVaultAmount: GovernanceIntegerLike;
1132
+ quoteHlpYlpVaultAmount: GovernanceIntegerLike;
1133
+ }): bigint {
1134
+ const totalOwnership =
1135
+ toU64BigInt(input.mintSupply, "mintSupply") +
1136
+ toU64BigInt(input.governanceLockedYlp, "governanceLockedYlp");
1137
+ if (totalOwnership > U64_MAX) throw new Error("total yLP ownership exceeded u64");
1138
+ const afterBase =
1139
+ totalOwnership - toU64BigInt(input.baseHlpYlpVaultAmount, "baseHlpYlpVaultAmount");
1140
+ if (afterBase < 0n) throw new Error("base hLP yLP vault exceeds total yLP ownership");
1141
+ const eligible =
1142
+ afterBase - toU64BigInt(input.quoteHlpYlpVaultAmount, "quoteHlpYlpVaultAmount");
1143
+ if (eligible < 0n) throw new Error("quote hLP yLP vault exceeds remaining yLP ownership");
1144
+ return eligible;
1145
+ }
1146
+
1147
+ export function governanceIntegerBN(value: GovernanceIntegerLike, label = "value"): BN {
1148
+ return toBN(toU64BigInt(value, label));
1149
+ }
1150
+
1151
+ function markdownBytes(markdown: ProposalMarkdown): Uint8Array {
1152
+ const bytes = typeof markdown === "string" ? new TextEncoder().encode(markdown) : markdown.slice();
1153
+ assertDescriptionLength(bytes.byteLength);
1154
+ try {
1155
+ new TextDecoder("utf-8", { fatal: true }).decode(bytes);
1156
+ } catch {
1157
+ throw new Error("proposal Markdown must contain valid UTF-8 bytes");
1158
+ }
1159
+ return bytes;
1160
+ }
1161
+
1162
+ function assertDescriptionLength(length: number): void {
1163
+ if (!Number.isInteger(length) || length < 1 || length > MAX_PROPOSAL_DESCRIPTION_BYTES) {
1164
+ throw new Error(`proposal Markdown must occupy 1-${MAX_PROPOSAL_DESCRIPTION_BYTES} bytes`);
1165
+ }
1166
+ }
1167
+
1168
+ function objectValue(value: unknown, label: string): Record<string, unknown> {
1169
+ if (value === null || typeof value !== "object") throw new Error(`${label} must be an object`);
1170
+ return value as Record<string, unknown>;
1171
+ }
1172
+
1173
+ function tupleField(value: unknown, label: string): unknown {
1174
+ const tuple = objectValue(value, `${label} tuple`);
1175
+ if (!("0" in tuple)) throw new Error(`${label} tuple is missing field 0`);
1176
+ return tuple["0"];
1177
+ }
1178
+
1179
+ function integerField(value: Record<string, unknown>, field: string): GovernanceIntegerLike {
1180
+ const candidate = value[field];
1181
+ if (
1182
+ typeof candidate !== "bigint" &&
1183
+ typeof candidate !== "number" &&
1184
+ typeof candidate !== "string" &&
1185
+ (candidate === null || typeof candidate !== "object" || !("toString" in candidate))
1186
+ ) {
1187
+ throw new Error(`${field} is missing or is not integer-like`);
1188
+ }
1189
+ return candidate as GovernanceIntegerLike;
1190
+ }
1191
+
1192
+ function numberField(value: Record<string, unknown>, field: string): number {
1193
+ const candidate = value[field];
1194
+ if (typeof candidate !== "number") throw new Error(`${field} is missing or is not a number`);
1195
+ return candidate;
1196
+ }
1197
+
1198
+ function assertBps(value: number, label: string, max: number, min = 0): void {
1199
+ if (!Number.isInteger(value) || value < min || value > max) {
1200
+ throw new Error(`${label} must be an integer from ${min} to ${max} bps`);
1201
+ }
1202
+ }
1203
+
1204
+ function assertRange(value: bigint, min: bigint, max: bigint, label: string): bigint {
1205
+ if (value < min || value > max) {
1206
+ throw new Error(`${label} must be between ${min} and ${max}`);
1207
+ }
1208
+ return value;
1209
+ }
1210
+
1211
+ function toU64BigInt(value: GovernanceIntegerLike, label: string): bigint {
1212
+ if (typeof value === "number" && !Number.isSafeInteger(value)) {
1213
+ throw new Error(`${label} must be a safe integer when supplied as a number`);
1214
+ }
1215
+ let normalized: bigint;
1216
+ try {
1217
+ normalized = BigInt(value.toString());
1218
+ } catch {
1219
+ throw new Error(`${label} must be an unsigned 64-bit integer`);
1220
+ }
1221
+ if (normalized < 0n || normalized > U64_MAX) {
1222
+ throw new Error(`${label} must be an unsigned 64-bit integer`);
1223
+ }
1224
+ return normalized;
1225
+ }
1226
+
1227
+ export function toBN(value: bigint): BN {
1228
+ return new AnchorBN(value.toString());
1229
+ }
1230
+
1231
+ function encodeParameterUpdate(update: ParameterUpdate): Uint8Array {
1232
+ assertParameterUpdate(update);
1233
+ switch (update.kind) {
1234
+ case "fee":
1235
+ return concatBytes(
1236
+ Uint8Array.of(0),
1237
+ encodeU16(update.profile.baseFeeBps),
1238
+ encodeU16(update.profile.divergenceFeeShareCapBps),
1239
+ encodeU16(update.profile.volatilityFeeShareCapBps),
1240
+ encodeU64(update.profile.divergenceFeeCoefficientNad, "divergenceFeeCoefficientNad"),
1241
+ encodeU64(update.profile.volatilityFeeCoefficientNad, "volatilityFeeCoefficientNad"),
1242
+ encodeU64(update.profile.volatilityHalfLifeMs, "volatilityHalfLifeMs"),
1243
+ encodeU64(update.profile.volatilityShockCapNad, "volatilityShockCapNad"),
1244
+ encodeU64(update.profile.volatilityAccumulatorCapNad, "volatilityAccumulatorCapNad"),
1245
+ Uint8Array.of(update.profile.swapFeeCollectMode),
1246
+ encodeU16(update.profile.compoundingFeeBps),
1247
+ encodeU16(update.profile.launchFeeStartBps),
1248
+ encodeU64(update.profile.launchFeeDurationSeconds, "launchFeeDurationSeconds"),
1249
+ Uint8Array.of(update.profile.launchFeeDecayMode),
1250
+ encodeU16(update.profile.launchMarketPriceStepBps),
1251
+ encodeU16(update.profile.launchMarketNumberOfPeriods),
1252
+ encodeU16(update.profile.launchMarketReductionFactorBps),
1253
+ Uint8Array.of(update.profile.launchRateLimitAsset),
1254
+ encodeU64(update.profile.launchRateLimitReferenceNad, "launchRateLimitReferenceNad"),
1255
+ encodeU16(update.profile.launchRateLimitIncrementBps),
1256
+ encodeU16(update.profile.launchRateLimitMaxFeeBps),
1257
+ encodeU64(
1258
+ update.profile.launchRateLimitDurationSeconds,
1259
+ "launchRateLimitDurationSeconds"
1260
+ )
1261
+ );
1262
+ case "concentration":
1263
+ return concatBytes(
1264
+ Uint8Array.of(1),
1265
+ encodeU64(update.peakAmplificationNad, "peakAmplificationNad"),
1266
+ encodeU16(update.coreHalfWidthBps),
1267
+ encodeU16(update.fadeWidthBps)
1268
+ );
1269
+ case "irm":
1270
+ return concatBytes(
1271
+ Uint8Array.of(2),
1272
+ encodeU64(update.config.lowerSignalNad, "lowerSignalNad"),
1273
+ encodeU64(update.config.upperSignalNad, "upperSignalNad"),
1274
+ encodeU64(update.config.halfLifeMs, "halfLifeMs"),
1275
+ encodeU64(update.config.initialAprNad, "initialAprNad"),
1276
+ encodeU64(update.config.minimumAprNad, "minimumAprNad"),
1277
+ encodeU64(update.config.maximumAprNad, "maximumAprNad"),
1278
+ encodeU16(update.config.borrowUtilizationLimitBps)
1279
+ );
1280
+ case "emaHalfLives":
1281
+ return concatBytes(
1282
+ Uint8Array.of(3),
1283
+ encodeU64(update.priceMs, "priceMs"),
1284
+ encodeU64(update.directionalPriceMs, "directionalPriceMs"),
1285
+ encodeU64(update.curveDepthMs, "curveDepthMs"),
1286
+ encodeU64(update.centerPriceMs, "centerPriceMs")
1287
+ );
1288
+ case "dailyBorrowLimit":
1289
+ return concatBytes(Uint8Array.of(4), encodeU16(update.maxDailyBorrowBps));
1290
+ case "centerController":
1291
+ return concatBytes(
1292
+ Uint8Array.of(5),
1293
+ encodeU64(update.adjustmentThresholdNad, "adjustmentThresholdNad"),
1294
+ encodeU64(update.adjustmentStepNad, "adjustmentStepNad"),
1295
+ encodeU64(update.minAdjustmentIntervalSlots, "minAdjustmentIntervalSlots")
1296
+ );
1297
+ case "oracle":
1298
+ return concatBytes(Uint8Array.of(7), encodeOraclePolicy(update.policy));
1299
+ case "insuranceDrawCaps":
1300
+ return concatBytes(Uint8Array.of(6), encodeU16(update.principalCoverageBps), encodeU16(update.perDayBps));
1301
+ case "tranche":
1302
+ return concatBytes(
1303
+ Uint8Array.of(8),
1304
+ encodeU16(update.juniorIncomeShareBps),
1305
+ encodeU16(update.requestFeeBps),
1306
+ encodeU16(update.liquidationFeeBps)
1307
+ );
1308
+ }
1309
+ }
1310
+
1311
+ function assertFamilyRevisionCount(revisions: readonly GovernanceIntegerLike[]): void {
1312
+ if (revisions.length !== PARAMETER_FAMILY_COUNT) {
1313
+ throw new Error(`expected ${PARAMETER_FAMILY_COUNT} family revisions, got ${revisions.length}`);
1314
+ }
1315
+ }
1316
+
1317
+ function encodeProposalMetadata(metadata: ProposalMetadataV1): Uint8Array {
1318
+ return concatBytes(
1319
+ Uint8Array.of(metadata.version),
1320
+ encodeBorshString(metadata.title),
1321
+ encodeBorshString(metadata.descriptionUri),
1322
+ Uint8Array.from(metadata.descriptionSha256),
1323
+ encodeU32(metadata.descriptionLen)
1324
+ );
1325
+ }
1326
+
1327
+ function encodeBorshString(value: string): Uint8Array {
1328
+ const bytes = new TextEncoder().encode(value);
1329
+ return concatBytes(encodeU32(bytes.byteLength), bytes);
1330
+ }
1331
+
1332
+ function encodeU16(value: number): Uint8Array {
1333
+ if (!Number.isInteger(value) || value < 0 || value > 0xffff) {
1334
+ throw new Error("value must fit in u16");
1335
+ }
1336
+ const bytes = new Uint8Array(2);
1337
+ new DataView(bytes.buffer).setUint16(0, value, true);
1338
+ return bytes;
1339
+ }
1340
+
1341
+ function encodeU32(value: number): Uint8Array {
1342
+ if (!Number.isInteger(value) || value < 0 || value > 0xffff_ffff) {
1343
+ throw new Error("value must fit in u32");
1344
+ }
1345
+ const bytes = new Uint8Array(4);
1346
+ new DataView(bytes.buffer).setUint32(0, value, true);
1347
+ return bytes;
1348
+ }
1349
+
1350
+ function encodeU64(value: GovernanceIntegerLike, label: string): Uint8Array {
1351
+ const normalized = toU64BigInt(value, label);
1352
+ const bytes = new Uint8Array(8);
1353
+ new DataView(bytes.buffer).setBigUint64(0, normalized, true);
1354
+ return bytes;
1355
+ }
1356
+
1357
+ function concatBytes(...parts: readonly Uint8Array[]): Uint8Array {
1358
+ const total = parts.reduce((sum, part) => sum + part.byteLength, 0);
1359
+ const output = new Uint8Array(total);
1360
+ let offset = 0;
1361
+ for (const part of parts) {
1362
+ output.set(part, offset);
1363
+ offset += part.byteLength;
1364
+ }
1365
+ return output;
1366
+ }
1367
+
1368
+ function equalBytes(left: Uint8Array | readonly number[], right: Uint8Array | readonly number[]): boolean {
1369
+ if (left.length !== right.length) return false;
1370
+ let difference = 0;
1371
+ for (let index = 0; index < left.length; index += 1) {
1372
+ difference |= left[index]! ^ right[index]!;
1373
+ }
1374
+ return difference === 0;
1375
+ }
1376
+
1377
+ async function readExactBody(response: Response, expectedLength: number): Promise<Uint8Array> {
1378
+ const contentRange = response.headers.get("content-range");
1379
+ if (response.status === 206) {
1380
+ const match = /^bytes\s+(\d+)-(\d+)\/(\d+|\*)$/i.exec(contentRange ?? "");
1381
+ if (!match) throw new Error("partial proposal response is missing a valid Content-Range");
1382
+ const start = Number(match[1]);
1383
+ const end = Number(match[2]);
1384
+ const total = match[3] === "*" ? null : Number(match[3]);
1385
+ if (start !== 0 || end + 1 !== expectedLength || total !== expectedLength) {
1386
+ throw new Error("proposal description response does not have the exact on-chain byte length");
1387
+ }
1388
+ } else {
1389
+ const contentLength = response.headers.get("content-length");
1390
+ const contentEncoding = response.headers.get("content-encoding");
1391
+ if (contentLength !== null && !contentEncoding && Number(contentLength) !== expectedLength) {
1392
+ throw new Error("proposal description Content-Length does not match on-chain metadata");
1393
+ }
1394
+ }
1395
+
1396
+ if (!response.body) {
1397
+ const bytes = new Uint8Array(await response.arrayBuffer());
1398
+ if (bytes.byteLength !== expectedLength) {
1399
+ throw new Error("proposal description byte length does not match on-chain metadata");
1400
+ }
1401
+ return bytes;
1402
+ }
1403
+
1404
+ const output = new Uint8Array(expectedLength);
1405
+ const reader = response.body.getReader();
1406
+ let offset = 0;
1407
+ while (true) {
1408
+ const { value, done } = await reader.read();
1409
+ if (done) break;
1410
+ if (!value) continue;
1411
+ if (offset + value.byteLength > expectedLength) {
1412
+ await reader.cancel();
1413
+ throw new Error("proposal description exceeds its on-chain byte length");
1414
+ }
1415
+ output.set(value, offset);
1416
+ offset += value.byteLength;
1417
+ }
1418
+ if (offset !== expectedLength) {
1419
+ throw new Error("proposal description byte length does not match on-chain metadata");
1420
+ }
1421
+ return output;
1422
+ }