api.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. import { ApiPromise } from '@polkadot/api'
  2. import moment from 'moment'
  3. // types
  4. import { AccountBalance, ElectionInfo, Round, ProposalDetail } from './types'
  5. import { Option, u32, u64, Vec } from '@polkadot/types'
  6. import type { Codec, Observable } from '@polkadot/types/types'
  7. import {
  8. AccountId,
  9. AccountInfo,
  10. AccountData,
  11. Balance,
  12. BlockNumber,
  13. EraIndex,
  14. EventRecord,
  15. Hash,
  16. Moment,
  17. } from '@polkadot/types/interfaces'
  18. import { SignedBlock } from '@polkadot/types/interfaces/runtime'
  19. import { PostId, ThreadId } from '@joystream/types/common'
  20. import { CategoryId, Category, Thread, Post } from '@joystream/types/forum'
  21. import {
  22. ElectionStage,
  23. ElectionStake,
  24. SealedVote,
  25. Seats,
  26. } from '@joystream/types/council'
  27. import { Entity, EntityId } from '@joystream/types/content-directory'
  28. import { ContentId, DataObject } from '@joystream/types/media'
  29. import { MemberId, Membership } from '@joystream/types/members'
  30. import { Mint, MintId } from '@joystream/types/mint'
  31. import {
  32. Proposal,
  33. ProposalId,
  34. ProposalDetails,
  35. DiscussionPost,
  36. SpendingParams,
  37. VoteKind,
  38. } from '@joystream/types/proposals'
  39. import { Stake, StakeId } from '@joystream/types/stake'
  40. import {
  41. RewardRelationship,
  42. RewardRelationshipId,
  43. } from '@joystream/types/recurring-rewards'
  44. import { WorkerId, Worker } from '@joystream/types/working-group'
  45. // blocks
  46. export const getBlock = (api: ApiPromise, hash: Hash): Promise<SignedBlock> =>
  47. api.rpc.chain.getBlock(hash)
  48. export const getBlockHash = (
  49. api: ApiPromise,
  50. block: BlockNumber | number
  51. ): Promise<Hash> => {
  52. try {
  53. return api.rpc.chain.getBlockHash(block)
  54. } catch (e) {
  55. console.error(`BlockHash: ${block}`)
  56. //const head =
  57. //return api.query.system.blockHash(head)
  58. //return api.query.system.parentHash()
  59. return api.rpc.chain.getFinalizedHead()
  60. }
  61. }
  62. export const getTimestamp = async (
  63. api: ApiPromise,
  64. hash: Hash
  65. ): Promise<number> =>
  66. moment.utc((await api.query.timestamp.now.at(hash)).toNumber()).valueOf()
  67. export const getIssuance = (api: ApiPromise, hash: Hash): Promise<Balance> =>
  68. api.query.balances.totalIssuance.at(hash)
  69. export const getEvents = (
  70. api: ApiPromise,
  71. hash: Hash
  72. ): Promise<Vec<EventRecord>> => api.query.system.events.at(hash)
  73. export const getEra = async (api: ApiPromise, hash: Hash): Promise<number> =>
  74. Number(api.query.staking.currentEra.at(hash))
  75. export const getEraStake = async (
  76. api: ApiPromise,
  77. hash: Hash,
  78. era: EraIndex | number
  79. ): Promise<number> =>
  80. (await api.query.staking.erasTotalStake.at(hash, era)).toNumber()
  81. // council
  82. export const getCouncil = (api: ApiPromise, hash: Hash): Promise<Seats> =>
  83. api.query.council.activeCouncil.at(hash)
  84. export const getCouncils = async (
  85. api: ApiPromise,
  86. head: number
  87. ): Promise<Round[]> => {
  88. // durations: [ announcing, voting, revealing, term, sum ]
  89. // each chain starts with an election (duration: d[0]+d[1]+d[2])
  90. // elections are repeated if not enough apply (round increments though)
  91. // first term starts at begin of d[3] or some electionDuration later
  92. // term lasts till the end of the next successful election
  93. // `council.termEndsAt` returns the end of the current round
  94. // to determine term starts check every electionDuration blocks
  95. const d: number[] = await getCouncilElectionDurations(
  96. api,
  97. await getBlockHash(api, 1)
  98. )
  99. const electionDuration = d[0] + d[1] + d[2]
  100. const starts: number[] = []
  101. let lastEnd = 1
  102. for (let block = lastEnd; block < head; block += electionDuration) {
  103. const hash = await getBlockHash(api, block)
  104. const end = Number(await api.query.council.termEndsAt.at(hash))
  105. if (end === lastEnd) continue
  106. lastEnd = end
  107. starts.push(end - d[3] + 1)
  108. }
  109. // index by round: each start is the end of the previous term
  110. const rounds: { [key: number]: Round } = {}
  111. await Promise.all(
  112. starts.map(async (start: number, index: number) => {
  113. const hash = await getBlockHash(api, start)
  114. const round = await getCouncilRound(api, hash)
  115. const isLast = index === starts.length - 1
  116. const end = isLast ? start + d[4] : starts[index + 1] - 1
  117. rounds[round] = { start, round, end }
  118. })
  119. )
  120. return Object.values(rounds)
  121. }
  122. export const getCouncilRound = async (
  123. api: ApiPromise,
  124. hash: Hash
  125. ): Promise<number> =>
  126. ((await api.query.councilElection.round.at(hash)) as u32).toNumber()
  127. export const getCouncilElectionStage = async (
  128. api: ApiPromise,
  129. hash: Hash
  130. ): Promise<ElectionStage> =>
  131. (await api.query.councilElection.stage.at(hash)) as ElectionStage
  132. export const getCouncilTermEnd = async (
  133. api: ApiPromise,
  134. hash: Hash
  135. ): Promise<number> =>
  136. ((await api.query.council.termEndsAt.at(hash)) as BlockNumber).toNumber()
  137. export const getCouncilElectionStatus = async (
  138. api: ApiPromise,
  139. hash: Hash
  140. ): Promise<ElectionInfo> => {
  141. const durations = await getCouncilElectionDurations(api, hash)
  142. const round = await getCouncilRound(api, hash)
  143. const stage: ElectionStage = await getCouncilElectionStage(api, hash)
  144. const stageEndsAt: number = Number(stage.value as BlockNumber)
  145. const termEndsAt: number = await getCouncilTermEnd(api, hash)
  146. return { round, stageEndsAt, termEndsAt, stage, durations }
  147. }
  148. export const getCouncilSize = async (
  149. api: ApiPromise,
  150. hash: Hash
  151. ): Promise<number> =>
  152. ((await api.query.councilElection.councilSize.at(hash)) as u32).toNumber()
  153. export const getCouncilApplicants = (
  154. api: ApiPromise,
  155. hash: Hash
  156. ): Promise<Vec<AccountId>> => api.query.councilElection.applicants.at(hash)
  157. export const getCouncilApplicantStakes = (
  158. api: ApiPromise,
  159. hash: Hash,
  160. applicant: AccountId
  161. ): Promise<ElectionStake> =>
  162. api.query.councilElection.applicantStakes.at(hash, applicant)
  163. export const getCouncilCommitments = (
  164. api: ApiPromise,
  165. hash: Hash
  166. ): Promise<Vec<Hash>> => api.query.councilElection.commitments.at(hash)
  167. export const getCouncilPayoutInterval = (
  168. api: ApiPromise,
  169. hash: Hash
  170. ): Promise<Option<BlockNumber>> => api.query.council.payoutInterval.at(hash)
  171. export const getCouncilPayout = (
  172. api: ApiPromise,
  173. hash: Hash
  174. ): Promise<Balance> => api.query.council.amountPerPayout.at(hash)
  175. const getCouncilElectionPeriod = (
  176. api: ApiPromise,
  177. hash: Hash,
  178. period: string
  179. ): Promise<BlockNumber> => api.query.councilElection[period].at(hash)
  180. export const getCouncilElectionDurations = async (
  181. api: ApiPromise,
  182. hash: Hash
  183. ): Promise<number[]> => {
  184. const periods = [
  185. 'announcingPeriod',
  186. 'votingPeriod',
  187. 'revealingPeriod',
  188. 'newTermDuration',
  189. ]
  190. let durations = await Promise.all(
  191. periods.map((period: string) => getCouncilElectionPeriod(api, hash, period))
  192. ).then((d) => d.map((block: BlockNumber) => block.toNumber()))
  193. durations.push(durations[0] + durations[1] + durations[2] + durations[3])
  194. return durations
  195. }
  196. // working groups
  197. export const getNextWorker = async (
  198. api: ApiPromise,
  199. group: string,
  200. hash: Hash
  201. ): Promise<number> =>
  202. ((await api.query[group].nextWorkerId.at(hash)) as WorkerId).toNumber()
  203. export const getWorker = (
  204. api: ApiPromise,
  205. group: string,
  206. hash: Hash,
  207. id: number
  208. ): Promise<Worker> => api.query[group].workerById.at(hash, id)
  209. export const getWorkers = (
  210. api: ApiPromise,
  211. group: string,
  212. hash: Hash
  213. ): Promise<number> => api.query[group].activeWorkerCount.at(hash)
  214. export const getStake = async (
  215. api: ApiPromise,
  216. id: StakeId | number
  217. ): Promise<Stake> => (await api.query.stake.stakes(id)) as Stake
  218. export const getWorkerReward = (
  219. api: ApiPromise,
  220. hash: Hash,
  221. id: RewardRelationshipId | number
  222. ): Promise<RewardRelationship> =>
  223. api.query.recurringRewards.rewardRelationships.at(hash, id)
  224. // mints
  225. export const getCouncilMint = (api: ApiPromise, hash: Hash): Promise<MintId> =>
  226. api.query.council.councilMint.at(hash)
  227. export const getGroupMint = (
  228. api: ApiPromise,
  229. group: string,
  230. hash: Hash
  231. ): Promise<MintId> => api.query[group].mint.at(hash)
  232. export const getMintsCreated = async (
  233. api: ApiPromise,
  234. hash: Hash
  235. ): Promise<number> => parseInt(await api.query.minting.mintsCreated.at(hash))
  236. export const getMint = (
  237. api: ApiPromise,
  238. hash: Hash,
  239. id: MintId | number
  240. ): Promise<Mint> => api.query.minting.mints.at(hash, id)
  241. // members
  242. export const getAccounts = async (
  243. api: ApiPromise
  244. ): Promise<AccountBalance[]> => {
  245. let accounts: AccountBalance[] = []
  246. const entries = await api.query.system.account.entries()
  247. for (const account of entries) {
  248. const accountId = String(account[0].toHuman())
  249. const balance = account[1].data.toJSON() as unknown as AccountData
  250. accounts.push({ accountId, balance })
  251. }
  252. return accounts
  253. }
  254. export const getAccount = (
  255. api: ApiPromise,
  256. hash: Hash,
  257. account: AccountId | string
  258. ): Promise<AccountInfo> => api.query.system.account.at(hash, account)
  259. export const getNextMember = async (
  260. api: ApiPromise,
  261. hash: Hash
  262. ): Promise<number> =>
  263. ((await api.query.members.nextMemberId.at(hash)) as MemberId).toNumber()
  264. export const getMember = async (
  265. api: ApiPromise,
  266. id: MemberId | number,
  267. hash?: Hash
  268. ): Promise<Membership> =>
  269. (await (hash
  270. ? api.query.members.membershipById.at(hash, id)
  271. : api.query.members.membershipById(id))) as Membership
  272. export const getMemberIdByAccount = async (
  273. api: ApiPromise,
  274. accountId: AccountId
  275. ): Promise<MemberId> => {
  276. const ids = (await api.query.members.memberIdsByRootAccountId(
  277. accountId
  278. )) as Vec<MemberId>
  279. return ids[0]
  280. }
  281. // forum
  282. export const getNextPost = async (
  283. api: ApiPromise,
  284. hash: Hash
  285. ): Promise<number> =>
  286. ((await api.query.forum.nextPostId.at(hash)) as PostId).toNumber()
  287. export const getNextThread = async (
  288. api: ApiPromise,
  289. hash: Hash
  290. ): Promise<number> =>
  291. ((await api.query.forum.nextThreadId.at(hash)) as ThreadId).toNumber()
  292. export const getNextCategory = async (
  293. api: ApiPromise,
  294. hash: Hash
  295. ): Promise<number> =>
  296. ((await api.query.forum.nextCategoryId.at(hash)) as CategoryId).toNumber()
  297. export const getCategory = async (
  298. api: ApiPromise,
  299. id: number
  300. ): Promise<Category> => (await api.query.forum.categoryById(id)) as Category
  301. export const getThread = async (api: ApiPromise, id: number): Promise<Thread> =>
  302. (await api.query.forum.threadById(id)) as Thread
  303. export const getPost = async (api: ApiPromise, id: number): Promise<Post> =>
  304. (await api.query.forum.postById(id)) as Post
  305. // proposals
  306. export const getProposalCount = async (
  307. api: ApiPromise,
  308. hash?: Hash
  309. ): Promise<number> =>
  310. (
  311. (await (hash
  312. ? api.query.proposalsEngine.proposalCount.at(hash)
  313. : api.query.proposalsEngine.proposalCount())) as u32
  314. ).toNumber()
  315. export const getProposalInfo = async (
  316. api: ApiPromise,
  317. id: ProposalId
  318. ): Promise<Proposal> =>
  319. (await api.query.proposalsEngine.proposals(id)) as Proposal
  320. export const getProposalDetails = async (
  321. api: ApiPromise,
  322. id: ProposalId
  323. ): Promise<ProposalDetails> =>
  324. (await api.query.proposalsCodex.proposalDetailsByProposalId(
  325. id
  326. )) as ProposalDetails
  327. export const getProposalType = async (
  328. api: ApiPromise,
  329. id: ProposalId
  330. ): Promise<string> => {
  331. const details = (await getProposalDetails(api, id)) as ProposalDetails
  332. const [type]: string[] = Object.getOwnPropertyNames(details.toJSON())
  333. return type
  334. }
  335. export const getProposal = async (
  336. api: ApiPromise,
  337. id: ProposalId
  338. ): Promise<ProposalDetail> => {
  339. const proposal = await getProposalInfo(api, id)
  340. const status: { [key: string]: any } = proposal.status
  341. const stage: string = status.isActive ? 'Active' : 'Finalized'
  342. const { finalizedAt, proposalStatus } = status[`as${stage}`]
  343. const result: string = proposalStatus
  344. ? (proposalStatus.isApproved && 'Approved') ||
  345. (proposalStatus.isCanceled && 'Canceled') ||
  346. (proposalStatus.isExpired && 'Expired') ||
  347. (proposalStatus.isRejected && 'Rejected') ||
  348. (proposalStatus.isSlashed && 'Slashed') ||
  349. (proposalStatus.isVetoed && 'Vetoed')
  350. : 'Pending'
  351. const exec = proposalStatus ? proposalStatus['Approved'] : null
  352. const { description, parameters, proposerId, votingResults } = proposal
  353. const member = await getMember(api, proposerId)
  354. const author = String(member ? member.handle : proposerId)
  355. const title = proposal.title.toString()
  356. const type = await getProposalType(api, id)
  357. const args: string[] = [String(id), title, type, stage, result, author]
  358. const message: string = `` //formatProposalMessage(args)
  359. const created: number = Number(proposal.createdAt)
  360. return {
  361. id: Number(id),
  362. title,
  363. created,
  364. finalizedAt,
  365. parameters: JSON.stringify(parameters),
  366. message,
  367. stage,
  368. result,
  369. exec,
  370. description: description.toHuman(),
  371. votes: votingResults,
  372. type,
  373. author,
  374. authorId: Number(proposerId),
  375. }
  376. }
  377. export const getProposalVotes = async (
  378. api: ApiPromise,
  379. id: ProposalId | number
  380. ): Promise<{ memberId: number; vote: string }[]> => {
  381. let votes: { memberId: number; vote: string }[] = []
  382. const entries =
  383. await api.query.proposalsEngine.voteExistsByProposalByVoter.entries(id)
  384. entries.forEach((entry: any) => {
  385. const memberId = entry[0].args[1].toJSON()
  386. const vote = entry[1].toString()
  387. votes.push({ memberId, vote })
  388. })
  389. return votes
  390. }
  391. export const getProposalPost = async (
  392. api: ApiPromise,
  393. threadId: ThreadId | number,
  394. postId: PostId | number
  395. ): Promise<DiscussionPost> =>
  396. (await api.query.proposalsDiscussion.postThreadIdByPostId(
  397. threadId,
  398. postId
  399. )) as DiscussionPost
  400. export const getProposalPostCount = async (api: ApiPromise): Promise<number> =>
  401. Number((await api.query.proposalsDiscussion.postCount()) as u64)
  402. export const getProposalThreadCount = async (
  403. api: ApiPromise
  404. ): Promise<number> =>
  405. Number((await api.query.proposalsDiscussion.threadCount()) as u64)
  406. // validators
  407. export const getValidatorCount = async (
  408. api: ApiPromise,
  409. hash: Hash
  410. ): Promise<number> =>
  411. ((await api.query.staking.validatorCount.at(hash)) as u32).toNumber()
  412. export const getValidators = async (
  413. api: ApiPromise,
  414. hash: Hash
  415. ): Promise<AccountId[]> =>
  416. (
  417. (await api.query.staking.snapshotValidators.at(hash)) as Option<
  418. Vec<AccountId>
  419. >
  420. ).unwrap()
  421. // media
  422. export const getNextEntity = async (
  423. api: ApiPromise,
  424. hash: Hash
  425. ): Promise<number> =>
  426. (
  427. (await api.query.contentDirectory.nextEntityId.at(hash)) as EntityId
  428. ).toNumber()
  429. export const getNextChannel = async (
  430. api: ApiPromise,
  431. hash: Hash
  432. ): Promise<number> => api.query.content.nextChannelId.at(hash)
  433. export const getNextVideo = async (
  434. api: ApiPromise,
  435. hash: Hash
  436. ): Promise<number> => api.query.content.nextVideoId.at(hash)
  437. export const getEntity = (
  438. api: ApiPromise,
  439. hash: Hash,
  440. id: number
  441. ): Promise<Entity> => api.query.contentDirectory.entityById.at(hash, id)
  442. export const getDataObjects = async (
  443. api: ApiPromise
  444. ): Promise<Map<ContentId, DataObject>> =>
  445. (await api.query.dataDirectory.dataByContentId.entries()) as unknown as Map<
  446. ContentId,
  447. DataObject
  448. >
  449. export const getDataObject = async (
  450. api: ApiPromise,
  451. id: ContentId
  452. ): Promise<Option<DataObject>> =>
  453. (await api.query.dataDirectory.dataByContentId(id)) as Option<DataObject>