-
Notifications
You must be signed in to change notification settings - Fork 302
Expand file tree
/
Copy pathsol.ts
More file actions
1771 lines (1539 loc) · 59.5 KB
/
sol.ts
File metadata and controls
1771 lines (1539 loc) · 59.5 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
/**
* @prettier
*/
import { TOKEN_2022_PROGRAM_ID, TOKEN_PROGRAM_ID } from '@solana/spl-token';
import BigNumber from 'bignumber.js';
import * as base58 from 'bs58';
import * as _ from 'lodash';
import * as request from 'superagent';
import { logger } from '@bitgo/logger';
import {
AuditDecryptedKeyParams,
BaseBroadcastTransactionOptions,
BaseBroadcastTransactionResult,
BaseCoin,
ParseTransactionOptions as BaseParseTransactionOptions,
BaseTransaction,
TransactionPrebuild as BaseTransactionPrebuild,
BitGoBase,
EDDSAMethods,
EDDSAMethodTypes,
Environments,
ITokenEnablement,
KeyPair,
Memo,
MPCAlgorithm,
MPCConsolidationRecoveryOptions,
MPCRecoveryOptions,
MPCSweepRecoveryOptions,
MPCSweepTxs,
MPCTx,
MPCTxs,
MPCUnsignedTx,
MultisigType,
multisigTypes,
OvcInput,
OvcOutput,
ParsedTransaction,
PopulatedIntent,
PrebuildTransactionWithIntentOptions,
PresignTransactionOptions,
PublicKey,
RecoveryTxRequest,
SignedTransaction,
SignTransactionOptions,
SolVersionedTransactionData,
TokenEnablement,
TokenEnablementConfig,
TransactionExplanation,
TransactionParams,
TransactionRecipient,
VerifyTransactionOptions,
TssVerifyAddressOptions,
verifyEddsaTssWalletAddress,
UnexpectedAddressError,
} from '@bitgo/sdk-core';
import { auditEddsaPrivateKey, getDerivationPath } from '@bitgo/sdk-lib-mpc';
import { BaseNetwork, CoinFamily, coins, SolCoin, BaseCoin as StaticsBaseCoin } from '@bitgo/statics';
import {
KeyPair as SolKeyPair,
Transaction,
TransactionBuilder,
TransactionBuilderFactory,
explainSolTransaction,
} from './lib';
import { TransactionExplanation as SolLibTransactionExplanation } from './lib/iface';
import {
getAssociatedTokenAccountAddress,
getSolTokenFromAddress,
getSolTokenFromTokenName,
isValidAddress,
isValidPrivateKey,
isValidPublicKey,
validateRawTransaction,
} from './lib/utils';
export const DEFAULT_SCAN_FACTOR = 20; // default number of receive addresses to scan for funds
export interface TransactionFee {
fee: string;
}
export type SolTransactionExplanation = TransactionExplanation;
export interface ExplainTransactionOptions {
txBase64: string;
feeInfo: TransactionFee;
tokenAccountRentExemptAmount?: string;
coinName?: string;
}
export interface TxInfo {
recipients: TransactionRecipient[];
from: string;
txid: string;
}
export interface SolSignTransactionOptions extends SignTransactionOptions {
txPrebuild: TransactionPrebuild;
prv: string | string[];
pubKeys?: string[];
}
export interface TransactionPrebuild extends BaseTransactionPrebuild {
txBase64: string;
txInfo: TxInfo;
source: string;
}
export interface SolVerifyTransactionOptions extends VerifyTransactionOptions {
memo?: Memo;
feePayer: string;
blockhash: string;
durableNonce?: { walletNonceAddress: string; authWalletAddress: number };
}
interface TransactionOutput {
address: string;
amount: number | string;
tokenName?: string;
}
type TransactionInput = TransactionOutput;
export interface SolParsedTransaction extends ParsedTransaction {
// total assets being moved, including fees
inputs: TransactionInput[];
// where assets are moved to
outputs: TransactionOutput[];
}
export interface SolParseTransactionOptions extends BaseParseTransactionOptions {
txBase64: string;
feeInfo: TransactionFee;
tokenAccountRentExemptAmount?: string;
}
interface SolDurableNonceFromNode {
authority: string;
blockhash: string;
}
interface TokenAmount {
amount: string;
decimals: number;
uiAmount: number;
uiAmountString: string;
}
interface TokenAccountInfo {
isNative: boolean;
mint: string;
owner: string;
state: string;
tokenAmount: TokenAmount;
}
interface TokenAccount {
info: TokenAccountInfo;
pubKey: string;
tokenName?: string;
}
export interface SolRecoveryOptions extends MPCRecoveryOptions {
durableNonce?: {
publicKey: string;
secretKey: string;
};
tokenContractAddress?: string;
closeAtaAddress?: string;
// destination address where token should be sent before closing the ATA address
recoveryDestinationAtaAddress?: string;
programId?: string; // programId of the token
apiKey?: string; // API key for node requests
}
export interface SolConsolidationRecoveryOptions extends MPCConsolidationRecoveryOptions {
durableNonces: {
publicKeys: string[];
secretKey: string;
};
tokenContractAddress?: string;
apiKey?: string; // API key for node requests
programId?: string; // programId of the token
}
const HEX_REGEX = /^[0-9a-fA-F]+$/;
const BLIND_SIGNING_TX_TYPES_TO_CHECK = { enabletoken: 'AssociatedTokenAccountInitialization' };
/**
* Get amount string corrected for architecture-specific endianness issues.
*
* On s390x (big-endian) architecture, the Solana transaction parser (via @solana/web3.js)
* incorrectly reads little-endian u64 amounts as big-endian, resulting in corrupted values.
*
* This function corrects all amounts on s390x by swapping byte order to undo
* the incorrect byte order that happened during transaction parsing.
*
* @param amount - The amount to check and potentially fix
* @returns The corrected amount as a string
*/
export function getAmountBasedOnEndianness(amount: string | number): string {
const amountStr = String(amount);
// Only s390x architecture has this endianness issue
const isS390x = process.arch === 's390x';
if (!isS390x) {
return amountStr;
}
try {
const amountBN = BigInt(amountStr);
// On s390x, the parser ALWAYS reads u64 as big-endian when it's actually little-endian
// So we ALWAYS need to swap bytes to get the correct value
const buf = Buffer.alloc(8);
buf.writeBigUInt64BE(amountBN, 0);
const fixed = buf.readBigUInt64LE(0);
return fixed.toString();
} catch (e) {
// If conversion fails, return original value
return amountStr;
}
}
export class Sol extends BaseCoin {
protected readonly _staticsCoin: Readonly<StaticsBaseCoin>;
constructor(bitgo: BitGoBase, staticsCoin?: Readonly<StaticsBaseCoin>) {
super(bitgo);
if (!staticsCoin) {
throw new Error('missing required constructor parameter staticsCoin');
}
this._staticsCoin = staticsCoin;
}
static createInstance(bitgo: BitGoBase, staticsCoin?: Readonly<StaticsBaseCoin>): BaseCoin {
return new Sol(bitgo, staticsCoin);
}
allowsAccountConsolidations(): boolean {
return true;
}
supportsTss(): boolean {
return true;
}
/** @inheritDoc */
supportsMessageSigning(): boolean {
return true;
}
/** inherited doc */
getDefaultMultisigType(): MultisigType {
return multisigTypes.tss;
}
getMPCAlgorithm(): MPCAlgorithm {
return 'eddsa';
}
getChain(): string {
return this._staticsCoin.name;
}
getFamily(): CoinFamily {
return this._staticsCoin.family;
}
getFullName(): string {
return this._staticsCoin.fullName;
}
getNetwork(): BaseNetwork {
return this._staticsCoin.network;
}
getBaseFactor(): string | number {
return Math.pow(10, this._staticsCoin.decimalPlaces);
}
verifyTxType(expectedTypeFromUserParams: string, actualTypeFromDecoded: string | undefined): void {
const matchFromUserToDecodedType = BLIND_SIGNING_TX_TYPES_TO_CHECK[expectedTypeFromUserParams];
if (matchFromUserToDecodedType !== actualTypeFromDecoded) {
throw new Error(
`Invalid transaction type on token enablement: expected "${matchFromUserToDecodedType}", got "${actualTypeFromDecoded}".`
);
}
}
throwIfMissingTokenEnablementsOrReturn(explanation: TransactionExplanation): ITokenEnablement[] {
if (!explanation.tokenEnablements || explanation.tokenEnablements.length === 0)
throw new Error('Missing tx token enablements data on token enablement tx prebuild');
return explanation.tokenEnablements;
}
throwIfMissingEnableTokenConfigOrReturn(txParams: TransactionParams): TokenEnablement[] {
if (!txParams.enableTokens || txParams.enableTokens.length === 0) throw new Error('Missing enable token config');
return txParams.enableTokens;
}
verifyTokenName(tokenEnablementsPrebuild: ITokenEnablement[], enableTokensConfig: TokenEnablement[]): void {
enableTokensConfig.forEach((enableTokenConfig) => {
const expectedTokenName = enableTokenConfig.name;
tokenEnablementsPrebuild.forEach((tokenEnablement) => {
if (!tokenEnablement.tokenName) throw new Error('Missing token name on token enablement tx');
if (tokenEnablement.tokenName !== expectedTokenName)
throw new Error(
`Invalid token name: expected ${expectedTokenName}, got ${tokenEnablement.tokenName} on token enablement tx`
);
});
});
}
async verifyTokenAddress(
tokenEnablementsPrebuild: ITokenEnablement[],
enableTokensConfig: TokenEnablement[]
): Promise<void> {
for (const enableTokenConfig of enableTokensConfig) {
const expectedTokenAddress = enableTokenConfig.address;
const expectedTokenName = enableTokenConfig.name;
if (!expectedTokenAddress) throw new Error('Missing token address on token enablement tx');
if (!expectedTokenName) throw new Error('Missing token name on token enablement tx');
for (const tokenEnablement of tokenEnablementsPrebuild) {
let tokenMintAddress: Readonly<SolCoin> | undefined;
try {
tokenMintAddress = getSolTokenFromTokenName(expectedTokenName);
} catch {
throw new Error(`Unable to derive ATA for token address: ${expectedTokenAddress}`);
}
if (
!tokenMintAddress ||
tokenMintAddress.tokenAddress === undefined ||
tokenMintAddress.programId === undefined
) {
throw new Error(`Unable to get token mint address for ${expectedTokenName}`);
}
let ata: string;
try {
ata = await getAssociatedTokenAccountAddress(
tokenMintAddress.tokenAddress,
expectedTokenAddress,
true,
tokenMintAddress.programId
);
} catch {
throw new Error(`Unable to derive ATA for token address: ${expectedTokenAddress}`);
}
if (ata !== tokenEnablement.address) {
throw new Error(
`Invalid token address: expected ${ata}, got ${tokenEnablement.address} on token enablement tx`
);
}
}
}
}
private hasSolVersionedTransactionData(
txParams: TransactionParams
): txParams is TransactionParams & { solVersionedTransactionData: SolVersionedTransactionData } {
return 'solVersionedTransactionData' in txParams && txParams.solVersionedTransactionData !== undefined;
}
/**
* Verify a versioned Solana transaction with basic structural validation
* @param params - verification parameters
* @returns true if verification passes
*/
private async verifyVersionedTransaction(params: SolVerifyTransactionOptions): Promise<boolean> {
const { txParams, txPrebuild } = params;
const rawTx = txPrebuild.txBase64 || txPrebuild.txHex;
if (!rawTx) {
throw new Error('missing required tx prebuild property txBase64 or txHex');
}
// Validate that the versioned transaction data is well-formed
if (!this.hasSolVersionedTransactionData(txParams)) {
throw new Error('solVersionedTransactionData is required for versioned transaction verification');
}
const versionedData = txParams.solVersionedTransactionData;
if (!versionedData.versionedInstructions || versionedData.versionedInstructions.length === 0) {
throw new Error('versioned transaction must have at least one instruction');
}
if (!versionedData.staticAccountKeys || versionedData.staticAccountKeys.length === 0) {
throw new Error('versioned transaction must have at least one static account key');
}
if (!versionedData.messageHeader) {
throw new Error('versioned transaction must have a message header');
}
// Validate that we can deserialize the transaction
let rawTxBase64 = rawTx;
if (HEX_REGEX.test(rawTx)) {
rawTxBase64 = Buffer.from(rawTx, 'hex').toString('base64');
}
try {
const txBytes = Buffer.from(rawTxBase64, 'base64');
if (txBytes.length < 1) {
throw new Error('transaction bytes are empty');
}
// Check version byte (after signatures)
const numSignatures = txBytes[0];
const signatureSize = 64;
const versionByteOffset = 1 + numSignatures * signatureSize;
if (txBytes.length <= versionByteOffset) {
throw new Error('transaction bytes are too short to contain version byte');
}
const versionByte = txBytes[versionByteOffset];
const isVersioned = (versionByte & 0x80) !== 0;
if (!isVersioned) {
throw new Error('transaction does not have versioned format');
}
} catch (error) {
throw new Error(`failed to validate versioned transaction format: ${error.message}`);
}
return true;
}
async verifyTransaction(params: SolVerifyTransactionOptions): Promise<boolean> {
// asset name to transfer amount map
const totalAmount: Record<string, BigNumber> = {};
const coinConfig = coins.get(this.getChain());
const {
txParams: txParams,
txPrebuild: txPrebuild,
memo: memo,
durableNonce: durableNonce,
verification: verificationOptions,
} = params;
if (this.hasSolVersionedTransactionData(txParams)) {
return this.verifyVersionedTransaction(params);
}
const transaction = new Transaction(coinConfig);
const rawTx = txPrebuild.txBase64 || txPrebuild.txHex;
const consolidateId = txPrebuild.consolidateId;
const walletRootAddress = params.wallet.coinSpecific()?.rootAddress;
if (!rawTx) {
throw new Error('missing required tx prebuild property txBase64 or txHex');
}
let rawTxBase64 = rawTx;
if (HEX_REGEX.test(rawTx)) {
rawTxBase64 = Buffer.from(rawTx, 'hex').toString('base64');
}
transaction.fromRawTransaction(rawTxBase64);
const explainedTx = transaction.explainTransaction();
if (txParams.type === 'enabletoken' && verificationOptions?.verifyTokenEnablement) {
this.verifyTxType(txParams.type, explainedTx.type);
const tokenEnablementsPrebuild = this.throwIfMissingTokenEnablementsOrReturn(explainedTx);
const enableTokensConfig = this.throwIfMissingEnableTokenConfigOrReturn(txParams);
this.verifyTokenName(tokenEnablementsPrebuild, enableTokensConfig);
await this.verifyTokenAddress(tokenEnablementsPrebuild, enableTokensConfig);
}
// users do not input recipients for consolidation requests as they are generated by the server
if (txParams.recipients !== undefined) {
const filteredRecipients = txParams.recipients?.map((recipient) =>
_.pick(recipient, ['address', 'amount', 'tokenName'])
);
const filteredOutputs = explainedTx.outputs.map((output) => _.pick(output, ['address', 'amount', 'tokenName']));
if (filteredRecipients.length !== filteredOutputs.length) {
throw new Error('Number of tx outputs does not match with number of txParams recipients');
}
// For each recipient, check if it's a token tx (tokenName will exist if so)
// If it is a token tx, verify that the recipient address equals the derived address from explainedTx
// Derive the ATA if it is a native address and confirm it is equal to the explained tx recipient
const recipientChecks = await Promise.all(
filteredRecipients.map(async (recipientFromUser, index) => {
const recipientFromTx = filteredOutputs[index]; // This address should be an ATA
// Compare the BigNumber values because amount is (string | number)
// Apply s390x endianness fix if needed
const userAmountStr = String(recipientFromUser.amount);
const txAmountStr = getAmountBasedOnEndianness(recipientFromTx.amount);
const userAmount = new BigNumber(userAmountStr);
const txAmount = new BigNumber(txAmountStr);
if (!userAmount.isEqualTo(txAmount)) {
return false;
}
// Compare the addresses and tokenNames
// Else if the addresses are not the same, check the derived ATA for parity
if (
recipientFromUser.address === recipientFromTx.address &&
recipientFromUser.tokenName === recipientFromTx.tokenName
) {
return true;
} else if (recipientFromUser.address !== recipientFromTx.address && recipientFromUser.tokenName) {
// Try to check if the user's derived ATA is equal to the tx recipient address
// If getAssociatedTokenAccountAddress throws an error, then we are unable to derive the ATA for that address.
// Return false and throw an error if that is the case.
try {
const tokenMintAddress = getSolTokenFromTokenName(recipientFromUser.tokenName);
return getAssociatedTokenAccountAddress(
tokenMintAddress!.tokenAddress,
recipientFromUser.address,
true,
tokenMintAddress!.programId
).then((ata: string) => {
return ata === recipientFromTx.address;
});
} catch {
// Unable to derive ATA
return false;
}
}
return false;
})
);
if (recipientChecks.includes(false)) {
throw new Error('Tx outputs does not match with expected txParams recipients');
}
} else if (verificationOptions?.consolidationToBaseAddress) {
//verify funds are sent to walletRootAddress for a consolidation
const filteredOutputs = explainedTx.outputs.map((output) => _.pick(output, ['address', 'amount', 'tokenName']));
// Cache to store already derived ATA addresses
const ataAddressCache: Record<string, string> = {};
for (const output of filteredOutputs) {
if (output.tokenName) {
// Check cache first before deriving ATA address
if (!ataAddressCache[output.tokenName]) {
const tokenMintAddress = getSolTokenFromTokenName(output.tokenName);
if (tokenMintAddress?.tokenAddress && tokenMintAddress?.programId) {
ataAddressCache[output.tokenName] = await getAssociatedTokenAccountAddress(
tokenMintAddress.tokenAddress,
walletRootAddress as string,
true,
tokenMintAddress.programId
);
} else {
throw new Error(`Unable to get token information for ${output.tokenName}`);
}
}
if (ataAddressCache[output.tokenName] !== output.address) {
throw new Error('tx outputs does not match with expected address');
}
} else if (output.address !== walletRootAddress) {
throw new Error('tx outputs does not match with expected address');
}
}
}
const transactionJson = transaction.toJson();
if (memo && memo.value !== explainedTx.memo) {
throw new Error('Tx memo does not match with expected txParams recipient memo');
}
if (txParams.recipients) {
for (const recipients of txParams.recipients) {
// totalAmount based on each token
const assetName = recipients.tokenName || this.getChain();
const amount = totalAmount[assetName] || new BigNumber(0);
totalAmount[assetName] = amount.plus(recipients.amount);
}
// total output amount from explainedTx
const explainedTxTotal: Record<string, BigNumber> = {};
for (const output of explainedTx.outputs) {
// Apply s390x endianness fix to output amounts before summing
const outputAmountStr = getAmountBasedOnEndianness(output.amount);
// total output amount based on each token
const assetName = output.tokenName || this.getChain();
const amount = explainedTxTotal[assetName] || new BigNumber(0);
explainedTxTotal[assetName] = amount.plus(outputAmountStr);
}
if (!_.isEqual(explainedTxTotal, totalAmount)) {
throw new Error('Tx total amount does not match with expected total amount field');
}
}
// For non-consolidate transactions, feePayer must be the wallet's root address
if (consolidateId === undefined && transactionJson.feePayer !== walletRootAddress) {
throw new Error('Tx fee payer is not the wallet root address');
}
if (durableNonce && !_.isEqual(explainedTx.durableNonce, durableNonce)) {
throw new Error('Tx durableNonce does not match with param durableNonce');
}
return true;
}
async isWalletAddress(params: TssVerifyAddressOptions): Promise<boolean> {
const result = await verifyEddsaTssWalletAddress(
params,
(address) => this.isValidAddress(address),
(publicKey) => this.getAddressFromPublicKey(publicKey)
);
if (!result) {
throw new UnexpectedAddressError(`address validation failure: ${params.address} is not a wallet address`);
}
return true;
}
/**
* Converts a Solana public key to an address
* @param publicKey Hex-encoded public key (64 hex characters = 32 bytes)
* @returns Base58-encoded Solana address
*/
getAddressFromPublicKey(publicKey: string): string {
const publicKeyBuffer = Buffer.from(publicKey, 'hex');
return base58.encode(publicKeyBuffer);
}
/**
* Generate Solana key pair
*
* @param {Buffer} seed - Seed from which the new SolKeyPair should be generated, otherwise a random seed is used
* @returns {Object} object with generated pub and prv
*/
generateKeyPair(seed?: Buffer | undefined): KeyPair {
const result = seed ? new SolKeyPair({ seed }).getKeys() : new SolKeyPair().getKeys();
return result as KeyPair;
}
/**
* Return boolean indicating whether input is valid public key for the coin
*
* @param {string} pub the prv to be checked
* @returns is it valid?
*/
isValidPub(pub: string): boolean {
return isValidPublicKey(pub);
}
/**
* Return boolean indicating whether input is valid private key for the coin
*
* @param {string} prv the prv to be checked
* @returns is it valid?
*/
isValidPrv(prv: string): boolean {
return isValidPrivateKey(prv);
}
isValidAddress(address: string): boolean {
return isValidAddress(address);
}
async signMessage(key: KeyPair, message: string | Buffer): Promise<Buffer> {
const solKeypair = new SolKeyPair({ prv: key.prv });
if (Buffer.isBuffer(message)) {
message = base58.encode(message);
}
return Buffer.from(solKeypair.signMessage(message));
}
/**
* Signs Solana transaction
* @param params
* @param callback
*/
async signTransaction(params: SolSignTransactionOptions): Promise<SignedTransaction> {
const factory = this.getBuilder();
const rawTx = params.txPrebuild.txHex || params.txPrebuild.txBase64;
const txBuilder = factory.from(rawTx);
txBuilder.sign({ key: params.prv });
const transaction: BaseTransaction = await txBuilder.build();
if (!transaction) {
throw new Error('Invalid transaction');
}
const serializedTx = (transaction as BaseTransaction).toBroadcastFormat();
return {
txHex: serializedTx,
} as any;
}
async parseTransaction(params: SolParseTransactionOptions): Promise<SolParsedTransaction> {
// explainTransaction now uses WASM for testnet automatically
const transactionExplanation = await this.explainTransaction({
txBase64: params.txBase64,
feeInfo: params.feeInfo,
tokenAccountRentExemptAmount: params.tokenAccountRentExemptAmount,
});
if (!transactionExplanation) {
throw new Error('Invalid transaction');
}
const solTransaction = transactionExplanation as SolTransactionExplanation;
if (solTransaction.outputs.length <= 0) {
return {
inputs: [],
outputs: [],
};
}
const senderAddress = solTransaction.outputs[0].address;
const feeAmount = new BigNumber(solTransaction.fee.fee);
// assume 1 sender, who is also the fee payer
const inputs = [
{
address: senderAddress,
amount: new BigNumber(solTransaction.outputAmount).plus(feeAmount).toNumber(),
},
];
const outputs: TransactionOutput[] = solTransaction.outputs.map(({ address, amount, tokenName }) => {
const output: TransactionOutput = { address, amount };
if (tokenName) {
output.tokenName = tokenName;
}
return output;
});
return {
inputs,
outputs,
};
}
/**
* Explain a Solana transaction from txBase64
* Uses WASM-based parsing for testnet, with fallback to legacy builder approach.
* @param params
*/
async explainTransaction(params: ExplainTransactionOptions): Promise<SolTransactionExplanation> {
// Use WASM-based parsing for testnet (simpler, faster, no @solana/web3.js rebuild)
if (this.getChain() === 'tsol') {
return this.explainTransactionWithWasm(params) as SolTransactionExplanation;
}
// Legacy approach for mainnet (until WASM is fully validated)
const factory = this.getBuilder();
let rebuiltTransaction;
try {
const transactionBuilder = factory.from(params.txBase64);
if (transactionBuilder instanceof TransactionBuilder) {
const txBuilder = transactionBuilder as TransactionBuilder;
txBuilder.fee({ amount: params.feeInfo.fee });
if (params.tokenAccountRentExemptAmount) {
txBuilder.associatedTokenAccountRent(params.tokenAccountRentExemptAmount);
}
}
rebuiltTransaction = await transactionBuilder.build();
} catch (e) {
logger.error(e);
throw new Error('Invalid transaction');
}
const explainedTransaction = (rebuiltTransaction as BaseTransaction).explainTransaction();
return explainedTransaction as SolTransactionExplanation;
}
/**
* Explain a Solana transaction using WASM parsing (bypasses @solana/web3.js rebuild).
* Delegates to standalone explainSolTransaction().
*/
explainTransactionWithWasm(params: ExplainTransactionOptions): SolLibTransactionExplanation {
return explainSolTransaction({ ...params, coinName: params.coinName ?? this.getChain() });
}
/** @inheritDoc */
async getSignablePayload(serializedTx: string): Promise<Buffer> {
const factory = this.getBuilder();
const rebuiltTransaction = await factory.from(serializedTx).build();
return rebuiltTransaction.signablePayload;
}
/** @inheritDoc */
async presignTransaction(params: PresignTransactionOptions): Promise<PresignTransactionOptions> {
// Hot wallet txns are only valid for 1-2 minutes.
// To buy more time, we rebuild the transaction with a new blockhash right before we sign.
if (params.walletData.type !== 'hot') {
return Promise.resolve(params);
}
const txRequestId = params.txPrebuild?.txRequestId;
if (txRequestId === undefined) {
throw new Error('Missing txRequestId');
}
const { tssUtils } = params;
await tssUtils!.deleteSignatureShares(txRequestId);
const recreated = await tssUtils!.getTxRequest(txRequestId);
let txHex = '';
if (recreated.unsignedTxs) {
txHex = recreated.unsignedTxs[0]?.serializedTxHex;
} else {
txHex = recreated.transactions ? recreated.transactions[0]?.unsignedTx.serializedTxHex : '';
}
if (!txHex) {
throw new Error('Missing serialized tx hex');
}
return Promise.resolve({
...params,
txPrebuild: recreated,
txHex,
});
}
protected getPublicNodeUrl(apiKey?: string): string {
if (apiKey) {
return Environments[this.bitgo.getEnv()].solAlchemyNodeUrl + `/${apiKey}`;
}
return Environments[this.bitgo.getEnv()].solNodeUrl;
}
/**
* Make a request to one of the public SOL nodes available
* @param params.payload
*/
protected async getDataFromNode(
params: { payload?: Record<string, unknown> },
apiKey?: string
): Promise<request.Response> {
const nodeUrl = this.getPublicNodeUrl(apiKey);
try {
return await request.post(nodeUrl).send(params.payload);
} catch (e) {
console.debug(e);
}
throw new Error(`Unable to call endpoint: '/' from node: ${nodeUrl}`);
}
protected async getBlockhash(apiKey?: string): Promise<string> {
const response = await this.getDataFromNode(
{
payload: {
id: '1',
jsonrpc: '2.0',
method: 'getLatestBlockhash',
params: [
{
commitment: 'finalized',
},
],
},
},
apiKey
);
if (response.status !== 200) {
throw new Error('Account not found');
}
return response.body.result.value.blockhash;
}
protected async getFeeForMessage(message: string, apiKey?: string): Promise<number> {
const response = await this.getDataFromNode(
{
payload: {
id: '1',
jsonrpc: '2.0',
method: 'getFeeForMessage',
params: [
message,
{
commitment: 'finalized',
},
],
},
},
apiKey
);
if (response.status !== 200) {
throw new Error('Account not found');
}
return response.body.result.value;
}
protected async getRentExemptAmount(apiKey?: string): Promise<number> {
const response = await this.getDataFromNode(
{
payload: {
jsonrpc: '2.0',
id: '1',
method: 'getMinimumBalanceForRentExemption',
params: [165],
},
},
apiKey
);
if (response.status !== 200 || response.error) {
throw new Error(JSON.stringify(response.error));
}
return response.body.result;
}
protected async getAccountBalance(pubKey: string, apiKey?: string): Promise<number> {
const response = await this.getDataFromNode(
{
payload: {
id: '1',
jsonrpc: '2.0',
method: 'getBalance',
params: [pubKey],
},
},
apiKey
);
if (response.status !== 200) {
throw new Error('Account not found');
}
return response.body.result.value;
}
protected async getAccountInfo(pubKey: string, apiKey?: string): Promise<SolDurableNonceFromNode> {
const response = await this.getDataFromNode(
{
payload: {
id: '1',
jsonrpc: '2.0',
method: 'getAccountInfo',
params: [
pubKey,
{
encoding: 'jsonParsed',
},
],
},
},
apiKey
);
if (response.status !== 200) {
throw new Error('Account not found');
}
return {
authority: response.body.result.value.data.parsed.info.authority,
blockhash: response.body.result.value.data.parsed.info.blockhash,
};
}
protected async getTokenAccountsByOwner(pubKey = '', programId = '', apiKey?: string): Promise<[] | TokenAccount[]> {
const response = await this.getDataFromNode(
{
payload: {
id: '1',
jsonrpc: '2.0',
method: 'getTokenAccountsByOwner',
params: [
pubKey,
{
programId:
programId.toString().toLowerCase() === TOKEN_2022_PROGRAM_ID.toString().toLowerCase()
? TOKEN_2022_PROGRAM_ID.toString()
: TOKEN_PROGRAM_ID.toString(),
},
{
encoding: 'jsonParsed',
},
],
},
},
apiKey
);
if (response.status !== 200) {
throw new Error('Account not found');
}
if (response.body.result.value.length !== 0) {
const tokenAccounts: TokenAccount[] = [];
for (const tokenAccount of response.body.result.value) {
tokenAccounts.push({ info: tokenAccount.account.data.parsed.info, pubKey: tokenAccount.pubKey });