Api.ts 18 KB

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