roles.js 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  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:roles');
  20. const { Null, u64 } = require('@polkadot/types');
  21. const { _ } = require('lodash');
  22. /*
  23. * Add role related functionality to the substrate API.
  24. */
  25. class RolesApi
  26. {
  27. static async create(base)
  28. {
  29. const ret = new RolesApi();
  30. ret.base = base;
  31. await ret.init();
  32. return ret;
  33. }
  34. async init()
  35. {
  36. debug('Init');
  37. // Constants
  38. this.ROLE_STORAGE = 'StorageProvider'; // new u64(0x00);
  39. }
  40. /*
  41. * Raises errors if the given account ID is not valid for staking as the given
  42. * role. The role should be one of the ROLE_* constants above.
  43. */
  44. async checkAccountForStaking(accountId, role)
  45. {
  46. role = role || this.ROLE_STORAGE;
  47. if (!await this.base.identities.isMember(accountId)) {
  48. const msg = `Account with id "${accountId}" is not a member!`;
  49. debug(msg);
  50. throw new Error(msg);
  51. }
  52. if (!await this.hasBalanceForRoleStaking(accountId, role)) {
  53. const msg = `Account with id "${accountId}" does not have sufficient free balance for role staking!`;
  54. debug(msg);
  55. throw new Error(msg);
  56. }
  57. debug(`Account with id "${accountId}" is a member with sufficient free balance, able to proceed.`);
  58. return true;
  59. }
  60. /*
  61. * Returns the required balance for staking for a role.
  62. */
  63. async requiredBalanceForRoleStaking(role)
  64. {
  65. const params = await this.base.api.query.actors.parameters(role);
  66. if (params.isNone) {
  67. throw new Error(`Role ${role} is not defined!`);
  68. }
  69. const result = params.raw.min_stake
  70. .add(params.raw.entry_request_fee)
  71. .add(await this.base.balances.baseTransactionFee());
  72. return result;
  73. }
  74. /*
  75. * Returns true/false if the given account has the balance required for
  76. * staking for the given role.
  77. */
  78. async hasBalanceForRoleStaking(accountId, role)
  79. {
  80. const required = await this.requiredBalanceForRoleStaking(role);
  81. return await this.base.balances.hasMinimumBalanceOf(accountId, required);
  82. }
  83. /*
  84. * Transfer enough funds to allow the recipient to stake for the given role.
  85. */
  86. async transferForStaking(from, to, role)
  87. {
  88. const required = await this.requiredBalanceForRoleStaking(role);
  89. return await this.base.balances.transfer(from, to, required);
  90. }
  91. /*
  92. * Return current accounts holding a role.
  93. */
  94. async accountIdsByRole(role)
  95. {
  96. const ids = await this.base.api.query.actors.accountIdsByRole(role);
  97. return ids.map(id => id.toString());
  98. }
  99. /*
  100. * Returns the number of slots available for a role
  101. */
  102. async availableSlotsForRole(role)
  103. {
  104. let params = await this.base.api.query.actors.parameters(role);
  105. if (params.isNone) {
  106. throw new Error(`Role ${role} is not defined!`);
  107. }
  108. params = params.unwrap();
  109. const slots = params.max_actors;
  110. const active = await this.accountIdsByRole(role);
  111. return (slots.subn(active.length)).toNumber();
  112. }
  113. /*
  114. * Send a role application.
  115. * - The role account must not be a member, but have sufficient funds for
  116. * staking.
  117. * - The member account must be a member.
  118. *
  119. * After sending this application, the member account will have role request
  120. * in the 'My Requests' tab of the app.
  121. */
  122. async applyForRole(roleAccountId, role, memberAccountId)
  123. {
  124. const memberId = await this.base.identities.firstMemberIdOf(memberAccountId);
  125. if (memberId == undefined) {
  126. throw new Error('Account is not a member!');
  127. }
  128. const tx = this.base.api.tx.actors.roleEntryRequest(role, memberId);
  129. return await this.base.signAndSend(roleAccountId, tx);
  130. }
  131. /*
  132. * Check whether the given role is occupying the given role.
  133. */
  134. async checkForRole(roleAccountId, role)
  135. {
  136. const actor = await this.base.api.query.actors.actorByAccountId(roleAccountId);
  137. return !_.isEqual(actor.raw, new Null());
  138. }
  139. /*
  140. * Same as checkForRole(), but if the account is not currently occupying the
  141. * role, wait for the appropriate `actors.Staked` event to be emitted.
  142. */
  143. async waitForRole(roleAccountId, role)
  144. {
  145. if (await this.checkForRole(roleAccountId, role)) {
  146. return true;
  147. }
  148. return new Promise((resolve, reject) => {
  149. this.base.waitForEvent('actors', 'Staked').then((values) => {
  150. const name = values[0][0];
  151. const payload = values[0][1];
  152. if (payload.AccountId == roleAccountId) {
  153. resolve(true);
  154. } else {
  155. // reject() ?
  156. }
  157. });
  158. });
  159. }
  160. }
  161. module.exports = {
  162. RolesApi: RolesApi,
  163. }