api.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  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 = (
  243. api: ApiPromise,
  244. group: string,
  245. hash: Hash
  246. ): Promise<MintId> => api.query[group].mint.at(hash);
  247. export const getMintsCreated = async (
  248. api: ApiPromise,
  249. hash: Hash
  250. ): Promise<number> => parseInt(await api.query.minting.mintsCreated.at(hash));
  251. export const getMint = (
  252. api: ApiPromise,
  253. hash: Hash,
  254. id: MintId | number
  255. ): Promise<Mint> => api.query.minting.mints.at(hash, id);
  256. // members
  257. export const getAccounts = async (
  258. api: ApiPromise
  259. ): Promise<AccountBalance[]> => {
  260. let accounts: AccountBalance[] = [];
  261. const entries = await api.query.system.account.entries();
  262. for (const account of entries) {
  263. const accountId = String(account[0].toHuman());
  264. const balance = account[1].data.toJSON() as unknown as AccountData;
  265. accounts.push({ accountId, balance });
  266. }
  267. return accounts;
  268. };
  269. export const getAccount = (
  270. api: ApiPromise,
  271. hash: Hash,
  272. account: AccountId | string
  273. ): Promise<AccountInfo> => api.query.system.account.at(hash, account);
  274. export const getNextMember = async (
  275. api: ApiPromise,
  276. hash: Hash
  277. ): Promise<number> =>
  278. ((await api.query.members.nextMemberId.at(hash)) as MemberId).toNumber();
  279. export const getMember = async (
  280. api: ApiPromise,
  281. id: MemberId | number,
  282. hash?: Hash
  283. ): Promise<Membership> =>
  284. (await (hash
  285. ? api.query.members.membershipById.at(hash, id)
  286. : api.query.members.membershipById(id))) as Membership;
  287. export const getMemberIdByAccount = async (
  288. api: ApiPromise,
  289. accountId: AccountId
  290. ): Promise<MemberId> => {
  291. const ids = (await api.query.members.memberIdsByRootAccountId(
  292. accountId
  293. )) as Vec<MemberId>;
  294. return ids[0];
  295. };
  296. // forum
  297. export const getNextPost = async (
  298. api: ApiPromise,
  299. hash: Hash
  300. ): Promise<number> =>
  301. ((await api.query.forum.nextPostId.at(hash)) as PostId).toNumber();
  302. export const getNextThread = async (
  303. api: ApiPromise,
  304. hash: Hash
  305. ): Promise<number> =>
  306. ((await api.query.forum.nextThreadId.at(hash)) as ThreadId).toNumber();
  307. export const getNextCategory = async (
  308. api: ApiPromise,
  309. hash: Hash
  310. ): Promise<number> =>
  311. ((await api.query.forum.nextCategoryId.at(hash)) as CategoryId).toNumber();
  312. export const getCategory = async (
  313. api: ApiPromise,
  314. id: number
  315. ): Promise<Category> => (await api.query.forum.categoryById(id)) as Category;
  316. export const getThread = async (api: ApiPromise, id: number): Promise<Thread> =>
  317. (await api.query.forum.threadById(id)) as Thread;
  318. export const getPost = async (api: ApiPromise, id: number): Promise<Post> =>
  319. (await api.query.forum.postById(id)) as Post;
  320. // proposals
  321. export const getProposalCount = async (
  322. api: ApiPromise,
  323. hash?: Hash
  324. ): Promise<number> =>
  325. (
  326. (await (hash
  327. ? api.query.proposalsEngine.proposalCount.at(hash)
  328. : api.query.proposalsEngine.proposalCount())) as u32
  329. ).toNumber();
  330. export const getProposalInfo = async (
  331. api: ApiPromise,
  332. id: ProposalId
  333. ): Promise<ProposalOf> =>
  334. (await api.query.proposalsEngine.proposals(id)) as ProposalOf;
  335. export const getProposalDetails = async (
  336. api: ApiPromise,
  337. id: ProposalId
  338. ): Promise<ProposalDetailsOf> =>
  339. (await api.query.proposalsCodex.proposalDetailsByProposalId(
  340. id
  341. )) as ProposalDetailsOf;
  342. export const getProposalType = async (
  343. api: ApiPromise,
  344. id: ProposalId
  345. ): Promise<string> => {
  346. const details = (await getProposalDetails(api, id)) as ProposalDetailsOf;
  347. const [type]: string[] = Object.getOwnPropertyNames(details.toJSON());
  348. return type;
  349. };
  350. export const getProposal = async (
  351. api: ApiPromise,
  352. id: ProposalId
  353. ): Promise<ProposalDetail> => {
  354. const proposal: ProposalOf = await getProposalInfo(api, id);
  355. const status: { [key: string]: any } = proposal.status;
  356. const stage: string = status.isActive ? "Active" : "Finalized";
  357. const { finalizedAt, proposalStatus } = status[`as${stage}`];
  358. const result: string = proposalStatus
  359. ? (proposalStatus.isApproved && "Approved") ||
  360. (proposalStatus.isCanceled && "Canceled") ||
  361. (proposalStatus.isExpired && "Expired") ||
  362. (proposalStatus.isRejected && "Rejected") ||
  363. (proposalStatus.isSlashed && "Slashed") ||
  364. (proposalStatus.isVetoed && "Vetoed")
  365. : "Pending";
  366. const exec = proposalStatus ? proposalStatus["Approved"] : null;
  367. const { description, parameters, proposerId, votingResults } = proposal;
  368. const member: Membership = await getMember(api, proposerId);
  369. const author = String(member ? member.handle : proposerId);
  370. const title = proposal.title.toString();
  371. const type: string = await getProposalType(api, id);
  372. const args: string[] = [String(id), title, type, stage, result, author];
  373. const message: string = ``; //formatProposalMessage(args)
  374. const created: number = Number(proposal.createdAt);
  375. return {
  376. id: Number(id),
  377. title,
  378. created,
  379. finalizedAt,
  380. parameters: JSON.stringify(parameters),
  381. message,
  382. stage,
  383. result,
  384. exec,
  385. description: description.toHuman(),
  386. votes: votingResults,
  387. type,
  388. author,
  389. authorId: Number(proposerId),
  390. };
  391. };
  392. export const getProposalVotes = async (
  393. api: ApiPromise,
  394. id: ProposalId | number
  395. ): Promise<{ memberId: number; vote: string }[]> => {
  396. let votes: { memberId: number; vote: string }[] = [];
  397. const entries =
  398. await api.query.proposalsEngine.voteExistsByProposalByVoter.entries(id);
  399. entries.forEach((entry: any) => {
  400. const memberId = entry[0].args[1].toJSON();
  401. const vote = entry[1].toString();
  402. votes.push({ memberId, vote });
  403. });
  404. return votes;
  405. };
  406. export const getProposalPost = async (
  407. api: ApiPromise,
  408. threadId: ThreadId | number,
  409. postId: PostId | number
  410. ): Promise<DiscussionPost> =>
  411. (await api.query.proposalsDiscussion.postThreadIdByPostId(
  412. threadId,
  413. postId
  414. )) as DiscussionPost;
  415. export const getProposalPosts = (
  416. api: ApiPromise
  417. ): Promise<[StorageKey<any>, DiscussionPost][]> =>
  418. api.query.proposalsDiscussion.postThreadIdByPostId.entries();
  419. export const getProposalPostCount = async (api: ApiPromise): Promise<number> =>
  420. Number((await api.query.proposalsDiscussion.postCount()) as u64);
  421. export const getProposalThreadCount = async (
  422. api: ApiPromise
  423. ): Promise<number> =>
  424. Number((await api.query.proposalsDiscussion.threadCount()) as u64);
  425. // validators
  426. export const getValidatorCount = async (
  427. api: ApiPromise,
  428. hash: Hash
  429. ): Promise<number> =>
  430. ((await api.query.staking.validatorCount.at(hash)) as u32).toNumber();
  431. export const getValidators = async (
  432. api: ApiPromise,
  433. hash: Hash
  434. ): Promise<AccountId[]> => {
  435. const snapshot = (await api.query.staking.snapshotValidators.at(
  436. hash
  437. )) as Option<Vec<AccountId>>;
  438. return snapshot.isSome ? snapshot.unwrap() : [];
  439. };
  440. // media
  441. export const getNextEntity = async (
  442. api: ApiPromise,
  443. hash: Hash
  444. ): Promise<number> =>
  445. (
  446. (await api.query.contentDirectory.nextEntityId.at(hash)) as EntityId
  447. ).toNumber();
  448. export const getNextChannel = async (
  449. api: ApiPromise,
  450. hash: Hash
  451. ): Promise<number> => Number(await api.query.content.nextChannelId.at(hash));
  452. export const getNextVideo = async (
  453. api: ApiPromise,
  454. hash: Hash
  455. ): Promise<number> => Number(await api.query.content.nextVideoId.at(hash));
  456. export const getEntity = (
  457. api: ApiPromise,
  458. hash: Hash,
  459. id: number
  460. ): Promise<Entity> => api.query.contentDirectory.entityById.at(hash, id);
  461. export const getDataObjects = async (
  462. api: ApiPromise
  463. ): Promise<Map<ContentId, DataObject>> =>
  464. (await api.query.dataDirectory.dataByContentId.entries()) as unknown as Map<
  465. ContentId,
  466. DataObject
  467. >;
  468. export const getDataObject = async (
  469. api: ApiPromise,
  470. id: ContentId
  471. ): Promise<Option<DataObject>> =>
  472. (await api.query.dataDirectory.dataByContentId(id)) as Option<DataObject>;