helpers.ts 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. import fs from "fs";
  2. import path from "path";
  3. import { Connection, Keypair, LAMPORTS_PER_SOL, PublicKey } from "@solana/web3.js";
  4. // define some default locations
  5. const DEFAULT_KEY_DIR_NAME = ".local_keys";
  6. const DEFAULT_PUBLIC_KEY_FILE = "keys.json";
  7. const DEFAULT_DEMO_DATA_FILE = "demo.json";
  8. /*
  9. Load locally stored PublicKey addresses
  10. */
  11. export function loadPublicKeysFromFile(
  12. absPath: string = `${DEFAULT_KEY_DIR_NAME}/${DEFAULT_PUBLIC_KEY_FILE}`,
  13. ) {
  14. try {
  15. if (!absPath) throw Error("No path provided");
  16. if (!fs.existsSync(absPath)) throw Error("File does not exist.");
  17. // load the public keys from the file
  18. const data = JSON.parse(fs.readFileSync(absPath, { encoding: "utf-8" })) || {};
  19. // convert all loaded keyed values into valid public keys
  20. for (const [key, value] of Object.entries(data)) {
  21. data[key] = new PublicKey(value as string) ?? "";
  22. }
  23. return data;
  24. } catch (err) {
  25. // console.warn("Unable to load local file");
  26. }
  27. // always return an object
  28. return {};
  29. }
  30. /*
  31. Locally save a demo data to the filesystem for later retrieval
  32. */
  33. export function saveDemoDataToFile(
  34. name: string,
  35. newData: any,
  36. absPath: string = `${DEFAULT_KEY_DIR_NAME}/${DEFAULT_DEMO_DATA_FILE}`,
  37. ) {
  38. try {
  39. let data: object = {};
  40. // fetch all the current values, when the storage file exists
  41. if (fs.existsSync(absPath))
  42. data = JSON.parse(fs.readFileSync(absPath, { encoding: "utf-8" })) || {};
  43. data = { ...data, [name]: newData };
  44. // actually save the data to the file
  45. fs.writeFileSync(absPath, JSON.stringify(data), {
  46. encoding: "utf-8",
  47. });
  48. return data;
  49. } catch (err) {
  50. console.warn("Unable to save to file");
  51. // console.warn(err);
  52. }
  53. // always return an object
  54. return {};
  55. }
  56. /*
  57. Locally save a PublicKey addresses to the filesystem for later retrieval
  58. */
  59. export function savePublicKeyToFile(
  60. name: string,
  61. publicKey: PublicKey,
  62. absPath: string = `${DEFAULT_KEY_DIR_NAME}/${DEFAULT_PUBLIC_KEY_FILE}`,
  63. ) {
  64. try {
  65. // if (!absPath) throw Error("No path provided");
  66. // if (!fs.existsSync(absPath)) throw Error("File does not exist.");
  67. // fetch all the current values
  68. let data: any = loadPublicKeysFromFile(absPath);
  69. // convert all loaded keyed values from PublicKeys to strings
  70. for (const [key, value] of Object.entries(data)) {
  71. data[key as any] = (value as PublicKey).toBase58();
  72. }
  73. data = { ...data, [name]: publicKey.toBase58() };
  74. // actually save the data to the file
  75. fs.writeFileSync(absPath, JSON.stringify(data), {
  76. encoding: "utf-8",
  77. });
  78. // reload the keys for sanity
  79. data = loadPublicKeysFromFile(absPath);
  80. return data;
  81. } catch (err) {
  82. console.warn("Unable to save to file");
  83. }
  84. // always return an object
  85. return {};
  86. }
  87. /*
  88. Load a locally stored JSON keypair file and convert it to a valid Keypair
  89. */
  90. export function loadKeypairFromFile(absPath: string) {
  91. try {
  92. if (!absPath) throw Error("No path provided");
  93. if (!fs.existsSync(absPath)) throw Error("File does not exist.");
  94. // load the keypair from the file
  95. const keyfileBytes = JSON.parse(fs.readFileSync(absPath, { encoding: "utf-8" }));
  96. // parse the loaded secretKey into a valid keypair
  97. const keypair = Keypair.fromSecretKey(new Uint8Array(keyfileBytes));
  98. return keypair;
  99. } catch (err) {
  100. // return false;
  101. throw err;
  102. }
  103. }
  104. /*
  105. Save a locally stored JSON keypair file for later importing
  106. */
  107. export function saveKeypairToFile(
  108. keypair: Keypair,
  109. fileName: string,
  110. dirName: string = DEFAULT_KEY_DIR_NAME,
  111. ) {
  112. fileName = path.join(dirName, `${fileName}.json`);
  113. // create the `dirName` directory, if it does not exists
  114. if (!fs.existsSync(`./${dirName}/`)) fs.mkdirSync(`./${dirName}/`);
  115. // remove the current file, if it already exists
  116. if (fs.existsSync(fileName)) fs.unlinkSync(fileName);
  117. // write the `secretKey` value as a string
  118. fs.writeFileSync(fileName, `[${keypair.secretKey.toString()}]`, {
  119. encoding: "utf-8",
  120. });
  121. return fileName;
  122. }
  123. /*
  124. Attempt to load a keypair from the filesystem, or generate and save a new one
  125. */
  126. export function loadOrGenerateKeypair(fileName: string, dirName: string = DEFAULT_KEY_DIR_NAME) {
  127. try {
  128. // compute the path to locate the file
  129. const searchPath = path.join(dirName, `${fileName}.json`);
  130. let keypair = Keypair.generate();
  131. // attempt to load the keypair from the file
  132. if (fs.existsSync(searchPath)) keypair = loadKeypairFromFile(searchPath);
  133. // when unable to locate the keypair, save the new one
  134. else saveKeypairToFile(keypair, fileName, dirName);
  135. return keypair;
  136. } catch (err) {
  137. console.error("loadOrGenerateKeypair:", err);
  138. throw err;
  139. }
  140. }
  141. /*
  142. Compute the Solana explorer address for the various data
  143. */
  144. export function explorerURL({
  145. address,
  146. txSignature,
  147. cluster,
  148. }: {
  149. address?: string;
  150. txSignature?: string;
  151. cluster?: "devnet" | "testnet" | "mainnet" | "mainnet-beta";
  152. }) {
  153. let baseUrl: string;
  154. //
  155. if (address) baseUrl = `https://explorer.solana.com/address/${address}`;
  156. else if (txSignature) baseUrl = `https://explorer.solana.com/tx/${txSignature}`;
  157. else return "[unknown]";
  158. // auto append the desired search params
  159. const url = new URL(baseUrl);
  160. url.searchParams.append("cluster", cluster || "devnet");
  161. return url.toString() + "\n";
  162. }
  163. /**
  164. * Auto airdrop the given wallet of of a balance of < 0.5 SOL
  165. */
  166. export async function airdropOnLowBalance(
  167. connection: Connection,
  168. keypair: Keypair,
  169. forceAirdrop: boolean = false,
  170. ) {
  171. // get the current balance
  172. let balance = await connection.getBalance(keypair.publicKey);
  173. // define the low balance threshold before airdrop
  174. const MIN_BALANCE_TO_AIRDROP = LAMPORTS_PER_SOL / 2; // current: 0.5 SOL
  175. // check the balance of the two accounts, airdrop when low
  176. if (forceAirdrop === true || balance < MIN_BALANCE_TO_AIRDROP) {
  177. console.log(`Requesting airdrop of 1 SOL to ${keypair.publicKey.toBase58()}...`);
  178. await connection.requestAirdrop(keypair.publicKey, LAMPORTS_PER_SOL).then(sig => {
  179. console.log("Tx signature:", sig);
  180. // balance = balance + LAMPORTS_PER_SOL;
  181. });
  182. // fetch the new balance
  183. // const newBalance = await connection.getBalance(keypair.publicKey);
  184. // return newBalance;
  185. }
  186. // else console.log("Balance of:", balance / LAMPORTS_PER_SOL, "SOL");
  187. return balance;
  188. }
  189. /*
  190. Helper function to extract a transaction signature from a failed transaction's error message
  191. */
  192. export async function extractSignatureFromFailedTransaction(
  193. connection: Connection,
  194. err: any,
  195. fetchLogs?: boolean,
  196. ) {
  197. if (err?.signature) return err.signature;
  198. // extract the failed transaction's signature
  199. const failedSig = new RegExp(/^((.*)?Error: )?(Transaction|Signature) ([A-Z0-9]{32,}) /gim).exec(
  200. err?.message?.toString(),
  201. )?.[4];
  202. // ensure a signature was found
  203. if (failedSig) {
  204. // when desired, attempt to fetch the program logs from the cluster
  205. if (fetchLogs)
  206. await connection
  207. .getTransaction(failedSig, {
  208. maxSupportedTransactionVersion: 0,
  209. })
  210. .then(tx => {
  211. console.log(`\n==== Transaction logs for ${failedSig} ====`);
  212. console.log(explorerURL({ txSignature: failedSig }), "");
  213. console.log(tx?.meta?.logMessages ?? "No log messages provided by RPC");
  214. console.log(`==== END LOGS ====\n`);
  215. });
  216. else {
  217. console.log("\n========================================");
  218. console.log(explorerURL({ txSignature: failedSig }));
  219. console.log("========================================\n");
  220. }
  221. }
  222. // always return the failed signature value
  223. return failedSig;
  224. }
  225. /*
  226. Standard number formatter
  227. */
  228. export function numberFormatter(num: number, forceDecimals = false) {
  229. // set the significant figures
  230. const minimumFractionDigits = num < 1 || forceDecimals ? 10 : 2;
  231. // do the formatting
  232. return new Intl.NumberFormat(undefined, {
  233. minimumFractionDigits,
  234. }).format(num);
  235. }
  236. /*
  237. Display a separator in the console, with our without a message
  238. */
  239. export function printConsoleSeparator(message?: string) {
  240. console.log("\n===============================================");
  241. console.log("===============================================\n");
  242. if (message) console.log(message);
  243. }