api.ts 15 KB

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