3
0

api.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  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 (api: ApiPromise): Promise<number[]> =>
  342. api.query.proposalsEngine.activeProposalIds
  343. .keys()
  344. .then((ids) => ids.map(([key]) => key));
  345. export const getProposalCount = async (
  346. api: ApiPromise,
  347. hash?: Hash
  348. ): Promise<number> =>
  349. (
  350. (await (hash
  351. ? api.query.proposalsEngine.proposalCount.at(hash)
  352. : api.query.proposalsEngine.proposalCount())) as u32
  353. ).toNumber();
  354. export const getProposalInfo = async (
  355. api: ApiPromise,
  356. id: ProposalId
  357. ): Promise<ProposalOf> =>
  358. (await api.query.proposalsEngine.proposals(id)) as ProposalOf;
  359. export const getProposalDetails = async (
  360. api: ApiPromise,
  361. id: ProposalId
  362. ): Promise<ProposalDetailsOf> =>
  363. (await api.query.proposalsCodex.proposalDetailsByProposalId(
  364. id
  365. )) as ProposalDetailsOf;
  366. export const getProposalType = async (
  367. api: ApiPromise,
  368. id: ProposalId
  369. ): Promise<string> => {
  370. const details = (await getProposalDetails(api, id)) as ProposalDetailsOf;
  371. const [type]: string[] = Object.getOwnPropertyNames(details.toJSON());
  372. return type;
  373. };
  374. export const getProposal = async (
  375. api: ApiPromise,
  376. id: ProposalId
  377. ): Promise<ProposalDetail> => {
  378. const proposal: ProposalOf = await getProposalInfo(api, id);
  379. const status: { [key: string]: any } = proposal.status;
  380. const stage: string = status.isActive ? "Active" : "Finalized";
  381. const { finalizedAt, proposalStatus } = status[`as${stage}`];
  382. const result: string = proposalStatus
  383. ? (proposalStatus.isApproved && "Approved") ||
  384. (proposalStatus.isCanceled && "Canceled") ||
  385. (proposalStatus.isExpired && "Expired") ||
  386. (proposalStatus.isRejected && "Rejected") ||
  387. (proposalStatus.isSlashed && "Slashed") ||
  388. (proposalStatus.isVetoed && "Vetoed")
  389. : "Pending";
  390. const exec = proposalStatus ? proposalStatus["Approved"] : null;
  391. const { description, parameters, proposerId, votingResults } = proposal;
  392. const member: Membership = await getMember(api, proposerId);
  393. const author = String(member ? member.handle : proposerId);
  394. const title = proposal.title.toString();
  395. const type: string = await getProposalType(api, id);
  396. const args: string[] = [String(id), title, type, stage, result, author];
  397. const message = formatProposalMessage(args);
  398. const created: number = Number(proposal.createdAt);
  399. return {
  400. id: Number(id),
  401. title,
  402. created,
  403. finalizedAt,
  404. parameters: JSON.stringify(parameters),
  405. message,
  406. stage,
  407. result,
  408. exec,
  409. description: description.toHuman(),
  410. votes: votingResults,
  411. type,
  412. author,
  413. authorId: Number(proposerId),
  414. };
  415. };
  416. const formatProposalMessage = (
  417. data: string[],
  418. domain = "https://testnet.joystream.org"
  419. ): { tg: string; discord: string } => {
  420. const [id, title, type, stage, result, handle] = data;
  421. 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}`;
  422. const discord = `**Type**: ${type}\n**Proposer**: ${handle}\n**Title**: ${title}\n**Stage**: ${stage}\n**Result**: ${result}`;
  423. return { tg, discord };
  424. };
  425. export const getProposalVotes = async (
  426. api: ApiPromise,
  427. id: ProposalId | number
  428. ): Promise<{ memberId: number; vote: string }[]> => {
  429. let votes: { memberId: number; vote: string }[] = [];
  430. const entries =
  431. await api.query.proposalsEngine.voteExistsByProposalByVoter.entries(id);
  432. entries.forEach((entry: any) => {
  433. const memberId = entry[0].args[1].toJSON();
  434. const vote = entry[1].toString();
  435. votes.push({ memberId, vote });
  436. });
  437. return votes;
  438. };
  439. export const getProposalPost = async (
  440. api: ApiPromise,
  441. threadId: ThreadId | number,
  442. postId: PostId | number
  443. ): Promise<DiscussionPost> =>
  444. (await api.query.proposalsDiscussion.postThreadIdByPostId(
  445. threadId,
  446. postId
  447. )) as DiscussionPost;
  448. export const getProposalPosts = (
  449. api: ApiPromise
  450. ): Promise<[StorageKey<any>, DiscussionPost][]> =>
  451. api.query.proposalsDiscussion.postThreadIdByPostId.entries();
  452. export const getProposalPostCount = async (api: ApiPromise): Promise<number> =>
  453. Number((await api.query.proposalsDiscussion.postCount()) as u64);
  454. export const getProposalThreadCount = async (
  455. api: ApiPromise
  456. ): Promise<number> =>
  457. Number((await api.query.proposalsDiscussion.threadCount()) as u64);
  458. // validators
  459. export const getValidatorCount = async (
  460. api: ApiPromise,
  461. hash: Hash
  462. ): Promise<number> =>
  463. ((await api.query.staking.validatorCount.at(hash)) as u32).toNumber();
  464. export const getValidators = async (
  465. api: ApiPromise,
  466. hash: Hash
  467. ): Promise<AccountId[]> => {
  468. const snapshot = (await api.query.staking.snapshotValidators.at(
  469. hash
  470. )) as Option<Vec<AccountId>>;
  471. return snapshot.isSome ? snapshot.unwrap() : [];
  472. };
  473. export const getPaidMembershipTermsById = (
  474. api: ApiPromise,
  475. hash: Hash,
  476. id: PaidTermId | number
  477. ): Promise<PaidMembershipTerms> =>
  478. api.query.members.paidMembershipTermsById.at(hash, id);
  479. // media
  480. export const getNextEntity = async (
  481. api: ApiPromise,
  482. hash: Hash
  483. ): Promise<number> =>
  484. (
  485. (await api.query.contentDirectory.nextEntityId.at(hash)) as EntityId
  486. ).toNumber();
  487. export const getNextChannel = (api: ApiPromise, hash: Hash): Promise<number> =>
  488. api.query.content.nextChannelId.at(hash);
  489. export const getNextVideo = (api: ApiPromise, hash: Hash): Promise<number> =>
  490. api.query.content.nextVideoId.at(hash);
  491. export const getEntity = (
  492. api: ApiPromise,
  493. hash: Hash,
  494. id: number
  495. ): Promise<Entity> => api.query.contentDirectory.entityById.at(hash, id);
  496. export const getDataObjects = async (
  497. api: ApiPromise
  498. ): Promise<Map<ContentId, DataObject>> =>
  499. (await api.query.dataDirectory.dataByContentId.entries()) as unknown as Map<
  500. ContentId,
  501. DataObject
  502. >;
  503. export const getDataObject = async (
  504. api: ApiPromise,
  505. id: ContentId
  506. ): Promise<Option<DataObject>> =>
  507. (await api.query.dataDirectory.dataByContentId(id)) as Option<DataObject>;