3
0

api.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  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 } 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 getTimestamp = async (
  65. api: ApiPromise,
  66. hash: Hash
  67. ): Promise<number> =>
  68. moment.utc((await api.query.timestamp.now.at(hash)).toNumber()).valueOf();
  69. export const getIssuance = (api: ApiPromise, hash: Hash): Promise<Balance> =>
  70. api.query.balances.totalIssuance.at(hash);
  71. export const getEvents = (
  72. api: ApiPromise,
  73. hash: Hash
  74. ): Promise<Vec<EventRecord>> => api.query.system.events.at(hash);
  75. export const getEra = async (api: ApiPromise, hash: Hash): Promise<number> =>
  76. Number(api.query.staking.currentEra.at(hash));
  77. export const getEraStake = async (
  78. api: ApiPromise,
  79. hash: Hash,
  80. era: EraIndex | number
  81. ): Promise<number> =>
  82. (await api.query.staking.erasTotalStake.at(hash, era)).toNumber();
  83. // council
  84. export const getCouncil = (api: ApiPromise, hash: Hash): Promise<Seats> =>
  85. api.query.council.activeCouncil.at(hash);
  86. export const getCouncils = async (
  87. api: ApiPromise,
  88. head: number
  89. ): Promise<Round[]> => {
  90. // durations: [ announcing, voting, revealing, term, sum ]
  91. // each chain starts with an election (duration: d[0]+d[1]+d[2])
  92. // elections are repeated if not enough apply (round increments though)
  93. // first term starts at begin of d[3] or some electionDuration later
  94. // term lasts till the end of the next successful election
  95. // `council.termEndsAt` returns the end of the current round
  96. // to determine term starts check every electionDuration blocks
  97. const d: number[] = await getCouncilElectionDurations(
  98. api,
  99. await getBlockHash(api, 1)
  100. );
  101. const electionDuration = d[0] + d[1] + d[2];
  102. const starts: number[] = [];
  103. let lastEnd = 1;
  104. for (let block = lastEnd; block < head; block += electionDuration) {
  105. const hash = await getBlockHash(api, block);
  106. const end = Number(await api.query.council.termEndsAt.at(hash));
  107. if (end === lastEnd) continue;
  108. lastEnd = end;
  109. starts.push(end - d[3]);
  110. }
  111. // index by round: each start is the end of the previous term
  112. const rounds: { [key: number]: Round } = {};
  113. await Promise.all(
  114. starts.map(async (start: number, index: number) => {
  115. const hash = await getBlockHash(api, start);
  116. const round = await getCouncilRound(api, hash);
  117. const isLast = index === starts.length - 1;
  118. const end = isLast ? start + d[4] - 1 : starts[index + 1] - 1;
  119. rounds[round] = { start, round, end };
  120. })
  121. );
  122. return Object.values(rounds);
  123. };
  124. export const getCouncilRound = async (
  125. api: ApiPromise,
  126. hash: Hash
  127. ): Promise<number> =>
  128. ((await api.query.councilElection.round.at(hash)) as u32).toNumber();
  129. export const getCouncilElectionStage = async (
  130. api: ApiPromise,
  131. hash: Hash
  132. ): Promise<ElectionStage> =>
  133. (await api.query.councilElection.stage.at(hash)) as ElectionStage;
  134. export const getCouncilTermEnd = async (
  135. api: ApiPromise,
  136. hash: Hash
  137. ): Promise<number> =>
  138. ((await api.query.council.termEndsAt.at(hash)) as BlockNumber).toNumber();
  139. export const getCouncilElectionStatus = async (
  140. api: ApiPromise,
  141. hash: Hash
  142. ): Promise<ElectionInfo> => {
  143. const durations = await getCouncilElectionDurations(api, hash);
  144. const round = await getCouncilRound(api, hash);
  145. const stage: ElectionStage = await getCouncilElectionStage(api, hash);
  146. const stageEndsAt: number = Number(stage.value as BlockNumber);
  147. const termEndsAt: number = await getCouncilTermEnd(api, hash);
  148. return { round, stageEndsAt, termEndsAt, stage, durations };
  149. };
  150. export const getCouncilSize = async (
  151. api: ApiPromise,
  152. hash: Hash
  153. ): Promise<number> =>
  154. ((await api.query.councilElection.councilSize.at(hash)) as u32).toNumber();
  155. export const getCouncilApplicants = (
  156. api: ApiPromise,
  157. hash: Hash
  158. ): Promise<Vec<AccountId>> => api.query.councilElection.applicants.at(hash);
  159. export const getCouncilApplicantStakes = (
  160. api: ApiPromise,
  161. hash: Hash,
  162. applicant: AccountId
  163. ): Promise<ElectionStake> =>
  164. api.query.councilElection.applicantStakes.at(hash, applicant);
  165. export const getCouncilCommitments = (
  166. api: ApiPromise,
  167. hash: Hash
  168. ): Promise<Vec<Hash>> => api.query.councilElection.commitments.at(hash);
  169. export const getCouncilPayoutInterval = (
  170. api: ApiPromise,
  171. hash: Hash
  172. ): Promise<Option<BlockNumber>> => api.query.council.payoutInterval.at(hash);
  173. export const getCouncilPayout = (
  174. api: ApiPromise,
  175. hash: Hash
  176. ): Promise<Balance> => api.query.council.amountPerPayout.at(hash);
  177. const getCouncilElectionPeriod = (
  178. api: ApiPromise,
  179. hash: Hash,
  180. period: string
  181. ): Promise<BlockNumber> => api.query.councilElection[period].at(hash);
  182. export const getCouncilElectionDurations = async (
  183. api: ApiPromise,
  184. hash: Hash
  185. ): Promise<number[]> => {
  186. const periods = [
  187. "announcingPeriod",
  188. "votingPeriod",
  189. "revealingPeriod",
  190. "newTermDuration",
  191. ];
  192. let durations = await Promise.all(
  193. periods.map((period: string) => getCouncilElectionPeriod(api, hash, period))
  194. ).then((d) => d.map((block: BlockNumber) => block.toNumber()));
  195. durations.push(durations[0] + durations[1] + durations[2] + durations[3]);
  196. return durations;
  197. };
  198. // working groups
  199. export const getNextWorker = async (
  200. api: ApiPromise,
  201. group: string,
  202. hash: Hash
  203. ): Promise<number> =>
  204. ((await api.query[group].nextWorkerId.at(hash)) as WorkerId).toNumber();
  205. export const getWorker = (
  206. api: ApiPromise,
  207. group: string,
  208. hash: Hash,
  209. id: number
  210. ): Promise<WorkerOf> => api.query[group].workerById.at(hash, id);
  211. export const getWorkers = (
  212. api: ApiPromise,
  213. group: string,
  214. hash: Hash
  215. ): Promise<number> => api.query[group].activeWorkerCount.at(hash);
  216. export const getStake = async (
  217. api: ApiPromise,
  218. id: StakeId | number
  219. ): Promise<Stake> => (await api.query.stake.stakes(id)) as Stake;
  220. export const getWorkerReward = (
  221. api: ApiPromise,
  222. hash: Hash,
  223. id: RewardRelationshipId | number
  224. ): Promise<RewardRelationship> =>
  225. api.query.recurringRewards.rewardRelationships.at(hash, id);
  226. // mints
  227. export const getCouncilMint = (api: ApiPromise, hash: Hash): Promise<MintId> =>
  228. api.query.council.councilMint.at(hash);
  229. export const getGroupMint = (
  230. api: ApiPromise,
  231. group: string,
  232. hash: Hash
  233. ): Promise<MintId> => api.query[group].mint.at(hash);
  234. export const getMintsCreated = async (
  235. api: ApiPromise,
  236. hash: Hash
  237. ): Promise<number> => parseInt(await api.query.minting.mintsCreated.at(hash));
  238. export const getMint = (
  239. api: ApiPromise,
  240. hash: Hash,
  241. id: MintId | number
  242. ): Promise<Mint> => api.query.minting.mints.at(hash, id);
  243. // members
  244. export const getAccounts = async (
  245. api: ApiPromise
  246. ): Promise<AccountBalance[]> => {
  247. let accounts: AccountBalance[] = [];
  248. const entries = await api.query.system.account.entries();
  249. for (const account of entries) {
  250. const accountId = String(account[0].toHuman());
  251. const balance = account[1].data.toJSON() as unknown as AccountData;
  252. accounts.push({ accountId, balance });
  253. }
  254. return accounts;
  255. };
  256. export const getAccount = (
  257. api: ApiPromise,
  258. hash: Hash,
  259. account: AccountId | string
  260. ): Promise<AccountInfo> => api.query.system.account.at(hash, account);
  261. export const getNextMember = async (
  262. api: ApiPromise,
  263. hash: Hash
  264. ): Promise<number> =>
  265. ((await api.query.members.nextMemberId.at(hash)) as MemberId).toNumber();
  266. export const getMember = async (
  267. api: ApiPromise,
  268. id: MemberId | number,
  269. hash?: Hash
  270. ): Promise<Membership> =>
  271. (await (hash
  272. ? api.query.members.membershipById.at(hash, id)
  273. : api.query.members.membershipById(id))) as Membership;
  274. export const getMemberIdByAccount = async (
  275. api: ApiPromise,
  276. accountId: AccountId
  277. ): Promise<MemberId> => {
  278. const ids = (await api.query.members.memberIdsByRootAccountId(
  279. accountId
  280. )) as Vec<MemberId>;
  281. return ids[0];
  282. };
  283. // forum
  284. export const getNextPost = async (
  285. api: ApiPromise,
  286. hash: Hash
  287. ): Promise<number> =>
  288. ((await api.query.forum.nextPostId.at(hash)) as PostId).toNumber();
  289. export const getNextThread = async (
  290. api: ApiPromise,
  291. hash: Hash
  292. ): Promise<number> =>
  293. ((await api.query.forum.nextThreadId.at(hash)) as ThreadId).toNumber();
  294. export const getNextCategory = async (
  295. api: ApiPromise,
  296. hash: Hash
  297. ): Promise<number> =>
  298. ((await api.query.forum.nextCategoryId.at(hash)) as CategoryId).toNumber();
  299. export const getCategory = async (
  300. api: ApiPromise,
  301. id: number
  302. ): Promise<Category> => (await api.query.forum.categoryById(id)) as Category;
  303. export const getThread = async (api: ApiPromise, id: number): Promise<Thread> =>
  304. (await api.query.forum.threadById(id)) as Thread;
  305. export const getPost = async (api: ApiPromise, id: number): Promise<Post> =>
  306. (await api.query.forum.postById(id)) as Post;
  307. // proposals
  308. export const getProposalCount = async (
  309. api: ApiPromise,
  310. hash?: Hash
  311. ): Promise<number> =>
  312. (
  313. (await (hash
  314. ? api.query.proposalsEngine.proposalCount.at(hash)
  315. : api.query.proposalsEngine.proposalCount())) as u32
  316. ).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 =
  385. await api.query.proposalsEngine.voteExistsByProposalByVoter.entries(id);
  386. entries.forEach((entry: any) => {
  387. const memberId = entry[0].args[1].toJSON();
  388. const vote = entry[1].toString();
  389. votes.push({ memberId, vote });
  390. });
  391. return votes;
  392. };
  393. export const getProposalPost = async (
  394. api: ApiPromise,
  395. threadId: ThreadId | number,
  396. postId: PostId | number
  397. ): Promise<DiscussionPost> =>
  398. (await api.query.proposalsDiscussion.postThreadIdByPostId(
  399. threadId,
  400. postId
  401. )) as DiscussionPost;
  402. export const getProposalPostCount = async (api: ApiPromise): Promise<number> =>
  403. Number((await api.query.proposalsDiscussion.postCount()) as u64);
  404. export const getProposalThreadCount = async (
  405. api: ApiPromise
  406. ): Promise<number> =>
  407. Number((await api.query.proposalsDiscussion.threadCount()) as u64);
  408. // validators
  409. export const getValidatorCount = async (
  410. api: ApiPromise,
  411. hash: Hash
  412. ): Promise<number> =>
  413. ((await api.query.staking.validatorCount.at(hash)) as u32).toNumber();
  414. export const getValidators = async (
  415. api: ApiPromise,
  416. hash: Hash
  417. ): Promise<AccountId[]> => {
  418. const snapshot = (await api.query.staking.snapshotValidators.at(
  419. hash
  420. )) as Option<Vec<AccountId>>;
  421. return snapshot.isSome ? snapshot.unwrap() : [];
  422. };
  423. // media
  424. export const getNextEntity = async (
  425. api: ApiPromise,
  426. hash: Hash
  427. ): Promise<number> =>
  428. (
  429. (await api.query.contentDirectory.nextEntityId.at(hash)) as EntityId
  430. ).toNumber();
  431. export const getNextChannel = async (
  432. api: ApiPromise,
  433. hash: Hash
  434. ): Promise<number> => api.query.content.nextChannelId.at(hash);
  435. export const getNextVideo = async (
  436. api: ApiPromise,
  437. hash: Hash
  438. ): Promise<number> => api.query.content.nextVideoId.at(hash);
  439. export const getEntity = (
  440. api: ApiPromise,
  441. hash: Hash,
  442. id: number
  443. ): Promise<Entity> => api.query.contentDirectory.entityById.at(hash, id);
  444. export const getDataObjects = async (
  445. api: ApiPromise
  446. ): Promise<Map<ContentId, DataObject>> =>
  447. (await api.query.dataDirectory.dataByContentId.entries()) as unknown as Map<
  448. ContentId,
  449. DataObject
  450. >;
  451. export const getDataObject = async (
  452. api: ApiPromise,
  453. id: ContentId
  454. ): Promise<Option<DataObject>> =>
  455. (await api.query.dataDirectory.dataByContentId(id)) as Option<DataObject>;