-
Notifications
You must be signed in to change notification settings - Fork 8
/
utils.ts
233 lines (217 loc) · 5.98 KB
/
utils.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
import { utils, Wallet } from "@project-serum/anchor";
import {
createAssociatedTokenAccountInstruction,
createInitializeMint2Instruction,
createMintToInstruction,
getAssociatedTokenAddressSync,
getMinimumBalanceForRentExemptMint,
MINT_SIZE,
TOKEN_PROGRAM_ID,
} from "@solana/spl-token";
import type { SendTransactionError, Signer } from "@solana/web3.js";
import {
Connection,
Keypair,
LAMPORTS_PER_SOL,
PublicKey,
sendAndConfirmRawTransaction,
SystemProgram,
Transaction,
} from "@solana/web3.js";
import { findAta } from "@solana-nft-programs/common";
import dotenv from "dotenv";
import { findMintManagerId, findMintMetadataId } from "./sdk";
import {
createInitMintManagerInstruction,
PROGRAM_ADDRESS,
} from "./sdk/generated";
dotenv.config();
export async function newAccountWithLamports(
connection: Connection,
lamports = LAMPORTS_PER_SOL,
keypair = Keypair.generate(),
): Promise<Keypair> {
const account = keypair;
const signature = await connection.requestAirdrop(
account.publicKey,
lamports,
);
await connection.confirmTransaction(signature, "confirmed");
return account;
}
export function getConnection(): Connection {
const url = "http://127.0.0.1:8899";
return new Connection(url, "confirmed");
}
export async function executeTransaction(
connection: Connection,
tx: Transaction,
wallet: Wallet,
signers?: Signer[],
): Promise<string> {
tx.recentBlockhash = (await connection.getLatestBlockhash()).blockhash;
tx.feePayer = wallet.publicKey;
await wallet.signTransaction(tx);
if (signers) {
tx.partialSign(...signers);
}
try {
const txid = await sendAndConfirmRawTransaction(connection, tx.serialize());
return txid;
} catch (e) {
handleError(e);
throw e;
}
}
export type SolanaProvider = {
connection: Connection;
wallet: Wallet;
keypair: Keypair;
};
export async function getProvider(): Promise<SolanaProvider> {
const connection = getConnection();
const keypair = await newAccountWithLamports(
connection,
LAMPORTS_PER_SOL,
keypairFrom(process.env.TEST_KEY ?? "./tests/test-keypairs/test-key.json"),
);
const wallet = new Wallet(keypair);
return {
connection,
wallet,
keypair,
};
}
export const TEST_PROGRAM_ID = process.env.TEST_PROGRAM_ID
? new PublicKey(process.env.TEST_PROGRAM_ID)
: PROGRAM_ADDRESS;
export const keypairFrom = (s: string, n?: string): Keypair => {
try {
if (s.includes("[")) {
return Keypair.fromSecretKey(
Buffer.from(
s
.replace("[", "")
.replace("]", "")
.split(",")
.map((c) => parseInt(c)),
),
);
} else {
return Keypair.fromSecretKey(utils.bytes.bs58.decode(s));
}
} catch (e) {
try {
return Keypair.fromSecretKey(
Buffer.from(
JSON.parse(
require("fs").readFileSync(s, {
encoding: "utf-8",
}),
),
),
);
} catch (e) {
process.stdout.write(`${n ?? "keypair"} is not valid keypair`);
process.exit(1);
}
}
};
export const handleError = (e: any) => {
const message = (e as SendTransactionError).message ?? "";
const logs = (e as SendTransactionError).logs;
if (logs) {
console.log(logs);
// const parsed = parseProgramLogs(logs, message);
// const fmt = formatInstructionLogsForConsole(parsed);
// console.log(fmt);
} else {
console.log(e, message);
}
};
const networkURLs: { [key: string]: { primary: string; secondary?: string } } =
{
["mainnet-beta"]: {
primary: process.env.RPC_URL || "https://solana-api.projectserum.com",
secondary: "https://solana-api.projectserum.com",
},
mainnet: {
primary: process.env.RPC_URL || "https://solana-api.projectserum.com",
secondary: "https://solana-api.projectserum.com",
},
devnet: { primary: "https://api.devnet.solana.com/" },
testnet: { primary: "https://api.testnet.solana.com/" },
localnet: { primary: "http://localhost:8899/" },
};
export const connectionFor = (
cluster: string | null,
defaultCluster = "mainnet",
) => {
return new Connection(
networkURLs[cluster || defaultCluster]!.primary,
"recent",
);
};
export const secondaryConnectionFor = (
cluster: string | null,
defaultCluster = "mainnet",
) => {
return new Connection(
process.env.RPC_URL ||
networkURLs[cluster || defaultCluster]?.secondary ||
networkURLs[cluster || defaultCluster]!.primary,
"recent",
);
};
export const createMintTx = async (
connection: Connection,
mint: PublicKey,
authority: PublicKey,
target = authority,
) => {
const ata = getAssociatedTokenAddressSync(mint, target);
return new Transaction().add(
SystemProgram.createAccount({
fromPubkey: authority,
newAccountPubkey: mint,
space: MINT_SIZE,
lamports: await getMinimumBalanceForRentExemptMint(connection),
programId: TOKEN_PROGRAM_ID,
}),
createInitializeMint2Instruction(mint, 0, authority, authority),
createAssociatedTokenAccountInstruction(authority, ata, target, mint),
createMintToInstruction(mint, ata, authority, 1),
);
};
export const createCCSMintTx = async (
connection: Connection,
mint: PublicKey,
authority: PublicKey,
rulesetId: PublicKey,
): Promise<Transaction> => {
const tx = await createMintTx(connection, mint, authority);
const mintManagerId = findMintManagerId(mint);
const mintMetadataId = findMintMetadataId(mint);
const targetTokenAccountId = await findAta(mint, authority, true);
tx.add(
createInitMintManagerInstruction({
mintManager: mintManagerId,
mint: mint,
mintMetadata: mintMetadataId,
ruleset: rulesetId,
holderTokenAccount: targetTokenAccountId,
tokenAuthority: authority,
authority: authority,
payer: authority,
}),
);
return tx;
};
type AccountFn<T> = () => Promise<T>;
export async function tryGetAccount<T>(fn: AccountFn<T>) {
try {
return await fn();
} catch {
return null;
}
}