@omnipair/dusk-sdk 2.0.2 → 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 (187) hide show
  1. package/README.md +1011 -16
  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 +71 -14
  7. package/dist/constants.d.ts.map +1 -1
  8. package/dist/constants.js +155 -28
  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 +3253 -378
  19. package/dist/get.d.ts.map +1 -1
  20. package/dist/get.js +130 -70
  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 +17175 -5862
  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/risk-pricing.d.ts +14 -0
  101. package/dist/risk-pricing.d.ts.map +1 -0
  102. package/dist/risk-pricing.js +25 -0
  103. package/dist/risk-pricing.js.map +1 -0
  104. package/dist/simulation.d.ts +45 -0
  105. package/dist/simulation.d.ts.map +1 -0
  106. package/dist/simulation.js +106 -0
  107. package/dist/simulation.js.map +1 -0
  108. package/dist/tranche-client.d.ts +121 -0
  109. package/dist/tranche-client.d.ts.map +1 -0
  110. package/dist/tranche-client.js +185 -0
  111. package/dist/tranche-client.js.map +1 -0
  112. package/dist/transfer-fees.d.ts +46 -0
  113. package/dist/transfer-fees.d.ts.map +1 -0
  114. package/dist/transfer-fees.js +76 -0
  115. package/dist/transfer-fees.js.map +1 -0
  116. package/dist/type-aliases.d.ts +271 -31
  117. package/dist/type-aliases.d.ts.map +1 -1
  118. package/dist/types_delegate.d.ts +6126 -0
  119. package/dist/types_delegate.d.ts.map +1 -0
  120. package/dist/types_delegate.js +2 -0
  121. package/dist/types_delegate.js.map +1 -0
  122. package/dist/types_v2.d.ts +17235 -5922
  123. package/dist/types_v2.d.ts.map +1 -1
  124. package/dist/virtual-book/index.d.ts +4 -0
  125. package/dist/virtual-book/index.d.ts.map +1 -0
  126. package/dist/virtual-book/index.js +4 -0
  127. package/dist/virtual-book/index.js.map +1 -0
  128. package/dist/virtual-book/market.d.ts +608 -0
  129. package/dist/virtual-book/market.d.ts.map +1 -0
  130. package/dist/virtual-book/market.js +59 -0
  131. package/dist/virtual-book/market.js.map +1 -0
  132. package/dist/virtual-book/projection.d.ts +44 -0
  133. package/dist/virtual-book/projection.d.ts.map +1 -0
  134. package/dist/virtual-book/projection.js +229 -0
  135. package/dist/virtual-book/projection.js.map +1 -0
  136. package/dist/virtual-book/quotes.d.ts +1241 -0
  137. package/dist/virtual-book/quotes.d.ts.map +1 -0
  138. package/dist/virtual-book/quotes.js +233 -0
  139. package/dist/virtual-book/quotes.js.map +1 -0
  140. package/dist/write.d.ts +517 -1
  141. package/dist/write.d.ts.map +1 -1
  142. package/dist/write.js +1172 -23
  143. package/dist/write.js.map +1 -1
  144. package/dist/yield-client.d.ts +51 -0
  145. package/dist/yield-client.d.ts.map +1 -0
  146. package/dist/yield-client.js +98 -0
  147. package/dist/yield-client.js.map +1 -0
  148. package/package.json +9 -2
  149. package/src/amounts.ts +13 -0
  150. package/src/constants.ts +236 -26
  151. package/src/delegate.ts +238 -0
  152. package/src/dusk.ts +28 -0
  153. package/src/get.ts +247 -82
  154. package/src/governance-client.ts +234 -0
  155. package/src/governance.ts +1422 -0
  156. package/src/hash.ts +15 -0
  157. package/src/hlp-liquidation-client.ts +195 -0
  158. package/src/idl_delegate.json +6119 -0
  159. package/src/idl_delegate.ts +3 -0
  160. package/src/idl_v2.json +17175 -5862
  161. package/src/index.ts +31 -0
  162. package/src/interest-accounting.ts +85 -0
  163. package/src/leverage-actions.ts +216 -0
  164. package/src/leverage-margins.ts +48 -0
  165. package/src/leverage-preview.ts +86 -0
  166. package/src/liquidation-client.ts +297 -0
  167. package/src/liquidation.ts +137 -0
  168. package/src/lp-naming.ts +127 -0
  169. package/src/lp-vanity.ts +135 -0
  170. package/src/market-bootstrap.ts +273 -0
  171. package/src/market-launch.ts +103 -0
  172. package/src/oracle.ts +120 -0
  173. package/src/preview.ts +53 -1
  174. package/src/protection.ts +112 -0
  175. package/src/risk-pricing.ts +28 -0
  176. package/src/simulation.ts +169 -0
  177. package/src/tranche-client.ts +187 -0
  178. package/src/transfer-fees.ts +99 -0
  179. package/src/type-aliases.ts +280 -31
  180. package/src/types_delegate.ts +6125 -0
  181. package/src/types_v2.ts +17174 -5861
  182. package/src/virtual-book/index.ts +3 -0
  183. package/src/virtual-book/market.ts +76 -0
  184. package/src/virtual-book/projection.ts +265 -0
  185. package/src/virtual-book/quotes.ts +308 -0
  186. package/src/write.ts +2073 -34
  187. package/src/yield-client.ts +117 -0
@@ -0,0 +1,902 @@
1
+ import { oraclePolicy, encodeOraclePolicy } from "./oracle.js";
2
+ import * as anchorNamespace from "@coral-xyz/anchor";
3
+ import { address } from "./address.js";
4
+ import { GOVERNANCE_BPS_DENOMINATOR, MAX_PROPOSAL_DESCRIPTION_BYTES, MAX_PROPOSAL_DESCRIPTION_URI_BYTES, MAX_PROPOSAL_TITLE_BYTES, PARAMETER_PROPOSAL_SPONSOR_BPS, PARAMETER_PROPOSAL_SUPPORT_BPS, PROPOSAL_METADATA_VERSION, } from "./constants.js";
5
+ import { sha256 } from "./hash.js";
6
+ export const NAD = 1000000000n;
7
+ export const MIN_PARAMETER_HALF_LIFE_MS = 60000n;
8
+ export const MAX_PARAMETER_HALF_LIFE_MS = 12n * 60n * 60n * 1000n;
9
+ export const MAX_PARAMETER_FEE_BPS = 5_000;
10
+ export const MIN_IRM_TARGET_UTILIZATION_BPS = 6_000;
11
+ export const MAX_IRM_TARGET_UTILIZATION_BPS = 7_500;
12
+ export const MIN_IRM_CURVE_STEEPNESS_NAD = 2n * NAD;
13
+ export const MAX_IRM_CURVE_STEEPNESS_NAD = 8n * NAD;
14
+ export const MIN_IRM_ADJUSTMENT_SPEED_PER_YEAR = 1n;
15
+ export const MAX_IRM_ADJUSTMENT_SPEED_PER_YEAR = 50n;
16
+ export const MAX_CONCENTRATION_AMPLIFICATION_NAD = 2000n * NAD;
17
+ export const MAX_FEE_COEFFICIENT_NAD = 100n * NAD;
18
+ export const MAX_VOLATILITY_ACCUMULATOR_NAD = 10n * NAD;
19
+ export const MAX_DAILY_BORROW_BPS = 3_000;
20
+ export const MIN_CENTER_ADJUSTMENT_NAD = NAD / 1000000n;
21
+ export const MAX_CENTER_ADJUSTMENT_NAD = NAD / 10n;
22
+ // One nominal day of scheduled 200 ms slots, matching the program cap.
23
+ export const MAX_CENTER_ADJUSTMENT_INTERVAL_SLOTS = 432000n;
24
+ export const MAX_LAUNCH_FEE_DURATION_SECONDS = 30n * 24n * 60n * 60n;
25
+ export const LAUNCH_FEE_DECAY_DISABLED = 0;
26
+ export const LAUNCH_FEE_DECAY_LINEAR = 1;
27
+ export const LAUNCH_FEE_DECAY_EXPONENTIAL = 2;
28
+ export const LAUNCH_RATE_LIMIT_ASSET_DISABLED = 0;
29
+ export const LAUNCH_RATE_LIMIT_ASSET_BASE = 1;
30
+ export const LAUNCH_RATE_LIMIT_ASSET_QUOTE = 2;
31
+ export const SWAP_FEE_COLLECT_INPUT_ASSET = 0;
32
+ export const SWAP_FEE_COLLECT_BASE_ONLY = 1;
33
+ export const SWAP_FEE_COLLECT_QUOTE_ONLY = 2;
34
+ export const MAX_LAUNCH_MARKET_FEE_PERIODS = 64;
35
+ export const MAX_INSURANCE_PRINCIPAL_COVERAGE_BPS = 7_500;
36
+ export const MAX_INSURANCE_DRAW_PER_DAY_BPS = 5_000;
37
+ export const MIN_JUNIOR_INCOME_SHARE_BPS = 1_000;
38
+ export const MAX_JUNIOR_INCOME_SHARE_BPS = 9_000;
39
+ export const MIN_JUNIOR_EXIT_REQUEST_FEE_BPS = 1;
40
+ export const MAX_JUNIOR_EXIT_REQUEST_FEE_BPS = 50;
41
+ export const MIN_LIQUIDATION_FEE_BPS = 25;
42
+ export const MAX_LIQUIDATION_FEE_BPS = 300;
43
+ /** Governed parameter families, and the length of a market's revision list. */
44
+ export const PARAMETER_FAMILY_COUNT = 9;
45
+ /** A proposal changes one to nine families, each at most once. */
46
+ export const MAX_PARAMETER_UPDATES_PER_PROPOSAL = PARAMETER_FAMILY_COUNT;
47
+ export const PARAMETER_PROPOSAL_DIGEST_DOMAIN = "DUSK_PARAMETER_PROPOSAL_V2";
48
+ const U64_MAX = 0xffffffffffffffffn;
49
+ const PROPOSAL_DIGEST_DOMAIN = new TextEncoder().encode(PARAMETER_PROPOSAL_DIGEST_DOMAIN);
50
+ const anchorExports = anchorNamespace;
51
+ const AnchorBN = (anchorExports.BN ?? anchorExports.default?.BN);
52
+ /** Normalize and validate the complete mutable fee family. */
53
+ export function feeParameterUpdate(input) {
54
+ assertBps(input.baseFeeBps, "baseFeeBps", MAX_PARAMETER_FEE_BPS);
55
+ assertBps(input.divergenceFeeShareCapBps, "divergenceFeeShareCapBps", MAX_PARAMETER_FEE_BPS);
56
+ assertBps(input.volatilityFeeShareCapBps, "volatilityFeeShareCapBps", MAX_PARAMETER_FEE_BPS);
57
+ if (input.baseFeeBps +
58
+ input.divergenceFeeShareCapBps +
59
+ input.volatilityFeeShareCapBps >
60
+ MAX_PARAMETER_FEE_BPS) {
61
+ throw new Error(`fee component caps must sum to at most ${MAX_PARAMETER_FEE_BPS} bps`);
62
+ }
63
+ const divergenceFeeCoefficientNad = toU64BigInt(input.divergenceFeeCoefficientNad, "divergenceFeeCoefficientNad");
64
+ const volatilityFeeCoefficientNad = toU64BigInt(input.volatilityFeeCoefficientNad, "volatilityFeeCoefficientNad");
65
+ const volatilityHalfLifeMs = assertRange(toU64BigInt(input.volatilityHalfLifeMs, "volatilityHalfLifeMs"), MIN_PARAMETER_HALF_LIFE_MS, MAX_PARAMETER_HALF_LIFE_MS, "volatilityHalfLifeMs");
66
+ const volatilityShockCapNad = toU64BigInt(input.volatilityShockCapNad, "volatilityShockCapNad");
67
+ const volatilityAccumulatorCapNad = toU64BigInt(input.volatilityAccumulatorCapNad, "volatilityAccumulatorCapNad");
68
+ assertRange(divergenceFeeCoefficientNad, 0n, MAX_FEE_COEFFICIENT_NAD, "divergenceFeeCoefficientNad");
69
+ assertRange(volatilityFeeCoefficientNad, 0n, MAX_FEE_COEFFICIENT_NAD, "volatilityFeeCoefficientNad");
70
+ const signalDisabled = volatilityShockCapNad === 0n && volatilityAccumulatorCapNad === 0n;
71
+ const signalValid = volatilityShockCapNad > 0n &&
72
+ volatilityShockCapNad <= volatilityAccumulatorCapNad &&
73
+ volatilityAccumulatorCapNad <= MAX_VOLATILITY_ACCUMULATOR_NAD;
74
+ if (!signalDisabled && !signalValid) {
75
+ throw new Error("volatility caps must both be zero, or shock > 0, shock <= accumulator, and accumulator <= 10 NAD");
76
+ }
77
+ if (volatilityFeeCoefficientNad !== 0n && !signalValid) {
78
+ throw new Error("a nonzero volatility fee coefficient requires an enabled volatility signal");
79
+ }
80
+ const swapFeeCollectMode = input.swapFeeCollectMode ?? SWAP_FEE_COLLECT_INPUT_ASSET;
81
+ if (![
82
+ SWAP_FEE_COLLECT_INPUT_ASSET,
83
+ SWAP_FEE_COLLECT_BASE_ONLY,
84
+ SWAP_FEE_COLLECT_QUOTE_ONLY,
85
+ ].includes(swapFeeCollectMode)) {
86
+ throw new Error("invalid swap fee collection mode");
87
+ }
88
+ const compoundingFeeBps = input.compoundingFeeBps ?? 0;
89
+ assertBps(compoundingFeeBps, "compoundingFeeBps", GOVERNANCE_BPS_DENOMINATOR);
90
+ const launchFeeStartBps = input.launchFeeStartBps ?? 0;
91
+ const launchFeeDurationSeconds = toU64BigInt(input.launchFeeDurationSeconds ?? 0, "launchFeeDurationSeconds");
92
+ const launchFeeDecayMode = input.launchFeeDecayMode ?? LAUNCH_FEE_DECAY_DISABLED;
93
+ const launchMarketPriceStepBps = input.launchMarketPriceStepBps ?? 0;
94
+ const launchMarketNumberOfPeriods = input.launchMarketNumberOfPeriods ?? 0;
95
+ const launchMarketReductionFactorBps = input.launchMarketReductionFactorBps ?? 0;
96
+ const marketScheduleDisabled = launchMarketPriceStepBps === 0 &&
97
+ launchMarketNumberOfPeriods === 0 &&
98
+ launchMarketReductionFactorBps === 0;
99
+ const marketScheduleEnabled = launchMarketPriceStepBps > 0 &&
100
+ launchMarketNumberOfPeriods > 0 &&
101
+ launchMarketNumberOfPeriods <= MAX_LAUNCH_MARKET_FEE_PERIODS &&
102
+ launchMarketReductionFactorBps > 0 &&
103
+ launchMarketReductionFactorBps < GOVERNANCE_BPS_DENOMINATOR;
104
+ const launchFeeDisabled = launchFeeStartBps === 0 &&
105
+ launchFeeDurationSeconds === 0n &&
106
+ launchFeeDecayMode === LAUNCH_FEE_DECAY_DISABLED &&
107
+ marketScheduleDisabled;
108
+ if (!launchFeeDisabled &&
109
+ (launchFeeStartBps <= input.baseFeeBps ||
110
+ launchFeeStartBps > MAX_PARAMETER_FEE_BPS ||
111
+ launchFeeDurationSeconds < 1n ||
112
+ launchFeeDurationSeconds > MAX_LAUNCH_FEE_DURATION_SECONDS ||
113
+ ![LAUNCH_FEE_DECAY_LINEAR, LAUNCH_FEE_DECAY_EXPONENTIAL].includes(launchFeeDecayMode))) {
114
+ throw new Error("invalid launch fee start, duration, or decay mode");
115
+ }
116
+ if (!launchFeeDisabled && !marketScheduleDisabled && !marketScheduleEnabled) {
117
+ throw new Error("invalid launch market-cap fee schedule");
118
+ }
119
+ if (marketScheduleEnabled &&
120
+ ![SWAP_FEE_COLLECT_BASE_ONLY, SWAP_FEE_COLLECT_QUOTE_ONLY].includes(swapFeeCollectMode)) {
121
+ throw new Error("a market-cap fee schedule requires a fixed fee asset");
122
+ }
123
+ if (!launchFeeDisabled &&
124
+ launchFeeStartBps + input.divergenceFeeShareCapBps + input.volatilityFeeShareCapBps >
125
+ MAX_PARAMETER_FEE_BPS) {
126
+ throw new Error(`launch fee component caps must sum to at most ${MAX_PARAMETER_FEE_BPS} bps`);
127
+ }
128
+ const launchRateLimitAsset = input.launchRateLimitAsset ?? LAUNCH_RATE_LIMIT_ASSET_DISABLED;
129
+ const launchRateLimitReferenceNad = toU64BigInt(input.launchRateLimitReferenceNad ?? 0, "launchRateLimitReferenceNad");
130
+ const launchRateLimitIncrementBps = input.launchRateLimitIncrementBps ?? 0;
131
+ const launchRateLimitMaxFeeBps = input.launchRateLimitMaxFeeBps ?? 0;
132
+ const launchRateLimitDurationSeconds = toU64BigInt(input.launchRateLimitDurationSeconds ?? 0, "launchRateLimitDurationSeconds");
133
+ const rateLimitDisabled = launchRateLimitAsset === LAUNCH_RATE_LIMIT_ASSET_DISABLED &&
134
+ launchRateLimitReferenceNad === 0n &&
135
+ launchRateLimitIncrementBps === 0 &&
136
+ launchRateLimitMaxFeeBps === 0 &&
137
+ launchRateLimitDurationSeconds === 0n;
138
+ const scheduledPeak = launchFeeDisabled ? input.baseFeeBps : launchFeeStartBps;
139
+ if (!rateLimitDisabled &&
140
+ (![LAUNCH_RATE_LIMIT_ASSET_BASE, LAUNCH_RATE_LIMIT_ASSET_QUOTE].includes(launchRateLimitAsset) ||
141
+ launchRateLimitReferenceNad === 0n ||
142
+ launchRateLimitIncrementBps <= 0 ||
143
+ launchRateLimitMaxFeeBps <= input.baseFeeBps ||
144
+ launchRateLimitMaxFeeBps < scheduledPeak ||
145
+ launchRateLimitDurationSeconds < 1n ||
146
+ launchRateLimitDurationSeconds > MAX_LAUNCH_FEE_DURATION_SECONDS)) {
147
+ throw new Error("invalid launch buy-size limiter configuration");
148
+ }
149
+ if (!rateLimitDisabled) {
150
+ assertBps(launchRateLimitIncrementBps, "launchRateLimitIncrementBps", MAX_PARAMETER_FEE_BPS, 1);
151
+ assertBps(launchRateLimitMaxFeeBps, "launchRateLimitMaxFeeBps", MAX_PARAMETER_FEE_BPS, 1);
152
+ if (launchRateLimitMaxFeeBps +
153
+ input.divergenceFeeShareCapBps +
154
+ input.volatilityFeeShareCapBps >
155
+ MAX_PARAMETER_FEE_BPS) {
156
+ throw new Error(`rate-limit fee component caps must sum to at most ${MAX_PARAMETER_FEE_BPS} bps`);
157
+ }
158
+ }
159
+ return {
160
+ kind: "fee",
161
+ profile: {
162
+ baseFeeBps: input.baseFeeBps,
163
+ divergenceFeeShareCapBps: input.divergenceFeeShareCapBps,
164
+ volatilityFeeShareCapBps: input.volatilityFeeShareCapBps,
165
+ divergenceFeeCoefficientNad: toBN(divergenceFeeCoefficientNad),
166
+ volatilityFeeCoefficientNad: toBN(volatilityFeeCoefficientNad),
167
+ volatilityHalfLifeMs: toBN(volatilityHalfLifeMs),
168
+ volatilityShockCapNad: toBN(volatilityShockCapNad),
169
+ volatilityAccumulatorCapNad: toBN(volatilityAccumulatorCapNad),
170
+ swapFeeCollectMode,
171
+ compoundingFeeBps,
172
+ launchFeeStartBps,
173
+ launchFeeDurationSeconds: toBN(launchFeeDurationSeconds),
174
+ launchFeeDecayMode,
175
+ launchMarketPriceStepBps,
176
+ launchMarketNumberOfPeriods,
177
+ launchMarketReductionFactorBps,
178
+ launchRateLimitAsset,
179
+ launchRateLimitReferenceNad: toBN(launchRateLimitReferenceNad),
180
+ launchRateLimitIncrementBps,
181
+ launchRateLimitMaxFeeBps,
182
+ launchRateLimitDurationSeconds: toBN(launchRateLimitDurationSeconds),
183
+ },
184
+ };
185
+ }
186
+ /** Standard launch-token fee template: Base is sold and all swap revenue is Quote. */
187
+ export function standardLaunchFeeParameterUpdate(input) {
188
+ return feeParameterUpdate({
189
+ ...input,
190
+ swapFeeCollectMode: SWAP_FEE_COLLECT_QUOTE_ONLY,
191
+ launchRateLimitAsset: LAUNCH_RATE_LIMIT_ASSET_BASE,
192
+ });
193
+ }
194
+ /** Build an atomic, protected concentration update. */
195
+ export function concentrationParameterUpdate(input) {
196
+ const peakAmplificationNad = toU64BigInt(input.peakAmplificationNad, "peakAmplificationNad");
197
+ assertBps(input.coreHalfWidthBps, "coreHalfWidthBps", 0xffff);
198
+ assertBps(input.fadeWidthBps, "fadeWidthBps", 0xffff);
199
+ if (input.coreHalfWidthBps + input.fadeWidthBps > 0xffff) {
200
+ throw new Error("coreHalfWidthBps + fadeWidthBps must fit in u16");
201
+ }
202
+ if (peakAmplificationNad === NAD) {
203
+ if (input.coreHalfWidthBps !== 0 || input.fadeWidthBps !== 0) {
204
+ throw new Error("CPMM concentration must use zero core and fade widths");
205
+ }
206
+ }
207
+ else {
208
+ if (peakAmplificationNad <= NAD || peakAmplificationNad > MAX_CONCENTRATION_AMPLIFICATION_NAD) {
209
+ throw new Error("peakAmplificationNad is outside the amplification policy");
210
+ }
211
+ if (input.coreHalfWidthBps === 0) {
212
+ throw new Error("concentrated curves require a nonzero coreHalfWidthBps");
213
+ }
214
+ }
215
+ return {
216
+ kind: "concentration",
217
+ peakAmplificationNad: toBN(peakAmplificationNad),
218
+ coreHalfWidthBps: input.coreHalfWidthBps,
219
+ fadeWidthBps: input.fadeWidthBps,
220
+ };
221
+ }
222
+ export function irmParameterUpdate(input) {
223
+ assertBps(input.borrowUtilizationLimitBps, "borrowUtilizationLimitBps", 10_000, 1);
224
+ const lowerSignalNad = toU64BigInt(input.lowerSignalNad, "lowerSignalNad");
225
+ const upperSignalNad = toU64BigInt(input.upperSignalNad, "upperSignalNad");
226
+ const halfLifeMs = toU64BigInt(input.halfLifeMs, "halfLifeMs");
227
+ const initialAprNad = toU64BigInt(input.initialAprNad, "initialAprNad");
228
+ const minimumAprNad = toU64BigInt(input.minimumAprNad, "minimumAprNad");
229
+ const maximumAprNad = toU64BigInt(input.maximumAprNad, "maximumAprNad");
230
+ if (lowerSignalNad === 0n || upperSignalNad <= lowerSignalNad)
231
+ throw new Error("Invalid coverage target band");
232
+ assertRange(halfLifeMs, 3600000n, 30n * 86400000n, "halfLifeMs");
233
+ if (initialAprNad === 0n || minimumAprNad > initialAprNad || (maximumAprNad !== 0n && maximumAprNad < initialAprNad)) {
234
+ throw new Error("Invalid initial APR, floor, or ceiling");
235
+ }
236
+ return { kind: "irm", config: {
237
+ lowerSignalNad: toBN(lowerSignalNad),
238
+ upperSignalNad: toBN(upperSignalNad),
239
+ halfLifeMs: toBN(halfLifeMs),
240
+ initialAprNad: toBN(initialAprNad),
241
+ minimumAprNad: toBN(minimumAprNad),
242
+ maximumAprNad: toBN(maximumAprNad),
243
+ borrowUtilizationLimitBps: input.borrowUtilizationLimitBps,
244
+ } };
245
+ }
246
+ export function emaHalfLivesParameterUpdate(input) {
247
+ const normalize = (value, label) => toBN(assertRange(toU64BigInt(value, label), MIN_PARAMETER_HALF_LIFE_MS, MAX_PARAMETER_HALF_LIFE_MS, label));
248
+ return {
249
+ kind: "emaHalfLives",
250
+ priceMs: normalize(input.priceMs, "priceMs"),
251
+ directionalPriceMs: normalize(input.directionalPriceMs, "directionalPriceMs"),
252
+ curveDepthMs: normalize(input.curveDepthMs, "curveDepthMs"),
253
+ centerPriceMs: normalize(input.centerPriceMs, "centerPriceMs"),
254
+ };
255
+ }
256
+ export function dailyBorrowLimitParameterUpdate(maxDailyBorrowBps) {
257
+ assertBps(maxDailyBorrowBps, "maxDailyBorrowBps", MAX_DAILY_BORROW_BPS);
258
+ return { kind: "dailyBorrowLimit", maxDailyBorrowBps };
259
+ }
260
+ export function centerControllerParameterUpdate(input) {
261
+ const adjustmentThresholdNad = toU64BigInt(input.adjustmentThresholdNad, "adjustmentThresholdNad");
262
+ const adjustmentStepNad = toU64BigInt(input.adjustmentStepNad, "adjustmentStepNad");
263
+ const minAdjustmentIntervalSlots = toU64BigInt(input.minAdjustmentIntervalSlots, "minAdjustmentIntervalSlots");
264
+ const disabled = adjustmentThresholdNad === 0n && adjustmentStepNad === 0n && minAdjustmentIntervalSlots === 0n;
265
+ if (!disabled &&
266
+ (adjustmentStepNad < MIN_CENTER_ADJUSTMENT_NAD ||
267
+ adjustmentStepNad > MAX_CENTER_ADJUSTMENT_NAD ||
268
+ adjustmentThresholdNad < adjustmentStepNad ||
269
+ adjustmentThresholdNad > MAX_CENTER_ADJUSTMENT_NAD ||
270
+ minAdjustmentIntervalSlots < 1n ||
271
+ minAdjustmentIntervalSlots > MAX_CENTER_ADJUSTMENT_INTERVAL_SLOTS)) {
272
+ throw new Error("invalid center-controller threshold, step, or interval");
273
+ }
274
+ return {
275
+ kind: "centerController",
276
+ adjustmentThresholdNad: toBN(adjustmentThresholdNad),
277
+ adjustmentStepNad: toBN(adjustmentStepNad),
278
+ minAdjustmentIntervalSlots: toBN(minAdjustmentIntervalSlots),
279
+ };
280
+ }
281
+ /** Insurance loss-concentration caps; they may only tighten the protocol ceilings. */
282
+ export function insuranceDrawCapsParameterUpdate(input) {
283
+ assertBps(input.principalCoverageBps, "principalCoverageBps", MAX_INSURANCE_PRINCIPAL_COVERAGE_BPS);
284
+ assertBps(input.perDayBps, "perDayBps", MAX_INSURANCE_DRAW_PER_DAY_BPS);
285
+ return {
286
+ kind: "insuranceDrawCaps",
287
+ principalCoverageBps: input.principalCoverageBps,
288
+ perDayBps: input.perDayBps,
289
+ };
290
+ }
291
+ export function oracleParameterUpdate(input) {
292
+ return { kind: "oracle", policy: oraclePolicy(input) };
293
+ }
294
+ export function trancheParameterUpdate(input) {
295
+ assertBps(input.juniorIncomeShareBps, "juniorIncomeShareBps", MAX_JUNIOR_INCOME_SHARE_BPS, MIN_JUNIOR_INCOME_SHARE_BPS);
296
+ assertBps(input.requestFeeBps, "requestFeeBps", MAX_JUNIOR_EXIT_REQUEST_FEE_BPS, MIN_JUNIOR_EXIT_REQUEST_FEE_BPS);
297
+ assertBps(input.liquidationFeeBps, "liquidationFeeBps", MAX_LIQUIDATION_FEE_BPS, MIN_LIQUIDATION_FEE_BPS);
298
+ return { kind: "tranche", ...input };
299
+ }
300
+ export const parameterUpdate = {
301
+ oracle: oracleParameterUpdate,
302
+ fee: feeParameterUpdate,
303
+ concentration: concentrationParameterUpdate,
304
+ irm: irmParameterUpdate,
305
+ emaHalfLives: emaHalfLivesParameterUpdate,
306
+ dailyBorrowLimit: dailyBorrowLimitParameterUpdate,
307
+ centerController: centerControllerParameterUpdate,
308
+ insuranceDrawCaps: insuranceDrawCapsParameterUpdate,
309
+ tranche: trancheParameterUpdate,
310
+ };
311
+ export function assertParameterUpdate(update) {
312
+ switch (update.kind) {
313
+ case "fee":
314
+ feeParameterUpdate(update.profile);
315
+ return;
316
+ case "concentration":
317
+ concentrationParameterUpdate(update);
318
+ return;
319
+ case "irm":
320
+ irmParameterUpdate(update.config);
321
+ return;
322
+ case "emaHalfLives":
323
+ emaHalfLivesParameterUpdate(update);
324
+ return;
325
+ case "dailyBorrowLimit":
326
+ dailyBorrowLimitParameterUpdate(update.maxDailyBorrowBps);
327
+ return;
328
+ case "centerController":
329
+ centerControllerParameterUpdate(update);
330
+ return;
331
+ case "oracle":
332
+ oraclePolicy(update.policy);
333
+ return;
334
+ case "insuranceDrawCaps":
335
+ insuranceDrawCapsParameterUpdate(update);
336
+ return;
337
+ case "tranche":
338
+ trancheParameterUpdate(update);
339
+ return;
340
+ }
341
+ }
342
+ export function parameterFamilyCode(update) {
343
+ switch (update.kind) {
344
+ case "fee":
345
+ return 0;
346
+ case "concentration":
347
+ return 1;
348
+ case "irm":
349
+ return 2;
350
+ case "emaHalfLives":
351
+ return 3;
352
+ case "dailyBorrowLimit":
353
+ return 4;
354
+ case "centerController":
355
+ return 5;
356
+ case "insuranceDrawCaps":
357
+ return 6;
358
+ case "oracle":
359
+ return 7;
360
+ case "tranche":
361
+ return 8;
362
+ }
363
+ }
364
+ /**
365
+ * The one encoding a proposal accepts for a set of updates: one to eight,
366
+ * each family at most once, in ascending family order. Throws on an empty
367
+ * set or a repeated family.
368
+ */
369
+ export function canonicalParameterUpdates(updates) {
370
+ if (updates.length === 0)
371
+ throw new Error("a proposal must change at least one parameter family");
372
+ if (updates.length > MAX_PARAMETER_UPDATES_PER_PROPOSAL) {
373
+ throw new Error(`a proposal changes at most ${MAX_PARAMETER_UPDATES_PER_PROPOSAL} parameter families`);
374
+ }
375
+ const sorted = [...updates].sort((left, right) => parameterFamilyCode(left) - parameterFamilyCode(right));
376
+ for (let index = 1; index < sorted.length; index += 1) {
377
+ if (parameterFamilyCode(sorted[index - 1]) === parameterFamilyCode(sorted[index])) {
378
+ throw new Error(`a proposal changes the ${sorted[index].kind} family more than once`);
379
+ }
380
+ }
381
+ sorted.forEach(assertParameterUpdate);
382
+ return sorted;
383
+ }
384
+ /**
385
+ * The revisions a new proposal binds: each updated family's current market
386
+ * revision, and zero for every family the proposal leaves alone.
387
+ */
388
+ export function updatedFamilyRevisions(updates, marketRevisions) {
389
+ assertFamilyRevisionCount(marketRevisions);
390
+ const revisions = new Array(PARAMETER_FAMILY_COUNT).fill(0n);
391
+ for (const update of canonicalParameterUpdates(updates)) {
392
+ const code = parameterFamilyCode(update);
393
+ revisions[code] = toU64BigInt(marketRevisions[code], `marketRevisions[${code}]`);
394
+ }
395
+ return revisions;
396
+ }
397
+ /** Convert the readable SDK union to Anchor's generated Rust-enum object. */
398
+ export function anchorParameterUpdate(update) {
399
+ assertParameterUpdate(update);
400
+ switch (update.kind) {
401
+ case "fee":
402
+ // Fee is a Rust tuple variant, so its one field is keyed by tuple index.
403
+ return { fee: { 0: update.profile } };
404
+ case "concentration":
405
+ return {
406
+ concentration: {
407
+ peakAmplificationNad: update.peakAmplificationNad,
408
+ coreHalfWidthBps: update.coreHalfWidthBps,
409
+ fadeWidthBps: update.fadeWidthBps,
410
+ },
411
+ };
412
+ case "irm":
413
+ return { irm: { 0: update.config } };
414
+ case "emaHalfLives":
415
+ return {
416
+ emaHalfLives: {
417
+ priceMs: update.priceMs,
418
+ directionalPriceMs: update.directionalPriceMs,
419
+ curveDepthMs: update.curveDepthMs,
420
+ centerPriceMs: update.centerPriceMs,
421
+ },
422
+ };
423
+ case "dailyBorrowLimit":
424
+ return { dailyBorrowLimit: { maxDailyBorrowBps: update.maxDailyBorrowBps } };
425
+ case "centerController":
426
+ return {
427
+ centerController: {
428
+ adjustmentThresholdNad: update.adjustmentThresholdNad,
429
+ adjustmentStepNad: update.adjustmentStepNad,
430
+ minAdjustmentIntervalSlots: update.minAdjustmentIntervalSlots,
431
+ },
432
+ };
433
+ case "oracle":
434
+ return { oracle: { 0: update.policy } };
435
+ case "insuranceDrawCaps":
436
+ return {
437
+ insuranceDrawCaps: { principalCoverageBps: update.principalCoverageBps, perDayBps: update.perDayBps },
438
+ };
439
+ case "tranche":
440
+ return {
441
+ tranche: {
442
+ juniorIncomeShareBps: update.juniorIncomeShareBps,
443
+ requestFeeBps: update.requestFeeBps,
444
+ liquidationFeeBps: update.liquidationFeeBps,
445
+ },
446
+ };
447
+ }
448
+ }
449
+ /** Convert a decoded Anchor enum (including tuple-field objects) to the readable SDK union. */
450
+ export function parameterUpdateFromAnchor(value) {
451
+ const update = objectValue(value, "market parameter update");
452
+ if (update.fee !== undefined) {
453
+ const profile = tupleField(update.fee, "fee");
454
+ return feeParameterUpdate(objectValue(profile, "fee profile"));
455
+ }
456
+ if (update.concentration !== undefined) {
457
+ const fields = objectValue(update.concentration, "concentration update");
458
+ return concentrationParameterUpdate({
459
+ peakAmplificationNad: integerField(fields, "peakAmplificationNad"),
460
+ coreHalfWidthBps: numberField(fields, "coreHalfWidthBps"),
461
+ fadeWidthBps: numberField(fields, "fadeWidthBps"),
462
+ });
463
+ }
464
+ if (update.irm !== undefined) {
465
+ const config = objectValue(tupleField(update.irm, "irm"), "IRM config");
466
+ return irmParameterUpdate({
467
+ lowerSignalNad: integerField(config, "lowerSignalNad"),
468
+ upperSignalNad: integerField(config, "upperSignalNad"),
469
+ halfLifeMs: integerField(config, "halfLifeMs"),
470
+ initialAprNad: integerField(config, "initialAprNad"),
471
+ minimumAprNad: integerField(config, "minimumAprNad"),
472
+ maximumAprNad: integerField(config, "maximumAprNad"),
473
+ borrowUtilizationLimitBps: numberField(config, "borrowUtilizationLimitBps"),
474
+ });
475
+ }
476
+ if (update.emaHalfLives !== undefined) {
477
+ const fields = objectValue(update.emaHalfLives, "EMA half-lives update");
478
+ return emaHalfLivesParameterUpdate({
479
+ priceMs: integerField(fields, "priceMs"),
480
+ directionalPriceMs: integerField(fields, "directionalPriceMs"),
481
+ curveDepthMs: integerField(fields, "curveDepthMs"),
482
+ centerPriceMs: integerField(fields, "centerPriceMs"),
483
+ });
484
+ }
485
+ if (update.dailyBorrowLimit !== undefined) {
486
+ const fields = objectValue(update.dailyBorrowLimit, "daily borrow-limit update");
487
+ return dailyBorrowLimitParameterUpdate(numberField(fields, "maxDailyBorrowBps"));
488
+ }
489
+ if (update.centerController !== undefined) {
490
+ const fields = objectValue(update.centerController, "center-controller update");
491
+ return centerControllerParameterUpdate({
492
+ adjustmentThresholdNad: integerField(fields, "adjustmentThresholdNad"),
493
+ adjustmentStepNad: integerField(fields, "adjustmentStepNad"),
494
+ minAdjustmentIntervalSlots: integerField(fields, "minAdjustmentIntervalSlots"),
495
+ });
496
+ }
497
+ if (update.insuranceDrawCaps !== undefined) {
498
+ const fields = objectValue(update.insuranceDrawCaps, "insurance draw-caps update");
499
+ return insuranceDrawCapsParameterUpdate({
500
+ principalCoverageBps: numberField(fields, "principalCoverageBps"),
501
+ perDayBps: numberField(fields, "perDayBps"),
502
+ });
503
+ }
504
+ if (update.oracle !== undefined) {
505
+ return oracleParameterUpdate(tupleField(update.oracle, "oracle"));
506
+ }
507
+ if (update.tranche !== undefined) {
508
+ const fields = objectValue(update.tranche, "tranche update");
509
+ return trancheParameterUpdate({
510
+ juniorIncomeShareBps: numberField(fields, "juniorIncomeShareBps"),
511
+ requestFeeBps: numberField(fields, "requestFeeBps"),
512
+ liquidationFeeBps: numberField(fields, "liquidationFeeBps"),
513
+ });
514
+ }
515
+ throw new Error("unknown market parameter update variant");
516
+ }
517
+ /** Create metadata from already-uploaded bytes, then retrieve and verify the URI. */
518
+ export async function createProposalMetadata(input) {
519
+ const bytes = markdownBytes(input.markdown);
520
+ const metadata = {
521
+ version: PROPOSAL_METADATA_VERSION,
522
+ title: input.title,
523
+ descriptionUri: input.descriptionUri,
524
+ descriptionSha256: [...(await sha256(bytes))],
525
+ descriptionLen: bytes.byteLength,
526
+ };
527
+ assertProposalMetadata(metadata);
528
+ await fetchAndVerifyProposalDescription(metadata, input);
529
+ return metadata;
530
+ }
531
+ /** Upload the exact Markdown bytes, fetch the returned URI, and verify length + SHA-256. */
532
+ export async function uploadProposalMetadata(input) {
533
+ assertProposalTitle(input.title);
534
+ const bytes = markdownBytes(input.markdown);
535
+ assertDescriptionLength(bytes.byteLength);
536
+ const uploaded = await input.upload(bytes.slice(), {
537
+ title: input.title,
538
+ contentType: "text/markdown; charset=utf-8",
539
+ });
540
+ const descriptionUri = typeof uploaded === "string" ? uploaded : uploaded.uri;
541
+ return createProposalMetadata({ ...input, descriptionUri, markdown: bytes });
542
+ }
543
+ export function assertProposalMetadata(metadata) {
544
+ if (metadata.version !== PROPOSAL_METADATA_VERSION) {
545
+ throw new Error(`proposal metadata version must be ${PROPOSAL_METADATA_VERSION}`);
546
+ }
547
+ assertProposalTitle(metadata.title);
548
+ assertProposalUri(metadata.descriptionUri);
549
+ assertDescriptionLength(metadata.descriptionLen);
550
+ if (!Number.isInteger(metadata.descriptionLen)) {
551
+ throw new Error("descriptionLen must be an integer byte length");
552
+ }
553
+ if (metadata.descriptionSha256.length !== 32) {
554
+ throw new Error("descriptionSha256 must contain exactly 32 bytes");
555
+ }
556
+ for (const byte of metadata.descriptionSha256) {
557
+ if (!Number.isInteger(byte) || byte < 0 || byte > 255) {
558
+ throw new Error("descriptionSha256 must contain only bytes");
559
+ }
560
+ }
561
+ if (metadata.descriptionSha256.every((byte) => byte === 0)) {
562
+ throw new Error("descriptionSha256 must be nonzero");
563
+ }
564
+ }
565
+ export function assertProposalTitle(title) {
566
+ const byteLength = new TextEncoder().encode(title).byteLength;
567
+ if (byteLength < 1 ||
568
+ byteLength > MAX_PROPOSAL_TITLE_BYTES ||
569
+ title !== title.trim() ||
570
+ /\p{Cc}/u.test(title)) {
571
+ throw new Error(`title must be trimmed, control-free UTF-8 occupying 1-${MAX_PROPOSAL_TITLE_BYTES} bytes`);
572
+ }
573
+ }
574
+ export function assertProposalUri(uri) {
575
+ const ascii = /^[\x00-\x7f]*$/.test(uri);
576
+ const validScheme = ["ipfs://", "ar://", "https://"].some((prefix) => uri.startsWith(prefix) && uri.length > prefix.length);
577
+ if (uri.length < 1 ||
578
+ uri.length > MAX_PROPOSAL_DESCRIPTION_URI_BYTES ||
579
+ !ascii ||
580
+ /[\x00-\x20\x7f]/.test(uri) ||
581
+ !validScheme) {
582
+ throw new Error(`description URI must be a whitespace-free ipfs://, ar://, or https:// URI of at most ${MAX_PROPOSAL_DESCRIPTION_URI_BYTES} ASCII bytes`);
583
+ }
584
+ }
585
+ /** Fetch no unbounded body, verify the exact byte count/hash, then decode strict UTF-8. */
586
+ export async function fetchAndVerifyProposalDescription(metadata, options = {}) {
587
+ assertProposalMetadata(metadata);
588
+ const fetchImpl = options.fetch ?? globalThis.fetch?.bind(globalThis);
589
+ if (!fetchImpl)
590
+ throw new Error("fetch is unavailable; supply ProposalDescriptionFetchOptions.fetch");
591
+ const resolved = options.resolveUri
592
+ ? await options.resolveUri(metadata.descriptionUri)
593
+ : resolveProposalDescriptionUri(metadata.descriptionUri, options);
594
+ const response = await fetchImpl(resolved, {
595
+ signal: options.signal,
596
+ headers: {
597
+ accept: "text/markdown, text/plain;q=0.9, application/octet-stream;q=0.8",
598
+ range: `bytes=0-${metadata.descriptionLen - 1}`,
599
+ },
600
+ });
601
+ if (!response.ok) {
602
+ throw new Error(`proposal description fetch failed with HTTP ${response.status}`);
603
+ }
604
+ const bytes = await readExactBody(response, metadata.descriptionLen);
605
+ const actualHash = await sha256(bytes);
606
+ if (!equalBytes(actualHash, metadata.descriptionSha256)) {
607
+ throw new Error("proposal description SHA-256 does not match its on-chain metadata");
608
+ }
609
+ let markdown;
610
+ try {
611
+ markdown = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
612
+ }
613
+ catch {
614
+ throw new Error("verified proposal description is not valid UTF-8");
615
+ }
616
+ return { verified: true, uri: metadata.descriptionUri, markdown, bytes };
617
+ }
618
+ /** UI-friendly verification: failure is data, so callers can show title + typed diff. */
619
+ export async function tryFetchProposalDescription(metadata, options = {}) {
620
+ try {
621
+ return await fetchAndVerifyProposalDescription(metadata, options);
622
+ }
623
+ catch (error) {
624
+ return {
625
+ verified: false,
626
+ uri: metadata.descriptionUri,
627
+ warning: "Proposal rationale is unavailable or failed on-chain length/hash verification.",
628
+ error,
629
+ };
630
+ }
631
+ }
632
+ export function resolveProposalDescriptionUri(uri, options = {}) {
633
+ assertProposalUri(uri);
634
+ if (uri.startsWith("https://"))
635
+ return uri;
636
+ if (uri.startsWith("ipfs://")) {
637
+ const payload = uri.slice("ipfs://".length).replace(/^ipfs\//, "");
638
+ const gateway = (options.ipfsGateway ?? "https://ipfs.io/ipfs/").replace(/\/*$/, "/");
639
+ return `${gateway}${payload}`;
640
+ }
641
+ const gateway = (options.arweaveGateway ?? "https://arweave.net/").replace(/\/*$/, "/");
642
+ return `${gateway}${uri.slice("ar://".length)}`;
643
+ }
644
+ /** Reproduce the immutable on-chain proposal digest over canonical Borsh bytes. */
645
+ export async function computeParameterProposalDigest(input) {
646
+ assertProposalMetadata(input.metadata);
647
+ assertFamilyRevisionCount(input.familyRevisions);
648
+ const updates = canonicalParameterUpdates(input.updates);
649
+ return sha256(concatBytes(PROPOSAL_DIGEST_DOMAIN, address(input.programId).toBytes(), address(input.market).toBytes(), address(input.proposer).toBytes(), encodeU64(input.nonce, "nonce"), ...input.familyRevisions.map((revision, family) => encodeU64(revision, `familyRevisions[${family}]`)), encodeU32(updates.length), ...updates.map(encodeParameterUpdate), encodeProposalMetadata(input.metadata)));
650
+ }
651
+ export async function verifyParameterProposalDigest(expected, input) {
652
+ return equalBytes(await computeParameterProposalDigest(input), expected);
653
+ }
654
+ export function computeDecodedParameterProposalDigest(programId, proposal) {
655
+ return computeParameterProposalDigest({
656
+ programId,
657
+ market: proposal.market,
658
+ proposer: proposal.proposer,
659
+ nonce: proposal.nonce,
660
+ familyRevisions: proposal.familyRevisions,
661
+ updates: proposal.updates.map(parameterUpdateFromAnchor),
662
+ metadata: proposal.metadata,
663
+ });
664
+ }
665
+ export async function verifyDecodedParameterProposalDigest(programId, proposal) {
666
+ if (!proposal.digest)
667
+ throw new Error("decoded proposal is missing its digest");
668
+ return equalBytes(await computeDecodedParameterProposalDigest(programId, proposal), proposal.digest);
669
+ }
670
+ export function proposalSponsorshipFloor(eligibleYlp) {
671
+ const eligible = toU64BigInt(eligibleYlp, "eligibleYlp");
672
+ if (eligible === 0n)
673
+ throw new Error("eligibleYlp must be nonzero");
674
+ return (eligible * BigInt(PARAMETER_PROPOSAL_SPONSOR_BPS) +
675
+ BigInt(GOVERNANCE_BPS_DENOMINATOR - 1)) / BigInt(GOVERNANCE_BPS_DENOMINATOR);
676
+ }
677
+ export function hasStrictProposalMajority(lockedSupport, eligibleYlp) {
678
+ const locked = toU64BigInt(lockedSupport, "lockedSupport");
679
+ const eligible = toU64BigInt(eligibleYlp, "eligibleYlp");
680
+ return (locked * BigInt(GOVERNANCE_BPS_DENOMINATOR) >
681
+ eligible * BigInt(PARAMETER_PROPOSAL_SUPPORT_BPS));
682
+ }
683
+ export function minimumProposalQueueSupport(eligibleYlp) {
684
+ const eligible = toU64BigInt(eligibleYlp, "eligibleYlp");
685
+ if (eligible === 0n)
686
+ throw new Error("eligibleYlp must be nonzero");
687
+ return eligible / 2n + 1n;
688
+ }
689
+ export function eligibleDirectYlp(input) {
690
+ const totalOwnership = toU64BigInt(input.mintSupply, "mintSupply") +
691
+ toU64BigInt(input.governanceLockedYlp, "governanceLockedYlp");
692
+ if (totalOwnership > U64_MAX)
693
+ throw new Error("total yLP ownership exceeded u64");
694
+ const afterBase = totalOwnership - toU64BigInt(input.baseHlpYlpVaultAmount, "baseHlpYlpVaultAmount");
695
+ if (afterBase < 0n)
696
+ throw new Error("base hLP yLP vault exceeds total yLP ownership");
697
+ const eligible = afterBase - toU64BigInt(input.quoteHlpYlpVaultAmount, "quoteHlpYlpVaultAmount");
698
+ if (eligible < 0n)
699
+ throw new Error("quote hLP yLP vault exceeds remaining yLP ownership");
700
+ return eligible;
701
+ }
702
+ export function governanceIntegerBN(value, label = "value") {
703
+ return toBN(toU64BigInt(value, label));
704
+ }
705
+ function markdownBytes(markdown) {
706
+ const bytes = typeof markdown === "string" ? new TextEncoder().encode(markdown) : markdown.slice();
707
+ assertDescriptionLength(bytes.byteLength);
708
+ try {
709
+ new TextDecoder("utf-8", { fatal: true }).decode(bytes);
710
+ }
711
+ catch {
712
+ throw new Error("proposal Markdown must contain valid UTF-8 bytes");
713
+ }
714
+ return bytes;
715
+ }
716
+ function assertDescriptionLength(length) {
717
+ if (!Number.isInteger(length) || length < 1 || length > MAX_PROPOSAL_DESCRIPTION_BYTES) {
718
+ throw new Error(`proposal Markdown must occupy 1-${MAX_PROPOSAL_DESCRIPTION_BYTES} bytes`);
719
+ }
720
+ }
721
+ function objectValue(value, label) {
722
+ if (value === null || typeof value !== "object")
723
+ throw new Error(`${label} must be an object`);
724
+ return value;
725
+ }
726
+ function tupleField(value, label) {
727
+ const tuple = objectValue(value, `${label} tuple`);
728
+ if (!("0" in tuple))
729
+ throw new Error(`${label} tuple is missing field 0`);
730
+ return tuple["0"];
731
+ }
732
+ function integerField(value, field) {
733
+ const candidate = value[field];
734
+ if (typeof candidate !== "bigint" &&
735
+ typeof candidate !== "number" &&
736
+ typeof candidate !== "string" &&
737
+ (candidate === null || typeof candidate !== "object" || !("toString" in candidate))) {
738
+ throw new Error(`${field} is missing or is not integer-like`);
739
+ }
740
+ return candidate;
741
+ }
742
+ function numberField(value, field) {
743
+ const candidate = value[field];
744
+ if (typeof candidate !== "number")
745
+ throw new Error(`${field} is missing or is not a number`);
746
+ return candidate;
747
+ }
748
+ function assertBps(value, label, max, min = 0) {
749
+ if (!Number.isInteger(value) || value < min || value > max) {
750
+ throw new Error(`${label} must be an integer from ${min} to ${max} bps`);
751
+ }
752
+ }
753
+ function assertRange(value, min, max, label) {
754
+ if (value < min || value > max) {
755
+ throw new Error(`${label} must be between ${min} and ${max}`);
756
+ }
757
+ return value;
758
+ }
759
+ function toU64BigInt(value, label) {
760
+ if (typeof value === "number" && !Number.isSafeInteger(value)) {
761
+ throw new Error(`${label} must be a safe integer when supplied as a number`);
762
+ }
763
+ let normalized;
764
+ try {
765
+ normalized = BigInt(value.toString());
766
+ }
767
+ catch {
768
+ throw new Error(`${label} must be an unsigned 64-bit integer`);
769
+ }
770
+ if (normalized < 0n || normalized > U64_MAX) {
771
+ throw new Error(`${label} must be an unsigned 64-bit integer`);
772
+ }
773
+ return normalized;
774
+ }
775
+ export function toBN(value) {
776
+ return new AnchorBN(value.toString());
777
+ }
778
+ function encodeParameterUpdate(update) {
779
+ assertParameterUpdate(update);
780
+ switch (update.kind) {
781
+ case "fee":
782
+ return concatBytes(Uint8Array.of(0), encodeU16(update.profile.baseFeeBps), encodeU16(update.profile.divergenceFeeShareCapBps), encodeU16(update.profile.volatilityFeeShareCapBps), encodeU64(update.profile.divergenceFeeCoefficientNad, "divergenceFeeCoefficientNad"), encodeU64(update.profile.volatilityFeeCoefficientNad, "volatilityFeeCoefficientNad"), encodeU64(update.profile.volatilityHalfLifeMs, "volatilityHalfLifeMs"), encodeU64(update.profile.volatilityShockCapNad, "volatilityShockCapNad"), encodeU64(update.profile.volatilityAccumulatorCapNad, "volatilityAccumulatorCapNad"), Uint8Array.of(update.profile.swapFeeCollectMode), encodeU16(update.profile.compoundingFeeBps), encodeU16(update.profile.launchFeeStartBps), encodeU64(update.profile.launchFeeDurationSeconds, "launchFeeDurationSeconds"), Uint8Array.of(update.profile.launchFeeDecayMode), encodeU16(update.profile.launchMarketPriceStepBps), encodeU16(update.profile.launchMarketNumberOfPeriods), encodeU16(update.profile.launchMarketReductionFactorBps), Uint8Array.of(update.profile.launchRateLimitAsset), encodeU64(update.profile.launchRateLimitReferenceNad, "launchRateLimitReferenceNad"), encodeU16(update.profile.launchRateLimitIncrementBps), encodeU16(update.profile.launchRateLimitMaxFeeBps), encodeU64(update.profile.launchRateLimitDurationSeconds, "launchRateLimitDurationSeconds"));
783
+ case "concentration":
784
+ return concatBytes(Uint8Array.of(1), encodeU64(update.peakAmplificationNad, "peakAmplificationNad"), encodeU16(update.coreHalfWidthBps), encodeU16(update.fadeWidthBps));
785
+ case "irm":
786
+ return concatBytes(Uint8Array.of(2), encodeU64(update.config.lowerSignalNad, "lowerSignalNad"), encodeU64(update.config.upperSignalNad, "upperSignalNad"), encodeU64(update.config.halfLifeMs, "halfLifeMs"), encodeU64(update.config.initialAprNad, "initialAprNad"), encodeU64(update.config.minimumAprNad, "minimumAprNad"), encodeU64(update.config.maximumAprNad, "maximumAprNad"), encodeU16(update.config.borrowUtilizationLimitBps));
787
+ case "emaHalfLives":
788
+ return concatBytes(Uint8Array.of(3), encodeU64(update.priceMs, "priceMs"), encodeU64(update.directionalPriceMs, "directionalPriceMs"), encodeU64(update.curveDepthMs, "curveDepthMs"), encodeU64(update.centerPriceMs, "centerPriceMs"));
789
+ case "dailyBorrowLimit":
790
+ return concatBytes(Uint8Array.of(4), encodeU16(update.maxDailyBorrowBps));
791
+ case "centerController":
792
+ return concatBytes(Uint8Array.of(5), encodeU64(update.adjustmentThresholdNad, "adjustmentThresholdNad"), encodeU64(update.adjustmentStepNad, "adjustmentStepNad"), encodeU64(update.minAdjustmentIntervalSlots, "minAdjustmentIntervalSlots"));
793
+ case "oracle":
794
+ return concatBytes(Uint8Array.of(7), encodeOraclePolicy(update.policy));
795
+ case "insuranceDrawCaps":
796
+ return concatBytes(Uint8Array.of(6), encodeU16(update.principalCoverageBps), encodeU16(update.perDayBps));
797
+ case "tranche":
798
+ return concatBytes(Uint8Array.of(8), encodeU16(update.juniorIncomeShareBps), encodeU16(update.requestFeeBps), encodeU16(update.liquidationFeeBps));
799
+ }
800
+ }
801
+ function assertFamilyRevisionCount(revisions) {
802
+ if (revisions.length !== PARAMETER_FAMILY_COUNT) {
803
+ throw new Error(`expected ${PARAMETER_FAMILY_COUNT} family revisions, got ${revisions.length}`);
804
+ }
805
+ }
806
+ function encodeProposalMetadata(metadata) {
807
+ return concatBytes(Uint8Array.of(metadata.version), encodeBorshString(metadata.title), encodeBorshString(metadata.descriptionUri), Uint8Array.from(metadata.descriptionSha256), encodeU32(metadata.descriptionLen));
808
+ }
809
+ function encodeBorshString(value) {
810
+ const bytes = new TextEncoder().encode(value);
811
+ return concatBytes(encodeU32(bytes.byteLength), bytes);
812
+ }
813
+ function encodeU16(value) {
814
+ if (!Number.isInteger(value) || value < 0 || value > 0xffff) {
815
+ throw new Error("value must fit in u16");
816
+ }
817
+ const bytes = new Uint8Array(2);
818
+ new DataView(bytes.buffer).setUint16(0, value, true);
819
+ return bytes;
820
+ }
821
+ function encodeU32(value) {
822
+ if (!Number.isInteger(value) || value < 0 || value > 0xffff_ffff) {
823
+ throw new Error("value must fit in u32");
824
+ }
825
+ const bytes = new Uint8Array(4);
826
+ new DataView(bytes.buffer).setUint32(0, value, true);
827
+ return bytes;
828
+ }
829
+ function encodeU64(value, label) {
830
+ const normalized = toU64BigInt(value, label);
831
+ const bytes = new Uint8Array(8);
832
+ new DataView(bytes.buffer).setBigUint64(0, normalized, true);
833
+ return bytes;
834
+ }
835
+ function concatBytes(...parts) {
836
+ const total = parts.reduce((sum, part) => sum + part.byteLength, 0);
837
+ const output = new Uint8Array(total);
838
+ let offset = 0;
839
+ for (const part of parts) {
840
+ output.set(part, offset);
841
+ offset += part.byteLength;
842
+ }
843
+ return output;
844
+ }
845
+ function equalBytes(left, right) {
846
+ if (left.length !== right.length)
847
+ return false;
848
+ let difference = 0;
849
+ for (let index = 0; index < left.length; index += 1) {
850
+ difference |= left[index] ^ right[index];
851
+ }
852
+ return difference === 0;
853
+ }
854
+ async function readExactBody(response, expectedLength) {
855
+ const contentRange = response.headers.get("content-range");
856
+ if (response.status === 206) {
857
+ const match = /^bytes\s+(\d+)-(\d+)\/(\d+|\*)$/i.exec(contentRange ?? "");
858
+ if (!match)
859
+ throw new Error("partial proposal response is missing a valid Content-Range");
860
+ const start = Number(match[1]);
861
+ const end = Number(match[2]);
862
+ const total = match[3] === "*" ? null : Number(match[3]);
863
+ if (start !== 0 || end + 1 !== expectedLength || total !== expectedLength) {
864
+ throw new Error("proposal description response does not have the exact on-chain byte length");
865
+ }
866
+ }
867
+ else {
868
+ const contentLength = response.headers.get("content-length");
869
+ const contentEncoding = response.headers.get("content-encoding");
870
+ if (contentLength !== null && !contentEncoding && Number(contentLength) !== expectedLength) {
871
+ throw new Error("proposal description Content-Length does not match on-chain metadata");
872
+ }
873
+ }
874
+ if (!response.body) {
875
+ const bytes = new Uint8Array(await response.arrayBuffer());
876
+ if (bytes.byteLength !== expectedLength) {
877
+ throw new Error("proposal description byte length does not match on-chain metadata");
878
+ }
879
+ return bytes;
880
+ }
881
+ const output = new Uint8Array(expectedLength);
882
+ const reader = response.body.getReader();
883
+ let offset = 0;
884
+ while (true) {
885
+ const { value, done } = await reader.read();
886
+ if (done)
887
+ break;
888
+ if (!value)
889
+ continue;
890
+ if (offset + value.byteLength > expectedLength) {
891
+ await reader.cancel();
892
+ throw new Error("proposal description exceeds its on-chain byte length");
893
+ }
894
+ output.set(value, offset);
895
+ offset += value.byteLength;
896
+ }
897
+ if (offset !== expectedLength) {
898
+ throw new Error("proposal description byte length does not match on-chain metadata");
899
+ }
900
+ return output;
901
+ }
902
+ //# sourceMappingURL=governance.js.map