3
0

api.ts 15 KB

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