3
0

api.ts 16 KB

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