balances.js 2.3 KB

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