@omnipair/dusk-sdk 2.0.0 → 2.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/write.ts CHANGED
@@ -1,12 +1,21 @@
1
1
  import type { Program } from "@coral-xyz/anchor";
2
- import { TOKEN_2022_PROGRAM_ID, TOKEN_PROGRAM_ID } from "@solana/spl-token";
2
+ import { getMint, TOKEN_2022_PROGRAM_ID, TOKEN_PROGRAM_ID } from "@solana/spl-token";
3
3
  import { SystemProgram, Transaction, type AccountMeta, type TransactionInstruction } from "@solana/web3.js";
4
4
 
5
5
  import { address, normalizeAccountKeys, type AddressLike } from "./address.js";
6
- import { deriveReferralProfileAddress } from "./constants.js";
7
6
  import {
8
- buildReferralVaultSetupInstruction,
7
+ deriveFutarchyAuthorityAddress,
8
+ deriveMarketInterestVaultAddress,
9
+ deriveYieldAccountAddress,
10
+ deriveYieldTransferHookValidationAddress,
11
+ deriveReferralPartnerAddress,
12
+ type YieldTokenKind,
13
+ } from "./constants.js";
14
+ import {
15
+ assertReferralInterestShareBps,
16
+ referralAccrualAddresses,
9
17
  resolveTransferHookAccountMetas,
18
+ tokenProgramForMint,
10
19
  type TransferHookTransfer,
11
20
  } from "./referral.js";
12
21
  import type { Dusk } from "./types_v2.js";
@@ -20,25 +29,48 @@ export interface DuskBuildOptions {
20
29
  remainingAccounts?: AccountMeta[];
21
30
  }
22
31
 
23
- export type ReferredActionName = "borrow" | "openLeverage" | "increaseLeverage";
32
+ export interface SwapBuildOptions extends DuskBuildOptions {
33
+ accounts: DuskAccounts;
34
+ market: AddressLike;
35
+ }
36
+
37
+ export type ReferredActionName = "borrow" | "openLeverage";
24
38
 
25
39
  export interface ReferredActionOptions extends DuskBuildOptions {
26
40
  accounts: DuskAccounts;
27
41
  payer: AddressLike;
28
42
  referrer: AddressLike;
43
+ market: AddressLike;
29
44
  debtMint: AddressLike;
30
- maxAcceptableReferralFeeBps: number;
31
45
  transferHookTransfers?: readonly TransferHookTransfer[];
32
46
  }
33
47
 
34
48
  export interface ReferredActionBuild {
35
- referralProfile: ReturnType<typeof deriveReferralProfileAddress>[0];
36
- referralVault: ReturnType<typeof deriveReferralProfileAddress>[0];
49
+ referralPartner: ReturnType<typeof deriveReferralPartnerAddress>[0];
50
+ referralAccrual: ReturnType<typeof deriveReferralPartnerAddress>[0];
37
51
  setupInstruction: TransactionInstruction;
38
52
  actionInstruction: TransactionInstruction;
39
53
  transaction: Transaction;
40
54
  }
41
55
 
56
+ export interface HlpLiquidityBuildOptions extends DuskBuildOptions {
57
+ accounts: DuskAccounts;
58
+ payer: AddressLike;
59
+ owner: AddressLike;
60
+ market: AddressLike;
61
+ targetHlpMint: AddressLike;
62
+ baseMint: AddressLike;
63
+ quoteMint: AddressLike;
64
+ }
65
+
66
+ export interface HlpLiquidityBuild {
67
+ baseYieldAccount: AccountMeta["pubkey"];
68
+ quoteYieldAccount: AccountMeta["pubkey"];
69
+ setupInstructions: TransactionInstruction[];
70
+ actionInstruction: TransactionInstruction;
71
+ transaction: Transaction;
72
+ }
73
+
42
74
  type AnchorMethodBuilder = {
43
75
  accounts(accounts: DuskAccounts): AnchorMethodBuilder;
44
76
  remainingAccounts(accounts: AccountMeta[]): AnchorMethodBuilder;
@@ -95,16 +127,272 @@ export class DuskWrite {
95
127
  return this.builder(name, args, options).rpc();
96
128
  }
97
129
 
130
+ async swapBuilder(
131
+ args: Record<string, unknown>,
132
+ options: SwapBuildOptions
133
+ ): Promise<AnchorMethodBuilder> {
134
+ const market = address(options.market);
135
+ const state = (await this.program.account.market.fetch(market)) as unknown as {
136
+ ylpMint: AccountMeta["pubkey"];
137
+ baseSide: { interestVault: AccountMeta["pubkey"] };
138
+ quoteSide: { interestVault: AccountMeta["pubkey"] };
139
+ baseHlpVault: {
140
+ hlpSupply: { toString(): string };
141
+ residualExposure: { toString(): string };
142
+ ylpVault: AccountMeta["pubkey"];
143
+ };
144
+ quoteHlpVault: {
145
+ hlpSupply: { toString(): string };
146
+ residualExposure: { toString(): string };
147
+ ylpVault: AccountMeta["pubkey"];
148
+ };
149
+ };
150
+ const hlpActive =
151
+ BigInt(state.baseHlpVault.hlpSupply.toString()) !== 0n ||
152
+ BigInt(state.quoteHlpVault.hlpSupply.toString()) !== 0n ||
153
+ BigInt(state.baseHlpVault.residualExposure.toString()) !== 0n ||
154
+ BigInt(state.quoteHlpVault.residualExposure.toString()) !== 0n;
155
+ const prefix: AccountMeta[] = hlpActive
156
+ ? [
157
+ { pubkey: state.ylpMint, isSigner: false, isWritable: true },
158
+ { pubkey: state.baseHlpVault.ylpVault, isSigner: false, isWritable: true },
159
+ { pubkey: state.quoteHlpVault.ylpVault, isSigner: false, isWritable: true },
160
+ { pubkey: state.baseSide.interestVault, isSigner: false, isWritable: true },
161
+ { pubkey: state.quoteSide.interestVault, isSigner: false, isWritable: true },
162
+ ]
163
+ : [];
164
+
165
+ return this.builder("swap", args, {
166
+ accounts: options.accounts,
167
+ // Prefix order is consensus-visible. Hook accounts must remain a tail,
168
+ // including any deliberate duplicate pubkeys required by a hook meta list.
169
+ remainingAccounts: [...prefix, ...(options.remainingAccounts ?? [])],
170
+ });
171
+ }
172
+
173
+ async swapInstruction(args: Record<string, unknown>, options: SwapBuildOptions) {
174
+ return (await this.swapBuilder(args, options)).instruction();
175
+ }
176
+
177
+ async swapTransaction(args: Record<string, unknown>, options: SwapBuildOptions) {
178
+ return (await this.swapBuilder(args, options)).transaction();
179
+ }
180
+
181
+ async swapRpc(args: Record<string, unknown>, options: SwapBuildOptions) {
182
+ return (await this.swapBuilder(args, options)).rpc();
183
+ }
184
+
185
+ async initializeYieldAccountsInstruction(params: {
186
+ payer: AddressLike;
187
+ owner: AddressLike;
188
+ market: AddressLike;
189
+ lpMint: AddressLike;
190
+ baseMint: AddressLike;
191
+ quoteMint: AddressLike;
192
+ tokenKind: YieldTokenKind;
193
+ }): Promise<TransactionInstruction> {
194
+ const payer = address(params.payer);
195
+ const owner = address(params.owner);
196
+ const market = address(params.market);
197
+ const lpMint = address(params.lpMint);
198
+ const baseMint = address(params.baseMint);
199
+ const quoteMint = address(params.quoteMint);
200
+ const tokenKind = params.tokenKind === "ylp" || params.tokenKind === 0 ? { ylp: {} } : { hlp: {} };
201
+ return this.instruction("initializeYieldAccounts" as DuskInstructionName, { owner, tokenKind }, {
202
+ accounts: {
203
+ payer,
204
+ market,
205
+ lpMint,
206
+ baseMint,
207
+ quoteMint,
208
+ baseYieldAccount: deriveYieldAccountAddress(market, owner, lpMint, baseMint, params.tokenKind)[0],
209
+ quoteYieldAccount: deriveYieldAccountAddress(market, owner, lpMint, quoteMint, params.tokenKind)[0],
210
+ systemProgram: SystemProgram.programId,
211
+ },
212
+ });
213
+ }
214
+
215
+ async initializeYieldAccountsTransaction(
216
+ params: Parameters<DuskWrite["initializeYieldAccountsInstruction"]>[0]
217
+ ): Promise<Transaction> {
218
+ return new Transaction().add(await this.initializeYieldAccountsInstruction(params));
219
+ }
220
+
221
+ async initializeLpTransferHookInstruction(params: {
222
+ payer: AddressLike;
223
+ market: AddressLike;
224
+ lpMint: AddressLike;
225
+ }): Promise<TransactionInstruction> {
226
+ const lpMint = address(params.lpMint);
227
+ return this.instruction("initializeLpTransferHook" as DuskInstructionName, undefined, {
228
+ accounts: {
229
+ payer: address(params.payer),
230
+ market: address(params.market),
231
+ lpMint,
232
+ validationAccount: deriveYieldTransferHookValidationAddress(lpMint)[0],
233
+ systemProgram: SystemProgram.programId,
234
+ },
235
+ });
236
+ }
237
+
238
+ async initializeLpTransferHookTransaction(
239
+ params: Parameters<DuskWrite["initializeLpTransferHookInstruction"]>[0]
240
+ ): Promise<Transaction> {
241
+ return new Transaction().add(await this.initializeLpTransferHookInstruction(params));
242
+ }
243
+
244
+ async hlpLiquidityAction(
245
+ name: "depositSingleSided" | "withdrawSingleSided",
246
+ args: Record<string, unknown>,
247
+ options: HlpLiquidityBuildOptions
248
+ ): Promise<HlpLiquidityBuild> {
249
+ const payer = address(options.payer);
250
+ const owner = address(options.owner);
251
+ const market = address(options.market);
252
+ const lpMint = address(options.targetHlpMint);
253
+ const baseMint = address(options.baseMint);
254
+ const quoteMint = address(options.quoteMint);
255
+ const baseYieldAccount = deriveYieldAccountAddress(market, owner, lpMint, baseMint, "hlp")[0];
256
+ const quoteYieldAccount = deriveYieldAccountAddress(market, owner, lpMint, quoteMint, "hlp")[0];
257
+ const [baseYieldInfo, quoteYieldInfo] = await Promise.all([
258
+ this.program.provider.connection.getAccountInfo(baseYieldAccount),
259
+ this.program.provider.connection.getAccountInfo(quoteYieldAccount),
260
+ ]);
261
+ const yieldAccountDefinition = this.program.idl.accounts?.find(
262
+ (account) => account.name === "yieldAccount"
263
+ );
264
+ if (!yieldAccountDefinition) {
265
+ throw new Error("Dusk IDL is missing YieldAccount");
266
+ }
267
+ const yieldAccountSize = this.program.coder.accounts.size("yieldAccount");
268
+ const yieldAccountDiscriminator = Buffer.from(yieldAccountDefinition.discriminator);
269
+ const yieldAccountsReady = [baseYieldInfo, quoteYieldInfo].every(
270
+ (info) =>
271
+ info !== null &&
272
+ info.owner.equals(this.program.programId) &&
273
+ info.data.length === yieldAccountSize &&
274
+ info.data.subarray(0, yieldAccountDiscriminator.length).equals(yieldAccountDiscriminator)
275
+ );
276
+ const setupInstructions =
277
+ yieldAccountsReady
278
+ ? []
279
+ : [
280
+ await this.initializeYieldAccountsInstruction({
281
+ payer,
282
+ owner,
283
+ market,
284
+ lpMint,
285
+ baseMint,
286
+ quoteMint,
287
+ tokenKind: "hlp",
288
+ }),
289
+ ];
290
+ const actionInstruction = await this.instruction(name, args, {
291
+ accounts: {
292
+ ...options.accounts,
293
+ market,
294
+ owner,
295
+ targetHlpMint: lpMint,
296
+ baseMint,
297
+ quoteMint,
298
+ baseYieldAccount,
299
+ quoteYieldAccount,
300
+ },
301
+ remainingAccounts: options.remainingAccounts,
302
+ });
303
+ return {
304
+ baseYieldAccount,
305
+ quoteYieldAccount,
306
+ setupInstructions,
307
+ actionInstruction,
308
+ transaction: new Transaction().add(...setupInstructions, actionInstruction),
309
+ };
310
+ }
311
+
312
+ depositSingleSided(args: Record<string, unknown>, options: HlpLiquidityBuildOptions) {
313
+ return this.hlpLiquidityAction("depositSingleSided", args, options);
314
+ }
315
+
316
+ withdrawSingleSided(args: Record<string, unknown>, options: HlpLiquidityBuildOptions) {
317
+ return this.hlpLiquidityAction("withdrawSingleSided", args, options);
318
+ }
319
+
320
+ async configureReferralPartnerInstruction(params: {
321
+ authoritySigner: AddressLike;
322
+ referrer: AddressLike;
323
+ interestShareBps: number;
324
+ active: boolean;
325
+ futarchyAuthority?: AddressLike;
326
+ }): Promise<TransactionInstruction> {
327
+ assertReferralInterestShareBps(params.interestShareBps);
328
+ const referrer = address(params.referrer);
329
+ return this.instruction(
330
+ "configureReferralPartner",
331
+ {
332
+ referrer,
333
+ interestShareBps: params.interestShareBps,
334
+ active: params.active,
335
+ },
336
+ {
337
+ accounts: {
338
+ authoritySigner: address(params.authoritySigner),
339
+ futarchyAuthority:
340
+ params.futarchyAuthority ?? deriveFutarchyAuthorityAddress()[0],
341
+ referralPartner: deriveReferralPartnerAddress(referrer)[0],
342
+ systemProgram: SystemProgram.programId,
343
+ },
344
+ }
345
+ );
346
+ }
347
+
348
+ async configureReferralPartnerTransaction(
349
+ params: Parameters<DuskWrite["configureReferralPartnerInstruction"]>[0]
350
+ ): Promise<Transaction> {
351
+ return new Transaction().add(await this.configureReferralPartnerInstruction(params));
352
+ }
353
+
354
+ async initializeReferralAccrualInstruction(params: {
355
+ payer: AddressLike;
356
+ referrer: AddressLike;
357
+ market: AddressLike;
358
+ assetMint: AddressLike;
359
+ }): Promise<TransactionInstruction> {
360
+ const referral = referralAccrualAddresses(params);
361
+ return this.instruction("initializeReferralAccrual", undefined, {
362
+ accounts: {
363
+ payer: address(params.payer),
364
+ referralPartner: referral.referralPartner,
365
+ market: address(params.market),
366
+ assetMint: address(params.assetMint),
367
+ referralAccrual: referral.referralAccrual,
368
+ systemProgram: SystemProgram.programId,
369
+ },
370
+ });
371
+ }
372
+
373
+ async initializeReferralAccrualTransaction(
374
+ params: Parameters<DuskWrite["initializeReferralAccrualInstruction"]>[0]
375
+ ): Promise<Transaction> {
376
+ return new Transaction().add(
377
+ await this.initializeReferralAccrualInstruction(params)
378
+ );
379
+ }
380
+
98
381
  async referredAction(
99
382
  name: ReferredActionName,
100
383
  args: Record<string, unknown>,
101
384
  options: ReferredActionOptions
102
385
  ): Promise<ReferredActionBuild> {
103
- const setup = await buildReferralVaultSetupInstruction({
104
- connection: this.program.provider.connection,
386
+ const referral = referralAccrualAddresses({
387
+ referrer: options.referrer,
388
+ market: options.market,
389
+ assetMint: options.debtMint,
390
+ });
391
+ const setupInstruction = await this.initializeReferralAccrualInstruction({
105
392
  payer: options.payer,
106
393
  referrer: options.referrer,
107
- mint: options.debtMint,
394
+ market: options.market,
395
+ assetMint: options.debtMint,
108
396
  });
109
397
  const hookAccounts = options.transferHookTransfers?.length
110
398
  ? await resolveTransferHookAccountMetas(
@@ -117,23 +405,22 @@ export class DuskWrite {
117
405
  {
118
406
  ...args,
119
407
  referrer: address(options.referrer),
120
- maxAcceptableReferralFeeBps: options.maxAcceptableReferralFeeBps,
121
408
  },
122
409
  {
123
410
  accounts: {
124
411
  ...options.accounts,
125
- referralProfile: setup.referralProfile,
126
- referralVault: setup.referralVault,
412
+ referralPartner: referral.referralPartner,
413
+ referralAccrual: referral.referralAccrual,
127
414
  },
128
415
  remainingAccounts: mergeAccountMetas(options.remainingAccounts ?? [], hookAccounts),
129
416
  }
130
417
  );
131
418
  return {
132
- referralProfile: setup.referralProfile,
133
- referralVault: setup.referralVault,
134
- setupInstruction: setup.instruction,
419
+ referralPartner: referral.referralPartner,
420
+ referralAccrual: referral.referralAccrual,
421
+ setupInstruction,
135
422
  actionInstruction,
136
- transaction: new Transaction().add(setup.instruction, actionInstruction),
423
+ transaction: new Transaction().add(setupInstruction, actionInstruction),
137
424
  };
138
425
  }
139
426
 
@@ -145,10 +432,6 @@ export class DuskWrite {
145
432
  return this.referredAction("openLeverage", args, options);
146
433
  }
147
434
 
148
- referredIncreaseLeverage(args: Record<string, unknown>, options: ReferredActionOptions) {
149
- return this.referredAction("increaseLeverage", args, options);
150
- }
151
-
152
435
  async setReferralRecipientInstruction(params: {
153
436
  authority: AddressLike;
154
437
  recipient: AddressLike;
@@ -160,39 +443,89 @@ export class DuskWrite {
160
443
  {
161
444
  accounts: {
162
445
  authority,
163
- referralProfile: deriveReferralProfileAddress(authority)[0],
164
- systemProgram: SystemProgram.programId,
446
+ referralPartner: deriveReferralPartnerAddress(authority)[0],
165
447
  },
166
448
  }
167
449
  );
168
450
  }
169
451
 
170
- async claimReferralFeesInstruction(params: {
452
+ async setReferralRecipientTransaction(params: {
171
453
  authority: AddressLike;
454
+ recipient: AddressLike;
455
+ }): Promise<Transaction> {
456
+ return new Transaction().add(await this.setReferralRecipientInstruction(params));
457
+ }
458
+
459
+ async claimReferralInterestInstruction(params: {
460
+ authority: AddressLike;
461
+ market: AddressLike;
172
462
  mint: AddressLike;
463
+ interestVault?: AddressLike;
173
464
  recipientTokenAccount: AddressLike;
174
465
  remainingAccounts?: AccountMeta[];
175
466
  }): Promise<TransactionInstruction> {
176
467
  const authority = address(params.authority);
177
- const setup = await buildReferralVaultSetupInstruction({
178
- connection: this.program.provider.connection,
179
- payer: authority,
468
+ const market = address(params.market);
469
+ const mintKey = address(params.mint);
470
+ const referral = referralAccrualAddresses({
180
471
  referrer: authority,
181
- mint: params.mint,
472
+ market,
473
+ assetMint: mintKey,
182
474
  });
183
- return this.instruction("claimReferralFees", undefined, {
475
+ const interestVault = address(
476
+ params.interestVault ?? deriveMarketInterestVaultAddress(market, mintKey)[0]
477
+ );
478
+ const recipientTokenAccount = address(params.recipientTokenAccount);
479
+ const tokenProgram = await tokenProgramForMint(
480
+ this.program.provider.connection,
481
+ mintKey
482
+ );
483
+ const [accrual, mint] = await Promise.all([
484
+ this.program.account.referralAccrual.fetch(referral.referralAccrual),
485
+ getMint(
486
+ this.program.provider.connection,
487
+ mintKey,
488
+ undefined,
489
+ tokenProgram
490
+ ),
491
+ ]);
492
+ const hookAccounts = await resolveTransferHookAccountMetas(
493
+ this.program.provider.connection,
494
+ [
495
+ {
496
+ source: interestVault,
497
+ mint: mintKey,
498
+ destination: recipientTokenAccount,
499
+ authority: market,
500
+ amount: accrual.amount,
501
+ decimals: mint.decimals,
502
+ tokenProgram,
503
+ },
504
+ ]
505
+ );
506
+ return this.instruction("claimReferralInterest", undefined, {
184
507
  accounts: {
508
+ market,
185
509
  authority,
186
- referralProfile: setup.referralProfile,
187
- assetMint: address(params.mint),
188
- referralVault: setup.referralVault,
189
- recipientTokenAccount: address(params.recipientTokenAccount),
510
+ referralPartner: referral.referralPartner,
511
+ assetMint: mintKey,
512
+ referralAccrual: referral.referralAccrual,
513
+ interestVault,
514
+ recipientTokenAccount,
190
515
  tokenProgram: TOKEN_PROGRAM_ID,
191
516
  token2022Program: TOKEN_2022_PROGRAM_ID,
192
517
  },
193
- remainingAccounts: params.remainingAccounts,
518
+ remainingAccounts: mergeAccountMetas(params.remainingAccounts ?? [], hookAccounts),
194
519
  });
195
520
  }
521
+
522
+ async claimReferralInterestTransaction(
523
+ params: Parameters<DuskWrite["claimReferralInterestInstruction"]>[0]
524
+ ): Promise<Transaction> {
525
+ return new Transaction().add(
526
+ await this.claimReferralInterestInstruction(params)
527
+ );
528
+ }
196
529
  }
197
530
 
198
531
  function normalizeArgs(args: DuskInstructionArgs): unknown[] {