balances.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /*
  2. * This file is part of the storage node for the Joystream project.
  3. * Copyright (C) 2019 Joystream Contributors
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. 'use strict'
  19. const debug = require('debug')('joystream:runtime:balances')
  20. /*
  21. * Bundle API calls related to account balances.
  22. */
  23. class BalancesApi {
  24. static async create(base) {
  25. const ret = new BalancesApi()
  26. ret.base = base
  27. await BalancesApi.init()
  28. return ret
  29. }
  30. static async init() {
  31. debug('Init')
  32. }
  33. /*
  34. * Return true/false if the account has a minimum spendable balance.
  35. */
  36. async hasMinimumBalanceOf(accountId, min) {
  37. const balance = await this.availableBalance(accountId)
  38. if (typeof min === 'number') {
  39. return balance.cmpn(min) >= 0
  40. }
  41. return balance.cmp(min) >= 0
  42. }
  43. /*
  44. * Return the account's available balance which can be spent.
  45. */
  46. async availableBalance(accountId) {
  47. const decoded = this.base.identities.keyring.decodeAddress(accountId, true)
  48. return (await this.base.api.derive.balances.all(decoded)).availableBalance
  49. }
  50. /*
  51. * Return the base transaction fee.
  52. */
  53. baseTransactionFee() {
  54. return this.base.api.consts.transactionPayment.transactionBaseFee
  55. }
  56. /*
  57. * Transfer amount currency from one address to another. The sending
  58. * address must be an unlocked key pair!
  59. */
  60. async transfer(from, to, amount) {
  61. const decode = require('@polkadot/keyring').decodeAddress
  62. const toDecoded = decode(to, true)
  63. const tx = this.base.api.tx.balances.transfer(toDecoded, amount)
  64. return this.base.signAndSend(from, tx)
  65. }
  66. }
  67. module.exports = {
  68. BalancesApi,
  69. }