-
Notifications
You must be signed in to change notification settings - Fork 302
Expand file tree
/
Copy pathinstructionParamsFactory.ts
More file actions
1278 lines (1187 loc) · 48.7 KB
/
instructionParamsFactory.ts
File metadata and controls
1278 lines (1187 loc) · 48.7 KB
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
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
DecodedTransferCheckedInstruction,
decodeTransferCheckedInstruction,
DecodedBurnInstruction,
decodeBurnInstruction,
DecodedMintToInstruction,
decodeMintToInstruction,
TOKEN_2022_PROGRAM_ID,
decodeApproveInstruction,
} from '@solana/spl-token';
import {
AllocateParams,
AssignParams,
CreateAccountParams,
DeactivateStakeParams,
DecodedTransferInstruction,
DelegateStakeParams,
InitializeStakeParams,
SplitStakeParams,
StakeInstruction,
StakeProgram,
SystemInstruction,
TransactionInstruction,
ComputeBudgetInstruction,
} from '@solana/web3.js';
import { SolStakingTypeEnum } from '@bitgo/public-types';
import { NotSupported, TransactionType } from '@bitgo/sdk-core';
import { coins, SolCoin } from '@bitgo/statics';
import assert from 'assert';
import { InstructionBuilderTypes, ValidInstructionTypesEnum, walletInitInstructionIndexes } from './constants';
import {
AtaClose,
AtaInit,
Burn,
InstructionParams,
Memo,
MintTo,
Nonce,
StakingActivate,
StakingAuthorize,
StakingDeactivate,
StakingDelegate,
StakingWithdraw,
TokenTransfer,
Transfer,
WalletInit,
SetComputeUnitLimit,
SetPriorityFee,
CustomInstruction,
Approve,
} from './iface';
import { getInstructionType } from './utils';
import { DepositSolParams, WithdrawStakeParams } from '@solana/spl-stake-pool';
import { decodeDepositSol, decodeWithdrawStake } from './jitoStakePoolOperations';
/**
* Construct instructions params from Solana instructions
*
* @param {TransactionType} type - the transaction type
* @param {TransactionInstruction[]} instructions - solana instructions
* @returns {InstructionParams[]} An array containing instruction params
*/
export function instructionParamsFactory(
type: TransactionType,
instructions: TransactionInstruction[],
coinName?: string,
instructionMetadata?: InstructionParams[],
_useTokenAddressTokenName?: boolean
): InstructionParams[] {
switch (type) {
case TransactionType.WalletInitialization:
return parseWalletInitInstructions(instructions);
case TransactionType.Send:
return parseSendInstructions(instructions, instructionMetadata, _useTokenAddressTokenName);
case TransactionType.StakingActivate:
return parseStakingActivateInstructions(instructions);
case TransactionType.StakingDeactivate:
return parseStakingDeactivateInstructions(instructions, coinName);
case TransactionType.StakingWithdraw:
return parseStakingWithdrawInstructions(instructions);
case TransactionType.AssociatedTokenAccountInitialization:
return parseAtaInitInstructions(instructions, instructionMetadata, _useTokenAddressTokenName);
case TransactionType.CloseAssociatedTokenAccount:
return parseAtaCloseInstructions(instructions);
case TransactionType.StakingAuthorize:
return parseStakingAuthorizeInstructions(instructions);
case TransactionType.StakingAuthorizeRaw:
return parseStakingAuthorizeRawInstructions(instructions);
case TransactionType.StakingDelegate:
return parseStakingDelegateInstructions(instructions);
case TransactionType.CustomTx:
return parseCustomInstructions(instructions, instructionMetadata);
default:
throw new NotSupported('Invalid transaction, transaction type not supported: ' + type);
}
}
/**
* Parses Solana instructions to Wallet initialization tx instructions params
*
* @param {TransactionInstruction[]} instructions - containing create and initialize nonce solana instructions
* @returns {InstructionParams[]} An array containing instruction params for Wallet initialization tx
*/
function parseWalletInitInstructions(instructions: TransactionInstruction[]): Array<WalletInit | Memo> {
const instructionData: Array<WalletInit | Memo> = [];
const createInstruction = SystemInstruction.decodeCreateAccount(instructions[walletInitInstructionIndexes.Create]);
const nonceInitInstruction = SystemInstruction.decodeNonceInitialize(
instructions[walletInitInstructionIndexes.InitializeNonceAccount]
);
const walletInit: WalletInit = {
type: InstructionBuilderTypes.CreateNonceAccount,
params: {
fromAddress: createInstruction.fromPubkey.toString(),
nonceAddress: nonceInitInstruction.noncePubkey.toString(),
authAddress: nonceInitInstruction.authorizedPubkey.toString(),
amount: createInstruction.lamports.toString(),
},
};
instructionData.push(walletInit);
const memo = getMemo(instructions, walletInitInstructionIndexes);
if (memo) {
instructionData.push(memo);
}
return instructionData;
}
/**
* Parses Solana instructions to Send tx instructions params
* Only supports Memo, Transfer and Advance Nonce Solana instructions
*
* @param {TransactionInstruction[]} instructions - an array of supported Solana instructions
* @returns {InstructionParams[]} An array containing instruction params for Send tx
*/
function parseSendInstructions(
instructions: TransactionInstruction[],
instructionMetadata?: InstructionParams[],
_useTokenAddressTokenName?: boolean
): Array<
| Nonce
| Memo
| Transfer
| TokenTransfer
| AtaInit
| AtaClose
| SetComputeUnitLimit
| SetPriorityFee
| MintTo
| Burn
| Approve
> {
const instructionData: Array<
| Nonce
| Memo
| Transfer
| TokenTransfer
| AtaInit
| AtaClose
| SetComputeUnitLimit
| SetPriorityFee
| MintTo
| Burn
| Approve
> = [];
for (const instruction of instructions) {
const type = getInstructionType(instruction);
switch (type) {
case ValidInstructionTypesEnum.Memo:
const memo: Memo = { type: InstructionBuilderTypes.Memo, params: { memo: instruction.data.toString() } };
instructionData.push(memo);
break;
case ValidInstructionTypesEnum.AdvanceNonceAccount:
const advanceNonceInstruction = SystemInstruction.decodeNonceAdvance(instruction);
const nonce: Nonce = {
type: InstructionBuilderTypes.NonceAdvance,
params: {
walletNonceAddress: advanceNonceInstruction.noncePubkey.toString(),
authWalletAddress: advanceNonceInstruction.authorizedPubkey.toString(),
},
};
instructionData.push(nonce);
break;
case ValidInstructionTypesEnum.Transfer:
const transferInstruction = SystemInstruction.decodeTransfer(instruction);
const transfer: Transfer = {
type: InstructionBuilderTypes.Transfer,
params: {
fromAddress: transferInstruction.fromPubkey.toString(),
toAddress: transferInstruction.toPubkey.toString(),
amount: transferInstruction.lamports.toString(),
},
};
instructionData.push(transfer);
break;
case ValidInstructionTypesEnum.TokenTransfer:
let tokenTransferInstruction: DecodedTransferCheckedInstruction;
if (instruction.programId.toString() !== TOKEN_2022_PROGRAM_ID.toString()) {
tokenTransferInstruction = decodeTransferCheckedInstruction(instruction);
} else {
tokenTransferInstruction = decodeTransferCheckedInstruction(instruction, TOKEN_2022_PROGRAM_ID);
}
const tokenAddress = tokenTransferInstruction.keys.mint.pubkey.toString();
const tokenName = findTokenName(tokenAddress, instructionMetadata, _useTokenAddressTokenName);
let programIDForTokenTransfer: string | undefined;
if (instruction.programId) {
programIDForTokenTransfer = instruction.programId.toString();
}
const tokenTransfer: TokenTransfer = {
type: InstructionBuilderTypes.TokenTransfer,
params: {
fromAddress: tokenTransferInstruction.keys.owner.pubkey.toString(),
toAddress: tokenTransferInstruction.keys.destination.pubkey.toString(),
amount: tokenTransferInstruction.data.amount.toString(),
tokenName,
sourceAddress: tokenTransferInstruction.keys.source.pubkey.toString(),
tokenAddress: tokenAddress,
programId: programIDForTokenTransfer,
decimalPlaces: tokenTransferInstruction.data.decimals,
},
};
instructionData.push(tokenTransfer);
break;
case ValidInstructionTypesEnum.Approve:
const programId = instruction.programId.equals(TOKEN_2022_PROGRAM_ID) ? TOKEN_2022_PROGRAM_ID : undefined;
const approveInstruction = decodeApproveInstruction(instruction, programId);
const approve: Approve = {
type: InstructionBuilderTypes.Approve,
params: {
accountAddress: approveInstruction.keys.account.toString(),
delegateAddress: approveInstruction.keys.delegate.toString(),
ownerAddress: approveInstruction.keys.owner.toString(),
amount: approveInstruction.data.amount.toString(),
programId: programId && programId.toString(),
},
};
instructionData.push(approve);
break;
case ValidInstructionTypesEnum.InitializeAssociatedTokenAccount:
const mintAddress = instruction.keys[ataInitInstructionKeysIndexes.MintAddress].pubkey.toString();
const mintTokenName = findTokenName(mintAddress, instructionMetadata, _useTokenAddressTokenName);
let programID: string | undefined;
if (instruction.programId) {
programID = instruction.programId.toString();
}
const ataInit: AtaInit = {
type: InstructionBuilderTypes.CreateAssociatedTokenAccount,
params: {
mintAddress,
ataAddress: instruction.keys[ataInitInstructionKeysIndexes.ATAAddress].pubkey.toString(),
ownerAddress: instruction.keys[ataInitInstructionKeysIndexes.OwnerAddress].pubkey.toString(),
payerAddress: instruction.keys[ataInitInstructionKeysIndexes.PayerAddress].pubkey.toString(),
tokenName: mintTokenName,
programId: programID,
},
};
instructionData.push(ataInit);
break;
case ValidInstructionTypesEnum.CloseAssociatedTokenAccount:
const accountAddress = instruction.keys[closeAtaInstructionKeysIndexes.AccountAddress].pubkey.toString();
const destinationAddress =
instruction.keys[closeAtaInstructionKeysIndexes.DestinationAddress].pubkey.toString();
const authorityAddress = instruction.keys[closeAtaInstructionKeysIndexes.AuthorityAddress].pubkey.toString();
const ataClose: AtaClose = {
type: InstructionBuilderTypes.CloseAssociatedTokenAccount,
params: {
accountAddress,
destinationAddress,
authorityAddress,
},
};
instructionData.push(ataClose);
break;
case ValidInstructionTypesEnum.SetComputeUnitLimit:
const setComputeUnitLimitParams = ComputeBudgetInstruction.decodeSetComputeUnitLimit(instruction);
const setComputeUnitLimit: SetComputeUnitLimit = {
type: InstructionBuilderTypes.SetComputeUnitLimit,
params: {
units: setComputeUnitLimitParams.units,
},
};
instructionData.push(setComputeUnitLimit);
break;
case ValidInstructionTypesEnum.SetPriorityFee:
const setComputeUnitPriceParams = ComputeBudgetInstruction.decodeSetComputeUnitPrice(instruction);
const setPriorityFee: SetPriorityFee = {
type: InstructionBuilderTypes.SetPriorityFee,
params: {
fee: setComputeUnitPriceParams.microLamports,
},
};
instructionData.push(setPriorityFee);
break;
case ValidInstructionTypesEnum.MintTo:
let mintToInstruction: DecodedMintToInstruction;
if (instruction.programId.toString() !== TOKEN_2022_PROGRAM_ID.toString()) {
mintToInstruction = decodeMintToInstruction(instruction);
} else {
mintToInstruction = decodeMintToInstruction(instruction, TOKEN_2022_PROGRAM_ID);
}
const mintAddressForMint = mintToInstruction.keys.mint.pubkey.toString();
const tokenNameForMint = findTokenName(mintAddressForMint, instructionMetadata, _useTokenAddressTokenName);
let programIDForMint: string | undefined;
if (instruction.programId) {
programIDForMint = instruction.programId.toString();
}
const mintTo: MintTo = {
type: InstructionBuilderTypes.MintTo,
params: {
mintAddress: mintAddressForMint,
destinationAddress: mintToInstruction.keys.destination.pubkey.toString(),
authorityAddress: mintToInstruction.keys.authority.pubkey.toString(),
amount: mintToInstruction.data.amount.toString(),
tokenName: tokenNameForMint,
decimalPlaces: undefined,
programId: programIDForMint,
},
};
instructionData.push(mintTo);
break;
case ValidInstructionTypesEnum.Burn:
let burnInstruction: DecodedBurnInstruction;
if (instruction.programId.toString() !== TOKEN_2022_PROGRAM_ID.toString()) {
burnInstruction = decodeBurnInstruction(instruction);
} else {
burnInstruction = decodeBurnInstruction(instruction, TOKEN_2022_PROGRAM_ID);
}
const mintAddressForBurn = burnInstruction.keys.mint.pubkey.toString();
const tokenNameForBurn = findTokenName(mintAddressForBurn, instructionMetadata, _useTokenAddressTokenName);
let programIDForBurn: string | undefined;
if (instruction.programId) {
programIDForBurn = instruction.programId.toString();
}
const burn: Burn = {
type: InstructionBuilderTypes.Burn,
params: {
mintAddress: mintAddressForBurn,
accountAddress: burnInstruction.keys.account.pubkey.toString(),
authorityAddress: burnInstruction.keys.owner.pubkey.toString(),
amount: burnInstruction.data.amount.toString(),
tokenName: tokenNameForBurn,
decimalPlaces: undefined,
programId: programIDForBurn,
},
};
instructionData.push(burn);
break;
default:
throw new NotSupported(
'Invalid transaction, instruction type not supported: ' + getInstructionType(instruction)
);
}
}
return instructionData;
}
type StakingInstructions = {
depositSol?: DepositSolParams;
create?: CreateAccountParams;
initialize?: InitializeStakeParams;
delegate?: DelegateStakeParams;
hasAtaInit?: boolean;
};
type JitoStakingInstructions = StakingInstructions & {
depositSol: NonNullable<StakingInstructions['depositSol']>;
};
function isJitoStakingInstructions(si: StakingInstructions): si is JitoStakingInstructions {
return si.depositSol !== undefined;
}
type MarinadeStakingInstructions = StakingInstructions & {
create: NonNullable<StakingInstructions['create']>;
initialize: NonNullable<StakingInstructions['initialize']>;
};
function isMarinadeStakingInstructions(si: StakingInstructions): si is MarinadeStakingInstructions {
return si.create !== undefined && si.initialize !== undefined && si.delegate === undefined;
}
type NativeStakingInstructions = StakingInstructions & {
create: NonNullable<StakingInstructions['create']>;
initialize: NonNullable<StakingInstructions['initialize']>;
delegate: NonNullable<StakingInstructions['delegate']>;
};
function isNativeStakingInstructions(si: StakingInstructions): si is NativeStakingInstructions {
return si.create !== undefined && si.initialize !== undefined && si.delegate !== undefined;
}
function getStakingTypeFromStakingInstructions(si: StakingInstructions): SolStakingTypeEnum {
const isJito = isJitoStakingInstructions(si);
const isMarinade = isMarinadeStakingInstructions(si);
const isNative = isNativeStakingInstructions(si);
assert([isJito, isMarinade, isNative].filter((x) => x).length === 1, 'StakingType is ambiguous');
if (isJito) return SolStakingTypeEnum.JITO;
if (isMarinade) return SolStakingTypeEnum.MARINADE;
if (isNative) return SolStakingTypeEnum.NATIVE;
assert(false, 'No StakingType found');
}
/**
* Parses Solana instructions to create staking tx and delegate tx instructions params
* Only supports Nonce, StakingActivate and Memo Solana instructions
*
* @param {TransactionInstruction[]} instructions - an array of supported Solana instructions
* @returns {InstructionParams[]} An array containing instruction params for staking activate tx
*/
function parseStakingActivateInstructions(
instructions: TransactionInstruction[]
): Array<Nonce | StakingActivate | Memo | AtaInit> {
const instructionData: Array<Nonce | StakingActivate | Memo | AtaInit> = [];
const stakingInstructions = {} as StakingInstructions;
for (const instruction of instructions) {
const type = getInstructionType(instruction);
switch (type) {
case ValidInstructionTypesEnum.AdvanceNonceAccount:
const advanceNonceInstruction = SystemInstruction.decodeNonceAdvance(instruction);
const nonce: Nonce = {
type: InstructionBuilderTypes.NonceAdvance,
params: {
walletNonceAddress: advanceNonceInstruction.noncePubkey.toString(),
authWalletAddress: advanceNonceInstruction.authorizedPubkey.toString(),
},
};
instructionData.push(nonce);
break;
case ValidInstructionTypesEnum.Memo:
const memo: Memo = { type: InstructionBuilderTypes.Memo, params: { memo: instruction.data.toString() } };
instructionData.push(memo);
break;
case ValidInstructionTypesEnum.Create:
stakingInstructions.create = SystemInstruction.decodeCreateAccount(instruction);
break;
case ValidInstructionTypesEnum.StakingInitialize:
stakingInstructions.initialize = StakeInstruction.decodeInitialize(instruction);
break;
case ValidInstructionTypesEnum.StakingDelegate:
stakingInstructions.delegate = StakeInstruction.decodeDelegate(instruction);
break;
case ValidInstructionTypesEnum.DepositSol:
stakingInstructions.depositSol = decodeDepositSol(instruction);
break;
case ValidInstructionTypesEnum.InitializeAssociatedTokenAccount:
stakingInstructions.hasAtaInit = true;
instructionData.push({
type: InstructionBuilderTypes.CreateAssociatedTokenAccount,
params: {
mintAddress: instruction.keys[ataInitInstructionKeysIndexes.MintAddress].pubkey.toString(),
ataAddress: instruction.keys[ataInitInstructionKeysIndexes.ATAAddress].pubkey.toString(),
ownerAddress: instruction.keys[ataInitInstructionKeysIndexes.OwnerAddress].pubkey.toString(),
payerAddress: instruction.keys[ataInitInstructionKeysIndexes.PayerAddress].pubkey.toString(),
tokenName: findTokenName(instruction.keys[ataInitInstructionKeysIndexes.MintAddress].pubkey.toString()),
},
});
break;
}
}
validateStakingInstructions(stakingInstructions);
const stakingType = getStakingTypeFromStakingInstructions(stakingInstructions);
let stakingActivate: StakingActivate | undefined;
switch (stakingType) {
case SolStakingTypeEnum.JITO: {
assert(isJitoStakingInstructions(stakingInstructions));
const { depositSol, hasAtaInit } = stakingInstructions;
stakingActivate = {
type: InstructionBuilderTypes.StakingActivate,
params: {
stakingType,
fromAddress: depositSol.fundingAccount.toString(),
stakingAddress: depositSol.stakePool.toString(),
amount: depositSol.lamports.toString(),
validator: depositSol.stakePool.toString(),
extraParams: {
stakePoolData: {
managerFeeAccount: depositSol.managerFeeAccount.toString(),
poolMint: depositSol.poolMint.toString(),
reserveStake: depositSol.reserveStake.toString(),
},
createAssociatedTokenAccount: !!hasAtaInit,
},
},
};
break;
}
case SolStakingTypeEnum.MARINADE: {
assert(isMarinadeStakingInstructions(stakingInstructions));
const { create, initialize } = stakingInstructions;
stakingActivate = {
type: InstructionBuilderTypes.StakingActivate,
params: {
stakingType,
fromAddress: create.fromPubkey.toString(),
stakingAddress: initialize.stakePubkey.toString(),
amount: create.lamports.toString(),
validator: initialize.authorized.staker.toString(),
},
};
break;
}
case SolStakingTypeEnum.NATIVE: {
assert(isNativeStakingInstructions(stakingInstructions));
const { create, initialize, delegate } = stakingInstructions;
stakingActivate = {
type: InstructionBuilderTypes.StakingActivate,
params: {
stakingType,
fromAddress: create.fromPubkey.toString(),
stakingAddress: initialize.stakePubkey.toString(),
amount: create.lamports.toString(),
validator: delegate.votePubkey.toString(),
},
};
break;
}
default: {
const unreachable: never = stakingType;
throw new Error(`Unknown staking type ${unreachable}`);
}
}
instructionData.push(stakingActivate);
return instructionData;
}
/**
* Parses Solana instructions to create delegate tx
* Only supports Nonce, StakingDelegate
*
* @param {TransactionInstruction[]} instructions - an array of supported Solana instructions
* @returns {InstructionParams[]} An array containing instruction params for staking delegate tx
*/
function parseStakingDelegateInstructions(instructions: TransactionInstruction[]): Array<Nonce | StakingDelegate> {
const instructionData: Array<Nonce | StakingDelegate> = [];
for (const instruction of instructions) {
const type = getInstructionType(instruction);
switch (type) {
case ValidInstructionTypesEnum.AdvanceNonceAccount:
const advanceNonceInstruction = SystemInstruction.decodeNonceAdvance(instruction);
const nonce: Nonce = {
type: InstructionBuilderTypes.NonceAdvance,
params: {
walletNonceAddress: advanceNonceInstruction.noncePubkey.toString(),
authWalletAddress: advanceNonceInstruction.authorizedPubkey.toString(),
},
};
instructionData.push(nonce);
break;
case ValidInstructionTypesEnum.StakingDelegate:
const stakingDelegateParams = StakeInstruction.decodeDelegate(instruction);
const stakingDelegate: StakingDelegate = {
type: InstructionBuilderTypes.StakingDelegate,
params: {
fromAddress: stakingDelegateParams.authorizedPubkey.toString() || '',
stakingAddress: stakingDelegateParams.stakePubkey.toString() || '',
validator: stakingDelegateParams.votePubkey.toString() || '',
},
};
instructionData.push(stakingDelegate);
break;
}
}
return instructionData;
}
function validateStakingInstructions(stakingInstructions: StakingInstructions) {
if (stakingInstructions.delegate === undefined && stakingInstructions.depositSol !== undefined) {
return;
}
if (!stakingInstructions.create) {
throw new NotSupported('Invalid staking activate transaction, missing create stake account instruction');
}
if (!stakingInstructions.delegate && !stakingInstructions.initialize) {
throw new NotSupported(
'Invalid staking activate transaction, missing initialize stake account/delegate instruction'
);
}
}
type UnstakingInstructions = {
allocate?: AllocateParams;
assign?: AssignParams;
split?: SplitStakeParams;
deactivate?: DeactivateStakeParams;
transfer?: DecodedTransferInstruction;
withdrawStake?: WithdrawStakeParams;
};
type JitoUnstakingInstructions = UnstakingInstructions & {
withdrawStake: NonNullable<UnstakingInstructions['withdrawStake']>;
};
function isJitoUnstakingInstructions(ui: UnstakingInstructions): ui is JitoUnstakingInstructions {
return ui.withdrawStake !== undefined && ui.deactivate !== undefined;
}
type MarinadeUnstakingInstructions = UnstakingInstructions & {
transfer: NonNullable<UnstakingInstructions['transfer']>;
};
function isMarinadeUnstakingInstructions(ui: UnstakingInstructions): ui is MarinadeUnstakingInstructions {
return ui.transfer !== undefined && ui.deactivate === undefined;
}
type NativeUnstakingInstructions = UnstakingInstructions & {
deactivate: NonNullable<UnstakingInstructions['deactivate']>;
split: UnstakingInstructions['split'];
};
function isNativeUnstakingInstructions(ui: UnstakingInstructions): ui is NativeUnstakingInstructions {
return ui.withdrawStake === undefined && ui.deactivate !== undefined;
}
function getStakingTypeFromUnstakingInstructions(ui: UnstakingInstructions): SolStakingTypeEnum {
const isJito = isJitoUnstakingInstructions(ui);
const isMarinade = isMarinadeUnstakingInstructions(ui);
const isNative = isNativeUnstakingInstructions(ui);
assert([isJito, isMarinade, isNative].filter((x) => x).length === 1, 'StakingType is ambiguous');
if (isJito) return SolStakingTypeEnum.JITO;
if (isMarinade) return SolStakingTypeEnum.MARINADE;
if (isNative) return SolStakingTypeEnum.NATIVE;
assert(false, 'No StakingType found');
}
/**
* Parses Solana instructions to create deactivate stake tx instructions params. Supports full stake
* account deactivation and partial stake account deactivation.
*
* When partially deactivating a stake account this method expects the following instructions: Allocate,
* to allocate a new staking account, Assign, to assign the newly created staking account to the
* Stake Program, Split, to split the current stake account, and StakingDeactivate to deactivate the
* newly created stake account.
*
* Supports Nonce, StakingDeactivate, Memo, Allocate, Assign, and Split Solana instructions.
*
* @param {TransactionInstruction[]} instructions - an array of supported Solana instructions
* @returns {InstructionParams[]} An array containing instruction params for staking deactivate tx
*/
function parseStakingDeactivateInstructions(
instructions: TransactionInstruction[],
coinName?: string
): Array<Nonce | StakingDeactivate | Memo> {
const instructionData: Array<Nonce | StakingDeactivate | Memo> = [];
const unstakingInstructions: UnstakingInstructions[] = [];
for (const instruction of instructions) {
const type = getInstructionType(instruction);
switch (type) {
case ValidInstructionTypesEnum.AdvanceNonceAccount:
const advanceNonceInstruction = SystemInstruction.decodeNonceAdvance(instruction);
const nonce: Nonce = {
type: InstructionBuilderTypes.NonceAdvance,
params: {
walletNonceAddress: advanceNonceInstruction.noncePubkey.toString(),
authWalletAddress: advanceNonceInstruction.authorizedPubkey.toString(),
},
};
instructionData.push(nonce);
break;
case ValidInstructionTypesEnum.Memo:
const memo: Memo = {
type: InstructionBuilderTypes.Memo,
params: { memo: instruction.data.toString() },
};
instructionData.push(memo);
break;
case ValidInstructionTypesEnum.Allocate:
if (
unstakingInstructions.length > 0 &&
unstakingInstructions[unstakingInstructions.length - 1].allocate === undefined
) {
unstakingInstructions[unstakingInstructions.length - 1].allocate =
SystemInstruction.decodeAllocate(instruction);
} else {
unstakingInstructions.push({
allocate: SystemInstruction.decodeAllocate(instruction),
});
}
break;
case ValidInstructionTypesEnum.Assign:
if (
unstakingInstructions.length > 0 &&
unstakingInstructions[unstakingInstructions.length - 1].assign === undefined
) {
unstakingInstructions[unstakingInstructions.length - 1].assign = SystemInstruction.decodeAssign(instruction);
} else {
unstakingInstructions.push({
assign: SystemInstruction.decodeAssign(instruction),
});
}
break;
case ValidInstructionTypesEnum.Split:
if (
unstakingInstructions.length > 0 &&
unstakingInstructions[unstakingInstructions.length - 1].split === undefined
) {
unstakingInstructions[unstakingInstructions.length - 1].split = StakeInstruction.decodeSplit(instruction);
} else {
unstakingInstructions.push({
split: StakeInstruction.decodeSplit(instruction),
});
}
break;
case ValidInstructionTypesEnum.StakingDeactivate:
if (
unstakingInstructions.length > 0 &&
unstakingInstructions[unstakingInstructions.length - 1].deactivate === undefined
) {
unstakingInstructions[unstakingInstructions.length - 1].deactivate =
StakeInstruction.decodeDeactivate(instruction);
} else {
unstakingInstructions.push({
deactivate: StakeInstruction.decodeDeactivate(instruction),
});
}
break;
case ValidInstructionTypesEnum.Transfer:
if (
unstakingInstructions.length > 0 &&
unstakingInstructions[unstakingInstructions.length - 1].transfer === undefined
) {
unstakingInstructions[unstakingInstructions.length - 1].transfer =
SystemInstruction.decodeTransfer(instruction);
} else {
unstakingInstructions.push({
transfer: SystemInstruction.decodeTransfer(instruction),
});
}
break;
case ValidInstructionTypesEnum.WithdrawStake:
if (
unstakingInstructions.length > 0 &&
unstakingInstructions[unstakingInstructions.length - 1].withdrawStake === undefined
) {
unstakingInstructions[unstakingInstructions.length - 1].withdrawStake = decodeWithdrawStake(instruction);
} else {
unstakingInstructions.push({
withdrawStake: decodeWithdrawStake(instruction),
});
}
break;
}
}
for (const unstakingInstruction of unstakingInstructions) {
validateUnstakingInstructions(unstakingInstruction);
const stakingType = getStakingTypeFromUnstakingInstructions(unstakingInstruction);
let stakingDeactivate: StakingDeactivate | undefined;
switch (stakingType) {
case SolStakingTypeEnum.JITO: {
assert(isJitoUnstakingInstructions(unstakingInstruction));
const { withdrawStake } = unstakingInstruction;
stakingDeactivate = {
type: InstructionBuilderTypes.StakingDeactivate,
params: {
stakingType,
fromAddress: withdrawStake.destinationStakeAuthority.toString(),
stakingAddress: withdrawStake.stakePool.toString(),
amount: withdrawStake.poolTokens.toString(),
unstakingAddress: withdrawStake.destinationStake.toString(),
extraParams: {
stakePoolData: {
managerFeeAccount: withdrawStake.managerFeeAccount.toString(),
poolMint: withdrawStake.poolMint.toString(),
validatorListAccount: withdrawStake.validatorList.toString(),
},
validatorAddress: withdrawStake.validatorStake.toString(),
transferAuthorityAddress: withdrawStake.sourceTransferAuthority.toString(),
},
},
};
break;
}
case SolStakingTypeEnum.MARINADE: {
assert(isMarinadeUnstakingInstructions(unstakingInstruction));
const { transfer } = unstakingInstruction;
stakingDeactivate = {
type: InstructionBuilderTypes.StakingDeactivate,
params: {
stakingType,
fromAddress: '',
stakingAddress: '',
recipients: [
{
address: transfer.toPubkey.toString() || '',
amount: transfer.lamports.toString() || '',
},
],
},
};
break;
}
case SolStakingTypeEnum.NATIVE: {
assert(isNativeUnstakingInstructions(unstakingInstruction));
const { deactivate, split } = unstakingInstruction;
stakingDeactivate = {
type: InstructionBuilderTypes.StakingDeactivate,
params: {
stakingType,
fromAddress: deactivate.authorizedPubkey.toString() || '',
stakingAddress: split?.stakePubkey.toString() || deactivate.stakePubkey.toString(),
amount: split?.lamports.toString(),
unstakingAddress: split?.splitStakePubkey.toString(),
},
};
break;
}
default: {
const unreachable: never = stakingType;
throw new Error(`Unknown staking type ${unreachable}`);
}
}
instructionData.push(stakingDeactivate);
}
return instructionData;
}
function validateUnstakingInstructions(unstakingInstructions: UnstakingInstructions) {
// Cases where exactly one field should be present
const unstakingInstructionsKeys: (keyof UnstakingInstructions)[] = [
'allocate',
'assign',
'split',
'deactivate',
'transfer',
] as const;
if (unstakingInstructionsKeys.every((k) => !!unstakingInstructions[k] === (k === 'transfer'))) {
return;
}
if (unstakingInstructionsKeys.every((k) => !!unstakingInstructions[k] === (k === 'withdrawStake'))) {
return;
}
if (unstakingInstructionsKeys.every((k) => !!unstakingInstructions[k] === (k === 'deactivate'))) {
return;
}
// Cases where deactivate field must be present with another field
if (!unstakingInstructions.deactivate) {
throw new NotSupported('Invalid deactivate stake transaction, missing deactivate stake account instruction');
}
// This is a stake pool instruction, not a partial unstake
if (unstakingInstructions.withdrawStake) {
return;
}
if (!unstakingInstructions.allocate) {
throw new NotSupported(
'Invalid partial deactivate stake transaction, missing allocate unstake account instruction'
);
} else if (!unstakingInstructions.assign) {
throw new NotSupported('Invalid partial deactivate stake transaction, missing assign unstake account instruction');
} else if (!unstakingInstructions.split) {
throw new NotSupported('Invalid partial deactivate stake transaction, missing split stake account instruction');
} else if (
unstakingInstructions.allocate.accountPubkey.toString() !== unstakingInstructions.assign.accountPubkey.toString()
) {
throw new NotSupported(
'Invalid partial deactivate stake transaction, must allocate and assign the same public key'
);
} else if (unstakingInstructions.allocate.space !== StakeProgram.space) {
throw new NotSupported(
`Invalid partial deactivate stake transaction, unstaking account must allocate ${StakeProgram.space} bytes`
);
} else if (unstakingInstructions.assign.programId.toString() !== StakeProgram.programId.toString()) {
throw new NotSupported(
'Invalid partial deactivate stake transaction, the unstake account must be assigned to the Stake Program'
);
} else if (
unstakingInstructions.allocate.accountPubkey.toString() !== unstakingInstructions.split.splitStakePubkey.toString()
) {
throw new NotSupported('Invalid partial deactivate stake transaction, must allocate the unstaking account');
} else if (
unstakingInstructions.split.stakePubkey.toString() === unstakingInstructions.split.splitStakePubkey.toString()
) {
throw new NotSupported(
'Invalid partial deactivate stake transaction, the unstaking account must be different from the Stake Account'
);
} else if (!unstakingInstructions.transfer) {
throw new NotSupported(
'Invalid partial deactivate stake transaction, missing funding of unstake address instruction'
);
}
}
/**
* Parses Solana instructions to create staking withdraw tx instructions params
* Only supports Nonce, StakingWithdraw, and Memo Solana instructions
*
* @param {TransactionInstruction[]} instructions - an array of supported Solana instructions
* @returns {InstructionParams[]} An array containing instruction params for staking withdraw tx
*/
function parseStakingWithdrawInstructions(
instructions: TransactionInstruction[]
): Array<Nonce | StakingWithdraw | Memo> {
const instructionData: Array<Nonce | StakingWithdraw | Memo> = [];
for (const instruction of instructions) {
const type = getInstructionType(instruction);
switch (type) {
case ValidInstructionTypesEnum.AdvanceNonceAccount:
const advanceNonceInstruction = SystemInstruction.decodeNonceAdvance(instruction);
const nonce: Nonce = {
type: InstructionBuilderTypes.NonceAdvance,
params: {
walletNonceAddress: advanceNonceInstruction.noncePubkey.toString(),
authWalletAddress: advanceNonceInstruction.authorizedPubkey.toString(),
},
};
instructionData.push(nonce);
break;
case ValidInstructionTypesEnum.Memo:
const memo: Memo = {
type: InstructionBuilderTypes.Memo,
params: { memo: instruction.data.toString() },
};
instructionData.push(memo);
break;
case ValidInstructionTypesEnum.StakingWithdraw:
const withdrawInstruction = StakeInstruction.decodeWithdraw(instruction);
const stakingWithdraw: StakingWithdraw = {
type: InstructionBuilderTypes.StakingWithdraw,
params: {
fromAddress: withdrawInstruction.authorizedPubkey.toString(),
stakingAddress: withdrawInstruction.stakePubkey.toString(),
amount: withdrawInstruction.lamports.toString(),
},
};
instructionData.push(stakingWithdraw);
break;
}
}
return instructionData;
}
/**
* Get the memo object from instructions if it exists
*
* @param {TransactionInstruction[]} instructions - the array of supported Solana instructions to be parsed
* @param {Record<string, number>} instructionIndexes - the instructions indexes of the current transaction
* @returns {Memo | undefined} - memo object or undefined
*/
function getMemo(instructions: TransactionInstruction[], instructionIndexes: Record<string, number>): Memo | undefined {
const instructionsLength = Object.keys(instructionIndexes).length;
if (instructions.length === instructionsLength && instructions[instructionIndexes.Memo]) {
return {
type: InstructionBuilderTypes.Memo,
params: { memo: instructions[instructionIndexes.Memo].data.toString() },
};
}
}
const ataInitInstructionKeysIndexes = {
PayerAddress: 0,
ATAAddress: 1,
OwnerAddress: 2,
MintAddress: 3,
};
const closeAtaInstructionKeysIndexes = {
AccountAddress: 0,
DestinationAddress: 1,
AuthorityAddress: 2,
};