3
0

api.ts 17 KB

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