Api.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. import BN from 'bn.js'
  2. import { types } from '@joystream/types/'
  3. import { ApiPromise, WsProvider } from '@polkadot/api'
  4. import { QueryableStorageMultiArg, SubmittableExtrinsic, QueryableStorageEntry } from '@polkadot/api/types'
  5. import { formatBalance } from '@polkadot/util'
  6. import { Balance, Moment, BlockNumber } from '@polkadot/types/interfaces'
  7. import { KeyringPair } from '@polkadot/keyring/types'
  8. import { Codec, CodecArg } from '@polkadot/types/types'
  9. import { Option, Vec, UInt } from '@polkadot/types'
  10. import {
  11. AccountSummary,
  12. CouncilInfoObj,
  13. CouncilInfoTuple,
  14. createCouncilInfoObj,
  15. WorkingGroups,
  16. Reward,
  17. GroupMember,
  18. OpeningStatus,
  19. GroupOpeningStage,
  20. GroupOpening,
  21. GroupApplication,
  22. openingPolicyUnstakingPeriodsKeys,
  23. UnstakingPeriods,
  24. StakingPolicyUnstakingPeriodKey,
  25. } from './Types'
  26. import { DeriveBalancesAll } from '@polkadot/api-derive/types'
  27. import { CLIError } from '@oclif/errors'
  28. import ExitCodes from './ExitCodes'
  29. import {
  30. Worker,
  31. WorkerId,
  32. RoleStakeProfile,
  33. Opening as WGOpening,
  34. Application as WGApplication,
  35. } from '@joystream/types/working-group'
  36. import {
  37. Opening,
  38. Application,
  39. OpeningStage,
  40. ApplicationStageKeys,
  41. ApplicationId,
  42. OpeningId,
  43. StakingPolicy,
  44. } from '@joystream/types/hiring'
  45. import { MemberId, Membership } from '@joystream/types/members'
  46. import { RewardRelationship, RewardRelationshipId } from '@joystream/types/recurring-rewards'
  47. import { Stake, StakeId } from '@joystream/types/stake'
  48. import { InputValidationLengthConstraint } from '@joystream/types/common'
  49. export const DEFAULT_API_URI = 'ws://localhost:9944/'
  50. const DEFAULT_DECIMALS = new BN(12)
  51. // Mapping of working group to api module
  52. export const apiModuleByGroup: { [key in WorkingGroups]: string } = {
  53. [WorkingGroups.StorageProviders]: 'storageWorkingGroup',
  54. }
  55. // Api wrapper for handling most common api calls and allowing easy API implementation switch in the future
  56. export default class Api {
  57. private _api: ApiPromise
  58. private constructor(originalApi: ApiPromise) {
  59. this._api = originalApi
  60. }
  61. public getOriginalApi(): ApiPromise {
  62. return this._api
  63. }
  64. private static async initApi(apiUri: string = DEFAULT_API_URI): Promise<ApiPromise> {
  65. const wsProvider: WsProvider = new WsProvider(apiUri)
  66. const api = await ApiPromise.create({ provider: wsProvider, types })
  67. // Initializing some api params based on pioneer/packages/react-api/Api.tsx
  68. const [properties] = await Promise.all([api.rpc.system.properties()])
  69. const tokenSymbol = properties.tokenSymbol.unwrapOr('DEV').toString()
  70. const tokenDecimals = properties.tokenDecimals.unwrapOr(DEFAULT_DECIMALS).toNumber()
  71. // formatBlanace config
  72. formatBalance.setDefaults({
  73. decimals: tokenDecimals,
  74. unit: tokenSymbol,
  75. })
  76. return api
  77. }
  78. static async create(apiUri: string = DEFAULT_API_URI): Promise<Api> {
  79. const originalApi: ApiPromise = await Api.initApi(apiUri)
  80. return new Api(originalApi)
  81. }
  82. private queryMultiOnce(queries: Parameters<typeof ApiPromise.prototype.queryMulti>[0]): Promise<Codec[]> {
  83. return new Promise((resolve, reject) => {
  84. let unsub: () => void
  85. this._api
  86. .queryMulti(queries, (res) => {
  87. // unsub should already be set at this point
  88. if (!unsub) {
  89. reject(new CLIError('API queryMulti issue - unsub method not set!', { exit: ExitCodes.ApiError }))
  90. }
  91. unsub()
  92. resolve(res)
  93. })
  94. .then((unsubscribe) => (unsub = unsubscribe))
  95. .catch((e) => reject(e))
  96. })
  97. }
  98. async getAccountsBalancesInfo(accountAddresses: string[]): Promise<DeriveBalancesAll[]> {
  99. const accountsBalances: DeriveBalancesAll[] = await Promise.all(
  100. accountAddresses.map((addr) => this._api.derive.balances.all(addr))
  101. )
  102. return accountsBalances
  103. }
  104. // Get on-chain data related to given account.
  105. // For now it's just account balances
  106. async getAccountSummary(accountAddresses: string): Promise<AccountSummary> {
  107. const balances: DeriveBalancesAll = (await this.getAccountsBalancesInfo([accountAddresses]))[0]
  108. // TODO: Some more information can be fetched here in the future
  109. return { balances }
  110. }
  111. async getCouncilInfo(): Promise<CouncilInfoObj> {
  112. const queries: { [P in keyof CouncilInfoObj]: QueryableStorageMultiArg<'promise'> } = {
  113. activeCouncil: this._api.query.council.activeCouncil,
  114. termEndsAt: this._api.query.council.termEndsAt,
  115. autoStart: this._api.query.councilElection.autoStart,
  116. newTermDuration: this._api.query.councilElection.newTermDuration,
  117. candidacyLimit: this._api.query.councilElection.candidacyLimit,
  118. councilSize: this._api.query.councilElection.councilSize,
  119. minCouncilStake: this._api.query.councilElection.minCouncilStake,
  120. minVotingStake: this._api.query.councilElection.minVotingStake,
  121. announcingPeriod: this._api.query.councilElection.announcingPeriod,
  122. votingPeriod: this._api.query.councilElection.votingPeriod,
  123. revealingPeriod: this._api.query.councilElection.revealingPeriod,
  124. round: this._api.query.councilElection.round,
  125. stage: this._api.query.councilElection.stage,
  126. }
  127. const results: CouncilInfoTuple = (await this.queryMultiOnce(Object.values(queries))) as CouncilInfoTuple
  128. return createCouncilInfoObj(...results)
  129. }
  130. async estimateFee(account: KeyringPair, tx: SubmittableExtrinsic<'promise'>): Promise<Balance> {
  131. const paymentInfo = await tx.paymentInfo(account)
  132. return paymentInfo.partialFee
  133. }
  134. createTransferTx(recipient: string, amount: BN) {
  135. return this._api.tx.balances.transfer(recipient, amount)
  136. }
  137. // Working groups
  138. // TODO: This is a lot of repeated logic from "/pioneer/joy-utils/transport"
  139. // It will be refactored to "joystream-js" soon
  140. async entriesByIds<IDType extends UInt, ValueType extends Codec>(
  141. apiMethod: QueryableStorageEntry<'promise'>,
  142. firstKey?: CodecArg // First key in case of double maps
  143. ): Promise<[IDType, ValueType][]> {
  144. const entries: [IDType, ValueType][] = (await apiMethod.entries<ValueType>(firstKey)).map(([storageKey, value]) => [
  145. // If double-map (first key is provided), we map entries by second key
  146. storageKey.args[firstKey !== undefined ? 1 : 0] as IDType,
  147. value,
  148. ])
  149. return entries.sort((a, b) => a[0].toNumber() - b[0].toNumber())
  150. }
  151. protected async blockHash(height: number): Promise<string> {
  152. const blockHash = await this._api.rpc.chain.getBlockHash(height)
  153. return blockHash.toString()
  154. }
  155. protected async blockTimestamp(height: number): Promise<Date> {
  156. const blockTime = (await this._api.query.timestamp.now.at(await this.blockHash(height))) as Moment
  157. return new Date(blockTime.toNumber())
  158. }
  159. protected workingGroupApiQuery(group: WorkingGroups) {
  160. const module = apiModuleByGroup[group]
  161. return this._api.query[module]
  162. }
  163. protected async membershipById(memberId: MemberId): Promise<Membership | null> {
  164. const profile = (await this._api.query.members.membershipById(memberId)) as Membership
  165. // Can't just use profile.isEmpty because profile.suspended is Bool (which isEmpty method always returns false)
  166. return profile.handle.isEmpty ? null : profile
  167. }
  168. async groupLead(group: WorkingGroups): Promise<GroupMember | null> {
  169. const optLeadId = (await this.workingGroupApiQuery(group).currentLead()) as Option<WorkerId>
  170. if (!optLeadId.isSome) {
  171. return null
  172. }
  173. const leadWorkerId = optLeadId.unwrap()
  174. const leadWorker = await this.workerByWorkerId(group, leadWorkerId.toNumber())
  175. return await this.parseGroupMember(leadWorkerId, leadWorker)
  176. }
  177. protected async stakeValue(stakeId: StakeId): Promise<Balance> {
  178. const stake = await this._api.query.stake.stakes<Stake>(stakeId)
  179. return stake.value
  180. }
  181. protected async workerStake(stakeProfile: RoleStakeProfile): Promise<Balance> {
  182. return this.stakeValue(stakeProfile.stake_id)
  183. }
  184. protected async workerReward(relationshipId: RewardRelationshipId): Promise<Reward> {
  185. const rewardRelationship = await this._api.query.recurringRewards.rewardRelationships<RewardRelationship>(
  186. relationshipId
  187. )
  188. return {
  189. totalRecieved: rewardRelationship.total_reward_received,
  190. value: rewardRelationship.amount_per_payout,
  191. interval: rewardRelationship.payout_interval.unwrapOr(undefined)?.toNumber(),
  192. nextPaymentBlock: rewardRelationship.next_payment_at_block.unwrapOr(new BN(0)).toNumber(),
  193. }
  194. }
  195. protected async parseGroupMember(id: WorkerId, worker: Worker): Promise<GroupMember> {
  196. const roleAccount = worker.role_account_id
  197. const memberId = worker.member_id
  198. const profile = await this.membershipById(memberId)
  199. if (!profile) {
  200. throw new Error(`Group member profile not found! (member id: ${memberId.toNumber()})`)
  201. }
  202. let stake: Balance | undefined
  203. if (worker.role_stake_profile && worker.role_stake_profile.isSome) {
  204. stake = await this.workerStake(worker.role_stake_profile.unwrap())
  205. }
  206. let reward: Reward | undefined
  207. if (worker.reward_relationship && worker.reward_relationship.isSome) {
  208. reward = await this.workerReward(worker.reward_relationship.unwrap())
  209. }
  210. return {
  211. workerId: id,
  212. roleAccount,
  213. memberId,
  214. profile,
  215. stake,
  216. reward,
  217. }
  218. }
  219. async workerByWorkerId(group: WorkingGroups, workerId: number): Promise<Worker> {
  220. const nextId = await this.workingGroupApiQuery(group).nextWorkerId<WorkerId>()
  221. // This is chain specfic, but if next id is still 0, it means no workers have been added yet
  222. if (workerId < 0 || workerId >= nextId.toNumber()) {
  223. throw new CLIError('Invalid worker id!')
  224. }
  225. const worker = await this.workingGroupApiQuery(group).workerById<Worker>(workerId)
  226. if (worker.isEmpty) {
  227. throw new CLIError('This worker is not active anymore')
  228. }
  229. return worker
  230. }
  231. async groupMember(group: WorkingGroups, workerId: number) {
  232. const worker = await this.workerByWorkerId(group, workerId)
  233. return await this.parseGroupMember(this._api.createType('WorkerId', workerId), worker)
  234. }
  235. async groupMembers(group: WorkingGroups): Promise<GroupMember[]> {
  236. const workerEntries = await this.entriesByIds<WorkerId, Worker>(this.workingGroupApiQuery(group).workerById)
  237. const groupMembers: GroupMember[] = await Promise.all(
  238. workerEntries.map(([id, worker]) => this.parseGroupMember(id, worker))
  239. )
  240. return groupMembers.reverse() // Sort by newest
  241. }
  242. async openingsByGroup(group: WorkingGroups): Promise<GroupOpening[]> {
  243. let openings: GroupOpening[] = []
  244. const nextId = await this.workingGroupApiQuery(group).nextOpeningId<OpeningId>()
  245. // This is chain specfic, but if next id is still 0, it means no openings have been added yet
  246. if (!nextId.eq(0)) {
  247. const ids = Array.from(Array(nextId.toNumber()).keys()).reverse() // Sort by newest
  248. openings = await Promise.all(ids.map((id) => this.groupOpening(group, id)))
  249. }
  250. return openings
  251. }
  252. protected async hiringOpeningById(id: number | OpeningId): Promise<Opening> {
  253. const result = await this._api.query.hiring.openingById<Opening>(id)
  254. return result
  255. }
  256. protected async hiringApplicationById(id: number | ApplicationId): Promise<Application> {
  257. const result = await this._api.query.hiring.applicationById<Application>(id)
  258. return result
  259. }
  260. async wgApplicationById(group: WorkingGroups, wgApplicationId: number): Promise<WGApplication> {
  261. const nextAppId = await this.workingGroupApiQuery(group).nextApplicationId<ApplicationId>()
  262. if (wgApplicationId < 0 || wgApplicationId >= nextAppId.toNumber()) {
  263. throw new CLIError('Invalid working group application ID!')
  264. }
  265. const result = await this.workingGroupApiQuery(group).applicationById<WGApplication>(wgApplicationId)
  266. return result
  267. }
  268. protected async parseApplication(wgApplicationId: number, wgApplication: WGApplication): Promise<GroupApplication> {
  269. const appId = wgApplication.application_id
  270. const application = await this.hiringApplicationById(appId)
  271. const { active_role_staking_id: roleStakingId, active_application_staking_id: appStakingId } = application
  272. return {
  273. wgApplicationId,
  274. applicationId: appId.toNumber(),
  275. wgOpeningId: wgApplication.opening_id.toNumber(),
  276. member: await this.membershipById(wgApplication.member_id),
  277. roleAccout: wgApplication.role_account_id,
  278. stakes: {
  279. application: appStakingId.isSome ? (await this.stakeValue(appStakingId.unwrap())).toNumber() : 0,
  280. role: roleStakingId.isSome ? (await this.stakeValue(roleStakingId.unwrap())).toNumber() : 0,
  281. },
  282. humanReadableText: application.human_readable_text.toString(),
  283. stage: application.stage.type as ApplicationStageKeys,
  284. }
  285. }
  286. async groupApplication(group: WorkingGroups, wgApplicationId: number): Promise<GroupApplication> {
  287. const wgApplication = await this.wgApplicationById(group, wgApplicationId)
  288. return await this.parseApplication(wgApplicationId, wgApplication)
  289. }
  290. protected async groupOpeningApplications(group: WorkingGroups, wgOpeningId: number): Promise<GroupApplication[]> {
  291. const wgApplicationEntries = await this.entriesByIds<ApplicationId, WGApplication>(
  292. this.workingGroupApiQuery(group).applicationById
  293. )
  294. return Promise.all(
  295. wgApplicationEntries
  296. .filter(([, /* id */ wgApplication]) => wgApplication.opening_id.eqn(wgOpeningId))
  297. .map(([id, wgApplication]) => this.parseApplication(id.toNumber(), wgApplication))
  298. )
  299. }
  300. async groupOpening(group: WorkingGroups, wgOpeningId: number): Promise<GroupOpening> {
  301. const nextId = ((await this.workingGroupApiQuery(group).nextOpeningId()) as OpeningId).toNumber()
  302. if (wgOpeningId < 0 || wgOpeningId >= nextId) {
  303. throw new CLIError('Invalid working group opening ID!')
  304. }
  305. const groupOpening = await this.workingGroupApiQuery(group).openingById<WGOpening>(wgOpeningId)
  306. const openingId = groupOpening.hiring_opening_id.toNumber()
  307. const opening = await this.hiringOpeningById(openingId)
  308. const applications = await this.groupOpeningApplications(group, wgOpeningId)
  309. const stage = await this.parseOpeningStage(opening.stage)
  310. const type = groupOpening.opening_type
  311. const { application_staking_policy: applSP, role_staking_policy: roleSP } = opening
  312. const stakes = {
  313. application: applSP.unwrapOr(undefined),
  314. role: roleSP.unwrapOr(undefined),
  315. }
  316. const unstakingPeriod = (period: Option<BlockNumber>) => period.unwrapOr(new BN(0)).toNumber()
  317. const spUnstakingPeriod = (sp: Option<StakingPolicy>, key: StakingPolicyUnstakingPeriodKey) =>
  318. sp.isSome ? unstakingPeriod(sp.unwrap()[key]) : 0
  319. const unstakingPeriods: Partial<UnstakingPeriods> = {
  320. 'review_period_expired_application_stake_unstaking_period_length': spUnstakingPeriod(
  321. applSP,
  322. 'review_period_expired_unstaking_period_length'
  323. ),
  324. 'crowded_out_application_stake_unstaking_period_length': spUnstakingPeriod(
  325. applSP,
  326. 'crowded_out_unstaking_period_length'
  327. ),
  328. 'review_period_expired_role_stake_unstaking_period_length': spUnstakingPeriod(
  329. roleSP,
  330. 'review_period_expired_unstaking_period_length'
  331. ),
  332. 'crowded_out_role_stake_unstaking_period_length': spUnstakingPeriod(
  333. roleSP,
  334. 'crowded_out_unstaking_period_length'
  335. ),
  336. }
  337. openingPolicyUnstakingPeriodsKeys.forEach((key) => {
  338. unstakingPeriods[key] = unstakingPeriod(groupOpening.policy_commitment[key])
  339. })
  340. return {
  341. wgOpeningId,
  342. openingId,
  343. opening,
  344. stage,
  345. stakes,
  346. applications,
  347. type,
  348. unstakingPeriods: unstakingPeriods as UnstakingPeriods,
  349. }
  350. }
  351. async parseOpeningStage(stage: OpeningStage): Promise<GroupOpeningStage> {
  352. let status: OpeningStatus | undefined, stageBlock: number | undefined, stageDate: Date | undefined
  353. if (stage.isOfType('WaitingToBegin')) {
  354. const stageData = stage.asType('WaitingToBegin')
  355. const currentBlockNumber = (await this._api.derive.chain.bestNumber()).toNumber()
  356. const expectedBlockTime = (this._api.consts.babe.expectedBlockTime as Moment).toNumber()
  357. status = OpeningStatus.WaitingToBegin
  358. stageBlock = stageData.begins_at_block.toNumber()
  359. stageDate = new Date(Date.now() + (stageBlock - currentBlockNumber) * expectedBlockTime)
  360. }
  361. if (stage.isOfType('Active')) {
  362. const stageData = stage.asType('Active')
  363. const substage = stageData.stage
  364. if (substage.isOfType('AcceptingApplications')) {
  365. status = OpeningStatus.AcceptingApplications
  366. stageBlock = substage.asType('AcceptingApplications').started_accepting_applicants_at_block.toNumber()
  367. }
  368. if (substage.isOfType('ReviewPeriod')) {
  369. status = OpeningStatus.InReview
  370. stageBlock = substage.asType('ReviewPeriod').started_review_period_at_block.toNumber()
  371. }
  372. if (substage.isOfType('Deactivated')) {
  373. status = substage.asType('Deactivated').cause.isOfType('Filled')
  374. ? OpeningStatus.Complete
  375. : OpeningStatus.Cancelled
  376. stageBlock = substage.asType('Deactivated').deactivated_at_block.toNumber()
  377. }
  378. if (stageBlock) {
  379. stageDate = new Date(await this.blockTimestamp(stageBlock))
  380. }
  381. }
  382. return {
  383. status: status || OpeningStatus.Unknown,
  384. block: stageBlock,
  385. date: stageDate,
  386. }
  387. }
  388. async getMemberIdsByControllerAccount(address: string): Promise<MemberId[]> {
  389. const ids = await this._api.query.members.memberIdsByControllerAccountId<Vec<MemberId>>(address)
  390. return ids.toArray()
  391. }
  392. async workerExitRationaleConstraint(group: WorkingGroups): Promise<InputValidationLengthConstraint> {
  393. return await this.workingGroupApiQuery(group).workerExitRationaleText<InputValidationLengthConstraint>()
  394. }
  395. }