@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,135 @@
1
+ /**
2
+ * Vanity addresses for LP mints.
3
+ *
4
+ * Production builds of the program accept an LP mint only if its address ends
5
+ * in `yLP` (the yLP mint) or `hLP` (either hLP mint); the check is an exact,
6
+ * case-sensitive comparison on the base58 string. Rather than grinding
7
+ * keypairs, the mint is created at a `create_with_seed` address, and what is
8
+ * ground is the seed: `sha256(base ‖ seed ‖ Token-2022)` until the encoding
9
+ * ends in the suffix. The creator's own key is the base, so nothing new has
10
+ * to be kept secret and nothing new has to sign.
11
+ *
12
+ * The grinding itself runs on the vanity server (omnipair/vanity-server), the
13
+ * same service the V1 app used for `omLP`. Three characters cost about 200k
14
+ * attempts, well under a second there. Every result is re-derived locally
15
+ * before it is trusted.
16
+ */
17
+ import { TOKEN_2022_PROGRAM_ID } from "@solana/spl-token";
18
+ import { PublicKey } from "@solana/web3.js";
19
+
20
+ import { address, type AddressLike } from "./address.js";
21
+ import type { MarketLpMintKind } from "./market-bootstrap.js";
22
+
23
+ /** The address suffix `initialize_market` requires for each LP mint kind. */
24
+ export const LP_MINT_ADDRESS_SUFFIX: Readonly<Record<MarketLpMintKind, string>> = {
25
+ ylp: "yLP",
26
+ baseHlp: "hLP",
27
+ quoteHlp: "hLP",
28
+ };
29
+
30
+ export const DEFAULT_VANITY_SERVER_URL = "https://vanity.omnipair.fi";
31
+
32
+ /** Whether `mint` satisfies the production address rule for `kind`. */
33
+ export function hasLpMintAddressSuffix(kind: MarketLpMintKind, mint: AddressLike): boolean {
34
+ return address(mint).toBase58().endsWith(LP_MINT_ADDRESS_SUFFIX[kind]);
35
+ }
36
+
37
+ /** The Token-2022 account address `base` and `seed` create. */
38
+ export function deriveLpMintFromSeed(base: AddressLike, seed: string): Promise<PublicKey> {
39
+ return PublicKey.createWithSeed(address(base), seed, TOKEN_2022_PROGRAM_ID);
40
+ }
41
+
42
+ export interface LpMintSeed {
43
+ readonly kind: MarketLpMintKind;
44
+ readonly base: PublicKey;
45
+ readonly seed: string;
46
+ readonly mint: PublicKey;
47
+ }
48
+
49
+ /** What `GET /grind` on the vanity server returns. */
50
+ interface VanityGrindResponse {
51
+ address?: unknown;
52
+ seed?: unknown;
53
+ base?: unknown;
54
+ owner?: unknown;
55
+ suffix?: unknown;
56
+ error?: unknown;
57
+ }
58
+
59
+ export interface GrindLpMintSeedOptions {
60
+ kind: MarketLpMintKind;
61
+ /** The creator's key: it signs `createAccountWithSeed`, and it is hashed into the address. */
62
+ base: AddressLike;
63
+ serverUrl?: string;
64
+ /** Overall deadline for one request. The server itself never times out. */
65
+ timeoutMs?: number;
66
+ fetch?: typeof fetch;
67
+ }
68
+
69
+ /**
70
+ * Ask the vanity server for a seed whose Token-2022 address ends in the
71
+ * suffix for `kind`, and verify the answer before returning it.
72
+ */
73
+ export async function grindLpMintSeed(options: GrindLpMintSeedOptions): Promise<LpMintSeed> {
74
+ const base = address(options.base);
75
+ const suffix = LP_MINT_ADDRESS_SUFFIX[options.kind];
76
+ const serverUrl = (options.serverUrl ?? DEFAULT_VANITY_SERVER_URL).replace(/\/+$/, "");
77
+ const url = new URL(`${serverUrl}/grind`);
78
+ url.searchParams.set("base", base.toBase58());
79
+ url.searchParams.set("suffix", suffix);
80
+ url.searchParams.set("owner", TOKEN_2022_PROGRAM_ID.toBase58());
81
+
82
+ const doFetch = options.fetch ?? globalThis.fetch;
83
+ if (typeof doFetch !== "function") {
84
+ throw new Error("grindLpMintSeed needs a fetch implementation");
85
+ }
86
+ const controller = new AbortController();
87
+ const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? 120_000);
88
+ let body: VanityGrindResponse;
89
+ try {
90
+ const response = await doFetch(url, { signal: controller.signal });
91
+ body = (await response.json().catch(() => ({}))) as VanityGrindResponse;
92
+ if (!response.ok) {
93
+ throw new Error(
94
+ `vanity server ${response.status}: ${typeof body.error === "string" ? body.error : "grind failed"}`
95
+ );
96
+ }
97
+ } finally {
98
+ clearTimeout(timer);
99
+ }
100
+
101
+ if (typeof body.seed !== "string" || typeof body.address !== "string") {
102
+ throw new Error("vanity server returned no seed");
103
+ }
104
+ // The server drops a suffix it cannot parse and grinds unconstrained; it
105
+ // echoes what it actually used, so an echo that differs means the result is
106
+ // not what was asked for.
107
+ if (body.suffix !== suffix) {
108
+ throw new Error(`vanity server ground suffix ${JSON.stringify(body.suffix)}, not ${suffix}`);
109
+ }
110
+ if (body.owner !== TOKEN_2022_PROGRAM_ID.toBase58()) {
111
+ throw new Error(`vanity server ground for owner ${String(body.owner)}, not Token-2022`);
112
+ }
113
+ const mint = await deriveLpMintFromSeed(base, body.seed);
114
+ if (mint.toBase58() !== body.address) {
115
+ throw new Error(
116
+ `vanity server address ${body.address} does not derive from base ${base.toBase58()} and seed "${body.seed}"`
117
+ );
118
+ }
119
+ if (!hasLpMintAddressSuffix(options.kind, mint)) {
120
+ throw new Error(`derived mint ${mint.toBase58()} does not end in ${suffix}`);
121
+ }
122
+ return { kind: options.kind, base, seed: body.seed, mint };
123
+ }
124
+
125
+ /** One seed per LP mint a market needs, ground for the same base. */
126
+ export async function grindMarketLpMintSeeds(
127
+ options: Omit<GrindLpMintSeedOptions, "kind">
128
+ ): Promise<Record<MarketLpMintKind, LpMintSeed>> {
129
+ const [ylp, baseHlp, quoteHlp] = await Promise.all([
130
+ grindLpMintSeed({ ...options, kind: "ylp" }),
131
+ grindLpMintSeed({ ...options, kind: "baseHlp" }),
132
+ grindLpMintSeed({ ...options, kind: "quoteHlp" }),
133
+ ]);
134
+ return { ylp, baseHlp, quoteHlp };
135
+ }
@@ -0,0 +1,273 @@
1
+ import { RISK_RATE_DEFAULTS } from "./risk-pricing.js";
2
+ /**
3
+ * Creating a market is a bootstrap, not an instruction.
4
+ *
5
+ * `initialize_market` needs three LP mints that already exist, each carrying a
6
+ * transfer-hook extension pointing back at the Dusk program, and each owned by
7
+ * a market PDA that does not exist yet. That ordering is the whole reason this
8
+ * module exists: the mints are plain Token-2022 accounts that have to be in
9
+ * place before the program instruction that adopts them.
10
+ *
11
+ * Two ways to create one. `createHookedLpMintInstructions` uses a fresh
12
+ * keypair, which must sign. `createHookedLpMintWithSeedInstructions` derives
13
+ * the address from the creator's key and a seed, so only the creator signs;
14
+ * that is how a browser wallet or a multisig can launch a market, and it is
15
+ * how the `yLP`/`hLP` address suffixes production builds require are produced
16
+ * (see `lp-vanity.ts`). Both produce instructions rather than sending anything.
17
+ */
18
+ import {
19
+ ExtensionType,
20
+ TOKEN_2022_PROGRAM_ID,
21
+ createInitializeMintInstruction,
22
+ createInitializeTransferHookInstruction,
23
+ getMintLen,
24
+ } from "@solana/spl-token";
25
+ import {
26
+ Keypair,
27
+ PublicKey,
28
+ SystemProgram,
29
+ type Connection,
30
+ type TransactionInstruction,
31
+ } from "@solana/web3.js";
32
+
33
+ import { address, type AddressLike } from "./address.js";
34
+ import { sha256 } from "./hash.js";
35
+
36
+ /** Every LP mint a market needs, in the order `initialize_market` takes them. */
37
+ export const MARKET_LP_MINT_KINDS = ["ylp", "baseHlp", "quoteHlp"] as const;
38
+
39
+ export type MarketLpMintKind = (typeof MARKET_LP_MINT_KINDS)[number];
40
+
41
+ /**
42
+ * A market's identity is its parameter hash, so two markets over the same pair
43
+ * are distinct only if their hashes are. The namespace keeps deployments from
44
+ * colliding: the same label and pair on devnet and mainnet hash differently.
45
+ */
46
+ export async function deriveMarketParamsHash(params: {
47
+ namespace: string;
48
+ label: string;
49
+ baseMint: AddressLike;
50
+ quoteMint: AddressLike;
51
+ }): Promise<Uint8Array> {
52
+ const baseMint = address(params.baseMint).toBase58();
53
+ const quoteMint = address(params.quoteMint).toBase58();
54
+ const preimage = `${params.namespace}:${params.label}:${baseMint}:${quoteMint}`;
55
+ return sha256(new TextEncoder().encode(preimage));
56
+ }
57
+
58
+ /**
59
+ * The parameters a market launches with.
60
+ *
61
+ * Every field is required rather than defaulted, because a market's economics
62
+ * are not something to inherit silently from a library version — see
63
+ * `defaultMarketLaunchConfig` for a starting point that can be overridden
64
+ * field by field.
65
+ */
66
+ export interface MarketLaunchConfig {
67
+ swapFeeBps: number;
68
+ divergenceFeeShareCapBps: number;
69
+ volatilityFeeShareCapBps: number;
70
+ targetHlpLeverageBps: number;
71
+ settlementDivergenceBps: number;
72
+ emaHalfLifeMs: bigint | number | string;
73
+ directionalEmaHalfLifeMs: bigint | number | string;
74
+ curveDepthEmaHalfLifeMs: bigint | number | string;
75
+ maxDailyBorrowBps: number;
76
+ globalHealthContributionCapBps: number;
77
+ borrowMarketHealthFloorBps: number;
78
+ amm: Record<string, unknown>;
79
+ irm: Record<string, unknown>;
80
+ startTime: bigint | number | string;
81
+ }
82
+
83
+ /**
84
+ * The configuration the devnet markets launched with, and a reasonable
85
+ * starting point for a new one. The zeroed AMM fields switch off the
86
+ * launch-fee ramp, the rate limiter and the dynamic fee coefficients: a market
87
+ * that wants any of those should set them deliberately.
88
+ */
89
+ export function defaultMarketLaunchConfig(
90
+ overrides: Partial<MarketLaunchConfig> = {}
91
+ ): MarketLaunchConfig {
92
+ return {
93
+ swapFeeBps: 30,
94
+ divergenceFeeShareCapBps: 0,
95
+ volatilityFeeShareCapBps: 0,
96
+ targetHlpLeverageBps: 20_000,
97
+ settlementDivergenceBps: 500,
98
+ emaHalfLifeMs: 60_000,
99
+ directionalEmaHalfLifeMs: 60_000,
100
+ curveDepthEmaHalfLifeMs: 60_000,
101
+ maxDailyBorrowBps: 2_000,
102
+ globalHealthContributionCapBps: 15_000,
103
+ borrowMarketHealthFloorBps: 11_000,
104
+ amm: {
105
+ peakAmplificationNad: 1_000_000_000,
106
+ coreHalfWidthBps: 0,
107
+ fadeWidthBps: 0,
108
+ centerEmaHalfLifeMs: 60_000,
109
+ volatilityHalfLifeMs: 60_000,
110
+ adjustmentThresholdNad: 0,
111
+ adjustmentStepNad: 0,
112
+ minAdjustmentIntervalSlots: 0,
113
+ volatilityShockCapNad: 0,
114
+ volatilityCapNad: 0,
115
+ divergenceFeeCoefficientNad: 0,
116
+ volatilityFeeCoefficientNad: 0,
117
+ swapFeeCollectMode: 0,
118
+ compoundingFeeBps: 0,
119
+ launchFeeStartBps: 0,
120
+ launchFeeDurationSeconds: 0,
121
+ launchFeeDecayMode: 0,
122
+ launchMarketPriceStepBps: 0,
123
+ launchMarketNumberOfPeriods: 0,
124
+ launchMarketReductionFactorBps: 0,
125
+ launchRateLimitAsset: 0,
126
+ launchRateLimitReferenceNad: 0,
127
+ launchRateLimitIncrementBps: 0,
128
+ launchRateLimitMaxFeeBps: 0,
129
+ launchRateLimitDurationSeconds: 0,
130
+ reserved: [],
131
+ },
132
+ startTime: 0,
133
+ ...overrides,
134
+ irm: { ...RISK_RATE_DEFAULTS, ...overrides.irm },
135
+ };
136
+ }
137
+
138
+ export interface HookedLpMint {
139
+ /** Must sign the transaction carrying these instructions. */
140
+ readonly keypair: Keypair;
141
+ readonly mint: PublicKey;
142
+ readonly instructions: readonly TransactionInstruction[];
143
+ }
144
+
145
+ /**
146
+ * Create one transfer-hooked LP mint.
147
+ *
148
+ * The extension has to be initialized between allocating the account and
149
+ * initializing the mint, and the account has to be sized for it up front —
150
+ * a mint initialized without the space cannot gain the extension afterwards.
151
+ * The hook authority is left unset (`PublicKey.default`) so nothing can
152
+ * repoint it; the program is the hook and that is fixed at creation.
153
+ */
154
+ export function createHookedLpMintInstructions(params: {
155
+ payer: AddressLike;
156
+ decimals: number;
157
+ /** The market PDA, which owns every LP mint it issues. */
158
+ mintAuthority: AddressLike;
159
+ transferHookProgramId: AddressLike;
160
+ /** From `getMinimumBalanceForRentExemption(lpMintLen())`. */
161
+ lamports: number;
162
+ /** Supply one to reproduce a known mint; otherwise a fresh key. */
163
+ keypair?: Keypair;
164
+ }): HookedLpMint {
165
+ const keypair = params.keypair ?? Keypair.generate();
166
+ const payer = address(params.payer);
167
+ return {
168
+ keypair,
169
+ mint: keypair.publicKey,
170
+ instructions: [
171
+ SystemProgram.createAccount({
172
+ fromPubkey: payer,
173
+ newAccountPubkey: keypair.publicKey,
174
+ lamports: params.lamports,
175
+ space: lpMintLen(),
176
+ programId: TOKEN_2022_PROGRAM_ID,
177
+ }),
178
+ createInitializeTransferHookInstruction(
179
+ keypair.publicKey,
180
+ PublicKey.default,
181
+ address(params.transferHookProgramId),
182
+ TOKEN_2022_PROGRAM_ID
183
+ ),
184
+ createInitializeMintInstruction(
185
+ keypair.publicKey,
186
+ params.decimals,
187
+ address(params.mintAuthority),
188
+ null,
189
+ TOKEN_2022_PROGRAM_ID
190
+ ),
191
+ ],
192
+ };
193
+ }
194
+
195
+ export interface SeededLpMint {
196
+ /** Signs `createAccountWithSeed`: the wallet the seed was ground for. */
197
+ readonly base: PublicKey;
198
+ readonly seed: string;
199
+ readonly mint: PublicKey;
200
+ readonly instructions: readonly TransactionInstruction[];
201
+ }
202
+
203
+ /**
204
+ * Create one transfer-hooked LP mint at a `create_with_seed` address.
205
+ *
206
+ * The mint address is `sha256(base ‖ seed ‖ Token-2022 program)`, so the
207
+ * creator can grind seeds until the address ends in the suffix
208
+ * `initialize_market` demands in production builds, and no second keypair
209
+ * ever exists: only `base` and the payer sign. The owner program is part of
210
+ * the derivation, which is why a seed ground for the SPL Token program does
211
+ * not produce the same address here.
212
+ */
213
+ export async function createHookedLpMintWithSeedInstructions(params: {
214
+ payer: AddressLike;
215
+ /** The key the seed was ground against. Must sign. */
216
+ base: AddressLike;
217
+ seed: string;
218
+ decimals: number;
219
+ /** The market PDA, which owns every LP mint it issues. */
220
+ mintAuthority: AddressLike;
221
+ transferHookProgramId: AddressLike;
222
+ /** From `getMinimumBalanceForRentExemption(lpMintLen())`. */
223
+ lamports: number;
224
+ /** The address the seed was ground for; rejected unless it derives from `base` and `seed`. */
225
+ mint?: AddressLike;
226
+ }): Promise<SeededLpMint> {
227
+ const base = address(params.base);
228
+ const mint = await PublicKey.createWithSeed(base, params.seed, TOKEN_2022_PROGRAM_ID);
229
+ if (params.mint !== undefined && !address(params.mint).equals(mint)) {
230
+ throw new Error(
231
+ `LP mint ${address(params.mint).toBase58()} does not derive from base ${base.toBase58()} and seed "${params.seed}" under Token-2022; got ${mint.toBase58()}`
232
+ );
233
+ }
234
+ return {
235
+ base,
236
+ seed: params.seed,
237
+ mint,
238
+ instructions: [
239
+ SystemProgram.createAccountWithSeed({
240
+ fromPubkey: address(params.payer),
241
+ newAccountPubkey: mint,
242
+ basePubkey: base,
243
+ seed: params.seed,
244
+ lamports: params.lamports,
245
+ space: lpMintLen(),
246
+ programId: TOKEN_2022_PROGRAM_ID,
247
+ }),
248
+ createInitializeTransferHookInstruction(
249
+ mint,
250
+ PublicKey.default,
251
+ address(params.transferHookProgramId),
252
+ TOKEN_2022_PROGRAM_ID
253
+ ),
254
+ createInitializeMintInstruction(
255
+ mint,
256
+ params.decimals,
257
+ address(params.mintAuthority),
258
+ null,
259
+ TOKEN_2022_PROGRAM_ID
260
+ ),
261
+ ],
262
+ };
263
+ }
264
+
265
+ /** Account size of an LP mint, which is a Token-2022 mint plus the hook. */
266
+ export function lpMintLen(): number {
267
+ return getMintLen([ExtensionType.TransferHook]);
268
+ }
269
+
270
+ /** Rent for one LP mint, to pass to `createHookedLpMintInstructions`. */
271
+ export function lpMintRent(connection: Connection): Promise<number> {
272
+ return connection.getMinimumBalanceForRentExemption(lpMintLen());
273
+ }
@@ -0,0 +1,103 @@
1
+ import {
2
+ AddressLookupTableAccount,
3
+ AddressLookupTableProgram,
4
+ ComputeBudgetProgram,
5
+ PublicKey,
6
+ TransactionMessage,
7
+ VersionedTransaction,
8
+ type TransactionInstruction,
9
+ } from "@solana/web3.js";
10
+
11
+ /** Prepare a lookup table for Dusk's atomic market and three-metadata CPI. */
12
+ export function marketCreationLookupTablePlan(params: {
13
+ payer: PublicKey;
14
+ recentSlot: number;
15
+ initializeMarketInstruction: TransactionInstruction;
16
+ }) {
17
+ const [createInstruction, address] = AddressLookupTableProgram.createLookupTable({
18
+ authority: params.payer,
19
+ payer: params.payer,
20
+ recentSlot: params.recentSlot,
21
+ });
22
+ const seen = new Set<string>();
23
+ const addresses = [
24
+ ...params.initializeMarketInstruction.keys
25
+ .filter((key) => !key.isSigner)
26
+ .map((key) => key.pubkey),
27
+ params.initializeMarketInstruction.programId,
28
+ ].filter((key) => {
29
+ const encoded = key.toBase58();
30
+ if (seen.has(encoded)) return false;
31
+ seen.add(encoded);
32
+ return true;
33
+ });
34
+ const extendInstructions = [];
35
+ for (let offset = 0; offset < addresses.length; offset += 20) {
36
+ extendInstructions.push(AddressLookupTableProgram.extendLookupTable({
37
+ lookupTable: address,
38
+ authority: params.payer,
39
+ payer: params.payer,
40
+ addresses: addresses.slice(offset, offset + 20),
41
+ }));
42
+ }
43
+ return { address, createInstruction, extendInstructions, addresses };
44
+ }
45
+
46
+ /** The lookup table must have been extended in an earlier slot. Includes the
47
+ * initial oracle policy in the same creation instruction. Metadata lengths and
48
+ * setup instructions must fit Solana's packet limit after address compression. */
49
+ export function marketCreationV0Transaction(params: {
50
+ payer: PublicKey;
51
+ recentBlockhash: string;
52
+ initializeMarketInstruction: TransactionInstruction;
53
+ /** Idempotent setup, such as creating the team treasury WSOL account. */
54
+ setupInstructions?: readonly TransactionInstruction[];
55
+ lookupTable: AddressLookupTableAccount;
56
+ computeUnitLimit?: number;
57
+ }): VersionedTransaction {
58
+ const instructions = [
59
+ ComputeBudgetProgram.setComputeUnitLimit({ units: params.computeUnitLimit ?? 800_000 }),
60
+ ...(params.setupInstructions ?? []),
61
+ params.initializeMarketInstruction,
62
+ ];
63
+ const message = new TransactionMessage({
64
+ payerKey: params.payer,
65
+ recentBlockhash: params.recentBlockhash,
66
+ instructions,
67
+ }).compileToV0Message([params.lookupTable]);
68
+ const tx = new VersionedTransaction(message);
69
+ try {
70
+ if (tx.serialize().length > 1232) throw new RangeError("packet size");
71
+ } catch (error) {
72
+ if (!(error instanceof RangeError)) throw error;
73
+ throw new Error("market creation exceeds transaction size; shorten LP metadata or add lookup-table addresses");
74
+ }
75
+ return tx;
76
+ }
77
+
78
+ /** Prepare addresses for a maximum-size parameter proposal. Submit the
79
+ * create/extend instructions and wait one slot before using the table. */
80
+ export function parameterProposalLookupTablePlan(params: {
81
+ payer: PublicKey;
82
+ recentSlot: number;
83
+ proposalInstruction: TransactionInstruction;
84
+ }) {
85
+ return marketCreationLookupTablePlan({payer: params.payer, recentSlot: params.recentSlot,
86
+ initializeMarketInstruction: params.proposalInstruction});
87
+ }
88
+
89
+ /** All eight parameter families plus maximum metadata need address lookup
90
+ * tables. The wire-size check includes signatures and compute instructions. */
91
+ export function parameterProposalV0Transaction(params: {
92
+ payer: PublicKey;
93
+ recentBlockhash: string;
94
+ proposalInstruction: TransactionInstruction;
95
+ lookupTables: readonly AddressLookupTableAccount[];
96
+ }): VersionedTransaction {
97
+ const message = new TransactionMessage({payerKey: params.payer, recentBlockhash: params.recentBlockhash,
98
+ instructions: [ComputeBudgetProgram.setComputeUnitLimit({units:1_400_000}), params.proposalInstruction],
99
+ }).compileToV0Message([...params.lookupTables]);
100
+ const tx = new VersionedTransaction(message);
101
+ if (tx.serialize().length > 1232) throw new Error("proposal exceeds transaction size; add lookup-table addresses");
102
+ return tx;
103
+ }
package/src/oracle.ts ADDED
@@ -0,0 +1,120 @@
1
+ import { ComputeBudgetProgram, PublicKey, type AccountMeta } from "@solana/web3.js";
2
+ import type { BN } from "@coral-xyz/anchor";
3
+ import { address, type AddressLike } from "./address.js";
4
+ import { governanceIntegerBN, type GovernanceIntegerLike } from "./governance.js";
5
+
6
+ export const NORMALIZED_ORACLE_V1 = 1;
7
+ export const PYTH_RATIO_V2 = 2;
8
+ export const PYTH_DIRECT_V3 = 3;
9
+ export const NORMALIZED_RATIO_V4 = 4;
10
+
11
+ /** Whether the pinned source composes two independently validated asset feeds. */
12
+ export function oracleUsesTwoFeeds(format: number): boolean {
13
+ return format === PYTH_RATIO_V2 || format === NORMALIZED_RATIO_V4;
14
+ }
15
+ export const PYTH_RECEIVER_PROGRAM = new PublicKey("rec5EKMGg6MxZYaMdyBfgwp4d5rB9T1VQH5pJv5LtFJ");
16
+
17
+ export interface OraclePolicyInput {
18
+ format: number;
19
+ provider: AddressLike;
20
+ baseAccount: AddressLike;
21
+ quoteAccount: AddressLike;
22
+ baseFeedId: readonly number[] | Uint8Array;
23
+ quoteFeedId: readonly number[] | Uint8Array;
24
+ lambdaBps: number;
25
+ adjustmentCapNad: GovernanceIntegerLike;
26
+ maxAgeSeconds: number;
27
+ maxAgeSlots: GovernanceIntegerLike;
28
+ maxConfidenceBps: number;
29
+ maxPublishSkewSeconds: number;
30
+ }
31
+ export interface OraclePolicy extends Omit<OraclePolicyInput,
32
+ "provider" | "baseAccount" | "quoteAccount" | "baseFeedId" | "quoteFeedId" | "adjustmentCapNad" | "maxAgeSlots"> {
33
+ provider: PublicKey;
34
+ baseAccount: PublicKey;
35
+ quoteAccount: PublicKey;
36
+ baseFeedId: number[];
37
+ quoteFeedId: number[];
38
+ adjustmentCapNad: BN;
39
+ maxAgeSlots: BN;
40
+ }
41
+
42
+ /** Validate the policy's mathematical bounds and source identity for any market. */
43
+ export function oraclePolicy(input: OraclePolicyInput): OraclePolicy {
44
+ const integer = (n: number, max: number, label: string) => {
45
+ if (!Number.isInteger(n) || n < 0 || n > max) throw new Error(`invalid ${label}`);
46
+ return n;
47
+ };
48
+ const id = (v: readonly number[] | Uint8Array) => {
49
+ if (v.length !== 32 || Array.from(v).some(n => !Number.isInteger(n) || n < 0 || n > 255))
50
+ throw new Error("oracle feed id must contain 32 bytes");
51
+ return Array.from(v);
52
+ };
53
+ const policy: OraclePolicy = {
54
+ format: integer(input.format, 255, "oracle format"), provider: address(input.provider),
55
+ baseAccount: address(input.baseAccount), quoteAccount: address(input.quoteAccount),
56
+ baseFeedId: id(input.baseFeedId), quoteFeedId: id(input.quoteFeedId),
57
+ lambdaBps: integer(input.lambdaBps, 9999, "lambdaBps"),
58
+ adjustmentCapNad: governanceIntegerBN(input.adjustmentCapNad, "adjustmentCapNad"),
59
+ maxAgeSeconds: integer(input.maxAgeSeconds, 0xffff_ffff, "maxAgeSeconds"),
60
+ maxAgeSlots: governanceIntegerBN(input.maxAgeSlots, "maxAgeSlots"),
61
+ maxConfidenceBps: integer(input.maxConfidenceBps, 9999, "maxConfidenceBps"),
62
+ maxPublishSkewSeconds: integer(input.maxPublishSkewSeconds, 0xffff_ffff, "maxPublishSkewSeconds"),
63
+ };
64
+ const zero = PublicKey.default;
65
+ const emptyId = (v: number[]) => v.every(n => n === 0);
66
+ if (policy.format === 0 && policy.lambdaBps === 0 && policy.provider.equals(zero)
67
+ && policy.baseAccount.equals(zero) && policy.quoteAccount.equals(zero)
68
+ && emptyId(policy.baseFeedId) && emptyId(policy.quoteFeedId) && policy.adjustmentCapNad.isZero()
69
+ && policy.maxAgeSeconds === 0 && policy.maxAgeSlots.isZero() && policy.maxConfidenceBps === 0
70
+ && policy.maxPublishSkewSeconds === 0) return policy;
71
+ if (BigInt(policy.adjustmentCapNad.toString()) <= 1_000_000_000n || policy.maxAgeSeconds === 0
72
+ || policy.maxAgeSlots.isZero() || policy.provider.equals(zero) || policy.baseAccount.equals(zero)
73
+ || emptyId(policy.baseFeedId)) throw new Error("invalid oracle policy");
74
+ if (![NORMALIZED_ORACLE_V1, PYTH_RATIO_V2, PYTH_DIRECT_V3, NORMALIZED_RATIO_V4].includes(policy.format))
75
+ throw new Error("unsupported oracle format");
76
+ if ((policy.format === PYTH_RATIO_V2 || policy.format === PYTH_DIRECT_V3)
77
+ && !policy.provider.equals(PYTH_RECEIVER_PROGRAM)) throw new Error("Pyth requires the verified receiver program");
78
+ if (oracleUsesTwoFeeds(policy.format)) {
79
+ if (policy.quoteAccount.equals(zero) || policy.baseAccount.equals(policy.quoteAccount)
80
+ || emptyId(policy.quoteFeedId) || policy.baseFeedId.every((v, i) => v === policy.quoteFeedId[i]))
81
+ throw new Error("ratio requires two distinct feeds with a common denomination");
82
+ } else if (!policy.quoteAccount.equals(zero) || !emptyId(policy.quoteFeedId) || policy.maxPublishSkewSeconds !== 0)
83
+ throw new Error("direct report must identify one pair account");
84
+ return policy;
85
+ }
86
+
87
+ /** Zero weight has no feed-account dependency, even with a retained source policy. */
88
+ export function oracleReadAccounts(policy?: OraclePolicyInput): AccountMeta[] {
89
+ if (!policy || policy.lambdaBps === 0) return [];
90
+ const checked = oraclePolicy(policy);
91
+ return [checked.baseAccount, ...(oracleUsesTwoFeeds(checked.format) ? [checked.quoteAccount] : [])]
92
+ .map(pubkey => ({ pubkey, isSigner: false, isWritable: false }));
93
+ }
94
+
95
+ /** Add once before composing positive-weight instructions. Raw instruction
96
+ * builders cannot attach a transaction budget. Index-bound flash plans must
97
+ * include these before their indices are bound; simulate the complete route.
98
+ */
99
+ export function oracleComputeBudgetInstructions(policy?: Pick<OraclePolicyInput, "lambdaBps">) {
100
+ return policy && policy.lambdaBps > 0 ? [
101
+ ComputeBudgetProgram.requestHeapFrame({ bytes: 256 * 1024 }),
102
+ ComputeBudgetProgram.setComputeUnitLimit({ units: 1_400_000 }),
103
+ ] : [];
104
+ }
105
+
106
+ /** Exact Borsh OraclePolicy payload, also used in proposal digests. */
107
+ export function encodeOraclePolicy(input: OraclePolicyInput): Uint8Array {
108
+ const p = oraclePolicy(input);
109
+ const data = Buffer.alloc(189);
110
+ let offset = 0;
111
+ const bytes = (v: Uint8Array | number[]) => { data.set(v, offset); offset += v.length; };
112
+ const u16 = (v: number) => { data.writeUInt16LE(v, offset); offset += 2; };
113
+ const u32 = (v: number) => { data.writeUInt32LE(v, offset); offset += 4; };
114
+ const u64 = (v: BN) => { data.writeBigUInt64LE(BigInt(v.toString()), offset); offset += 8; };
115
+ data[offset++] = p.format;
116
+ bytes(p.provider.toBytes()); bytes(p.baseAccount.toBytes()); bytes(p.quoteAccount.toBytes());
117
+ bytes(p.baseFeedId); bytes(p.quoteFeedId); u16(p.lambdaBps); u64(p.adjustmentCapNad);
118
+ u32(p.maxAgeSeconds); u64(p.maxAgeSlots); u16(p.maxConfidenceBps); u32(p.maxPublishSkewSeconds);
119
+ return data;
120
+ }