api.ts 16 KB

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