api.ts 15 KB

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