-
Notifications
You must be signed in to change notification settings - Fork 123
Expand file tree
/
Copy pathmain.ts
More file actions
102 lines (84 loc) · 2.51 KB
/
main.ts
File metadata and controls
102 lines (84 loc) · 2.51 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
/**
* Cross Program Invocation
*/
import {
Connection,
Keypair,
PublicKey,
TransactionInstruction,
sendAndConfirmTransaction,
Transaction,
} from "@solana/web3.js";
import path from "path";
import {
getPayer,
establishConnection,
checkAccountDeployed,
checkBinaryExists,
establishEnoughSol,
getBalance,
} from "../../../utils/utils";
// directory with binary and keypair
const PROGRAM_PATH = path.resolve(__dirname, "../../target/deploy/");
// Path to program shared object file which should be deployed on chain.
const PROGRAM_SO_PATH = path.join(PROGRAM_PATH, "cpi.so");
// Path to the keypair of the deployed program (This file is created when running `solana program deploy)
const PROGRAM_KEYPAIR_PATH = path.join(PROGRAM_PATH, "cpi-keypair.json");
async function main() {
console.log("Let's invoke other program!");
let payer: Keypair = await getPayer();
// Establish connection to the cluster
let connection: Connection = await establishConnection();
await establishEnoughSol(connection, payer);
// balance after top-up
let [startBalanceSol, startBalanceLamport] = await getBalance(
connection,
payer
);
// Check if binary exists
let programID = await checkBinaryExists(PROGRAM_KEYPAIR_PATH);
// Check if deployed
if (await checkAccountDeployed(connection, programID)) {
await invoke(programID, connection, payer);
// Print fees used up
let [endBalanceSol, endBalanceLamport] = await getBalance(
connection,
payer
);
console.log(
`\nIt cost:\n\t${startBalanceSol - endBalanceSol} SOL\n\t${
startBalanceLamport - endBalanceLamport
} Lamports\nto perform the call`
);
} else {
console.log(`\nProgram ${PROGRAM_SO_PATH} not deployed!\n`);
}
}
export async function invoke(
programId: PublicKey,
connection: Connection,
payer: Keypair
): Promise<void> {
// load key of the hello world
let programIDHelloWorld = await checkBinaryExists(
path.join(PROGRAM_PATH, "helloworld-keypair.json")
);
console.log("programIDHelloWorld: ", programIDHelloWorld.toBase58());
const instruction = new TransactionInstruction({
keys: [{ pubkey: programIDHelloWorld, isSigner: false, isWritable: false }],
programId,
data: Buffer.alloc(0), // Instruction data unnecessary to simply log output
});
await sendAndConfirmTransaction(
connection,
new Transaction().add(instruction),
[payer]
);
}
main().then(
() => process.exit(),
(err) => {
console.error(err);
process.exit(-1);
}
);