Api.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. import BN from 'bn.js'
  2. import { types } from '@joystream/types/'
  3. import { ApiPromise, WsProvider } from '@polkadot/api'
  4. import { QueryableStorageMultiArg, SubmittableExtrinsic, QueryableStorageEntry } from '@polkadot/api/types'
  5. import { formatBalance } from '@polkadot/util'
  6. import { Balance, Moment, BlockNumber } from '@polkadot/types/interfaces'
  7. import { KeyringPair } from '@polkadot/keyring/types'
  8. import { Codec, CodecArg } from '@polkadot/types/types'
  9. import { Option, Vec, UInt } from '@polkadot/types'
  10. import {
  11. AccountSummary,
  12. CouncilInfoObj,
  13. CouncilInfoTuple,
  14. createCouncilInfoObj,
  15. WorkingGroups,
  16. Reward,
  17. GroupMember,
  18. OpeningStatus,
  19. GroupOpeningStage,
  20. GroupOpening,
  21. GroupApplication,
  22. openingPolicyUnstakingPeriodsKeys,
  23. UnstakingPeriods,
  24. StakingPolicyUnstakingPeriodKey,
  25. } from './Types'
  26. import { DeriveBalancesAll } from '@polkadot/api-derive/types'
  27. import { CLIError } from '@oclif/errors'
  28. import ExitCodes from './ExitCodes'
  29. import {
  30. Worker,
  31. WorkerId,
  32. RoleStakeProfile,
  33. Opening as WGOpening,
  34. Application as WGApplication,
  35. StorageProviderId,
  36. } from '@joystream/types/working-group'
  37. import {
  38. Opening,
  39. Application,
  40. OpeningStage,
  41. ApplicationStageKeys,
  42. ApplicationId,
  43. OpeningId,
  44. StakingPolicy,
  45. } from '@joystream/types/hiring'
  46. import { MemberId, Membership } from '@joystream/types/members'
  47. import { RewardRelationship, RewardRelationshipId } from '@joystream/types/recurring-rewards'
  48. import { Stake, StakeId } from '@joystream/types/stake'
  49. import { InputValidationLengthConstraint } from '@joystream/types/common'
  50. import { Class, ClassId, CuratorGroup, CuratorGroupId, Entity, EntityId } from '@joystream/types/content-directory'
  51. import { ContentId, DataObject } from '@joystream/types/media'
  52. import { ServiceProviderRecord, Url } from '@joystream/types/discovery'
  53. import _ from 'lodash'
  54. export const DEFAULT_API_URI = 'ws://localhost:9944/'
  55. const DEFAULT_DECIMALS = new BN(12)
  56. // Mapping of working group to api module
  57. export const apiModuleByGroup: { [key in WorkingGroups]: string } = {
  58. [WorkingGroups.StorageProviders]: 'storageWorkingGroup',
  59. [WorkingGroups.Curators]: 'contentDirectoryWorkingGroup',
  60. }
  61. // Api wrapper for handling most common api calls and allowing easy API implementation switch in the future
  62. export default class Api {
  63. private _api: ApiPromise
  64. private _cdClassesCache: [ClassId, Class][] | null = null
  65. private constructor(originalApi: ApiPromise) {
  66. this._api = originalApi
  67. }
  68. public getOriginalApi(): ApiPromise {
  69. return this._api
  70. }
  71. private static async initApi(apiUri: string = DEFAULT_API_URI): Promise<ApiPromise> {
  72. const wsProvider: WsProvider = new WsProvider(apiUri)
  73. const api = await ApiPromise.create({ provider: wsProvider, types })
  74. // Initializing some api params based on pioneer/packages/react-api/Api.tsx
  75. const [properties] = await Promise.all([api.rpc.system.properties()])
  76. const tokenSymbol = properties.tokenSymbol.unwrapOr('DEV').toString()
  77. const tokenDecimals = properties.tokenDecimals.unwrapOr(DEFAULT_DECIMALS).toNumber()
  78. // formatBlanace config
  79. formatBalance.setDefaults({
  80. decimals: tokenDecimals,
  81. unit: tokenSymbol,
  82. })
  83. return api
  84. }
  85. static async create(apiUri: string = DEFAULT_API_URI): Promise<Api> {
  86. const originalApi: ApiPromise = await Api.initApi(apiUri)
  87. return new Api(originalApi)
  88. }
  89. private queryMultiOnce(queries: Parameters<typeof ApiPromise.prototype.queryMulti>[0]): Promise<Codec[]> {
  90. return new Promise((resolve, reject) => {
  91. let unsub: () => void
  92. this._api
  93. .queryMulti(queries, (res) => {
  94. // unsub should already be set at this point
  95. if (!unsub) {
  96. reject(new CLIError('API queryMulti issue - unsub method not set!', { exit: ExitCodes.ApiError }))
  97. }
  98. unsub()
  99. resolve(res)
  100. })
  101. .then((unsubscribe) => (unsub = unsubscribe))
  102. .catch((e) => reject(e))
  103. })
  104. }
  105. async bestNumber(): Promise<number> {
  106. return (await this._api.derive.chain.bestNumber()).toNumber()
  107. }
  108. async getAccountsBalancesInfo(accountAddresses: string[]): Promise<DeriveBalancesAll[]> {
  109. const accountsBalances: DeriveBalancesAll[] = await Promise.all(
  110. accountAddresses.map((addr) => this._api.derive.balances.all(addr))
  111. )
  112. return accountsBalances
  113. }
  114. // Get on-chain data related to given account.
  115. // For now it's just account balances
  116. async getAccountSummary(accountAddresses: string): Promise<AccountSummary> {
  117. const balances: DeriveBalancesAll = (await this.getAccountsBalancesInfo([accountAddresses]))[0]
  118. // TODO: Some more information can be fetched here in the future
  119. return { balances }
  120. }
  121. async getCouncilInfo(): Promise<CouncilInfoObj> {
  122. const queries: { [P in keyof CouncilInfoObj]: QueryableStorageMultiArg<'promise'> } = {
  123. activeCouncil: this._api.query.council.activeCouncil,
  124. termEndsAt: this._api.query.council.termEndsAt,
  125. autoStart: this._api.query.councilElection.autoStart,
  126. newTermDuration: this._api.query.councilElection.newTermDuration,
  127. candidacyLimit: this._api.query.councilElection.candidacyLimit,
  128. councilSize: this._api.query.councilElection.councilSize,
  129. minCouncilStake: this._api.query.councilElection.minCouncilStake,
  130. minVotingStake: this._api.query.councilElection.minVotingStake,
  131. announcingPeriod: this._api.query.councilElection.announcingPeriod,
  132. votingPeriod: this._api.query.councilElection.votingPeriod,
  133. revealingPeriod: this._api.query.councilElection.revealingPeriod,
  134. round: this._api.query.councilElection.round,
  135. stage: this._api.query.councilElection.stage,
  136. }
  137. const results: CouncilInfoTuple = (await this.queryMultiOnce(Object.values(queries))) as CouncilInfoTuple
  138. return createCouncilInfoObj(...results)
  139. }
  140. async estimateFee(account: KeyringPair, tx: SubmittableExtrinsic<'promise'>): Promise<Balance> {
  141. const paymentInfo = await tx.paymentInfo(account)
  142. return paymentInfo.partialFee
  143. }
  144. createTransferTx(recipient: string, amount: BN) {
  145. return this._api.tx.balances.transfer(recipient, amount)
  146. }
  147. // Working groups
  148. // TODO: This is a lot of repeated logic from "/pioneer/joy-utils/transport"
  149. // It will be refactored to "joystream-js" soon
  150. async entriesByIds<IDType extends UInt, ValueType extends Codec>(
  151. apiMethod: QueryableStorageEntry<'promise'>,
  152. firstKey?: CodecArg // First key in case of double maps
  153. ): Promise<[IDType, ValueType][]> {
  154. const entries: [IDType, ValueType][] = (await apiMethod.entries<ValueType>(firstKey)).map(([storageKey, value]) => [
  155. // If double-map (first key is provided), we map entries by second key
  156. storageKey.args[firstKey !== undefined ? 1 : 0] as IDType,
  157. value,
  158. ])
  159. return entries.sort((a, b) => a[0].toNumber() - b[0].toNumber())
  160. }
  161. protected async blockHash(height: number): Promise<string> {
  162. const blockHash = await this._api.rpc.chain.getBlockHash(height)
  163. return blockHash.toString()
  164. }
  165. protected async blockTimestamp(height: number): Promise<Date> {
  166. const blockTime = (await this._api.query.timestamp.now.at(await this.blockHash(height))) as Moment
  167. return new Date(blockTime.toNumber())
  168. }
  169. protected workingGroupApiQuery(group: WorkingGroups) {
  170. const module = apiModuleByGroup[group]
  171. return this._api.query[module]
  172. }
  173. protected async membershipById(memberId: MemberId): Promise<Membership | null> {
  174. const profile = (await this._api.query.members.membershipById(memberId)) as Membership
  175. // Can't just use profile.isEmpty because profile.suspended is Bool (which isEmpty method always returns false)
  176. return profile.handle.isEmpty ? null : profile
  177. }
  178. async groupLead(group: WorkingGroups): Promise<GroupMember | null> {
  179. const optLeadId = (await this.workingGroupApiQuery(group).currentLead()) as Option<WorkerId>
  180. if (!optLeadId.isSome) {
  181. return null
  182. }
  183. const leadWorkerId = optLeadId.unwrap()
  184. const leadWorker = await this.workerByWorkerId(group, leadWorkerId.toNumber())
  185. return await this.parseGroupMember(leadWorkerId, leadWorker)
  186. }
  187. protected async stakeValue(stakeId: StakeId): Promise<Balance> {
  188. const stake = await this._api.query.stake.stakes<Stake>(stakeId)
  189. return stake.value
  190. }
  191. protected async workerStake(stakeProfile: RoleStakeProfile): Promise<Balance> {
  192. return this.stakeValue(stakeProfile.stake_id)
  193. }
  194. protected async workerReward(relationshipId: RewardRelationshipId): Promise<Reward> {
  195. const rewardRelationship = await this._api.query.recurringRewards.rewardRelationships<RewardRelationship>(
  196. relationshipId
  197. )
  198. return {
  199. totalRecieved: rewardRelationship.total_reward_received,
  200. value: rewardRelationship.amount_per_payout,
  201. interval: rewardRelationship.payout_interval.unwrapOr(undefined)?.toNumber(),
  202. nextPaymentBlock: rewardRelationship.next_payment_at_block.unwrapOr(new BN(0)).toNumber(),
  203. }
  204. }
  205. protected async parseGroupMember(id: WorkerId, worker: Worker): Promise<GroupMember> {
  206. const roleAccount = worker.role_account_id
  207. const memberId = worker.member_id
  208. const profile = await this.membershipById(memberId)
  209. if (!profile) {
  210. throw new Error(`Group member profile not found! (member id: ${memberId.toNumber()})`)
  211. }
  212. let stake: Balance | undefined
  213. if (worker.role_stake_profile && worker.role_stake_profile.isSome) {
  214. stake = await this.workerStake(worker.role_stake_profile.unwrap())
  215. }
  216. let reward: Reward | undefined
  217. if (worker.reward_relationship && worker.reward_relationship.isSome) {
  218. reward = await this.workerReward(worker.reward_relationship.unwrap())
  219. }
  220. return {
  221. workerId: id,
  222. roleAccount,
  223. memberId,
  224. profile,
  225. stake,
  226. reward,
  227. }
  228. }
  229. async workerByWorkerId(group: WorkingGroups, workerId: number): Promise<Worker> {
  230. const nextId = await this.workingGroupApiQuery(group).nextWorkerId<WorkerId>()
  231. // This is chain specfic, but if next id is still 0, it means no workers have been added yet
  232. if (workerId < 0 || workerId >= nextId.toNumber()) {
  233. throw new CLIError('Invalid worker id!')
  234. }
  235. const worker = await this.workingGroupApiQuery(group).workerById<Worker>(workerId)
  236. if (worker.isEmpty) {
  237. throw new CLIError('This worker is not active anymore')
  238. }
  239. return worker
  240. }
  241. async groupMember(group: WorkingGroups, workerId: number) {
  242. const worker = await this.workerByWorkerId(group, workerId)
  243. return await this.parseGroupMember(this._api.createType('WorkerId', workerId), worker)
  244. }
  245. async groupMembers(group: WorkingGroups): Promise<GroupMember[]> {
  246. const workerEntries = await this.groupWorkers(group)
  247. const groupMembers: GroupMember[] = await Promise.all(
  248. workerEntries.map(([id, worker]) => this.parseGroupMember(id, worker))
  249. )
  250. return groupMembers.reverse() // Sort by newest
  251. }
  252. groupWorkers(group: WorkingGroups): Promise<[WorkerId, Worker][]> {
  253. return this.entriesByIds<WorkerId, Worker>(this.workingGroupApiQuery(group).workerById)
  254. }
  255. async openingsByGroup(group: WorkingGroups): Promise<GroupOpening[]> {
  256. let openings: GroupOpening[] = []
  257. const nextId = await this.workingGroupApiQuery(group).nextOpeningId<OpeningId>()
  258. // This is chain specfic, but if next id is still 0, it means no openings have been added yet
  259. if (!nextId.eq(0)) {
  260. const ids = Array.from(Array(nextId.toNumber()).keys()).reverse() // Sort by newest
  261. openings = await Promise.all(ids.map((id) => this.groupOpening(group, id)))
  262. }
  263. return openings
  264. }
  265. protected async hiringOpeningById(id: number | OpeningId): Promise<Opening> {
  266. const result = await this._api.query.hiring.openingById<Opening>(id)
  267. return result
  268. }
  269. protected async hiringApplicationById(id: number | ApplicationId): Promise<Application> {
  270. const result = await this._api.query.hiring.applicationById<Application>(id)
  271. return result
  272. }
  273. async wgApplicationById(group: WorkingGroups, wgApplicationId: number): Promise<WGApplication> {
  274. const nextAppId = await this.workingGroupApiQuery(group).nextApplicationId<ApplicationId>()
  275. if (wgApplicationId < 0 || wgApplicationId >= nextAppId.toNumber()) {
  276. throw new CLIError('Invalid working group application ID!')
  277. }
  278. const result = await this.workingGroupApiQuery(group).applicationById<WGApplication>(wgApplicationId)
  279. return result
  280. }
  281. protected async parseApplication(wgApplicationId: number, wgApplication: WGApplication): Promise<GroupApplication> {
  282. const appId = wgApplication.application_id
  283. const application = await this.hiringApplicationById(appId)
  284. const { active_role_staking_id: roleStakingId, active_application_staking_id: appStakingId } = application
  285. return {
  286. wgApplicationId,
  287. applicationId: appId.toNumber(),
  288. wgOpeningId: wgApplication.opening_id.toNumber(),
  289. member: await this.membershipById(wgApplication.member_id),
  290. roleAccout: wgApplication.role_account_id,
  291. stakes: {
  292. application: appStakingId.isSome ? (await this.stakeValue(appStakingId.unwrap())).toNumber() : 0,
  293. role: roleStakingId.isSome ? (await this.stakeValue(roleStakingId.unwrap())).toNumber() : 0,
  294. },
  295. humanReadableText: application.human_readable_text.toString(),
  296. stage: application.stage.type as ApplicationStageKeys,
  297. }
  298. }
  299. async groupApplication(group: WorkingGroups, wgApplicationId: number): Promise<GroupApplication> {
  300. const wgApplication = await this.wgApplicationById(group, wgApplicationId)
  301. return await this.parseApplication(wgApplicationId, wgApplication)
  302. }
  303. protected async groupOpeningApplications(group: WorkingGroups, wgOpeningId: number): Promise<GroupApplication[]> {
  304. const wgApplicationEntries = await this.entriesByIds<ApplicationId, WGApplication>(
  305. this.workingGroupApiQuery(group).applicationById
  306. )
  307. return Promise.all(
  308. wgApplicationEntries
  309. .filter(([, /* id */ wgApplication]) => wgApplication.opening_id.eqn(wgOpeningId))
  310. .map(([id, wgApplication]) => this.parseApplication(id.toNumber(), wgApplication))
  311. )
  312. }
  313. async groupOpening(group: WorkingGroups, wgOpeningId: number): Promise<GroupOpening> {
  314. const nextId = ((await this.workingGroupApiQuery(group).nextOpeningId()) as OpeningId).toNumber()
  315. if (wgOpeningId < 0 || wgOpeningId >= nextId) {
  316. throw new CLIError('Invalid working group opening ID!')
  317. }
  318. const groupOpening = await this.workingGroupApiQuery(group).openingById<WGOpening>(wgOpeningId)
  319. const openingId = groupOpening.hiring_opening_id.toNumber()
  320. const opening = await this.hiringOpeningById(openingId)
  321. const applications = await this.groupOpeningApplications(group, wgOpeningId)
  322. const stage = await this.parseOpeningStage(opening.stage)
  323. const type = groupOpening.opening_type
  324. const { application_staking_policy: applSP, role_staking_policy: roleSP } = opening
  325. const stakes = {
  326. application: applSP.unwrapOr(undefined),
  327. role: roleSP.unwrapOr(undefined),
  328. }
  329. const unstakingPeriod = (period: Option<BlockNumber>) => period.unwrapOr(new BN(0)).toNumber()
  330. const spUnstakingPeriod = (sp: Option<StakingPolicy>, key: StakingPolicyUnstakingPeriodKey) =>
  331. sp.isSome ? unstakingPeriod(sp.unwrap()[key]) : 0
  332. const unstakingPeriods: Partial<UnstakingPeriods> = {
  333. 'review_period_expired_application_stake_unstaking_period_length': spUnstakingPeriod(
  334. applSP,
  335. 'review_period_expired_unstaking_period_length'
  336. ),
  337. 'crowded_out_application_stake_unstaking_period_length': spUnstakingPeriod(
  338. applSP,
  339. 'crowded_out_unstaking_period_length'
  340. ),
  341. 'review_period_expired_role_stake_unstaking_period_length': spUnstakingPeriod(
  342. roleSP,
  343. 'review_period_expired_unstaking_period_length'
  344. ),
  345. 'crowded_out_role_stake_unstaking_period_length': spUnstakingPeriod(
  346. roleSP,
  347. 'crowded_out_unstaking_period_length'
  348. ),
  349. }
  350. openingPolicyUnstakingPeriodsKeys.forEach((key) => {
  351. unstakingPeriods[key] = unstakingPeriod(groupOpening.policy_commitment[key])
  352. })
  353. return {
  354. wgOpeningId,
  355. openingId,
  356. opening,
  357. stage,
  358. stakes,
  359. applications,
  360. type,
  361. unstakingPeriods: unstakingPeriods as UnstakingPeriods,
  362. }
  363. }
  364. async parseOpeningStage(stage: OpeningStage): Promise<GroupOpeningStage> {
  365. let status: OpeningStatus | undefined, stageBlock: number | undefined, stageDate: Date | undefined
  366. if (stage.isOfType('WaitingToBegin')) {
  367. const stageData = stage.asType('WaitingToBegin')
  368. const currentBlockNumber = (await this._api.derive.chain.bestNumber()).toNumber()
  369. const expectedBlockTime = (this._api.consts.babe.expectedBlockTime as Moment).toNumber()
  370. status = OpeningStatus.WaitingToBegin
  371. stageBlock = stageData.begins_at_block.toNumber()
  372. stageDate = new Date(Date.now() + (stageBlock - currentBlockNumber) * expectedBlockTime)
  373. }
  374. if (stage.isOfType('Active')) {
  375. const stageData = stage.asType('Active')
  376. const substage = stageData.stage
  377. if (substage.isOfType('AcceptingApplications')) {
  378. status = OpeningStatus.AcceptingApplications
  379. stageBlock = substage.asType('AcceptingApplications').started_accepting_applicants_at_block.toNumber()
  380. }
  381. if (substage.isOfType('ReviewPeriod')) {
  382. status = OpeningStatus.InReview
  383. stageBlock = substage.asType('ReviewPeriod').started_review_period_at_block.toNumber()
  384. }
  385. if (substage.isOfType('Deactivated')) {
  386. status = substage.asType('Deactivated').cause.isOfType('Filled')
  387. ? OpeningStatus.Complete
  388. : OpeningStatus.Cancelled
  389. stageBlock = substage.asType('Deactivated').deactivated_at_block.toNumber()
  390. }
  391. if (stageBlock) {
  392. stageDate = new Date(await this.blockTimestamp(stageBlock))
  393. }
  394. }
  395. return {
  396. status: status || OpeningStatus.Unknown,
  397. block: stageBlock,
  398. date: stageDate,
  399. }
  400. }
  401. async getMemberIdsByControllerAccount(address: string): Promise<MemberId[]> {
  402. const ids = await this._api.query.members.memberIdsByControllerAccountId<Vec<MemberId>>(address)
  403. return ids.toArray()
  404. }
  405. async workerExitRationaleConstraint(group: WorkingGroups): Promise<InputValidationLengthConstraint> {
  406. return await this.workingGroupApiQuery(group).workerExitRationaleText<InputValidationLengthConstraint>()
  407. }
  408. // Content directory
  409. async availableClasses(useCache = true): Promise<[ClassId, Class][]> {
  410. return useCache && this._cdClassesCache
  411. ? this._cdClassesCache
  412. : await this.entriesByIds<ClassId, Class>(this._api.query.contentDirectory.classById)
  413. }
  414. availableCuratorGroups(): Promise<[CuratorGroupId, CuratorGroup][]> {
  415. return this.entriesByIds<CuratorGroupId, CuratorGroup>(this._api.query.contentDirectory.curatorGroupById)
  416. }
  417. async curatorGroupById(id: number): Promise<CuratorGroup | null> {
  418. const exists = !!(await this._api.query.contentDirectory.curatorGroupById.size(id)).toNumber()
  419. return exists ? await this._api.query.contentDirectory.curatorGroupById<CuratorGroup>(id) : null
  420. }
  421. async nextCuratorGroupId(): Promise<number> {
  422. return (await this._api.query.contentDirectory.nextCuratorGroupId<CuratorGroupId>()).toNumber()
  423. }
  424. async classById(id: number): Promise<Class | null> {
  425. const c = await this._api.query.contentDirectory.classById<Class>(id)
  426. return c.isEmpty ? null : c
  427. }
  428. async entitiesByClassId(classId: number): Promise<[EntityId, Entity][]> {
  429. const entityEntries = await this.entriesByIds<EntityId, Entity>(this._api.query.contentDirectory.entityById)
  430. return entityEntries.filter(([, entity]) => entity.class_id.toNumber() === classId)
  431. }
  432. async entityById(id: number): Promise<Entity | null> {
  433. const exists = !!(await this._api.query.contentDirectory.curatorGroupById.size(id))
  434. return exists ? await this._api.query.contentDirectory.entityById<Entity>(id) : null
  435. }
  436. async dataObjectByContentId(contentId: ContentId): Promise<DataObject | null> {
  437. const dataObject = await this._api.query.dataDirectory.dataObjectByContentId<Option<DataObject>>(contentId)
  438. return dataObject.unwrapOr(null)
  439. }
  440. async ipnsIdentity(storageProviderId: number): Promise<string | null> {
  441. const accountInfo = await this._api.query.discovery.accountInfoByStorageProviderId<ServiceProviderRecord>(
  442. storageProviderId
  443. )
  444. return accountInfo.isEmpty || accountInfo.expires_at.toNumber() <= (await this.bestNumber())
  445. ? null
  446. : accountInfo.identity.toString()
  447. }
  448. async getRandomBootstrapEndpoint(): Promise<string | null> {
  449. const endpoints = await this._api.query.discovery.bootstrapEndpoints<Vec<Url>>()
  450. const randomEndpoint = _.sample(endpoints.toArray())
  451. return randomEndpoint ? randomEndpoint.toString() : null
  452. }
  453. async isAnyProviderAvailable(): Promise<boolean> {
  454. const accounInfoEntries = await this.entriesByIds<StorageProviderId, ServiceProviderRecord>(
  455. this._api.query.discovery.accountInfoByStorageProviderId
  456. )
  457. const bestNumber = await this.bestNumber()
  458. return !!accounInfoEntries.filter(([, info]) => info.expires_at.toNumber() > bestNumber)
  459. }
  460. }