api.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  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. Exposure,
  16. Hash,
  17. Moment,
  18. } from "@polkadot/types/interfaces";
  19. import { SignedBlock } from "@polkadot/types/interfaces/runtime";
  20. import { types } from "@joystream/types";
  21. import { MemberId, PostId, ThreadId } from "@joystream/types/common";
  22. import { CategoryId, Category, Thread, Post } from "@joystream/types/forum";
  23. import {
  24. Candidate,
  25. CouncilMember,
  26. CouncilStage,
  27. } from "@joystream/types/council";
  28. import { Membership } from "@joystream/types/members";
  29. import {
  30. Proposal,
  31. ProposalId,
  32. ProposalCreationParameters,
  33. DiscussionPost,
  34. SpendingParams,
  35. VoteKind,
  36. } from "@joystream/types/proposals";
  37. import { WorkerId, Worker } from "@joystream/types/working-group";
  38. import { ProposalOf, ProposalDetailsOf } from "@joystream/types/augment/types";
  39. export const connectApi = async (
  40. url: string = "ws://localhost:9944"
  41. ): Promise<ApiPromise> => {
  42. const provider = new WsProvider(url);
  43. return await ApiPromise.create({ provider, types });
  44. };
  45. // blocks
  46. export const getBlock = (api: ApiPromise, hash: Hash): Promise<SignedBlock> =>
  47. api.rpc.chain.getBlock(hash);
  48. export const getBlockHash = (
  49. api: ApiPromise,
  50. block: BlockNumber | number
  51. ): Promise<Hash> => {
  52. try {
  53. return api.rpc.chain.getBlockHash(block);
  54. } catch (e) {
  55. return getBestHash(api);
  56. }
  57. };
  58. export const getHead = (api: ApiPromise) => api.derive.chain.bestNumber();
  59. export const getBestHash = (api: ApiPromise) =>
  60. api.rpc.chain.getFinalizedHead();
  61. export const getTimestamp = async (
  62. api: ApiPromise,
  63. hash: Hash
  64. ): Promise<number> =>
  65. moment.utc((await api.query.timestamp.now.at(hash)).toNumber()).valueOf();
  66. export const getIssuance = (api: ApiPromise, hash: Hash): Promise<Balance> =>
  67. api.query.balances.totalIssuance.at(hash);
  68. export const getEvents = (
  69. api: ApiPromise,
  70. hash: Hash
  71. ): Promise<Vec<EventRecord>> => api.query.system.events.at(hash);
  72. export const getEra = async (api: ApiPromise, hash: Hash): Promise<number> =>
  73. Number(await api.query.staking.currentEra.at(hash));
  74. export const getEraStake = async (
  75. api: ApiPromise,
  76. hash: Hash,
  77. era: EraIndex | number
  78. ): Promise<number> =>
  79. (await api.query.staking.erasTotalStake.at(hash, era)).toNumber();
  80. export const getStake = async (
  81. api: ApiPromise,
  82. accountId: AccountId,
  83. hash?: Hash
  84. ): Promise<Exposure> =>
  85. (await (hash
  86. ? api.query.staking.erasStakers.at(hash, accountId)
  87. : api.query.staking.erasStakers(accountId))) as Exposure;
  88. // council
  89. export const getCouncils = async (
  90. api: ApiPromise,
  91. head: number
  92. ): Promise<Round[]> => {
  93. // durations: [ announcing, voting, revealing, term, sum ]
  94. // each chain starts with an election (duration: d[0]+d[1]+d[2])
  95. // elections are repeated if not enough apply (round increments though)
  96. // first term starts at begin of d[3] or some electionDuration later
  97. // term lasts till the end of the next successful election
  98. // `council.termEndsAt` returns the end of the current round
  99. // to determine term starts check every electionDuration blocks
  100. const d: number[] = await getCouncilElectionDurations(
  101. api,
  102. await getBlockHash(api, 1)
  103. );
  104. const electionDuration = d[0] + d[1] + d[2];
  105. const starts: number[] = [];
  106. let lastEnd = 1;
  107. for (let block = lastEnd; block < head; block += electionDuration) {
  108. const hash = await getBlockHash(api, block);
  109. const end = Number(await api.query.council.termEndsAt.at(hash));
  110. if (end === lastEnd) continue;
  111. lastEnd = end;
  112. starts.push(end - d[3]);
  113. }
  114. // index by round: each start is the end of the previous term
  115. const rounds: { [key: number]: Round } = {};
  116. await Promise.all(
  117. starts.map(async (start: number, index: number) => {
  118. const hash = await getBlockHash(api, start);
  119. const round = await getCouncilRound(api, hash);
  120. const isLast = index === starts.length - 1;
  121. const end = isLast ? start + d[4] - 1 : starts[index + 1] - 1;
  122. rounds[round] = { start, round, end };
  123. })
  124. );
  125. return Object.values(rounds);
  126. };
  127. export const getCouncilRound = async (
  128. api: ApiPromise,
  129. hash?: Hash
  130. ): Promise<number> =>
  131. hash
  132. ? ((await api.query.councilElection.round.at(hash)) as u32).toNumber()
  133. : ((await api.query.councilElection.round()) as u32).toNumber();
  134. export const getCouncilElectionStage = (api: ApiPromise, hash: Hash) =>
  135. getCouncilStage(api, hash); // deprecated
  136. export const getCouncilStage = async (
  137. api: ApiPromise,
  138. hash: Hash
  139. ): Promise<CouncilStage> =>
  140. (await api.query.councilElection.stage.at(hash)) as CouncilStage;
  141. export const getCouncilTermEnd = async (
  142. api: ApiPromise,
  143. hash: Hash
  144. ): Promise<number> =>
  145. ((await api.query.council.termEndsAt.at(hash)) as BlockNumber).toNumber();
  146. export const getCouncilElectionStatus = async (
  147. api: ApiPromise,
  148. hash: Hash
  149. ): Promise<ElectionInfo> => {
  150. const durations = await getCouncilElectionDurations(api, hash);
  151. const round = await getCouncilRound(api, hash);
  152. const stage: CouncilStage = await getCouncilStage(api, hash);
  153. const stageEndsAt: number = Number(stage.value as BlockNumber);
  154. const termEndsAt: number = await getCouncilTermEnd(api, hash);
  155. return { round, stageEndsAt, termEndsAt, stage, durations };
  156. };
  157. export const getCouncilSize = async (
  158. api: ApiPromise,
  159. hash: Hash
  160. ): Promise<number> =>
  161. ((await api.query.councilElection.councilSize.at(hash)) as u32).toNumber();
  162. export const getCouncilApplicants = (
  163. api: ApiPromise,
  164. hash: Hash
  165. ): Promise<Vec<AccountId>> => api.query.council.applicants.at(hash);
  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.council[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. // working groups
  200. export const getNextWorker = async (
  201. api: ApiPromise,
  202. group: string,
  203. hash: Hash
  204. ): Promise<number> =>
  205. ((await api.query[group].nextWorkerId.at(hash)) as WorkerId).toNumber();
  206. export const getWorker = (
  207. api: ApiPromise,
  208. group: string,
  209. hash: Hash,
  210. id: number
  211. ): Promise<Worker> => api.query[group].workerById.at(hash, id);
  212. export const getWorkers = async (
  213. api: ApiPromise,
  214. group: string,
  215. hash: Hash
  216. ): Promise<number> => Number(await api.query[group].activeWorkerCount.at(hash));
  217. // members
  218. export const getAccounts = async (
  219. api: ApiPromise
  220. ): Promise<AccountBalance[]> => {
  221. let accounts: AccountBalance[] = [];
  222. const entries = await api.query.system.account.entries();
  223. for (const account of entries) {
  224. const accountId = String(account[0].toHuman());
  225. const balance = account[1].data.toJSON() as unknown as AccountData;
  226. accounts.push({ accountId, balance });
  227. }
  228. return accounts;
  229. };
  230. export const getAccount = (
  231. api: ApiPromise,
  232. hash: Hash,
  233. account: AccountId | string
  234. ): Promise<AccountInfo> => api.query.system.account.at(hash, account);
  235. export const getNextMember = async (
  236. api: ApiPromise,
  237. hash: Hash
  238. ): Promise<number> =>
  239. ((await api.query.members.nextMemberId.at(hash)) as MemberId).toNumber();
  240. export const getMember = async (
  241. api: ApiPromise,
  242. id: MemberId | number,
  243. hash?: Hash
  244. ): Promise<Membership> =>
  245. (await (hash
  246. ? api.query.members.membershipById.at(hash, id)
  247. : api.query.members.membershipById(id))) as Membership;
  248. export const getMemberIdByAccount = async (
  249. api: ApiPromise,
  250. accountId: AccountId
  251. ): Promise<MemberId> => {
  252. const ids = (await api.query.members.memberIdsByRootAccountId(
  253. accountId
  254. )) as Vec<MemberId>;
  255. return ids[0];
  256. };
  257. export const getMemberHandle = async (
  258. api: ApiPromise,
  259. id: MemberId
  260. ): Promise<string> =>
  261. getMember(api, id).then((member: Membership) => String(member.handle_hash));
  262. export const getMemberHandleByAccount = async (
  263. api: ApiPromise,
  264. account: AccountId
  265. ): Promise<string> =>
  266. getMemberHandle(api, await getMemberIdByAccount(api, account));
  267. // forum
  268. export const getNextPost = async (
  269. api: ApiPromise,
  270. hash: Hash
  271. ): Promise<number> =>
  272. ((await api.query.forum.nextPostId.at(hash)) as PostId).toNumber();
  273. export const getNextThread = async (
  274. api: ApiPromise,
  275. hash: Hash
  276. ): Promise<number> =>
  277. ((await api.query.forum.nextThreadId.at(hash)) as ThreadId).toNumber();
  278. export const getNextCategory = async (
  279. api: ApiPromise,
  280. hash: Hash
  281. ): Promise<number> =>
  282. ((await api.query.forum.nextCategoryId.at(hash)) as CategoryId).toNumber();
  283. export const getCategory = async (
  284. api: ApiPromise,
  285. id: number
  286. ): Promise<Category> => (await api.query.forum.categoryById(id)) as Category;
  287. export const getThread = async (api: ApiPromise, id: number): Promise<Thread> =>
  288. (await api.query.forum.threadById(id)) as Thread;
  289. export const getPost = async (api: ApiPromise, id: number): Promise<Post> =>
  290. (await api.query.forum.postById(id)) as Post;
  291. // proposals
  292. export const getActiveProposals = async (
  293. api: ApiPromise
  294. ): Promise<ProposalId[]> =>
  295. api.query.proposalsEngine.activeProposalIds
  296. .keys()
  297. .then((keys) => keys.map(({ args: [id] }) => id as ProposalId));
  298. export const getProposalCount = async (
  299. api: ApiPromise,
  300. hash?: Hash
  301. ): Promise<number> =>
  302. (
  303. (await (hash
  304. ? api.query.proposalsEngine.proposalCount.at(hash)
  305. : api.query.proposalsEngine.proposalCount())) as u32
  306. ).toNumber();
  307. export const getProposalInfo = async (
  308. api: ApiPromise,
  309. id: ProposalId
  310. ): Promise<ProposalOf> =>
  311. (await api.query.proposalsEngine.proposals(id)) as ProposalOf;
  312. export const getProposalDetails = async (
  313. api: ApiPromise,
  314. id: ProposalId
  315. ): Promise<ProposalDetailsOf> =>
  316. (await api.query.proposalsCodex.proposalDetailsByProposalId(
  317. id
  318. )) as ProposalDetailsOf;
  319. export const getProposalType = async (
  320. api: ApiPromise,
  321. id: ProposalId
  322. ): Promise<string> => {
  323. const details = (await getProposalDetails(api, id)) as ProposalDetailsOf;
  324. const [type]: string[] = Object.getOwnPropertyNames(details.toJSON());
  325. return type;
  326. };
  327. export const getProposal = async (
  328. api: ApiPromise,
  329. id: ProposalId
  330. ): Promise<ProposalDetail> => {
  331. const proposal: ProposalOf = await getProposalInfo(api, id);
  332. const {
  333. parameters,
  334. proposerId,
  335. activatedAt,
  336. status,
  337. votingResults,
  338. exactExecutionBlock,
  339. nrOfCouncilConfirmations,
  340. stakingAccountId,
  341. } = proposal;
  342. const stage: string = status.isActive ? "Active" : "Finalized";
  343. const member: Membership = await getMember(api, proposerId);
  344. const author = String(member ? member.handle_hash : proposerId);
  345. //const title = String(proposal.title.toHuman());
  346. const type: string = await getProposalType(api, id);
  347. const args: string[] = [String(id), ``, type, stage, ``, author];
  348. const message = formatProposalMessage(args);
  349. return {
  350. id: Number(id),
  351. activatedAt: +activatedAt,
  352. executedAt: +exactExecutionBlock,
  353. parameters: JSON.stringify(parameters),
  354. message,
  355. status,
  356. votes: votingResults,
  357. type,
  358. author,
  359. authorId: Number(proposerId),
  360. };
  361. };
  362. const formatProposalMessage = (
  363. data: string[],
  364. domain = "https://testnet.joystream.org"
  365. ): { tg: string; discord: string } => {
  366. const [id, title, type, stage, result, handle] = data;
  367. 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}`;
  368. const discord = `**Type**: ${type}\n**Proposer**: ${handle}\n**Title**: ${title}\n**Stage**: ${stage}\n**Result**: ${result}`;
  369. return { tg, discord };
  370. };
  371. export const getProposalVotes = async (
  372. api: ApiPromise,
  373. id: ProposalId | number
  374. ): Promise<{ memberId: MemberId; vote: string }[]> => {
  375. let votes: { memberId: MemberId; vote: string }[] = [];
  376. const entries =
  377. await api.query.proposalsEngine.voteExistsByProposalByVoter.entries(id);
  378. entries.forEach((entry: any) => {
  379. const memberId = entry[0].args[1] as MemberId;
  380. const vote = entry[1].toString();
  381. votes.push({ memberId, vote });
  382. });
  383. return votes;
  384. };
  385. export const getProposalPost = async (
  386. api: ApiPromise,
  387. threadId: ThreadId | number,
  388. postId: PostId | number
  389. ): Promise<DiscussionPost> =>
  390. (await api.query.proposalsDiscussion.postThreadIdByPostId(
  391. threadId,
  392. postId
  393. )) as DiscussionPost;
  394. export const getProposalPosts = (
  395. api: ApiPromise
  396. ): Promise<[StorageKey<any>, DiscussionPost][]> =>
  397. api.query.proposalsDiscussion.postThreadIdByPostId.entries();
  398. export const getProposalPostCount = async (api: ApiPromise): Promise<number> =>
  399. Number((await api.query.proposalsDiscussion.postCount()) as u64);
  400. export const getProposalThreadCount = async (
  401. api: ApiPromise
  402. ): Promise<number> =>
  403. Number((await api.query.proposalsDiscussion.threadCount()) as u64);
  404. // validators
  405. export const getValidatorCount = async (
  406. api: ApiPromise,
  407. hash: Hash
  408. ): Promise<number> =>
  409. ((await api.query.staking.validatorCount.at(hash)) as u32).toNumber();
  410. export const getValidators = async (
  411. api: ApiPromise,
  412. hash: Hash
  413. ): Promise<AccountId[]> => {
  414. const snapshot = (await api.query.staking.snapshotValidators.at(
  415. hash
  416. )) as Option<Vec<AccountId>>;
  417. return snapshot.isSome ? snapshot.unwrap() : [];
  418. };
  419. export {
  420. getChannel,
  421. getChannelCategory,
  422. getCuratorGroup,
  423. getVideo,
  424. getVideoCategory,
  425. getNextChannel,
  426. getNextChannelCategory,
  427. getNextCuratorGroup,
  428. getNextPerson,
  429. getNextPlaylist,
  430. getNextSeries,
  431. getNextVideo,
  432. getNextVideoCategory,
  433. } from "./content";
  434. export {
  435. feePerMegabyte,
  436. maxStorageBucketsPerBag,
  437. maxDistributionBucketsPerBag,
  438. maxStorageBucketObjects,
  439. maxStorageBucketSize,
  440. uploadingBlocked,
  441. getBlacklist,
  442. getBlacklistSize,
  443. getDynamicBagPolicy,
  444. getNextDataObject,
  445. getNextStorageBucket,
  446. getNextDistributionFamily,
  447. getBag,
  448. getBags,
  449. getObject,
  450. getBagObjects,
  451. getStorageBucket,
  452. getStorageBuckets,
  453. getDistributionFamily,
  454. getDistributionFamilies,
  455. getDistributionFamilyNumber,
  456. getDistributionFamilyBucket,
  457. getDistributionFamilyBuckets,
  458. } from "./storage";