-
Notifications
You must be signed in to change notification settings - Fork 0
/
solana.js
210 lines (177 loc) · 6.85 KB
/
solana.js
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
const {
Account,
Connection,
BpfLoader,
BPF_LOADER_PROGRAM_ID,
PublicKey,
LAMPORTS_PER_SOL,
SystemProgram,
TransactionInstruction,
Transaction,
sendAndConfirmTransaction,
} = require('@solana/web3.js');
const bs58 = require('bs58');
const DataLayouts = require('../scripts/layouts');
class Solana {
constructor(config) {
this.serviceUri = config.httpUri;
this.connection = new Connection(this.serviceUri, 'singleGossip');
}
static getPublicKey(publicKey) {
return typeof publicKey === 'string' ? new PublicKey(publicKey) : publicKey;
}
static getSigningAccount(privateKey) {
return new Account(privateKey);
}
async getAccountInfo(publicKey) {
return await this.connection.getAccountInfo(Solana.getPublicKey(publicKey));
}
static getDataLayouts() {
return DataLayouts.get();
}
async getAccountBalance(publicKey) {
return await this.connection.getBalance(Solana.getPublicKey(publicKey));
}
async airDrop(account, lamports) {
await this.connection.requestAirdrop(Solana.getPublicKey(account), lamports);
}
async createSystemAccount() {
let self = this;
let lamports = 1;
let account = new Account();
console.log(`🤖 Account ${account.publicKey} created. Requesting Airdrop...`);
await self.airDrop(Solana.getPublicKey(account.publicKey), lamports);
return account;
}
/**
* Creates an account and adds lamports
*
* @param options lamports: Number of lamports to add
* entropy: Secret key used to generate account keypair Buffer | Uint8Array | Array<number>
* @returns Account that was created
*/
async createAccount(options) {
let self = this;
let lamports = options.lamports || 1000000;
let account = options.entropy ? new Account(options.entropy) : new Account();
let retries = 10;
console.log(`🤖 Account ${account.publicKey} created. Requesting Airdrop...`);
await self.airDrop(Solana.getPublicKey(account.publicKey), lamports);
for (;;) {
await Solana._sleep(500);
if (lamports == (await self.getAccountBalance(Solana.getPublicKey(account.publicKey)))) {
console.log(`🪂 Airdrop success for ${account.publicKey} (balance: ${lamports})`);
return account;
}
if (--retries <= 0) {
break;
}
console.log(`--- Airdrop retry #${retries} for ${account.publicKey}`);
}
throw new Error(`Airdrop of ${lamports} failed for ${account.publicKey}`);
}
async createPayerAccount(program) {
let self = this;
let dataLayouts = Solana.getDataLayouts();
let fees = 0;
const {feeCalculator} = await self.connection.getRecentBlockhash();
// Calculate the cost to load the program
const NUM_RETRIES = 500;
fees +=
feeCalculator.lamportsPerSignature *
(BpfLoader.getMinNumSignatures(program.length) + NUM_RETRIES) +
(await self.connection.getMinimumBalanceForRentExemption(program.length));
// Calculate the cost to fund all state accounts
for(let l=0; l<dataLayouts.length; l++) {
fees += await self.connection.getMinimumBalanceForRentExemption(
dataLayouts[l].span,
);
}
// Calculate the cost of sending the transactions
fees += feeCalculator.lamportsPerSignature * 100; // wag
// Fund a new payer via airdrop
return await self.createAccount({ lamports: fees });
}
async deployProgram(program){
let self = this;
let dataLayouts = Solana.getDataLayouts();
let payerAccount = await self.createPayerAccount(program);
let deployAccounts = {
"payer": {
publicKey: payerAccount.publicKey.toBase58(),
privateKey: bs58.encode(payerAccount.secretKey),
lamports: await self.getAccountBalance(payerAccount.publicKey)
}
};
let programAccount = new Account();
await BpfLoader.load(
self.connection,
payerAccount,
programAccount,
program,
BPF_LOADER_PROGRAM_ID,
);
let programId = programAccount.publicKey;
// Create all the state accounts
let transactionAccounts = [ payerAccount ];
let transaction = new Transaction();
for(let l=0; l<dataLayouts.length; l++) {
let stateAccount = new Account();
transactionAccounts.push(stateAccount);
let space = dataLayouts[l].layout.span;
let lamports = await self.connection.getMinimumBalanceForRentExemption(
dataLayouts[l].layout.span,
);
transaction.add(
SystemProgram.createAccount({
fromPubkey: payerAccount.publicKey,
newAccountPubkey: stateAccount.publicKey,
lamports,
space,
programId,
}),
);
deployAccounts[dataLayouts[l].name] = {
publicKey: stateAccount.publicKey.toBase58(),
privateKey: bs58.encode(stateAccount.secretKey),
lamports
}
}
await sendAndConfirmTransaction(
self.connection,
transaction,
transactionAccounts,
{
commitment: 'singleGossip',
preflightCommitment: 'singleGossip',
},
);
return {
programId: programAccount.publicKey.toBase58(),
programAccounts: deployAccounts
}
}
async submitTransaction(options) {
let self = this;
let instruction = new TransactionInstruction({
keys: options.keys,
programId: options.programId,
data: options.data
});
return await sendAndConfirmTransaction(
self.connection,
new Transaction().add(instruction),
[ options.payer ],
{
commitment: 'singleGossip',
preflightCommitment: 'singleGossip',
},
);
}
static async _sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
}
module.exports = {
Solana
}