api.ts 16 KB

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