api.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  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 {
  29. MemberId,
  30. Membership,
  31. PaidMembershipTerms,
  32. PaidTermId,
  33. } from "@joystream/types/members";
  34. import { Mint, MintId } from "@joystream/types/mint";
  35. import {
  36. Proposal,
  37. ProposalId,
  38. DiscussionPost,
  39. SpendingParams,
  40. VoteKind,
  41. } from "@joystream/types/proposals";
  42. import { Stake, StakeId } from "@joystream/types/stake";
  43. import {
  44. RewardRelationship,
  45. RewardRelationshipId,
  46. } from "@joystream/types/recurring-rewards";
  47. import { WorkerId, Worker } from "@joystream/types/working-group";
  48. import { ProposalOf, ProposalDetailsOf } from "@joystream/types/augment/types";
  49. import { WorkerOf } from "@joystream/types/augment-codec/all";
  50. export const connectApi = async (url: string): Promise<ApiPromise> => {
  51. const provider = new WsProvider(url);
  52. return await ApiPromise.create({ provider, types });
  53. };
  54. // blocks
  55. export const getBlock = (api: ApiPromise, hash: Hash): Promise<SignedBlock> =>
  56. api.rpc.chain.getBlock(hash);
  57. export const getBlockHash = (
  58. api: ApiPromise,
  59. block: BlockNumber | number
  60. ): Promise<Hash> => {
  61. try {
  62. return api.rpc.chain.getBlockHash(block);
  63. } catch (e) {
  64. return getBestHash(api);
  65. }
  66. };
  67. export const getHead = (api: ApiPromise) => api.derive.chain.bestNumber();
  68. export const getBestHash = (api: ApiPromise) =>
  69. api.rpc.chain.getFinalizedHead();
  70. export const getTimestamp = async (
  71. api: ApiPromise,
  72. hash: Hash
  73. ): Promise<number> =>
  74. moment.utc((await api.query.timestamp.now.at(hash)).toNumber()).valueOf();
  75. export const getIssuance = (api: ApiPromise, hash: Hash): Promise<Balance> =>
  76. api.query.balances.totalIssuance.at(hash);
  77. export const getEvents = (
  78. api: ApiPromise,
  79. hash: Hash
  80. ): Promise<Vec<EventRecord>> => api.query.system.events.at(hash);
  81. export const getEra = async (api: ApiPromise, hash: Hash): Promise<number> =>
  82. Number(await api.query.staking.currentEra.at(hash));
  83. export const getEraStake = async (
  84. api: ApiPromise,
  85. hash: Hash,
  86. era: EraIndex | number
  87. ): Promise<number> =>
  88. (await api.query.staking.erasTotalStake.at(hash, era)).toNumber();
  89. // council
  90. export const getCouncil = async (api: ApiPromise): Promise<Seats> =>
  91. (await api.query.council.activeCouncil()) as Seats;
  92. export const getCouncilAt = (api: ApiPromise, hash: Hash): Promise<Seats> =>
  93. api.query.council.activeCouncil.at(hash);
  94. export const getCouncils = async (
  95. api: ApiPromise,
  96. head: number
  97. ): Promise<Round[]> => {
  98. // durations: [ announcing, voting, revealing, term, sum ]
  99. // each chain starts with an election (duration: d[0]+d[1]+d[2])
  100. // elections are repeated if not enough apply (round increments though)
  101. // first term starts at begin of d[3] or some electionDuration later
  102. // term lasts till the end of the next successful election
  103. // `council.termEndsAt` returns the end of the current round
  104. // to determine term starts check every electionDuration blocks
  105. const d: number[] = await getCouncilElectionDurations(
  106. api,
  107. await getBlockHash(api, 1)
  108. );
  109. const electionDuration = d[0] + d[1] + d[2];
  110. const starts: number[] = [];
  111. let lastEnd = 1;
  112. for (let block = lastEnd; block < head; block += electionDuration) {
  113. const hash = await getBlockHash(api, block);
  114. const end = Number(await api.query.council.termEndsAt.at(hash));
  115. if (end === lastEnd) continue;
  116. lastEnd = end;
  117. starts.push(end - d[3]);
  118. }
  119. // index by round: each start is the end of the previous term
  120. const rounds: { [key: number]: Round } = {};
  121. await Promise.all(
  122. starts.map(async (start: number, index: number) => {
  123. const hash = await getBlockHash(api, start);
  124. const round = await getCouncilRound(api, hash);
  125. const isLast = index === starts.length - 1;
  126. const end = isLast ? start + d[4] - 1 : starts[index + 1] - 1;
  127. rounds[round] = { start, round, end };
  128. })
  129. );
  130. return Object.values(rounds);
  131. };
  132. export const getCouncilRound = async (
  133. api: ApiPromise,
  134. hash?: Hash
  135. ): Promise<number> =>
  136. hash
  137. ? ((await api.query.councilElection.round.at(hash)) as u32).toNumber()
  138. : ((await api.query.councilElection.round()) as u32).toNumber();
  139. export const getCouncilElectionStage = async (
  140. api: ApiPromise,
  141. hash: Hash
  142. ): Promise<ElectionStage> =>
  143. (await api.query.councilElection.stage.at(hash)) as ElectionStage;
  144. export const getCouncilTermEnd = async (
  145. api: ApiPromise,
  146. hash: Hash
  147. ): Promise<number> =>
  148. ((await api.query.council.termEndsAt.at(hash)) as BlockNumber).toNumber();
  149. export const getCouncilElectionStatus = async (
  150. api: ApiPromise,
  151. hash: Hash
  152. ): Promise<ElectionInfo> => {
  153. const durations = await getCouncilElectionDurations(api, hash);
  154. const round = await getCouncilRound(api, hash);
  155. const stage: ElectionStage = await getCouncilElectionStage(api, hash);
  156. const stageEndsAt: number = Number(stage.value as BlockNumber);
  157. const termEndsAt: number = await getCouncilTermEnd(api, hash);
  158. return { round, stageEndsAt, termEndsAt, stage, durations };
  159. };
  160. export const getCouncilSize = async (
  161. api: ApiPromise,
  162. hash: Hash
  163. ): Promise<number> =>
  164. ((await api.query.councilElection.councilSize.at(hash)) as u32).toNumber();
  165. export const getCouncilApplicants = (
  166. api: ApiPromise,
  167. hash: Hash
  168. ): Promise<Vec<AccountId>> => api.query.councilElection.applicants.at(hash);
  169. export const getCouncilApplicantStakes = (
  170. api: ApiPromise,
  171. hash: Hash,
  172. applicant: AccountId
  173. ): Promise<ElectionStake> =>
  174. api.query.councilElection.applicantStakes.at(hash, applicant);
  175. export const getCouncilCommitments = (
  176. api: ApiPromise,
  177. hash: Hash
  178. ): Promise<Vec<Hash>> => api.query.councilElection.commitments.at(hash);
  179. export const getCouncilPayoutInterval = (
  180. api: ApiPromise,
  181. hash: Hash
  182. ): Promise<Option<BlockNumber>> => api.query.council.payoutInterval.at(hash);
  183. export const getCouncilPayout = (
  184. api: ApiPromise,
  185. hash: Hash
  186. ): Promise<Balance> => api.query.council.amountPerPayout.at(hash);
  187. const getCouncilElectionPeriod = (
  188. api: ApiPromise,
  189. hash: Hash,
  190. period: string
  191. ): Promise<BlockNumber> => api.query.councilElection[period].at(hash);
  192. export const getCouncilElectionDurations = async (
  193. api: ApiPromise,
  194. hash: Hash
  195. ): Promise<number[]> => {
  196. const periods = [
  197. "announcingPeriod",
  198. "votingPeriod",
  199. "revealingPeriod",
  200. "newTermDuration",
  201. ];
  202. let durations = await Promise.all(
  203. periods.map((period: string) => getCouncilElectionPeriod(api, hash, period))
  204. ).then((d) => d.map((block: BlockNumber) => block.toNumber()));
  205. durations.push(durations[0] + durations[1] + durations[2] + durations[3]);
  206. return durations;
  207. };
  208. export const getCommitments = (api: ApiPromise, hash: Hash): Promise<Hash[]> =>
  209. api.query.councilElection.commitments.at(hash);
  210. export const getCommitment = (
  211. api: ApiPromise,
  212. blockHash: Hash,
  213. voteHash: Hash
  214. ): Promise<SealedVote> =>
  215. api.query.councilElection.votes.at(blockHash, voteHash);
  216. // working groups
  217. export const getNextWorker = async (
  218. api: ApiPromise,
  219. group: string,
  220. hash: Hash
  221. ): Promise<number> =>
  222. ((await api.query[group].nextWorkerId.at(hash)) as WorkerId).toNumber();
  223. export const getWorker = (
  224. api: ApiPromise,
  225. group: string,
  226. hash: Hash,
  227. id: number
  228. ): Promise<WorkerOf> => api.query[group].workerById.at(hash, id);
  229. export const getWorkers = async (
  230. api: ApiPromise,
  231. group: string,
  232. hash: Hash
  233. ): Promise<number> => Number(await api.query[group].activeWorkerCount.at(hash));
  234. export const getStake = async (
  235. api: ApiPromise,
  236. id: StakeId | number,
  237. hash?: Hash
  238. ): Promise<Stake> =>
  239. (await (hash
  240. ? api.query.stake.stakes.at(hash, id)
  241. : api.query.stake.stakes(id))) as Stake;
  242. export const getWorkerReward = (
  243. api: ApiPromise,
  244. hash: Hash,
  245. id: RewardRelationshipId | number
  246. ): Promise<RewardRelationship> =>
  247. api.query.recurringRewards.rewardRelationships.at(hash, id);
  248. // mints
  249. export const getCouncilMint = (api: ApiPromise, hash: Hash): Promise<MintId> =>
  250. api.query.council.councilMint.at(hash);
  251. export const getGroupMint = async (
  252. api: ApiPromise,
  253. group: string
  254. ): Promise<MintId> => (await api.query[group].mint()) as MintId;
  255. export const getMintsCreated = async (
  256. api: ApiPromise,
  257. hash: Hash
  258. ): Promise<number> => parseInt(await api.query.minting.mintsCreated.at(hash));
  259. export const getMint = (
  260. api: ApiPromise,
  261. hash: Hash,
  262. id: MintId | number
  263. ): Promise<Mint> => api.query.minting.mints.at(hash, id);
  264. // members
  265. export const getAccounts = async (
  266. api: ApiPromise
  267. ): Promise<AccountBalance[]> => {
  268. let accounts: AccountBalance[] = [];
  269. const entries = await api.query.system.account.entries();
  270. for (const account of entries) {
  271. const accountId = String(account[0].toHuman());
  272. const balance = account[1].data.toJSON() as unknown as AccountData;
  273. accounts.push({ accountId, balance });
  274. }
  275. return accounts;
  276. };
  277. export const getAccount = (
  278. api: ApiPromise,
  279. hash: Hash,
  280. account: AccountId | string
  281. ): Promise<AccountInfo> => api.query.system.account.at(hash, account);
  282. export const getNextMember = async (
  283. api: ApiPromise,
  284. hash: Hash
  285. ): Promise<number> =>
  286. ((await api.query.members.nextMemberId.at(hash)) as MemberId).toNumber();
  287. export const getMember = async (
  288. api: ApiPromise,
  289. id: MemberId | number,
  290. hash?: Hash
  291. ): Promise<Membership> =>
  292. (await (hash
  293. ? api.query.members.membershipById.at(hash, id)
  294. : api.query.members.membershipById(id))) as Membership;
  295. export const getMemberIdByAccount = async (
  296. api: ApiPromise,
  297. accountId: AccountId
  298. ): Promise<MemberId> => {
  299. const ids = (await api.query.members.memberIdsByRootAccountId(
  300. accountId
  301. )) as Vec<MemberId>;
  302. return ids[0];
  303. };
  304. export const getMemberHandle = async (
  305. api: ApiPromise,
  306. id: MemberId
  307. ): Promise<string> =>
  308. getMember(api, id).then((member: Membership) => String(member.handle));
  309. export const getMemberHandleByAccount = async (
  310. api: ApiPromise,
  311. account: AccountId
  312. ): Promise<string> =>
  313. getMemberHandle(api, await getMemberIdByAccount(api, account));
  314. // forum
  315. export const getNextPost = async (
  316. api: ApiPromise,
  317. hash: Hash
  318. ): Promise<number> =>
  319. ((await api.query.forum.nextPostId.at(hash)) as PostId).toNumber();
  320. export const getNextThread = async (
  321. api: ApiPromise,
  322. hash: Hash
  323. ): Promise<number> =>
  324. ((await api.query.forum.nextThreadId.at(hash)) as ThreadId).toNumber();
  325. export const getNextCategory = async (
  326. api: ApiPromise,
  327. hash: Hash
  328. ): Promise<number> =>
  329. ((await api.query.forum.nextCategoryId.at(hash)) as CategoryId).toNumber();
  330. export const getCategory = async (
  331. api: ApiPromise,
  332. id: number
  333. ): Promise<Category> => (await api.query.forum.categoryById(id)) as Category;
  334. export const getThread = async (api: ApiPromise, id: number): Promise<Thread> =>
  335. (await api.query.forum.threadById(id)) as Thread;
  336. export const getPost = async (api: ApiPromise, id: number): Promise<Post> =>
  337. (await api.query.forum.postById(id)) as Post;
  338. // proposals
  339. export const getActiveProposals = async (
  340. api: ApiPromise
  341. ): Promise<ProposalId[]> =>
  342. api.query.proposalsEngine.activeProposalIds
  343. .keys()
  344. .then((keys) => keys.map(({ args: [id] }) => id as ProposalId));
  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 = String(proposal.title.toHuman());
  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: MemberId; vote: string }[]> => {
  429. let votes: { memberId: MemberId; 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] as MemberId;
  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. export {
  480. getChannel,
  481. getChannelCategory,
  482. getCuratorGroup,
  483. getPerson,
  484. getPlaylist,
  485. getSeries,
  486. getVideo,
  487. getVideoCategory,
  488. getNextChannel,
  489. getNextChannelCategory,
  490. getNextChannelOwnershipTransferRequestId,
  491. getNextCuratorGroup,
  492. getNextPerson,
  493. getNextPlaylist,
  494. getNextSeries,
  495. getNextVideo,
  496. getNextVideoCategory,
  497. } from "./content";
  498. export {
  499. feePerMegabyte,
  500. maxStorageBucketsPerBag,
  501. maxDistributionBucketsPerBag,
  502. maxStorageBucketObjects,
  503. maxStorageBucketSize,
  504. uploadingBlocked,
  505. getBlacklist,
  506. getBlacklistSize,
  507. getDynamicBagPolicy,
  508. getNextDataObject,
  509. getNextStorageBucket,
  510. getNextDistributionFamily,
  511. getBag,
  512. getBags,
  513. getObject,
  514. getBagObjects,
  515. getStorageBucket,
  516. getStorageBuckets,
  517. getDistributionFamily,
  518. getDistributionFamilies,
  519. getDistributionFamilyNumber,
  520. getDistributionFamilyBucket,
  521. getDistributionFamilyBuckets,
  522. } from "./storage";