@omnipair/dusk-sdk 2.0.2 → 2.18.0-next.20261106

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (187) hide show
  1. package/README.md +863 -42
  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 +68 -27
  7. package/dist/constants.d.ts.map +1 -1
  8. package/dist/constants.js +153 -41
  9. package/dist/constants.js.map +1 -1
  10. package/dist/delegate.d.ts +97 -0
  11. package/dist/delegate.d.ts.map +1 -0
  12. package/dist/delegate.js +152 -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 +3033 -385
  19. package/dist/get.d.ts.map +1 -1
  20. package/dist/get.js +109 -72
  21. package/dist/get.js.map +1 -1
  22. package/dist/hash.d.ts +9 -0
  23. package/dist/hash.d.ts.map +1 -0
  24. package/dist/hash.js +16 -0
  25. package/dist/hash.js.map +1 -0
  26. package/dist/hlp-liquidation-client.d.ts +104 -0
  27. package/dist/hlp-liquidation-client.d.ts.map +1 -0
  28. package/dist/hlp-liquidation-client.js +146 -0
  29. package/dist/hlp-liquidation-client.js.map +1 -0
  30. package/dist/idl_delegate.d.ts +3 -0
  31. package/dist/idl_delegate.d.ts.map +1 -0
  32. package/dist/idl_delegate.js +3 -0
  33. package/dist/idl_delegate.js.map +1 -0
  34. package/dist/idl_delegate.json +6268 -0
  35. package/dist/idl_v2.json +16746 -6676
  36. package/dist/index.d.ts +23 -0
  37. package/dist/index.d.ts.map +1 -1
  38. package/dist/index.js +23 -0
  39. package/dist/index.js.map +1 -1
  40. package/dist/interest-accounting.d.ts +45 -0
  41. package/dist/interest-accounting.d.ts.map +1 -0
  42. package/dist/interest-accounting.js +59 -0
  43. package/dist/interest-accounting.js.map +1 -0
  44. package/dist/leverage-actions.d.ts +122 -0
  45. package/dist/leverage-actions.d.ts.map +1 -0
  46. package/dist/leverage-actions.js +228 -0
  47. package/dist/leverage-actions.js.map +1 -0
  48. package/dist/leverage-margins.d.ts +12 -0
  49. package/dist/leverage-margins.d.ts.map +1 -0
  50. package/dist/leverage-margins.js +45 -0
  51. package/dist/leverage-margins.js.map +1 -0
  52. package/dist/leverage-preview.d.ts +598 -0
  53. package/dist/leverage-preview.d.ts.map +1 -0
  54. package/dist/leverage-preview.js +89 -0
  55. package/dist/leverage-preview.js.map +1 -0
  56. package/dist/liquidation-client.d.ts +226 -0
  57. package/dist/liquidation-client.d.ts.map +1 -0
  58. package/dist/liquidation-client.js +237 -0
  59. package/dist/liquidation-client.js.map +1 -0
  60. package/dist/liquidation.d.ts +72 -0
  61. package/dist/liquidation.d.ts.map +1 -0
  62. package/dist/liquidation.js +104 -0
  63. package/dist/liquidation.js.map +1 -0
  64. package/dist/lp-naming.d.ts +43 -0
  65. package/dist/lp-naming.d.ts.map +1 -0
  66. package/dist/lp-naming.js +81 -0
  67. package/dist/lp-naming.js.map +1 -0
  68. package/dist/lp-vanity.d.ts +33 -0
  69. package/dist/lp-vanity.d.ts.map +1 -0
  70. package/dist/lp-vanity.js +94 -0
  71. package/dist/lp-vanity.js.map +1 -0
  72. package/dist/market-bootstrap.d.ts +109 -0
  73. package/dist/market-bootstrap.d.ts.map +1 -0
  74. package/dist/market-bootstrap.js +156 -0
  75. package/dist/market-bootstrap.js.map +1 -0
  76. package/dist/market-launch.d.ts +45 -0
  77. package/dist/market-launch.d.ts.map +1 -0
  78. package/dist/market-launch.js +76 -0
  79. package/dist/market-launch.js.map +1 -0
  80. package/dist/operator-client.d.ts +99 -0
  81. package/dist/operator-client.d.ts.map +1 -0
  82. package/dist/operator-client.js +153 -0
  83. package/dist/operator-client.js.map +1 -0
  84. package/dist/oracle.d.ts +46 -0
  85. package/dist/oracle.d.ts.map +1 -0
  86. package/dist/oracle.js +103 -0
  87. package/dist/oracle.js.map +1 -0
  88. package/dist/parameters.d.ts +231 -0
  89. package/dist/parameters.d.ts.map +1 -0
  90. package/dist/parameters.js +683 -0
  91. package/dist/parameters.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 +12 -0
  101. package/dist/risk-pricing.d.ts.map +1 -0
  102. package/dist/risk-pricing.js +23 -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 +265 -31
  117. package/dist/type-aliases.d.ts.map +1 -1
  118. package/dist/types_delegate.d.ts +6275 -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 +16654 -6584
  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 +619 -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 +1263 -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 +427 -0
  141. package/dist/write.d.ts.map +1 -1
  142. package/dist/write.js +970 -26
  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 +11 -4
  149. package/src/amounts.ts +13 -0
  150. package/src/constants.ts +220 -46
  151. package/src/delegate.ts +259 -0
  152. package/src/dusk.ts +28 -0
  153. package/src/get.ts +201 -86
  154. package/src/hash.ts +15 -0
  155. package/src/hlp-liquidation-client.ts +189 -0
  156. package/src/idl_delegate.json +6268 -0
  157. package/src/idl_delegate.ts +3 -0
  158. package/src/idl_v2.json +16746 -6676
  159. package/src/index.ts +31 -0
  160. package/src/interest-accounting.ts +73 -0
  161. package/src/leverage-actions.ts +216 -0
  162. package/src/leverage-margins.ts +48 -0
  163. package/src/leverage-preview.ts +86 -0
  164. package/src/liquidation-client.ts +295 -0
  165. package/src/liquidation.ts +119 -0
  166. package/src/lp-naming.ts +127 -0
  167. package/src/lp-vanity.ts +135 -0
  168. package/src/market-bootstrap.ts +271 -0
  169. package/src/market-launch.ts +103 -0
  170. package/src/operator-client.ts +169 -0
  171. package/src/oracle.ts +120 -0
  172. package/src/parameters.ts +1019 -0
  173. package/src/preview.ts +53 -1
  174. package/src/protection.ts +112 -0
  175. package/src/risk-pricing.ts +26 -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 +294 -32
  180. package/src/types_delegate.ts +6274 -0
  181. package/src/types_v2.ts +16745 -6675
  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 +1650 -28
  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 `srLP` (the srLP 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`. A four-character srLP suffix takes about 58 times as many
14
+ * attempts as a three-character hLP suffix. 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
+ srlp: "srLP",
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 [srlp, baseHlp, quoteHlp] = await Promise.all([
130
+ grindLpMintSeed({ ...options, kind: "srlp" }),
131
+ grindLpMintSeed({ ...options, kind: "baseHlp" }),
132
+ grindLpMintSeed({ ...options, kind: "quoteHlp" }),
133
+ ]);
134
+ return { srlp, baseHlp, quoteHlp };
135
+ }
@@ -0,0 +1,271 @@
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 `srLP`/`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 = ["srlp", "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
+ adjustmentStepNad: 1_000_000,
111
+ volatilityShockCapNad: 0,
112
+ volatilityCapNad: 0,
113
+ divergenceFeeCoefficientNad: 0,
114
+ volatilityFeeCoefficientNad: 0,
115
+ swapFeeCollectMode: 0,
116
+ compoundingFeeBps: 0,
117
+ launchFeeStartBps: 0,
118
+ launchFeeDurationSeconds: 0,
119
+ launchFeeDecayMode: 0,
120
+ launchMarketPriceStepBps: 0,
121
+ launchMarketNumberOfPeriods: 0,
122
+ launchMarketReductionFactorBps: 0,
123
+ launchRateLimitAsset: 0,
124
+ launchRateLimitReferenceNad: 0,
125
+ launchRateLimitIncrementBps: 0,
126
+ launchRateLimitMaxFeeBps: 0,
127
+ launchRateLimitDurationSeconds: 0,
128
+ reserved: [],
129
+ },
130
+ startTime: 0,
131
+ ...overrides,
132
+ irm: { ...RISK_RATE_DEFAULTS, ...overrides.irm },
133
+ };
134
+ }
135
+
136
+ export interface HookedLpMint {
137
+ /** Must sign the transaction carrying these instructions. */
138
+ readonly keypair: Keypair;
139
+ readonly mint: PublicKey;
140
+ readonly instructions: readonly TransactionInstruction[];
141
+ }
142
+
143
+ /**
144
+ * Create one transfer-hooked LP mint.
145
+ *
146
+ * The extension has to be initialized between allocating the account and
147
+ * initializing the mint, and the account has to be sized for it up front —
148
+ * a mint initialized without the space cannot gain the extension afterwards.
149
+ * The hook authority is left unset (`PublicKey.default`) so nothing can
150
+ * repoint it; the program is the hook and that is fixed at creation.
151
+ */
152
+ export function createHookedLpMintInstructions(params: {
153
+ payer: AddressLike;
154
+ decimals: number;
155
+ /** The market PDA, which owns every LP mint it issues. */
156
+ mintAuthority: AddressLike;
157
+ transferHookProgramId: AddressLike;
158
+ /** From `getMinimumBalanceForRentExemption(lpMintLen())`. */
159
+ lamports: number;
160
+ /** Supply one to reproduce a known mint; otherwise a fresh key. */
161
+ keypair?: Keypair;
162
+ }): HookedLpMint {
163
+ const keypair = params.keypair ?? Keypair.generate();
164
+ const payer = address(params.payer);
165
+ return {
166
+ keypair,
167
+ mint: keypair.publicKey,
168
+ instructions: [
169
+ SystemProgram.createAccount({
170
+ fromPubkey: payer,
171
+ newAccountPubkey: keypair.publicKey,
172
+ lamports: params.lamports,
173
+ space: lpMintLen(),
174
+ programId: TOKEN_2022_PROGRAM_ID,
175
+ }),
176
+ createInitializeTransferHookInstruction(
177
+ keypair.publicKey,
178
+ PublicKey.default,
179
+ address(params.transferHookProgramId),
180
+ TOKEN_2022_PROGRAM_ID
181
+ ),
182
+ createInitializeMintInstruction(
183
+ keypair.publicKey,
184
+ params.decimals,
185
+ address(params.mintAuthority),
186
+ null,
187
+ TOKEN_2022_PROGRAM_ID
188
+ ),
189
+ ],
190
+ };
191
+ }
192
+
193
+ export interface SeededLpMint {
194
+ /** Signs `createAccountWithSeed`: the wallet the seed was ground for. */
195
+ readonly base: PublicKey;
196
+ readonly seed: string;
197
+ readonly mint: PublicKey;
198
+ readonly instructions: readonly TransactionInstruction[];
199
+ }
200
+
201
+ /**
202
+ * Create one transfer-hooked LP mint at a `create_with_seed` address.
203
+ *
204
+ * The mint address is `sha256(base ‖ seed ‖ Token-2022 program)`, so the
205
+ * creator can grind seeds until the address ends in the suffix
206
+ * `initialize_market` demands in production builds, and no second keypair
207
+ * ever exists: only `base` and the payer sign. The owner program is part of
208
+ * the derivation, which is why a seed ground for the SPL Token program does
209
+ * not produce the same address here.
210
+ */
211
+ export async function createHookedLpMintWithSeedInstructions(params: {
212
+ payer: AddressLike;
213
+ /** The key the seed was ground against. Must sign. */
214
+ base: AddressLike;
215
+ seed: string;
216
+ decimals: number;
217
+ /** The market PDA, which owns every LP mint it issues. */
218
+ mintAuthority: AddressLike;
219
+ transferHookProgramId: AddressLike;
220
+ /** From `getMinimumBalanceForRentExemption(lpMintLen())`. */
221
+ lamports: number;
222
+ /** The address the seed was ground for; rejected unless it derives from `base` and `seed`. */
223
+ mint?: AddressLike;
224
+ }): Promise<SeededLpMint> {
225
+ const base = address(params.base);
226
+ const mint = await PublicKey.createWithSeed(base, params.seed, TOKEN_2022_PROGRAM_ID);
227
+ if (params.mint !== undefined && !address(params.mint).equals(mint)) {
228
+ throw new Error(
229
+ `LP mint ${address(params.mint).toBase58()} does not derive from base ${base.toBase58()} and seed "${params.seed}" under Token-2022; got ${mint.toBase58()}`
230
+ );
231
+ }
232
+ return {
233
+ base,
234
+ seed: params.seed,
235
+ mint,
236
+ instructions: [
237
+ SystemProgram.createAccountWithSeed({
238
+ fromPubkey: address(params.payer),
239
+ newAccountPubkey: mint,
240
+ basePubkey: base,
241
+ seed: params.seed,
242
+ lamports: params.lamports,
243
+ space: lpMintLen(),
244
+ programId: TOKEN_2022_PROGRAM_ID,
245
+ }),
246
+ createInitializeTransferHookInstruction(
247
+ mint,
248
+ PublicKey.default,
249
+ address(params.transferHookProgramId),
250
+ TOKEN_2022_PROGRAM_ID
251
+ ),
252
+ createInitializeMintInstruction(
253
+ mint,
254
+ params.decimals,
255
+ address(params.mintAuthority),
256
+ null,
257
+ TOKEN_2022_PROGRAM_ID
258
+ ),
259
+ ],
260
+ };
261
+ }
262
+
263
+ /** Account size of an LP mint, which is a Token-2022 mint plus the hook. */
264
+ export function lpMintLen(): number {
265
+ return getMintLen([ExtensionType.TransferHook]);
266
+ }
267
+
268
+ /** Rent for one LP mint, to pass to `createHookedLpMintInstructions`. */
269
+ export function lpMintRent(connection: Connection): Promise<number> {
270
+ return connection.getMinimumBalanceForRentExemption(lpMintLen());
271
+ }
@@ -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 operatorChangeLookupTablePlan(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
+ /** Maximum parameter bundles plus metadata may need address lookup
90
+ * tables. The wire-size check includes signatures and compute instructions. */
91
+ export function operatorChangeV0Transaction(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
+ }
@@ -0,0 +1,169 @@
1
+ import type { Program } from "@coral-xyz/anchor";
2
+ import { ComputeBudgetProgram, SystemProgram, Transaction, type AccountMeta, type PublicKey } from "@solana/web3.js";
3
+ import { address, type AddressLike } from "./address.js";
4
+ import { deriveOperatorProposalAddress, deriveOperatorRevenueAddress, OPERATOR_POLICY_VERSION } from "./constants.js";
5
+ import { sha256 } from "./hash.js";
6
+ import {
7
+ anchorParameterUpdate, assertProposalMetadata, canonicalParameterUpdates, integerBN,
8
+ type IntegerLike, type ParameterUpdate, type ProposalMetadataV1,
9
+ } from "./parameters.js";
10
+ import type { Market, OperatorProposal, OperatorRevenueAccount } from "./type-aliases.js";
11
+ import type { Dusk } from "./types_v2.js";
12
+ import { DuskWrite } from "./write.js";
13
+ import { createAssociatedTokenAccountIdempotentInstruction, getAssociatedTokenAddressSync, TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID, getMint } from "@solana/spl-token";
14
+ import { tokenProgramForMint, resolveTransferHookAccountMetas } from "./referral.js";
15
+
16
+ export interface AnnounceOperatorChangeParams {
17
+ payer: AddressLike;
18
+ operator: AddressLike;
19
+ market: AddressLike;
20
+ updates?: readonly ParameterUpdate[];
21
+ nextOperator?: AddressLike;
22
+ /** Optional parameter delegate. The default public key clears it. */
23
+ nextManager?: AddressLike;
24
+ revenueRecipient?: AddressLike;
25
+ interestShareBps?: number;
26
+ metadata: ProposalMetadataV1;
27
+ /** Optional concurrency commitments; defaults are fetched from the market. */
28
+ nonce?: IntegerLike;
29
+ expectedEpoch?: IntegerLike;
30
+ }
31
+
32
+ /** Core authority only. Token voting, elections and distribution live in the
33
+ * external program that holds the operator signer PDA. Payers are independent. */
34
+ export class DuskOperator {
35
+ readonly write: DuskWrite;
36
+ constructor(readonly program: Program<Dusk>) { this.write = new DuskWrite(program); }
37
+
38
+ market(key: AddressLike): Promise<Market> {
39
+ return this.program.account.market.fetch(address(key));
40
+ }
41
+ proposal(key: AddressLike): Promise<OperatorProposal> {
42
+ return this.program.account.operatorProposal.fetch(address(key));
43
+ }
44
+ async pending(market: AddressLike): Promise<{ address: PublicKey; proposal: OperatorProposal } | null> {
45
+ const state = await this.market(market);
46
+ if (state.operator.pending.equals(SystemProgram.programId)) return null;
47
+ return { address: state.operator.pending, proposal: await this.proposal(state.operator.pending) };
48
+ }
49
+ async announce(params: AnnounceOperatorChangeParams) {
50
+ assertProposalMetadata(params.metadata);
51
+ if (params.nextOperator !== undefined && params.nextManager !== undefined) {
52
+ throw new Error("an operator transfer clears the manager; appoint a manager separately");
53
+ }
54
+ const updates = params.updates?.length ? canonicalParameterUpdates(params.updates) : [];
55
+ if (!updates.length && params.nextOperator === undefined && params.nextManager === undefined && params.revenueRecipient === undefined && params.interestShareBps === undefined) {
56
+ throw new Error("an operator bundle must change at least one setting");
57
+ }
58
+ if (params.interestShareBps !== undefined && (!Number.isInteger(params.interestShareBps) || params.interestShareBps < 0 || params.interestShareBps > 5_000)) {
59
+ throw new Error("operator interest share must be 0–5000 bps");
60
+ }
61
+ const market = address(params.market);
62
+ const state = await this.market(market);
63
+ const nonce = integerBN(params.nonce ?? state.operator.nextNonce, "nonce");
64
+ const [proposal] = deriveOperatorProposalAddress(market, nonce, this.program.programId);
65
+ const instruction = await this.write.instruction("announceOperatorChange", {
66
+ nonce, expectedEpoch: integerBN(params.expectedEpoch ?? state.operator.epoch, "expectedEpoch"),
67
+ updates: updates.map(anchorParameterUpdate), nextOperator: params.nextOperator === undefined ? null : address(params.nextOperator),
68
+ nextManager: params.nextManager === undefined ? null : address(params.nextManager),
69
+ revenueRecipient: params.revenueRecipient === undefined ? null : address(params.revenueRecipient),
70
+ interestShareBps: params.interestShareBps ?? null, metadata: params.metadata,
71
+ }, { accounts: {payer: address(params.payer), operator: address(params.operator), market, proposal, systemProgram: SystemProgram.programId} });
72
+ return { proposal, instruction, transaction: new Transaction().add(instruction) };
73
+ }
74
+ async execute(params: {market: AddressLike; proposal: AddressLike; payer?:AddressLike; acceptingOperator?: AddressLike; remainingAccounts?: AccountMeta[]}) {
75
+ const state = await this.market(params.market);
76
+ const proposal = await this.proposal(params.proposal);
77
+ const next = proposal.revenueRecipient ?? (proposal.nextOperator && !proposal.nextOperator.equals(SystemProgram.programId)
78
+ ? proposal.nextOperator : state.operator.revenueRecipient);
79
+ let previousRevenue:PublicKey|null=null;
80
+ const setupInstructions=[];
81
+ if (!next.equals(state.operator.revenueRecipient)) {
82
+ previousRevenue=deriveOperatorRevenueAddress(address(params.market),state.operator.revenueEpoch,this.program.programId)[0];
83
+ if(!await this.program.provider.connection.getAccountInfo(previousRevenue)) {
84
+ const payer=params.payer ?? (this.program.provider as {publicKey?:PublicKey}).publicKey;
85
+ if(!payer)throw new Error("a funded payer is required to preserve the previous recipient's revenue");
86
+ setupInstructions.push(await this.initializeRevenueInstruction({market:params.market,payer}));
87
+ }
88
+ }
89
+ const builder = this.write.builder("executeOperatorChange", undefined, {
90
+ oraclePolicy: state.oracle?.policy,
91
+ accounts: {market: address(params.market), proposal: address(params.proposal), previousRevenue,
92
+ acceptingOperator: params.acceptingOperator === undefined ? null : address(params.acceptingOperator)},
93
+ remainingAccounts: params.remainingAccounts,
94
+ });
95
+ const instruction = await builder.instruction();
96
+ const transaction = await builder.transaction();
97
+ transaction.instructions.unshift(...setupInstructions);
98
+ if (!state.oracle?.policy.lambdaBps) transaction.instructions.unshift(ComputeBudgetProgram.setComputeUnitLimit({units:1_400_000}));
99
+ return { instruction, setupInstructions, transaction };
100
+ }
101
+ async removeManager(params: {market: AddressLike; operator: AddressLike}) {
102
+ const instruction = await this.write.instruction("removeMarketManager", undefined,
103
+ {accounts: {market: address(params.market), operator: address(params.operator)}});
104
+ return {instruction, transaction: new Transaction().add(instruction)};
105
+ }
106
+ async initializeRevenueInstruction(params:{market:AddressLike;payer:AddressLike}) {
107
+ const state=await this.market(params.market);
108
+ const [revenue]=deriveOperatorRevenueAddress(address(params.market),state.operator.revenueEpoch,this.program.programId);
109
+ return this.write.instruction("initializeOperatorRevenue",undefined,{accounts:{market:address(params.market),payer:address(params.payer),revenue,systemProgram:SystemProgram.programId}});
110
+ }
111
+ revenue(key:AddressLike):Promise<OperatorRevenueAccount> {
112
+ return this.program.account.operatorRevenueAccount.fetch(address(key));
113
+ }
114
+
115
+ async claim(params:{market:AddressLike;revenueEpoch?:IntegerLike;assetMint:AddressLike;payer:AddressLike;maxDebit?:IntegerLike;minimumCredit?:IntegerLike;remainingAccounts?:AccountMeta[]}) {
116
+ const market=address(params.market),payer=address(params.payer),mint=address(params.assetMint);
117
+ const state=await this.market(market);
118
+ const epoch=integerBN(params.revenueEpoch??state.operator.revenueEpoch,"revenueEpoch");
119
+ const current=epoch.eq(state.operator.revenueEpoch);
120
+ const revenue=current?null:deriveOperatorRevenueAddress(market,epoch,this.program.programId)[0];
121
+ const archive=revenue?await this.revenue(revenue):null;
122
+ const recipient=current?state.operator.revenueRecipient:archive!.recipient;
123
+ const side=state.baseSide.assetMint.equals(mint)?state.baseSide:state.quoteSide.assetMint.equals(mint)?state.quoteSide:null;
124
+ if(!side)throw new Error("asset mint is not part of the market");
125
+ const asset=state.baseSide.assetMint.equals(mint)?0:1;
126
+ let claimable=0n;
127
+ for(const i of [asset,asset+2]) {
128
+ const revenueBook=state.income.revenue[i]!;
129
+ claimable+=BigInt((current?revenueBook.operatorClaimable:archive!.claimable[i]!).toString());
130
+ }
131
+ const requested=BigInt(integerBN(params.maxDebit??0xffff_ffff_ffff_ffffn,"maxDebit").toString());
132
+ const debit=claimable<requested?claimable:requested;
133
+ if(debit===0n)throw new Error("no collected operator cash is claimable");
134
+ const tokenProgram=await tokenProgramForMint(this.program.provider.connection,mint);
135
+ const mintState=await getMint(this.program.provider.connection,mint,undefined,tokenProgram);
136
+ const ata=getAssociatedTokenAddressSync(mint,recipient,true,tokenProgram);
137
+ const hook=await resolveTransferHookAccountMetas(this.program.provider.connection,[{
138
+ mint,source:side.interestVault,destination:ata,authority:market,amount:debit,decimals:mintState.decimals,tokenProgram,
139
+ }]);
140
+ const instruction=await this.write.instruction("claimOperatorRevenue",{revenueEpoch:epoch,
141
+ maxDebit:integerBN(debit,"maxDebit"),minimumCredit:integerBN(params.minimumCredit??0,"minimumCredit")},
142
+ {accounts:{market,revenue,recipient,assetMint:mint,interestVault:side.interestVault,recipientAssetAccount:ata,
143
+ tokenProgram:TOKEN_PROGRAM_ID,token2022Program:TOKEN_2022_PROGRAM_ID},remainingAccounts:[...hook,...(params.remainingAccounts??[])]});
144
+ const transaction=new Transaction().add(createAssociatedTokenAccountIdempotentInstruction(payer,ata,recipient,mint,tokenProgram),instruction);
145
+ return {instruction,transaction,recipient,revenue,recipientAssetAccount:ata};
146
+ }
147
+ async resolve(params: {market: AddressLike; proposal: AddressLike; operator?: AddressLike; cancel?: boolean}) {
148
+ const proposal = await this.proposal(params.proposal);
149
+ if (!proposal.market.equals(address(params.market))) throw new Error("proposal belongs to another market");
150
+ const instruction = await this.write.instruction("resolveOperatorChange", params.cancel ?? false, {
151
+ accounts: {market: address(params.market), proposal: address(params.proposal), rentRefund: proposal.rentRefund,
152
+ operator: params.operator === undefined ? null : address(params.operator)},
153
+ });
154
+ return { instruction, transaction: new Transaction().add(instruction) };
155
+ }
156
+ cancel(params: {market: AddressLike; proposal: AddressLike; operator: AddressLike}) {
157
+ return this.resolve({...params, cancel: true});
158
+ }
159
+
160
+ /** Verify the on-chain notice commitment using the generated Borsh layout.
161
+ * Immutable fields precede the trailing digest (32), executed (1), bump (1). */
162
+ async verifyDigest(proposal: OperatorProposal): Promise<boolean> {
163
+ if (proposal.policyVersion.toString() !== OPERATOR_POLICY_VERSION.toString()) return false;
164
+ const bytes = await this.program.coder.accounts.encode("operatorProposal", proposal);
165
+ const domain = Buffer.from("DUSK_OPERATOR_CHANGE_V2");
166
+ const digest = await sha256(Buffer.concat([domain, this.program.programId.toBuffer(), bytes.subarray(8, bytes.length - 34)]));
167
+ return digest.every((value, index) => value === proposal.digest[index]);
168
+ }
169
+ }