api.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  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. ((await api.query.councilElection.round.at(hash)) as u32).toNumber();
  130. export const getCouncilElectionStage = async (
  131. api: ApiPromise,
  132. hash: Hash
  133. ): Promise<ElectionStage> =>
  134. (await api.query.councilElection.stage.at(hash)) as ElectionStage;
  135. export const getCouncilTermEnd = async (
  136. api: ApiPromise,
  137. hash: Hash
  138. ): Promise<number> =>
  139. ((await api.query.council.termEndsAt.at(hash)) as BlockNumber).toNumber();
  140. export const getCouncilElectionStatus = async (
  141. api: ApiPromise,
  142. hash: Hash
  143. ): Promise<ElectionInfo> => {
  144. const durations = await getCouncilElectionDurations(api, hash);
  145. const round = await getCouncilRound(api, hash);
  146. const stage: ElectionStage = await getCouncilElectionStage(api, hash);
  147. const stageEndsAt: number = Number(stage.value as BlockNumber);
  148. const termEndsAt: number = await getCouncilTermEnd(api, hash);
  149. return { round, stageEndsAt, termEndsAt, stage, durations };
  150. };
  151. export const getCouncilSize = async (
  152. api: ApiPromise,
  153. hash: Hash
  154. ): Promise<number> =>
  155. ((await api.query.councilElection.councilSize.at(hash)) as u32).toNumber();
  156. export const getCouncilApplicants = (
  157. api: ApiPromise,
  158. hash: Hash
  159. ): Promise<Vec<AccountId>> => api.query.councilElection.applicants.at(hash);
  160. export const getCouncilApplicantStakes = (
  161. api: ApiPromise,
  162. hash: Hash,
  163. applicant: AccountId
  164. ): Promise<ElectionStake> =>
  165. api.query.councilElection.applicantStakes.at(hash, applicant);
  166. export const getCouncilCommitments = (
  167. api: ApiPromise,
  168. hash: Hash
  169. ): Promise<Vec<Hash>> => api.query.councilElection.commitments.at(hash);
  170. export const getCouncilPayoutInterval = (
  171. api: ApiPromise,
  172. hash: Hash
  173. ): Promise<Option<BlockNumber>> => api.query.council.payoutInterval.at(hash);
  174. export const getCouncilPayout = (
  175. api: ApiPromise,
  176. hash: Hash
  177. ): Promise<Balance> => api.query.council.amountPerPayout.at(hash);
  178. const getCouncilElectionPeriod = (
  179. api: ApiPromise,
  180. hash: Hash,
  181. period: string
  182. ): Promise<BlockNumber> => api.query.councilElection[period].at(hash);
  183. export const getCouncilElectionDurations = async (
  184. api: ApiPromise,
  185. hash: Hash
  186. ): Promise<number[]> => {
  187. const periods = [
  188. "announcingPeriod",
  189. "votingPeriod",
  190. "revealingPeriod",
  191. "newTermDuration",
  192. ];
  193. let durations = await Promise.all(
  194. periods.map((period: string) => getCouncilElectionPeriod(api, hash, period))
  195. ).then((d) => d.map((block: BlockNumber) => block.toNumber()));
  196. durations.push(durations[0] + durations[1] + durations[2] + durations[3]);
  197. return durations;
  198. };
  199. export const getCommitments = (api: ApiPromise, hash: Hash): Promise<Hash[]> =>
  200. api.query.councilElection.commitments.at(hash);
  201. export const getCommitment = (
  202. api: ApiPromise,
  203. blockHash: Hash,
  204. voteHash: Hash
  205. ): Promise<SealedVote> =>
  206. api.query.councilElection.votes.at(blockHash, voteHash);
  207. // working groups
  208. export const getNextWorker = async (
  209. api: ApiPromise,
  210. group: string,
  211. hash: Hash
  212. ): Promise<number> =>
  213. ((await api.query[group].nextWorkerId.at(hash)) as WorkerId).toNumber();
  214. export const getWorker = (
  215. api: ApiPromise,
  216. group: string,
  217. hash: Hash,
  218. id: number
  219. ): Promise<WorkerOf> => api.query[group].workerById.at(hash, id);
  220. export const getWorkers = async (
  221. api: ApiPromise,
  222. group: string,
  223. hash: Hash
  224. ): Promise<number> => Number(await api.query[group].activeWorkerCount.at(hash));
  225. export const getStake = async (
  226. api: ApiPromise,
  227. id: StakeId | number,
  228. hash?: Hash
  229. ): Promise<Stake> =>
  230. (await (hash
  231. ? api.query.stake.stakes.at(hash, id)
  232. : api.query.stake.stakes(id))) as Stake;
  233. export const getWorkerReward = (
  234. api: ApiPromise,
  235. hash: Hash,
  236. id: RewardRelationshipId | number
  237. ): Promise<RewardRelationship> =>
  238. api.query.recurringRewards.rewardRelationships.at(hash, id);
  239. // mints
  240. export const getCouncilMint = (api: ApiPromise, hash: Hash): Promise<MintId> =>
  241. api.query.council.councilMint.at(hash);
  242. export const getGroupMint = async (
  243. api: ApiPromise,
  244. group: string
  245. ): Promise<MintId> => (await api.query[group].mint()) as MintId;
  246. export const getMintsCreated = async (
  247. api: ApiPromise,
  248. hash: Hash
  249. ): Promise<number> => parseInt(await api.query.minting.mintsCreated.at(hash));
  250. export const getMint = (
  251. api: ApiPromise,
  252. hash: Hash,
  253. id: MintId | number
  254. ): Promise<Mint> => api.query.minting.mints.at(hash, id);
  255. // members
  256. export const getAccounts = async (
  257. api: ApiPromise
  258. ): Promise<AccountBalance[]> => {
  259. let accounts: AccountBalance[] = [];
  260. const entries = await api.query.system.account.entries();
  261. for (const account of entries) {
  262. const accountId = String(account[0].toHuman());
  263. const balance = account[1].data.toJSON() as unknown as AccountData;
  264. accounts.push({ accountId, balance });
  265. }
  266. return accounts;
  267. };
  268. export const getAccount = (
  269. api: ApiPromise,
  270. hash: Hash,
  271. account: AccountId | string
  272. ): Promise<AccountInfo> => api.query.system.account.at(hash, account);
  273. export const getNextMember = async (
  274. api: ApiPromise,
  275. hash: Hash
  276. ): Promise<number> =>
  277. ((await api.query.members.nextMemberId.at(hash)) as MemberId).toNumber();
  278. export const getMember = async (
  279. api: ApiPromise,
  280. id: MemberId | number,
  281. hash?: Hash
  282. ): Promise<Membership> =>
  283. (await (hash
  284. ? api.query.members.membershipById.at(hash, id)
  285. : api.query.members.membershipById(id))) as Membership;
  286. export const getMemberIdByAccount = async (
  287. api: ApiPromise,
  288. accountId: AccountId
  289. ): Promise<MemberId> => {
  290. const ids = (await api.query.members.memberIdsByRootAccountId(
  291. accountId
  292. )) as Vec<MemberId>;
  293. return ids[0];
  294. };
  295. // forum
  296. export const getNextPost = async (
  297. api: ApiPromise,
  298. hash: Hash
  299. ): Promise<number> =>
  300. ((await api.query.forum.nextPostId.at(hash)) as PostId).toNumber();
  301. export const getNextThread = async (
  302. api: ApiPromise,
  303. hash: Hash
  304. ): Promise<number> =>
  305. ((await api.query.forum.nextThreadId.at(hash)) as ThreadId).toNumber();
  306. export const getNextCategory = async (
  307. api: ApiPromise,
  308. hash: Hash
  309. ): Promise<number> =>
  310. ((await api.query.forum.nextCategoryId.at(hash)) as CategoryId).toNumber();
  311. export const getCategory = async (
  312. api: ApiPromise,
  313. id: number
  314. ): Promise<Category> => (await api.query.forum.categoryById(id)) as Category;
  315. export const getThread = async (api: ApiPromise, id: number): Promise<Thread> =>
  316. (await api.query.forum.threadById(id)) as Thread;
  317. export const getPost = async (api: ApiPromise, id: number): Promise<Post> =>
  318. (await api.query.forum.postById(id)) as Post;
  319. // proposals
  320. export const getProposalCount = async (
  321. api: ApiPromise,
  322. hash?: Hash
  323. ): Promise<number> =>
  324. (
  325. (await (hash
  326. ? api.query.proposalsEngine.proposalCount.at(hash)
  327. : api.query.proposalsEngine.proposalCount())) as u32
  328. ).toNumber();
  329. export const getProposalInfo = async (
  330. api: ApiPromise,
  331. id: ProposalId
  332. ): Promise<ProposalOf> =>
  333. (await api.query.proposalsEngine.proposals(id)) as ProposalOf;
  334. export const getProposalDetails = async (
  335. api: ApiPromise,
  336. id: ProposalId
  337. ): Promise<ProposalDetailsOf> =>
  338. (await api.query.proposalsCodex.proposalDetailsByProposalId(
  339. id
  340. )) as ProposalDetailsOf;
  341. export const getProposalType = async (
  342. api: ApiPromise,
  343. id: ProposalId
  344. ): Promise<string> => {
  345. const details = (await getProposalDetails(api, id)) as ProposalDetailsOf;
  346. const [type]: string[] = Object.getOwnPropertyNames(details.toJSON());
  347. return type;
  348. };
  349. export const getProposal = async (
  350. api: ApiPromise,
  351. id: ProposalId
  352. ): Promise<ProposalDetail> => {
  353. const proposal: ProposalOf = await getProposalInfo(api, id);
  354. const status: { [key: string]: any } = proposal.status;
  355. const stage: string = status.isActive ? "Active" : "Finalized";
  356. const { finalizedAt, proposalStatus } = status[`as${stage}`];
  357. const result: string = proposalStatus
  358. ? (proposalStatus.isApproved && "Approved") ||
  359. (proposalStatus.isCanceled && "Canceled") ||
  360. (proposalStatus.isExpired && "Expired") ||
  361. (proposalStatus.isRejected && "Rejected") ||
  362. (proposalStatus.isSlashed && "Slashed") ||
  363. (proposalStatus.isVetoed && "Vetoed")
  364. : "Pending";
  365. const exec = proposalStatus ? proposalStatus["Approved"] : null;
  366. const { description, parameters, proposerId, votingResults } = proposal;
  367. const member: Membership = await getMember(api, proposerId);
  368. const author = String(member ? member.handle : proposerId);
  369. const title = proposal.title.toString();
  370. const type: string = await getProposalType(api, id);
  371. const args: string[] = [String(id), title, type, stage, result, author];
  372. const message: string = ``; //formatProposalMessage(args)
  373. const created: number = Number(proposal.createdAt);
  374. return {
  375. id: Number(id),
  376. title,
  377. created,
  378. finalizedAt,
  379. parameters: JSON.stringify(parameters),
  380. message,
  381. stage,
  382. result,
  383. exec,
  384. description: description.toHuman(),
  385. votes: votingResults,
  386. type,
  387. author,
  388. authorId: Number(proposerId),
  389. };
  390. };
  391. export const getProposalVotes = async (
  392. api: ApiPromise,
  393. id: ProposalId | number
  394. ): Promise<{ memberId: number; vote: string }[]> => {
  395. let votes: { memberId: number; vote: string }[] = [];
  396. const entries =
  397. await api.query.proposalsEngine.voteExistsByProposalByVoter.entries(id);
  398. entries.forEach((entry: any) => {
  399. const memberId = entry[0].args[1].toJSON();
  400. const vote = entry[1].toString();
  401. votes.push({ memberId, vote });
  402. });
  403. return votes;
  404. };
  405. export const getProposalPost = async (
  406. api: ApiPromise,
  407. threadId: ThreadId | number,
  408. postId: PostId | number
  409. ): Promise<DiscussionPost> =>
  410. (await api.query.proposalsDiscussion.postThreadIdByPostId(
  411. threadId,
  412. postId
  413. )) as DiscussionPost;
  414. export const getProposalPosts = (
  415. api: ApiPromise
  416. ): Promise<[StorageKey<any>, DiscussionPost][]> =>
  417. api.query.proposalsDiscussion.postThreadIdByPostId.entries();
  418. export const getProposalPostCount = async (api: ApiPromise): Promise<number> =>
  419. Number((await api.query.proposalsDiscussion.postCount()) as u64);
  420. export const getProposalThreadCount = async (
  421. api: ApiPromise
  422. ): Promise<number> =>
  423. Number((await api.query.proposalsDiscussion.threadCount()) as u64);
  424. // validators
  425. export const getValidatorCount = async (
  426. api: ApiPromise,
  427. hash: Hash
  428. ): Promise<number> =>
  429. ((await api.query.staking.validatorCount.at(hash)) as u32).toNumber();
  430. export const getValidators = async (
  431. api: ApiPromise,
  432. hash: Hash
  433. ): Promise<AccountId[]> => {
  434. const snapshot = (await api.query.staking.snapshotValidators.at(
  435. hash
  436. )) as Option<Vec<AccountId>>;
  437. return snapshot.isSome ? snapshot.unwrap() : [];
  438. };
  439. export const getPaidMembershipTermsById = (
  440. api: ApiPromise,
  441. hash: Hash,
  442. id: PaidTermId | number
  443. ): Promise<PaidMembershipTerms> => api.query.members.paidMembershipTermsById.at(hash, id);
  444. // media
  445. export const getNextEntity = async (
  446. api: ApiPromise,
  447. hash: Hash
  448. ): Promise<number> =>
  449. (
  450. (await api.query.contentDirectory.nextEntityId.at(hash)) as EntityId
  451. ).toNumber();
  452. export const getNextChannel = async (
  453. api: ApiPromise,
  454. hash: Hash
  455. ): Promise<number> => Number(await api.query.content.nextChannelId.at(hash));
  456. export const getNextVideo = async (
  457. api: ApiPromise,
  458. hash: Hash
  459. ): Promise<number> => Number(await api.query.content.nextVideoId.at(hash));
  460. export const getEntity = (
  461. api: ApiPromise,
  462. hash: Hash,
  463. id: number
  464. ): Promise<Entity> => api.query.contentDirectory.entityById.at(hash, id);
  465. export const getDataObjects = async (
  466. api: ApiPromise
  467. ): Promise<Map<ContentId, DataObject>> =>
  468. (await api.query.dataDirectory.dataByContentId.entries()) as unknown as Map<
  469. ContentId,
  470. DataObject
  471. >;
  472. export const getDataObject = async (
  473. api: ApiPromise,
  474. id: ContentId
  475. ): Promise<Option<DataObject>> =>
  476. (await api.query.dataDirectory.dataByContentId(id)) as Option<DataObject>;