3
0

api.ts 15 KB

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