accounts.ts 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import fs from 'fs'
  2. import path from 'path'
  3. import { CLIError } from '@oclif/errors'
  4. import { Keyring } from '@polkadot/keyring'
  5. import { KeyringPair, KeyringPair$Json } from '@polkadot/keyring/types'
  6. import ExitCodes from '../../command-base/ExitCodes'
  7. /**
  8. * Parses the JSON file with account data and KeyPair instance.
  9. *
  10. * @param jsonBackupFilePath - JSON-file path
  11. * @returns KeyPair instance.
  12. */
  13. export function getAccountFromJsonFile(jsonBackupFilePath: string): KeyringPair {
  14. if (!fs.existsSync(jsonBackupFilePath)) {
  15. throw new CLIError('Input file does not exist!', {
  16. exit: ExitCodes.FileError,
  17. })
  18. }
  19. if (path.extname(jsonBackupFilePath) !== '.json') {
  20. throw new CLIError('Invalid input file: File extension should be .json', {
  21. exit: ExitCodes.FileError,
  22. })
  23. }
  24. let accountJsonObj: KeyringPair$Json
  25. try {
  26. const accountJson = fs.readFileSync(jsonBackupFilePath)
  27. accountJsonObj = JSON.parse(accountJson.toString())
  28. } catch (e) {
  29. throw new CLIError('Provided backup file is not valid or cannot be accessed', { exit: ExitCodes.FileError })
  30. }
  31. if (typeof accountJsonObj !== 'object' || accountJsonObj === null) {
  32. throw new CLIError('Provided backup file is not valid', {
  33. exit: ExitCodes.FileError,
  34. })
  35. }
  36. const keyring = configureKeyring()
  37. let account: KeyringPair
  38. try {
  39. // Try adding and retrieving the keys in order to validate that the backup file is correct
  40. keyring.addFromJson(accountJsonObj)
  41. account = keyring.getPair(accountJsonObj.address)
  42. } catch (e) {
  43. throw new CLIError('Provided backup file is not valid', {
  44. exit: ExitCodes.FileError,
  45. })
  46. }
  47. return account
  48. }
  49. /**
  50. * Returns 'Alice' KeyPair instance.
  51. *
  52. * @remarks
  53. * This method should be used in the development mode only.
  54. *
  55. * @returns 'Alice' KeyPair instance.
  56. */
  57. export function getAlicePair(): KeyringPair {
  58. return getAccountFromUri('//Alice')
  59. }
  60. /**
  61. * Create KeyPair instance from the account URI.
  62. *
  63. * @param accountURI - account URI (//Alice)
  64. * @returns KeyPair instance.
  65. */
  66. export function getAccountFromUri(accountURI: string): KeyringPair {
  67. const keyring = configureKeyring()
  68. return keyring.addFromUri(accountURI)
  69. }
  70. /**
  71. * Configures the Keyring with the proper account type.
  72. *
  73. * @returns configured Keyring.
  74. */
  75. function configureKeyring(): Keyring {
  76. return new Keyring({ type: 'sr25519' })
  77. }