3
0

api.ts 16 KB

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