-
Notifications
You must be signed in to change notification settings - Fork 80
/
wallet.ts
66 lines (57 loc) · 1.54 KB
/
wallet.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
import {
Keypair,
PublicKey,
Transaction,
VersionedTransaction,
} from '@solana/web3.js';
import { IWallet, IVersionedWallet } from './types';
import fs from 'fs';
import bs58 from 'bs58';
export class Wallet implements IWallet, IVersionedWallet {
constructor(readonly payer: Keypair) {}
async signTransaction(tx: Transaction): Promise<Transaction> {
tx.partialSign(this.payer);
return tx;
}
async signVersionedTransaction(
tx: VersionedTransaction
): Promise<VersionedTransaction> {
tx.sign([this.payer]);
return tx;
}
async signAllTransactions(txs: Transaction[]): Promise<Transaction[]> {
return txs.map((t) => {
t.partialSign(this.payer);
return t;
});
}
async signAllVersionedTransactions(
txs: VersionedTransaction[]
): Promise<VersionedTransaction[]> {
return txs.map((t) => {
t.sign([this.payer]);
return t;
});
}
get publicKey(): PublicKey {
return this.payer.publicKey;
}
}
export function loadKeypair(privateKey: string): Keypair {
// try to load privateKey as a filepath
let loadedKey: Uint8Array;
if (fs.existsSync(privateKey)) {
privateKey = fs.readFileSync(privateKey).toString();
}
if (privateKey.includes('[') && privateKey.includes(']')) {
loadedKey = Uint8Array.from(JSON.parse(privateKey));
} else if (privateKey.includes(',')) {
loadedKey = Uint8Array.from(
privateKey.split(',').map((val) => Number(val))
);
} else {
privateKey = privateKey.replace(/\s/g, '');
loadedKey = new Uint8Array(bs58.decode(privateKey));
}
return Keypair.fromSecretKey(Uint8Array.from(loadedKey));
}