balances.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. const { IdentitiesApi } = require('@joystream/storage-runtime-api/identities')
  21. /*
  22. * Bundle API calls related to account balances.
  23. */
  24. class BalancesApi {
  25. static async create(base) {
  26. const ret = new BalancesApi()
  27. ret.base = base
  28. await ret.init()
  29. return ret
  30. }
  31. async init(account_file) {
  32. debug('Init')
  33. }
  34. /*
  35. * Return true/false if the account has the minimum balance given.
  36. */
  37. async hasMinimumBalanceOf(accountId, min) {
  38. const balance = await this.freeBalance(accountId)
  39. if (typeof min === 'number') {
  40. return balance.cmpn(min) >= 0
  41. }
  42. return balance.cmp(min) >= 0
  43. }
  44. /*
  45. * Return the account's current free balance.
  46. */
  47. async freeBalance(accountId) {
  48. const decoded = this.base.identities.keyring.decodeAddress(accountId, true)
  49. return this.base.api.query.balances.freeBalance(decoded)
  50. }
  51. /*
  52. * Return the base transaction fee.
  53. */
  54. baseTransactionFee() {
  55. return this.base.api.consts.transactionPayment.transactionBaseFee
  56. }
  57. /*
  58. * Transfer amount currency from one address to another. The sending
  59. * address must be an unlocked key pair!
  60. */
  61. async transfer(from, to, amount) {
  62. const decode = require('@polkadot/keyring').decodeAddress
  63. const to_decoded = decode(to, true)
  64. const tx = this.base.api.tx.balances.transfer(to_decoded, amount)
  65. return this.base.signAndSend(from, tx)
  66. }
  67. }
  68. module.exports = {
  69. BalancesApi,
  70. }