transferTokens.ts 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import BN from 'bn.js'
  2. import AccountsCommandBase from '../../base/AccountsCommandBase'
  3. import chalk from 'chalk'
  4. import ExitCodes from '../../ExitCodes'
  5. import { formatBalance } from '@polkadot/util'
  6. import { Hash } from '@polkadot/types/interfaces'
  7. import { NamedKeyringPair } from '../../Types'
  8. import { checkBalance, validateAddress } from '../../helpers/validation'
  9. type AccountTransferArgs = {
  10. recipient: string
  11. amount: string
  12. }
  13. export default class AccountTransferTokens extends AccountsCommandBase {
  14. static description = 'Transfer tokens from currently choosen account'
  15. static args = [
  16. {
  17. name: 'recipient',
  18. required: true,
  19. description: 'Address of the transfer recipient',
  20. },
  21. {
  22. name: 'amount',
  23. required: true,
  24. description: 'Amount of tokens to transfer',
  25. },
  26. ]
  27. async run() {
  28. const args: AccountTransferArgs = this.parse(AccountTransferTokens).args as AccountTransferArgs
  29. const selectedAccount: NamedKeyringPair = await this.getRequiredSelectedAccount()
  30. const amountBN: BN = new BN(args.amount)
  31. // Initial validation
  32. validateAddress(args.recipient, 'Invalid recipient address')
  33. const accBalances = (await this.getApi().getAccountsBalancesInfo([selectedAccount.address]))[0]
  34. checkBalance(accBalances, amountBN)
  35. await this.requestAccountDecoding(selectedAccount)
  36. this.log(chalk.white('Estimating fee...'))
  37. const tx = await this.getApi().createTransferTx(args.recipient, amountBN)
  38. let estimatedFee: BN
  39. try {
  40. estimatedFee = await this.getApi().estimateFee(selectedAccount, tx)
  41. } catch (e) {
  42. this.error('Could not estimate the fee.', { exit: ExitCodes.UnexpectedException })
  43. }
  44. const totalAmount: BN = amountBN.add(estimatedFee)
  45. this.log(chalk.white('Estimated fee:', formatBalance(estimatedFee)))
  46. this.log(chalk.white('Total transfer amount:', formatBalance(totalAmount)))
  47. checkBalance(accBalances, totalAmount)
  48. await this.requireConfirmation('Do you confirm the transfer?')
  49. try {
  50. const txHash: Hash = await tx.signAndSend(selectedAccount)
  51. this.log(chalk.greenBright('Transaction succesfully sent!'))
  52. this.log(chalk.white('Hash:', txHash.toString()))
  53. } catch (e) {
  54. this.error('Could not send the transaction.', { exit: ExitCodes.UnexpectedException })
  55. }
  56. }
  57. }