-
Notifications
You must be signed in to change notification settings - Fork 3
/
socean.ts
754 lines (700 loc) · 25.8 KB
/
socean.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
/**
* Socean class
*
* Implements the client that interacts with Socean stake pool.
*
* @module
*/
import { TOKEN_PROGRAM_ID } from "@solana/spl-token";
import {
Commitment,
ConfirmOptions,
Connection,
Context,
Keypair,
PublicKey,
Signer,
StakeAuthorizationLayout,
StakeProgram,
Transaction,
} from "@solana/web3.js";
import BN from "bn.js";
import { signAndSendTransactionSequence } from "@/socean";
import { ClusterType, SoceanConfig } from "@/socean/config";
import {
AccountDoesNotExistError,
StakeAccountNotRentExemptError,
StakeAccountToDepositInvalidError,
WalletPublicKeyUnavailableError,
} from "@/socean/err";
import {
TRANSACTION_SEQUENCE_DEFAULT_CONFIRM_OPTIONS,
TransactionSequence,
TransactionSequenceSignatures,
TransactionWithSigners,
WalletAdapter,
} from "@/socean/transactions";
import {
cleanupRemovedValidatorsInstruction,
depositSolInstruction,
depositStakeInstruction,
updateStakePoolBalanceInstruction,
updateValidatorListBalanceTransaction,
} from "@/stake-pool/instructions";
import { ParsedStakeAccount } from "@/stake-pool/stakeAccount";
import {
Numberu64,
StakePoolAccount,
ValidatorAllStakeAccounts,
ValidatorListAccount,
} from "@/stake-pool/types";
import {
calcWithdrawals,
getOrCreateAssociatedAddress,
getStakePoolFromAccountInfo,
getValidatorListFromAccountInfo,
getValidatorStakeAccount,
getValidatorTransientStakeAccount,
getWithdrawAuthority,
getWithdrawStakeTransactions,
STAKE_ACCOUNT_RENT_EXEMPT_LAMPORTS,
tryRpc,
} from "@/stake-pool/utils";
export class Socean {
public readonly config: SoceanConfig;
/**
* Instantiates a Socean client
* @param clusterType The cluster, for eg. mainnet-beta, to connect to
* @param connectionOption Accepts either a `Connection` or a `rpcEndpoint` string
*/
constructor(
clusterType: ClusterType = "testnet",
connectionOption?: Connection | string,
) {
this.config = new SoceanConfig(clusterType, connectionOption);
}
/**
* Signs, sends and confirms the transactions required to deposit SOL
* into the Socean stake pool.
* Creates the scnSOL associated token account for the wallet if it doesnt exist.
* @param walletAdapter SOL wallet to deposit SOL from
* @param amountLamports amount to deposit in lamports
* @param referrerPoolTokenAccount PublicKey of a scnSOL token account of the referrer for this deposit
* @param confirmOptions transaction confirm options for each transaction
* @returns the transaction signatures of the transactions sent and confirmed
* @throws RpcError
* @throws AccountDoesNotExistError if stake pool does not exist
* @throws WalletPublicKeyUnavailableError
*/
async depositSol(
walletAdapter: WalletAdapter,
amountLamports: Numberu64,
referrerPoolTokenAccount?: PublicKey,
confirmOptions: ConfirmOptions = TRANSACTION_SEQUENCE_DEFAULT_CONFIRM_OPTIONS,
): Promise<TransactionSequenceSignatures> {
const walletPubkey = walletAdapter.publicKey;
if (!walletPubkey) throw new WalletPublicKeyUnavailableError();
const txSeq = await this.depositSolTransactions(
walletPubkey,
amountLamports,
referrerPoolTokenAccount,
);
return this.signAndSend(walletAdapter, txSeq, confirmOptions);
}
/**
* Creates a `TransactionSequence` that deposits SOL into Socean stake pool
* Each inner `TransactionWithSigners` array must be executed and confirmed
* before going to the next one.
* Creates the scnSOL associated token account for the wallet if it doesnt exist.
* This is a lower-level API for compatibility, recommend using `depositSol()` instead if possible.
* @param walletPubkey SOL wallet to deposit SOL from
* @param amountLamports amount to deposit in lamports
* @param referrerPoolTokenAccount PublicKey of a scnSOL token account of the referrer for this deposit
* @returns the deposit transaction sequence
* @throws RpcError
* @throws AccountDoesNotExistError if stake pool does not exist
*/
async depositSolTransactions(
walletPubkey: PublicKey,
amountLamports: Numberu64,
referrerPoolTokenAccount?: PublicKey,
): Promise<TransactionSequence> {
const stakePool = await this.getStakePoolAccount();
const tx = new Transaction();
// get associated token account for scnSOL, if not exist create one
const poolTokenTo = await getOrCreateAssociatedAddress(
this.config.connection,
stakePool.account.data.poolMint,
walletPubkey,
tx,
);
// prep deposit sol instruction
const stakePoolWithdrawAuthority = await getWithdrawAuthority(
this.config.stakePoolProgramId,
this.config.stakePoolAccountPubkey,
);
const ix = depositSolInstruction(
this.config.stakePoolProgramId,
this.config.stakePoolAccountPubkey,
stakePoolWithdrawAuthority,
stakePool.account.data.reserveStake,
walletPubkey,
poolTokenTo,
stakePool.account.data.managerFeeAccount,
referrerPoolTokenAccount ?? stakePool.account.data.managerFeeAccount,
stakePool.account.data.poolMint,
TOKEN_PROGRAM_ID,
amountLamports,
);
tx.add(ix);
const transactionSequence: TransactionSequence = [
[
{
tx,
signers: [],
},
],
];
const currEpoch = await this.getCurrentEpoch();
if (stakePool.account.data.lastUpdateEpoch.lt(new BN(currEpoch))) {
const validatorListAcc = await this.getValidatorListAccount(
stakePool.account.data.validatorList,
);
const updateTxSeq = await this.updateTransactionSequence(
stakePool,
validatorListAcc,
);
transactionSequence.unshift(...updateTxSeq);
}
return transactionSequence;
}
/**
* Signs, sends and confirms the transactions required to deposit a stake account
* into the Socean stake pool
* Creates the scnSOL associated token account for the wallet if it doesnt exist.
* @param walletAdapter SOL wallet to deposit SOL from
* @param stakeAccount The stake account to deposit.
* Must be active and delegated to a validator in the stake pool.
* @param amountLamports The amount of stake to split from `stakeAccount` to deposit.
* If not provided, 0, or greater than the staked balance, the entire stake account is deposited.
* Otherwise, a stake account containing `amountLamports` is first split from `stakeAccount` and then deposited.
* Must be greater than `STAKE_ACCOUNT_RENT_EXEMPT_LAMPORTS` and leave more than `STAKE_ACCOUNT_RENT_EXEMPT_LAMPORTS`
* remaining in the stake account it is split from.
* @param referrerPoolTokenAccount PublicKey of a scnSOL token account of the referrer for this deposit
* @param confirmOptions transaction confirm options for each transaction
* @returns the transaction signatures of the transactions sent and confirmed
* @throws RpcError
* @throws AccountDoesNotExistError if stake pool or main validator stake account for `stakeAccount`'s validator does not exist
* @throws WalletPublicKeyUnavailableError
* @throws StakeAccountToDepositInvalidError if stake account to deposit does not meet deposit requirements
* @throws StakeAccountNotRentExempt if provided `amountLamports` leaves a stake account at or below below rent-exempt balance
*/
async depositStake(
walletAdapter: WalletAdapter,
stakeAccount: PublicKey,
amountLamports?: Numberu64,
referrerPoolTokenAccount?: PublicKey,
confirmOptions: ConfirmOptions = TRANSACTION_SEQUENCE_DEFAULT_CONFIRM_OPTIONS,
): Promise<TransactionSequenceSignatures> {
const walletPubkey = walletAdapter.publicKey;
if (!walletPubkey) throw new WalletPublicKeyUnavailableError();
const txSeq = await this.depositStakeTransactions(
walletPubkey,
stakeAccount,
amountLamports,
referrerPoolTokenAccount,
);
return this.signAndSend(walletAdapter, txSeq, confirmOptions);
}
/**
* Creates a `TransactionSequence` that deposits an active stake account currently staked
* with one of the Socean stake pool's validators into Socean stake pool
* Each inner `TransactionWithSigners` array must be executed and confirmed
* before going to the next one.
* Creates the scnSOL associated token account for the wallet if it doesnt exist.
* This is a lower-level API for compatibility, recommend using `depositStake()` instead if possible.
* @param walletPubkey SOL wallet to deposit SOL from
* @param stakeAccount The stake account to deposit.
* Must be active and delegated to a validator in the stake pool.
* @param amountLamports The amount of stake to split from `stakeAccount` to deposit.
* If not provided, 0, or greater than the staked balance, the entire stake account is deposited.
* Otherwise, a stake account containing `amountLamports` is first split from `stakeAccount` and then deposited.
* Must be greater than `STAKE_ACCOUNT_RENT_EXEMPT_LAMPORTS` and leave more than `STAKE_ACCOUNT_RENT_EXEMPT_LAMPORTS`
* remaining in the stake account it is split from.
* @param referrerPoolTokenAccount PublicKey of a scnSOL token account of the referrer for this deposit
* @returns the deposit transaction sequence
* @throws RpcError
* @throws AccountDoesNotExistError if stake pool or main validator stake account for `stakeAccount`'s validator does not exist
* @throws StakeAccountToDepositInvalidError if stake account to deposit does not meet deposit requirements
* @throws StakeAccountNotRentExempt if provided `amountLamports` leaves a stake account at or below rent-exempt balance
*/
async depositStakeTransactions(
walletPubkey: PublicKey,
stakeAccount: PublicKey,
amountLamports?: Numberu64,
referrerPoolTokenAccount?: PublicKey,
): Promise<TransactionSequence> {
const { value } = await this.config.connection.getParsedAccountInfo(
stakeAccount,
);
if (!value)
throw new StakeAccountToDepositInvalidError(
"stake account does not exist",
);
if (
value.data instanceof Buffer ||
!value.owner.equals(StakeProgram.programId)
)
throw new StakeAccountToDepositInvalidError("not a stake account");
const stakeAccountInfo: ParsedStakeAccount = value.data.parsed;
const stakeAccountLamports = new Numberu64(value.lamports);
if (
!stakeAccountInfo.info.stake.delegation.voter ||
!stakeAccountInfo.info.stake.delegation.stake
)
throw new StakeAccountToDepositInvalidError(
"stake account not delegated",
);
const voteAcc = new PublicKey(stakeAccountInfo.info.stake.delegation.voter);
const vsa = await getValidatorStakeAccount(
this.config.stakePoolProgramId,
this.config.stakePoolAccountPubkey,
voteAcc,
);
const { value: vsaAcc } = await this.config.connection.getParsedAccountInfo(
vsa,
);
if (!vsaAcc) throw new AccountDoesNotExistError(vsa);
const stakePool = await this.getStakePoolAccount();
const tx = new Transaction();
// get associated token account for scnSOL, if not exist create one
const poolTokenTo = await getOrCreateAssociatedAddress(
this.config.connection,
stakePool.account.data.poolMint,
walletPubkey,
tx,
);
const stakePoolWithdrawAuthority = await getWithdrawAuthority(
this.config.stakePoolProgramId,
this.config.stakePoolAccountPubkey,
);
const signers: Signer[] = [];
let stakeAccountToDeposit = stakeAccount;
if (
amountLamports &&
!amountLamports.isZero() &&
amountLamports.lt(stakeAccountLamports)
) {
if (
amountLamports.lte(STAKE_ACCOUNT_RENT_EXEMPT_LAMPORTS) ||
stakeAccountLamports
.sub(amountLamports)
.lte(STAKE_ACCOUNT_RENT_EXEMPT_LAMPORTS)
) {
throw new StakeAccountNotRentExemptError();
}
const splitStakeAccount = Keypair.generate();
signers.push(splitStakeAccount);
stakeAccountToDeposit = splitStakeAccount.publicKey;
const splitTx = StakeProgram.split({
stakePubkey: stakeAccount,
authorizedPubkey: walletPubkey,
splitStakePubkey: splitStakeAccount.publicKey,
lamports: amountLamports.toNumber(),
});
tx.add(splitTx);
}
// set stake and withdraw authority to stake pool deposit authority
tx.add(
StakeProgram.authorize({
stakePubkey: stakeAccountToDeposit,
authorizedPubkey: walletPubkey,
newAuthorizedPubkey: stakePool.account.data.depositAuthority,
stakeAuthorizationType: StakeAuthorizationLayout.Staker,
}),
);
tx.add(
StakeProgram.authorize({
stakePubkey: stakeAccountToDeposit,
authorizedPubkey: walletPubkey,
newAuthorizedPubkey: stakePool.account.data.depositAuthority,
stakeAuthorizationType: StakeAuthorizationLayout.Withdrawer,
}),
);
const ix = depositStakeInstruction(
this.config.stakePoolProgramId,
this.config.stakePoolAccountPubkey,
stakePool.account.data.validatorList,
stakePool.account.data.depositAuthority,
stakePoolWithdrawAuthority,
stakeAccountToDeposit,
vsa,
stakePool.account.data.reserveStake,
poolTokenTo,
stakePool.account.data.managerFeeAccount,
referrerPoolTokenAccount ?? stakePool.account.data.managerFeeAccount,
stakePool.account.data.poolMint,
TOKEN_PROGRAM_ID,
);
tx.add(ix);
const transactionSequence: TransactionSequence = [
[
{
tx,
signers,
},
],
];
const currEpoch = await this.getCurrentEpoch();
if (stakePool.account.data.lastUpdateEpoch.lt(new BN(currEpoch))) {
const validatorListAcc = await this.getValidatorListAccount(
stakePool.account.data.validatorList,
);
const updateTxSeq = await this.updateTransactionSequence(
stakePool,
validatorListAcc,
);
transactionSequence.unshift(...updateTxSeq);
}
return transactionSequence;
}
/**
* Signs, sends and confirms the transactions required to withdraw stake from the Socean stake pool
* @param walletAdapter the SOL wallet to withdraw stake to. scnSOL is deducted from this wallet's associated token account.
* @param amountDroplets amount of scnSOL to withdraw in droplets (1 scnSOL = 10^9 droplets)
* @param confirmOptions transaction confirm options for each transaction
* @returns the transaction signatures of the transactions sent and confirmed
* and the newly created stake accounts to receive the withdrawn stake
* @throws RpcError
* @throws AccountDoesNotExistError if stake pool does not exist
* @throws WalletPublicKeyUnavailableError
*/
async withdrawStake(
walletAdapter: WalletAdapter,
amountDroplets: Numberu64,
confirmOptions: ConfirmOptions = TRANSACTION_SEQUENCE_DEFAULT_CONFIRM_OPTIONS,
): Promise<WithdrawStakeReturn> {
const walletPubkey = walletAdapter.publicKey;
if (!walletPubkey) throw new WalletPublicKeyUnavailableError();
const { transactionSequence, stakeAccounts } =
await this.withdrawStakeTransactions(walletPubkey, amountDroplets);
const transactionSignatures = await this.signAndSend(
walletAdapter,
transactionSequence,
confirmOptions,
);
return {
transactionSignatures,
stakeAccounts,
};
}
/**
* Creates a set of transactions and signer keypairs for withdrawing stake from the Socean stake pool,
* and the new stake accounts to receive the withdrawn stake
* Each inner `TransactionWithSigners` array of `transactionSequence` must be executed and confirmed
* before going to the next one.
* This is a lower-level API for compatibility, recommend using `withdrawStake()` instead if possible.
* @param walletPubkey the SOL wallet to withdraw stake to. scnSOL is deducted from this wallet's associated token account.
* @param amountDroplets amount of scnSOL to withdraw in droplets (1 scnSOL = 10^9 droplets)
* @returns `{transactionSequence, stakeAccounts}`, where
* `transactionSequence` is the `TransactionSequence` that needs to be sent in order, and
* `stakeAccounts` is the array of `Keypair`s for the newly created stake accounts to receive the withdrawn stake
* @throws RpcError
* @throws AccountDoesNotExistError if stake pool or validator list does not exist
* @throws WithdrawalUnserviceableError if a suitable withdraw procedure is not found
*/
// NOTE: amountDroplets is in type Numberu64 to enforce it to be in the unit of droplets (lamports)
async withdrawStakeTransactions(
walletPubkey: PublicKey,
amountDroplets: Numberu64,
): Promise<WithdrawStakeTransactionsReturn> {
const stakePool = await this.getStakePoolAccount();
// get ValidatorListAccount
const validatorListAcc = await this.getValidatorListAccount(
stakePool.account.data.validatorList,
);
// calculate the amounts to withdraw from for each validator
const validatorWithdrawalReceipts = await calcWithdrawals(
amountDroplets,
stakePool,
validatorListAcc.account.data,
);
const [transactions, stakeAccounts] = await getWithdrawStakeTransactions(
this.config.connection,
walletPubkey,
this.config.stakePoolProgramId,
stakePool,
validatorListAcc,
validatorWithdrawalReceipts,
);
const res = {
transactionSequence: [transactions],
stakeAccounts,
};
const currEpoch = await this.getCurrentEpoch();
if (stakePool.account.data.lastUpdateEpoch.lt(new BN(currEpoch))) {
const updateTxSeq = await this.updateTransactionSequence(
stakePool,
validatorListAcc,
);
res.transactionSequence.unshift(...updateTxSeq);
}
return res;
}
private async signAndSend(
walletAdapter: WalletAdapter,
transactionSequence: TransactionSequence,
confirmOptions: ConfirmOptions,
): Promise<TransactionSequenceSignatures> {
return signAndSendTransactionSequence(
walletAdapter,
transactionSequence,
this.config.connection,
confirmOptions,
);
}
/**
* Creates the `TransactionSequence` required to perform the full update
*/
private async updateTransactionSequence(
stakePool: StakePoolAccount,
validatorListAcc: ValidatorListAccount,
): Promise<TransactionSequence> {
const { stakePoolProgramId, stakePoolAccountPubkey } = this.config;
const withdrawAuthority = await getWithdrawAuthority(
stakePoolProgramId,
stakePoolAccountPubkey,
);
const updateValidatorListBalance =
await this.updateValidatorListBalanceTransactions(
stakePool,
validatorListAcc,
withdrawAuthority,
);
const {
account: {
data: { reserveStake, managerFeeAccount, poolMint, tokenProgramId },
},
} = stakePool;
const finalTx = new Transaction();
finalTx.add(
updateStakePoolBalanceInstruction(
stakePoolProgramId,
stakePoolAccountPubkey,
withdrawAuthority,
validatorListAcc.publicKey,
reserveStake,
managerFeeAccount,
poolMint,
tokenProgramId,
),
);
finalTx.add(
cleanupRemovedValidatorsInstruction(
stakePoolProgramId,
stakePoolAccountPubkey,
validatorListAcc.publicKey,
),
);
const finalTxWithSigners = {
tx: finalTx,
signers: [],
};
return [updateValidatorListBalance, [finalTxWithSigners]].filter(
(arr) => arr.length > 0,
);
}
/**
* Creates the list of transactions to completely update the validator list
* @param stakePool
* @param validatorListAcc
* @param withdrawAuthority
*/
private async updateValidatorListBalanceTransactions(
stakePool: StakePoolAccount,
validatorListAcc: ValidatorListAccount,
withdrawAuthority: PublicKey,
): Promise<TransactionWithSigners[]> {
// Based on transaction size limits
const MAX_VALIDATORS_TO_UPDATE = 5;
const currentEpoch = new BN(await this.getCurrentEpoch());
const { validators } = validatorListAcc.account.data;
const voteAccounts = validators.map(
(validator) => validator.voteAccountAddress,
);
const res: TransactionWithSigners[] = [];
let startIndex = 0;
do {
const remaining = validators.slice(startIndex);
const firstNonUpdated = remaining.findIndex((validator) =>
validator.lastUpdateEpoch.lt(currentEpoch),
);
if (firstNonUpdated === -1) {
break;
}
startIndex += firstNonUpdated;
const endIndex = startIndex + MAX_VALIDATORS_TO_UPDATE;
const chunk = voteAccounts.slice(startIndex, endIndex);
// eslint-disable-next-line no-await-in-loop
const validatorsAllStakeAccounts = await Promise.all(
chunk.map((voteAccount) =>
this.getValidatorAllStakeAccounts(voteAccount),
),
);
res.push({
tx: updateValidatorListBalanceTransaction(
this.config.stakePoolProgramId,
this.config.stakePoolAccountPubkey,
withdrawAuthority,
validatorListAcc.publicKey,
stakePool.account.data.reserveStake,
validatorsAllStakeAccounts,
startIndex,
false, // TODO: no_merge?
),
signers: [],
});
startIndex = endIndex;
} while (startIndex < voteAccounts.length);
return res;
}
private async getCurrentEpoch(): Promise<number> {
const { epoch } = await tryRpc(this.config.connection.getEpochInfo());
return epoch;
}
/**
* Retrieves and deserializes a StakePool account
* @returns The deserialized StakePoolAccount
* @throws RpcError
* @throws AccountDoesNotExistError if stake pool does not exist
*/
async getStakePoolAccount(): Promise<StakePoolAccount> {
const account = await tryRpc(
this.config.connection.getAccountInfo(this.config.stakePoolAccountPubkey),
);
if (account === null)
throw new AccountDoesNotExistError(this.config.stakePoolAccountPubkey);
return getStakePoolFromAccountInfo(
this.config.stakePoolAccountPubkey,
account,
);
}
/**
* Retrieves and deserializes a ValidatorList account
* @returns The deserialized ValidatorListAccount
* @throws RpcError
* @throws AccountDoesNotExistError if validator list does not exist
*/
async getValidatorListAccount(
validatorListPubkey: PublicKey,
): Promise<ValidatorListAccount> {
const account = await tryRpc(
this.config.connection.getAccountInfo(validatorListPubkey),
);
if (account === null)
throw new AccountDoesNotExistError(validatorListPubkey);
return getValidatorListFromAccountInfo(validatorListPubkey, account);
}
/**
* Returns the validator stake account given the validator's vote account
* @param voteAccount
*/
async validatorStakeAccount(voteAccount: PublicKey): Promise<PublicKey> {
return getValidatorStakeAccount(
this.config.stakePoolProgramId,
this.config.stakePoolAccountPubkey,
voteAccount,
);
}
/**
* Returns the transient stake account given the validator's vote account
* @param voteAccount
*/
async transientStakeAccount(voteAccount: PublicKey): Promise<PublicKey> {
return getValidatorTransientStakeAccount(
this.config.stakePoolProgramId,
this.config.stakePoolAccountPubkey,
voteAccount,
);
}
/**
* Returns both the validator stake account and transient stake account
* given the validator's vote account
*/
async getValidatorAllStakeAccounts(
voteAccount: PublicKey,
): Promise<ValidatorAllStakeAccounts> {
const main = await this.validatorStakeAccount(voteAccount);
const transient = await this.transientStakeAccount(voteAccount);
return {
main,
transient,
};
}
/**
* Register an onAccountChange websocket listener for the stake pool account
* and returns the websocket clientSubscriptionId
* To remove, call this.config.connection.removeAccountChangeListener(clientSubscriptionId)
* @param callback
* @param commitment
* @returns clientSubscriptionId
*/
onStakePoolChange(
callback: (stakePoolAccount: StakePoolAccount, context: Context) => void,
commitment?: Commitment,
): number {
return this.config.connection.onAccountChange(
this.config.stakePoolAccountPubkey,
(account, context) => {
const stakePoolAccount = getStakePoolFromAccountInfo(
this.config.stakePoolAccountPubkey,
account,
);
callback(stakePoolAccount, context);
},
commitment,
);
}
/**
* Register an onAccountChange websocket listener for the validator list account
* and returns the websocket clientSubscriptionId
* To remove, call this.config.connection.removeAccountChangeListener(clientSubscriptionId)
* @param callback
* @param commitment
* @returns clientSubscriptionId
* @throws RpcError
* @throws AccountDoesNotExistError if stake pool does not exist
*/
async onValidatorListChange(
callback: (
validatorListAccount: ValidatorListAccount,
context: Context,
) => void,
commitment?: Commitment,
): Promise<number> {
const {
account: {
data: { validatorList },
},
} = await this.getStakePoolAccount();
return this.config.connection.onAccountChange(
validatorList,
(account, context) => {
const validatorListAccount = getValidatorListFromAccountInfo(
validatorList,
account,
);
callback(validatorListAccount, context);
},
commitment,
);
}
}
type WithdrawStakeTransactionsReturn = {
transactionSequence: TransactionSequence;
stakeAccounts: Keypair[];
};
type WithdrawStakeReturn = {
transactionSignatures: TransactionSequenceSignatures;
stakeAccounts: Keypair[];
};