solanaCli.ts 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import { Language } from './getLanguage';
  2. import {
  3. hasCommand,
  4. readStdout,
  5. spawnCommand,
  6. waitForCommand,
  7. } from './runCommands';
  8. export async function detectSolanaVersion(language: Language): Promise<string> {
  9. const hasSolanaCli = await hasCommand('solana');
  10. if (!hasSolanaCli) {
  11. throw new Error(
  12. language.errors.solanaCliNotFound.replace('$command', 'solana')
  13. );
  14. }
  15. const child = spawnCommand('solana', ['--version']);
  16. const [stdout] = await Promise.all([
  17. readStdout(child),
  18. waitForCommand(child),
  19. ]);
  20. const version = stdout.join('').match(/(\d+\.\d+\.\d+)/)?.[1];
  21. return version!;
  22. }
  23. export async function patchSolanaDependencies(
  24. targetDirectory: string,
  25. solanaVersion: string
  26. ): Promise<void> {
  27. const patchMap: Record<string, string[]> = {
  28. '1.17': ['-p ahash@0.8 --precise 0.8.6'],
  29. };
  30. const patches = patchMap[solanaVersion] ?? [];
  31. await Promise.all(
  32. patches.map((patch) =>
  33. waitForCommand(
  34. spawnCommand('cargo', ['update', ...patch.split(' ')], {
  35. cwd: targetDirectory,
  36. })
  37. )
  38. )
  39. );
  40. }
  41. export function toMinorSolanaVersion(
  42. language: Language,
  43. version: string
  44. ): string {
  45. const validVersion = version.match(/^(\d+\.\d+)/);
  46. if (!validVersion) {
  47. throw new Error(
  48. language.errors.invalidSolanaVersion.replace('$version', version)
  49. );
  50. }
  51. return validVersion[0];
  52. }
  53. export async function generateKeypair(
  54. language: Language,
  55. outfile: string
  56. ): Promise<string> {
  57. const hasSolanaKeygen = await hasCommand('solana-keygen');
  58. if (!hasSolanaKeygen) {
  59. throw new Error(
  60. language.errors.solanaCliNotFound.replace('$command', 'solana-keygen')
  61. );
  62. }
  63. // Run the solana-keygen command to generate a new keypair.
  64. const child = spawnCommand('solana-keygen', [
  65. 'new',
  66. '--no-bip39-passphrase',
  67. '--outfile',
  68. outfile,
  69. ]);
  70. // Wait for the command to finish and read the stdout.
  71. const [stdout] = await Promise.all([
  72. readStdout(child),
  73. waitForCommand(child),
  74. ]);
  75. // Update the render context with the generated address.
  76. const address = stdout.join('').match(/pubkey: (\w+)/)?.[1];
  77. if (!address) {
  78. throw new Error(language.errors.solanaKeygenFailed);
  79. }
  80. return address;
  81. }