-
Notifications
You must be signed in to change notification settings - Fork 859
/
hello_world.ts
242 lines (216 loc) · 6.37 KB
/
hello_world.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
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
import {
Account,
Connection,
PublicKey,
LAMPORTS_PER_SOL,
SystemProgram,
TransactionInstruction,
Transaction,
sendAndConfirmTransaction,
} from '@solana/web3.js';
import fs from 'mz/fs';
import path from 'path';
import * as borsh from 'borsh';
import {
getPayer,
getRpcUrl,
newAccountWithLamports,
readAccountFromFile,
} from './utils';
/**
* Connection to the network
*/
let connection: Connection;
/**
* Connection to the network
*/
let payerAccount: Account;
/**
* Hello world's program id
*/
let programId: PublicKey;
/**
* The public key of the account we are saying hello to
*/
let greetedPubkey: PublicKey;
/**
* Path to program files
*/
const PROGRAM_PATH = path.resolve(__dirname, '../../dist/program');
/**
* Path to program shared object file which should be deployed on chain.
* This file is created when running either:
* - `npm run build:program-c`
* - `npm run build:program-rust`
*/
const PROGRAM_SO_PATH = path.join(PROGRAM_PATH, 'helloworld.so');
/**
* Path to the keypair of the deployed program.
* This file is created when running `solana program deploy dist/program/helloworld.so`
*/
const PROGRAM_KEYPAIR_PATH = path.join(PROGRAM_PATH, 'helloworld-keypair.json');
/**
* The state of a greeting account managed by the hello world program
*/
class GreetingAccount {
counter = 0;
constructor(fields: {counter: number} | undefined = undefined) {
if (fields) {
this.counter = fields.counter;
}
}
}
/**
* Borsh schema definition for greeting accounts
*/
const GreetingSchema = new Map([
[GreetingAccount, {kind: 'struct', fields: [['counter', 'u32']]}],
]);
/**
* The expected size of each greeting account.
*/
const GREETING_SIZE = borsh.serialize(GreetingSchema, new GreetingAccount())
.length;
/**
* Establish a connection to the cluster
*/
export async function establishConnection(): Promise<void> {
const rpcUrl = await getRpcUrl();
connection = new Connection(rpcUrl, 'confirmed');
const version = await connection.getVersion();
console.log('Connection to cluster established:', rpcUrl, version);
}
/**
* Establish an account to pay for everything
*/
export async function establishPayer(): Promise<void> {
let fees = 0;
if (!payerAccount) {
const {feeCalculator} = await connection.getRecentBlockhash();
// Calculate the cost to fund the greeter account
fees += await connection.getMinimumBalanceForRentExemption(GREETING_SIZE);
// Calculate the cost of sending transactions
fees += feeCalculator.lamportsPerSignature * 100; // wag
try {
// Get payer from cli config
payerAccount = await getPayer();
} catch (err) {
// Fund a new payer via airdrop
payerAccount = await newAccountWithLamports(connection, fees);
}
}
const lamports = await connection.getBalance(payerAccount.publicKey);
if (lamports < fees) {
// This should only happen when using cli config keypair
const sig = await connection.requestAirdrop(
payerAccount.publicKey,
fees - lamports,
);
await connection.confirmTransaction(sig);
}
console.log(
'Using account',
payerAccount.publicKey.toBase58(),
'containing',
lamports / LAMPORTS_PER_SOL,
'SOL to pay for fees',
);
}
/**
* Check if the hello world BPF program has been deployed
*/
export async function checkProgram(): Promise<void> {
// Read program id from keypair file
try {
const programAccount = await readAccountFromFile(PROGRAM_KEYPAIR_PATH);
programId = programAccount.publicKey;
} catch (err) {
const errMsg = (err as Error).message;
throw new Error(
`Failed to read program keypair at '${PROGRAM_KEYPAIR_PATH}' due to error: ${errMsg}. Program may need to be deployed with \`solana program deploy dist/program/helloworld.so\``,
);
}
// Check if the program has been deployed
const programInfo = await connection.getAccountInfo(programId);
if (programInfo === null) {
if (fs.existsSync(PROGRAM_SO_PATH)) {
throw new Error(
'Program needs to be deployed with `solana program deploy dist/program/helloworld.so`',
);
} else {
throw new Error('Program needs to be built and deployed');
}
} else if (!programInfo.executable) {
throw new Error(`Program is not executable`);
}
console.log(`Using program ${programId.toBase58()}`);
// Derive the address of a greeting account from the program so that it's easy to find later.
const GREETING_SEED = 'hello';
greetedPubkey = await PublicKey.createWithSeed(
payerAccount.publicKey,
GREETING_SEED,
programId,
);
// Check if the greeting account has already been created
const greetedAccount = await connection.getAccountInfo(greetedPubkey);
if (greetedAccount === null) {
console.log(
'Creating account',
greetedPubkey.toBase58(),
'to say hello to',
);
const lamports = await connection.getMinimumBalanceForRentExemption(
GREETING_SIZE,
);
const transaction = new Transaction().add(
SystemProgram.createAccountWithSeed({
fromPubkey: payerAccount.publicKey,
basePubkey: payerAccount.publicKey,
seed: GREETING_SEED,
newAccountPubkey: greetedPubkey,
lamports,
space: GREETING_SIZE,
programId,
}),
);
await sendAndConfirmTransaction(connection, transaction, [payerAccount]);
}
}
/**
* Say hello
*/
export async function sayHello(): Promise<void> {
console.log('Saying hello to', greetedPubkey.toBase58());
const instruction = new TransactionInstruction({
keys: [{pubkey: greetedPubkey, isSigner: false, isWritable: true}],
programId,
data: Buffer.alloc(0), // All instructions are hellos
});
await sendAndConfirmTransaction(
connection,
new Transaction().add(instruction),
[payerAccount],
);
}
/**
* Report the number of times the greeted account has been said hello to
*/
export async function reportGreetings(): Promise<void> {
const accountInfo = await connection.getAccountInfo(greetedPubkey);
if (accountInfo === null) {
throw 'Error: cannot find the greeted account';
}
const greeting = borsh.deserialize(
GreetingSchema,
GreetingAccount,
accountInfo.data,
);
console.log(
greetedPubkey.toBase58(),
'has been greeted',
greeting.counter,
'time(s)',
);
}