1
0
mirror of https://github.com/oceanprotocol/market.git synced 2024-06-30 05:41:41 +02:00
market/src/@utils/aquarius.ts

442 lines
11 KiB
TypeScript
Raw Normal View History

import { Asset, LoggerInstance } from '@oceanprotocol/lib'
2021-11-15 19:29:20 +01:00
import { AssetSelectionAsset } from '@shared/FormFields/AssetSelection'
import axios, { CancelToken, AxiosResponse } from 'axios'
import { OrdersData_orders as OrdersData } from '../@types/subgraph/OrdersData'
import { metadataCacheUri, v3MetadataCacheUri } from '../../app.config'
2021-10-21 13:31:19 +02:00
import {
SortDirectionOptions,
SortTermOptions
} from '../@types/aquarius/SearchQuery'
import { transformAssetToAssetSelection } from './assetConvertor'
export const MAXIMUM_NUMBER_OF_PAGES_WITH_RESULTS = 476
Restore compute functionality (#1069) * add balance check and check is consumable * add isOrderable and other helpers * finish start compute job * removed unused methods * add more comments * add pool logic for order * move asset selection to compute helper * small fix * fixed get algo list * refactor start compute job and more fixes * update order params * use compute env and compute consumer address * fix prices * fix algorithms selection list on allowAllPublisher case * fix edit compute settings * update compute resources valid until logic * fixes and cleanups * wip compute jobs * fix compute timeout value * fixed compute jobs logic * fix algo selection list name * fixed compute jobs from profile loading * update start compute flow messages * update set algo access details * update compute message logic * added logs * update package lock * remove logs * fix edit compute checksums for files and container * Fix compute dataset algorithm list (#1194) * fix query Signed-off-by: mihaisc <mihai.scarlat@smartcontrol.ro> * remove comment Signed-off-by: mihaisc <mihai.scarlat@smartcontrol.ro> * Fix previous order tx (#1197) * rename nft update query Signed-off-by: mihaisc <mihai.scarlat@smartcontrol.ro> * fix previous order Signed-off-by: mihaisc <mihai.scarlat@smartcontrol.ro> * fix build * handle order price, NaN and default 0 * optional value for all fee, prevent breaking when no value * fix aquarius call and added logs * update provider compute status call * remove percentage fee from price sum, depends smart contract calculation (#1249) Co-authored-by: Soon Huat <soon_huat.phan@daimler.com> * fix display of compute datasets with free price * removed to lowerCase on eth address * fix compute jobs section and your jobs * bumo ocean lib to 1.0.0-next.32 * c2d show price with fee, exclude provider fee * wip get results * include loading when calculating data + algo price, tooltip show order price * update get compute url and use oceanjs helper for download * update computeStatus signature to fix build and CI * added logs * refactor setting price and fees for assets * update compute details and compute results UI and style * update flex value * update download buttons style * update download buttons text * bump ocean lib version and lint fixes * get provier uri for compute results based on job input did * use zero adress for price and fees order * some fixes * Add reuse order in start compute flow (#1352) * wip add reuse order logic * add reuse order in start job * added missing check if no jobs found * update lib Signed-off-by: mihaisc <mihai.scarlat@smartcontrol.ro> * fix lint Signed-off-by: mihaisc <mihai.scarlat@smartcontrol.ro> Co-authored-by: mihaisc <mihai.scarlat@smartcontrol.ro> * fix fixed rate * fix build * fix your compute jobs section when asset network not selected * disable edit compute settings for algorithms * fix compute jobs infinite loading when no jobs found * fix compute form * show token symbol for free assets also on compute price output * removed swp file * some decimal fixes * partial fix for asset with pool fees, algo not working yet * more decimal fixes * fix algo with pool price and fees fetching * fix selecting algorithms when on different network * fix compute jobs table auto refresh and details modal closing * wip compute initialize * order fixes * fix lint * fix conditions and cleanups * fix compute status text display * init prices and fees after starting a compute job * start/order button tweaks * kick in loader earlier * update compute status feedback messages * fixed initial price * compute jobs refetch and reuse order * remove logs * removed logs and added some explanations * use compute env max duration value in seconds * error handling on intializeCompute and order * removed console logs and added one new check * use optional on initialized provider check * remove toast from provider helper * fix compute env issue on start order * disable job selection during actions execution * temporary fix publish algo with custom docker image * fix provider fee display * remove unnecessary condition * fix alignment based button on action type (#1491) * fix alignment based on action type * moving to CSS modules * send providerFeeAmount as string * remove cast on providerFeeAmount * removed some logs and added few comments * update price output tooltip and total price logic * set providerFee amount only when avaialable * bump oceanlib to 1.1.2 * replace FIleMetadata to fix build * used approveWei for approving provider fees * fix free algo price selection and display * fix provider fee load at first algo selection * update compute help text * fix provider fee approve for free assets * cleanup * remove commented out code * remove unused state * removed unused imports * typos in comments, variables, props * more typos * shorten getAccessDetailsFromTokenPrice() a bit * state & hooks access reordering * Update src/@utils/ddo.ts remove metadata from service type Co-authored-by: Matthias Kretschmann <m@kretschmann.io> * effect dependency fixes * state renaming * effect dependency fixes * compute jobs profile visual fixes * effect dependency fixes * more comments removal * add accountId as a dependency in effect * move isOwner to asset provider * refactor handleComputeOrder for less complexity and more useful error reporting * more proper error throwing * provider fee statement tweak * more obvious edit action * empty array for `publisherTrustedAlgorithms` & `publisherTrustedAlgorithmPublishers` by default * ref #1538 * ref #1539 * don t use initial tx values as valid order use subgraph value * fix algo list fetching * closes #1537 * addresses #1538 * fix disable compute button if algo is consumable * move isOwner check to single effect * Correctly display trusted algorithms in compute asset (#1541) * fix allowed algo * fix trusted algo filter Co-authored-by: mihaisc <mihai.scarlat@smartcontrol.ro> Co-authored-by: Soon Huat <soon_huat.phan@daimler.com> Co-authored-by: Soon Huat <soonhuat.phan@hotmail.com> Co-authored-by: Enzo Vezzaro <enzo-vezzaro@live.it> Co-authored-by: Matthias Kretschmann <m@kretschmann.io> Co-authored-by: mihaisc <mihai@oceanprotocol.com>
2022-06-23 17:53:05 +02:00
export function escapeEsReservedCharacters(value: string): string {
// eslint-disable-next-line no-useless-escape
const pattern = /([\!\*\+\-\=\<\>\&\|\(\)\[\]\{\}\^\~\?\:\\/"])/g
return value.replace(pattern, '\\$1')
}
/**
* @param filterField the name of the actual field from the ddo schema e.g. 'id','service.attributes.main.type'
* @param value the value of the filter
* @returns json structure of the es filter
*/
export function getFilterTerm(
filterField: string,
value: string | number | boolean | number[] | string[]
): FilterTerm {
const isArray = Array.isArray(value)
return {
[isArray ? 'terms' : 'term']: {
[filterField]: value
}
}
}
export function generateBaseQuery(
baseQueryParams: BaseQueryParams
): SearchQuery {
const generatedQuery = {
from: baseQueryParams.esPaginationOptions?.from || 0,
size: baseQueryParams.esPaginationOptions?.size || 1000,
query: {
bool: {
...baseQueryParams.nestedQuery,
filter: [
...(baseQueryParams.filters || []),
getFilterTerm('chainId', baseQueryParams.chainIds),
getFilterTerm('_index', 'aquarius'),
...(baseQueryParams.ignorePurgatory
? []
: [getFilterTerm('purgatory.state', false)])
]
}
}
} as SearchQuery
if (baseQueryParams.aggs !== undefined) {
generatedQuery.aggs = baseQueryParams.aggs
}
if (baseQueryParams.sortOptions !== undefined)
generatedQuery.sort = {
[baseQueryParams.sortOptions.sortBy]:
baseQueryParams.sortOptions.sortDirection ||
SortDirectionOptions.Descending
}
return generatedQuery
}
export function transformQueryResult(
queryResult: SearchResponse,
from = 0,
size = 21
): PagedAssets {
const result: PagedAssets = {
results: [],
page: 0,
totalPages: 0,
totalResults: 0,
aggregations: []
}
result.results = (queryResult.hits.hits || []).map(
(hit) => hit._source as Asset
)
result.aggregations = queryResult.aggregations
2022-02-17 22:38:40 +01:00
result.totalResults = queryResult.hits.total.value
result.totalPages =
result.totalResults / size < 1
? Math.floor(result.totalResults / size)
: Math.ceil(result.totalResults / size)
result.page = from ? from / size + 1 : 1
return result
}
export async function queryMetadata(
query: SearchQuery,
cancelToken: CancelToken
): Promise<PagedAssets> {
try {
const response: AxiosResponse<SearchResponse> = await axios.post(
`${metadataCacheUri}/api/aquarius/assets/query`,
{ ...query },
{ cancelToken }
)
if (!response || response.status !== 200 || !response.data) return
return transformQueryResult(response.data, query.from, query.size)
} catch (error) {
if (axios.isCancel(error)) {
LoggerInstance.log(error.message)
} else {
LoggerInstance.error(error.message)
}
}
}
export async function retrieveAsset(
did: string,
cancelToken: CancelToken
): Promise<Asset> {
try {
const response: AxiosResponse<Asset> = await axios.get(
`${metadataCacheUri}/api/aquarius/assets/ddo/${did}`,
{ cancelToken }
)
if (!response || response.status !== 200 || !response.data) return
const data = { ...response.data }
return data
} catch (error) {
if (axios.isCancel(error)) {
LoggerInstance.log(error.message)
} else {
LoggerInstance.error(error.message)
}
}
}
export async function checkV3Asset(
did: string,
cancelToken: CancelToken
): Promise<boolean> {
try {
const response: AxiosResponse<Asset> = await axios.get(
`${v3MetadataCacheUri}/api/v1/aquarius/assets/ddo/${did}`,
{ cancelToken }
)
if (!response || response.status !== 200 || !response.data) return false
return true
} catch (error) {
if (axios.isCancel(error)) {
LoggerInstance.log(error.message)
} else {
LoggerInstance.error(error.message)
}
return false
}
}
export async function getAssetsNames(
didList: string[],
cancelToken: CancelToken
): Promise<Record<string, string>> {
try {
const response: AxiosResponse<Record<string, string>> = await axios.post(
`${metadataCacheUri}/api/aquarius/assets/names`,
{ didList },
{ cancelToken }
)
if (!response || response.status !== 200 || !response.data) return
return response.data
} catch (error) {
if (axios.isCancel(error)) {
LoggerInstance.log(error.message)
} else {
LoggerInstance.error(error.message)
}
}
}
Edit compute dataset (#417) * WIP * created form for editing compute privacy * used editComputePrivacy method * select and update trusted algorithm * display and select multiple trusted algorithms * fixed update when trusted algorithm list not changed * code refactoring * moved separator inside condition * moved functions and interface from EditComputeDataset component * moved algorithmOptions to parent component * used AssetSelection to display algorithms * use AssetSelection to select trusted algorithms * getAlgorithmsOptions function review * review fixes * removed unused imports * merge fixes * AssetSelection style & usability tweaks * use custom radio & checkbox styles * add simple search for name & DID * spacing adjustments * copy updates, remove raw algo input, hardcode allowRawAlgorithm * copy * AssetSelection usability tweaks * make rows clickable * tweak layout, style and markup * use formik set function to update values * sorted algorithm list, added checked field * sort assetSelection list on user select * fix getAlgorithmsForAssetSelection breaking on empty responses * form debug output * another empty publisherTrustedAlgorithms fix * created separate algorithms state for the form, sort list on edit * refactor * use Formik functionality wherever possible * unify transforming form data to final data * fix form debug transformation * fix form submit, fix defaultChecked * refactor * use Formik functionality wherever possible * unify transforming form data to final data * fix form debug transformation * fix form submit, fix defaultChecked * disable assetSelection when allowAllAlgorithms is true * added loader to AssetSelection * changed allowAllAlgorithms to allowAllPublishedAlgorithms * fixed lint error * updated transformComputeFormToServiceComputePrivacy * lint fix * modify publish defaults Co-authored-by: Matthias Kretschmann <m@kretschmann.io>
2021-03-25 08:34:07 +01:00
export async function getAssetsFromDidList(
didList: string[],
chainIds: number[],
cancelToken: CancelToken
Restore compute functionality (#1069) * add balance check and check is consumable * add isOrderable and other helpers * finish start compute job * removed unused methods * add more comments * add pool logic for order * move asset selection to compute helper * small fix * fixed get algo list * refactor start compute job and more fixes * update order params * use compute env and compute consumer address * fix prices * fix algorithms selection list on allowAllPublisher case * fix edit compute settings * update compute resources valid until logic * fixes and cleanups * wip compute jobs * fix compute timeout value * fixed compute jobs logic * fix algo selection list name * fixed compute jobs from profile loading * update start compute flow messages * update set algo access details * update compute message logic * added logs * update package lock * remove logs * fix edit compute checksums for files and container * Fix compute dataset algorithm list (#1194) * fix query Signed-off-by: mihaisc <mihai.scarlat@smartcontrol.ro> * remove comment Signed-off-by: mihaisc <mihai.scarlat@smartcontrol.ro> * Fix previous order tx (#1197) * rename nft update query Signed-off-by: mihaisc <mihai.scarlat@smartcontrol.ro> * fix previous order Signed-off-by: mihaisc <mihai.scarlat@smartcontrol.ro> * fix build * handle order price, NaN and default 0 * optional value for all fee, prevent breaking when no value * fix aquarius call and added logs * update provider compute status call * remove percentage fee from price sum, depends smart contract calculation (#1249) Co-authored-by: Soon Huat <soon_huat.phan@daimler.com> * fix display of compute datasets with free price * removed to lowerCase on eth address * fix compute jobs section and your jobs * bumo ocean lib to 1.0.0-next.32 * c2d show price with fee, exclude provider fee * wip get results * include loading when calculating data + algo price, tooltip show order price * update get compute url and use oceanjs helper for download * update computeStatus signature to fix build and CI * added logs * refactor setting price and fees for assets * update compute details and compute results UI and style * update flex value * update download buttons style * update download buttons text * bump ocean lib version and lint fixes * get provier uri for compute results based on job input did * use zero adress for price and fees order * some fixes * Add reuse order in start compute flow (#1352) * wip add reuse order logic * add reuse order in start job * added missing check if no jobs found * update lib Signed-off-by: mihaisc <mihai.scarlat@smartcontrol.ro> * fix lint Signed-off-by: mihaisc <mihai.scarlat@smartcontrol.ro> Co-authored-by: mihaisc <mihai.scarlat@smartcontrol.ro> * fix fixed rate * fix build * fix your compute jobs section when asset network not selected * disable edit compute settings for algorithms * fix compute jobs infinite loading when no jobs found * fix compute form * show token symbol for free assets also on compute price output * removed swp file * some decimal fixes * partial fix for asset with pool fees, algo not working yet * more decimal fixes * fix algo with pool price and fees fetching * fix selecting algorithms when on different network * fix compute jobs table auto refresh and details modal closing * wip compute initialize * order fixes * fix lint * fix conditions and cleanups * fix compute status text display * init prices and fees after starting a compute job * start/order button tweaks * kick in loader earlier * update compute status feedback messages * fixed initial price * compute jobs refetch and reuse order * remove logs * removed logs and added some explanations * use compute env max duration value in seconds * error handling on intializeCompute and order * removed console logs and added one new check * use optional on initialized provider check * remove toast from provider helper * fix compute env issue on start order * disable job selection during actions execution * temporary fix publish algo with custom docker image * fix provider fee display * remove unnecessary condition * fix alignment based button on action type (#1491) * fix alignment based on action type * moving to CSS modules * send providerFeeAmount as string * remove cast on providerFeeAmount * removed some logs and added few comments * update price output tooltip and total price logic * set providerFee amount only when avaialable * bump oceanlib to 1.1.2 * replace FIleMetadata to fix build * used approveWei for approving provider fees * fix free algo price selection and display * fix provider fee load at first algo selection * update compute help text * fix provider fee approve for free assets * cleanup * remove commented out code * remove unused state * removed unused imports * typos in comments, variables, props * more typos * shorten getAccessDetailsFromTokenPrice() a bit * state & hooks access reordering * Update src/@utils/ddo.ts remove metadata from service type Co-authored-by: Matthias Kretschmann <m@kretschmann.io> * effect dependency fixes * state renaming * effect dependency fixes * compute jobs profile visual fixes * effect dependency fixes * more comments removal * add accountId as a dependency in effect * move isOwner to asset provider * refactor handleComputeOrder for less complexity and more useful error reporting * more proper error throwing * provider fee statement tweak * more obvious edit action * empty array for `publisherTrustedAlgorithms` & `publisherTrustedAlgorithmPublishers` by default * ref #1538 * ref #1539 * don t use initial tx values as valid order use subgraph value * fix algo list fetching * closes #1537 * addresses #1538 * fix disable compute button if algo is consumable * move isOwner check to single effect * Correctly display trusted algorithms in compute asset (#1541) * fix allowed algo * fix trusted algo filter Co-authored-by: mihaisc <mihai.scarlat@smartcontrol.ro> Co-authored-by: Soon Huat <soon_huat.phan@daimler.com> Co-authored-by: Soon Huat <soonhuat.phan@hotmail.com> Co-authored-by: Enzo Vezzaro <enzo-vezzaro@live.it> Co-authored-by: Matthias Kretschmann <m@kretschmann.io> Co-authored-by: mihaisc <mihai@oceanprotocol.com>
2022-06-23 17:53:05 +02:00
): Promise<PagedAssets> {
try {
if (!(didList.length > 0)) return
const baseParams = {
chainIds,
filters: [getFilterTerm('_id', didList)],
ignorePurgatory: true
} as BaseQueryParams
const query = generateBaseQuery(baseParams)
const queryResult = await queryMetadata(query, cancelToken)
return queryResult
} catch (error) {
LoggerInstance.error(error.message)
}
}
export async function getAssetsFromDtList(
dtList: string[],
chainIds: number[],
cancelToken: CancelToken
): Promise<Asset[]> {
try {
if (!(dtList.length > 0)) return
const baseParams = {
chainIds,
filters: [getFilterTerm('services.datatokenAddress', dtList)],
ignorePurgatory: true
} as BaseQueryParams
const query = generateBaseQuery(baseParams)
const queryResult = await queryMetadata(query, cancelToken)
return queryResult?.results
} catch (error) {
LoggerInstance.error(error.message)
}
}
export async function retrieveDDOListByDIDs(
didList: string[],
chainIds: number[],
cancelToken: CancelToken
): Promise<Asset[]> {
2022-02-18 12:46:34 +01:00
if (didList?.length === 0 || chainIds?.length === 0) return []
try {
const orderedDDOListByDIDList: Asset[] = []
const baseQueryparams = {
chainIds,
filters: [getFilterTerm('_id', didList)],
ignorePurgatory: true
} as BaseQueryParams
const query = generateBaseQuery(baseQueryparams)
const result = await queryMetadata(query, cancelToken)
2022-02-18 12:46:34 +01:00
didList.forEach((did: string) => {
const ddo = result.results.find((ddo: Asset) => ddo.id === did)
2022-02-18 12:46:34 +01:00
if (ddo) orderedDDOListByDIDList.push(ddo)
})
return orderedDDOListByDIDList
} catch (error) {
LoggerInstance.error(error.message)
}
}
export async function getAlgorithmDatasetsForCompute(
algorithmId: string,
datasetProviderUri: string,
datasetChainId?: number,
cancelToken?: CancelToken
): Promise<AssetSelectionAsset[]> {
const baseQueryParams = {
chainIds: [datasetChainId],
Restore compute functionality (#1069) * add balance check and check is consumable * add isOrderable and other helpers * finish start compute job * removed unused methods * add more comments * add pool logic for order * move asset selection to compute helper * small fix * fixed get algo list * refactor start compute job and more fixes * update order params * use compute env and compute consumer address * fix prices * fix algorithms selection list on allowAllPublisher case * fix edit compute settings * update compute resources valid until logic * fixes and cleanups * wip compute jobs * fix compute timeout value * fixed compute jobs logic * fix algo selection list name * fixed compute jobs from profile loading * update start compute flow messages * update set algo access details * update compute message logic * added logs * update package lock * remove logs * fix edit compute checksums for files and container * Fix compute dataset algorithm list (#1194) * fix query Signed-off-by: mihaisc <mihai.scarlat@smartcontrol.ro> * remove comment Signed-off-by: mihaisc <mihai.scarlat@smartcontrol.ro> * Fix previous order tx (#1197) * rename nft update query Signed-off-by: mihaisc <mihai.scarlat@smartcontrol.ro> * fix previous order Signed-off-by: mihaisc <mihai.scarlat@smartcontrol.ro> * fix build * handle order price, NaN and default 0 * optional value for all fee, prevent breaking when no value * fix aquarius call and added logs * update provider compute status call * remove percentage fee from price sum, depends smart contract calculation (#1249) Co-authored-by: Soon Huat <soon_huat.phan@daimler.com> * fix display of compute datasets with free price * removed to lowerCase on eth address * fix compute jobs section and your jobs * bumo ocean lib to 1.0.0-next.32 * c2d show price with fee, exclude provider fee * wip get results * include loading when calculating data + algo price, tooltip show order price * update get compute url and use oceanjs helper for download * update computeStatus signature to fix build and CI * added logs * refactor setting price and fees for assets * update compute details and compute results UI and style * update flex value * update download buttons style * update download buttons text * bump ocean lib version and lint fixes * get provier uri for compute results based on job input did * use zero adress for price and fees order * some fixes * Add reuse order in start compute flow (#1352) * wip add reuse order logic * add reuse order in start job * added missing check if no jobs found * update lib Signed-off-by: mihaisc <mihai.scarlat@smartcontrol.ro> * fix lint Signed-off-by: mihaisc <mihai.scarlat@smartcontrol.ro> Co-authored-by: mihaisc <mihai.scarlat@smartcontrol.ro> * fix fixed rate * fix build * fix your compute jobs section when asset network not selected * disable edit compute settings for algorithms * fix compute jobs infinite loading when no jobs found * fix compute form * show token symbol for free assets also on compute price output * removed swp file * some decimal fixes * partial fix for asset with pool fees, algo not working yet * more decimal fixes * fix algo with pool price and fees fetching * fix selecting algorithms when on different network * fix compute jobs table auto refresh and details modal closing * wip compute initialize * order fixes * fix lint * fix conditions and cleanups * fix compute status text display * init prices and fees after starting a compute job * start/order button tweaks * kick in loader earlier * update compute status feedback messages * fixed initial price * compute jobs refetch and reuse order * remove logs * removed logs and added some explanations * use compute env max duration value in seconds * error handling on intializeCompute and order * removed console logs and added one new check * use optional on initialized provider check * remove toast from provider helper * fix compute env issue on start order * disable job selection during actions execution * temporary fix publish algo with custom docker image * fix provider fee display * remove unnecessary condition * fix alignment based button on action type (#1491) * fix alignment based on action type * moving to CSS modules * send providerFeeAmount as string * remove cast on providerFeeAmount * removed some logs and added few comments * update price output tooltip and total price logic * set providerFee amount only when avaialable * bump oceanlib to 1.1.2 * replace FIleMetadata to fix build * used approveWei for approving provider fees * fix free algo price selection and display * fix provider fee load at first algo selection * update compute help text * fix provider fee approve for free assets * cleanup * remove commented out code * remove unused state * removed unused imports * typos in comments, variables, props * more typos * shorten getAccessDetailsFromTokenPrice() a bit * state & hooks access reordering * Update src/@utils/ddo.ts remove metadata from service type Co-authored-by: Matthias Kretschmann <m@kretschmann.io> * effect dependency fixes * state renaming * effect dependency fixes * compute jobs profile visual fixes * effect dependency fixes * more comments removal * add accountId as a dependency in effect * move isOwner to asset provider * refactor handleComputeOrder for less complexity and more useful error reporting * more proper error throwing * provider fee statement tweak * more obvious edit action * empty array for `publisherTrustedAlgorithms` & `publisherTrustedAlgorithmPublishers` by default * ref #1538 * ref #1539 * don t use initial tx values as valid order use subgraph value * fix algo list fetching * closes #1537 * addresses #1538 * fix disable compute button if algo is consumable * move isOwner check to single effect * Correctly display trusted algorithms in compute asset (#1541) * fix allowed algo * fix trusted algo filter Co-authored-by: mihaisc <mihai.scarlat@smartcontrol.ro> Co-authored-by: Soon Huat <soon_huat.phan@daimler.com> Co-authored-by: Soon Huat <soonhuat.phan@hotmail.com> Co-authored-by: Enzo Vezzaro <enzo-vezzaro@live.it> Co-authored-by: Matthias Kretschmann <m@kretschmann.io> Co-authored-by: mihaisc <mihai@oceanprotocol.com>
2022-06-23 17:53:05 +02:00
nestedQuery: {
must: {
match: {
'services.compute.publisherTrustedAlgorithms.did': {
query: escapeEsReservedCharacters(algorithmId)
}
}
}
},
sortOptions: {
sortBy: SortTermOptions.Created,
sortDirection: SortDirectionOptions.Descending
}
} as BaseQueryParams
const query = generateBaseQuery(baseQueryParams)
const computeDatasets = await queryMetadata(query, cancelToken)
if (computeDatasets.totalResults === 0) return []
const datasets = await transformAssetToAssetSelection(
datasetProviderUri,
computeDatasets.results,
[]
)
return datasets
}
export async function getPublishedAssets(
accountId: string,
chainIds: number[],
cancelToken: CancelToken,
page?: number,
type?: string,
accesType?: string
): Promise<PagedAssets> {
if (!accountId) return
const filters: FilterTerm[] = []
filters.push(getFilterTerm('nft.owner', accountId.toLowerCase()))
accesType !== undefined &&
filters.push(getFilterTerm('services.type', accesType))
type !== undefined && filters.push(getFilterTerm('metadata.type', type))
const baseQueryParams = {
chainIds,
filters,
sortOptions: {
sortBy: SortTermOptions.Created,
sortDirection: SortDirectionOptions.Descending
},
aggs: {
totalOrders: {
sum: {
field: SortTermOptions.Stats
}
}
},
ignorePurgatory: true,
esPaginationOptions: {
from: (Number(page) - 1 || 0) * 9,
size: 9
}
} as BaseQueryParams
const query = generateBaseQuery(baseQueryParams)
try {
const result = await queryMetadata(query, cancelToken)
return result
} catch (error) {
if (axios.isCancel(error)) {
LoggerInstance.log(error.message)
} else {
LoggerInstance.error(error.message)
}
}
}
export async function getTopPublishers(
chainIds: number[],
cancelToken: CancelToken,
page?: number,
type?: string,
accesType?: string
): Promise<PagedAssets> {
const filters: FilterTerm[] = []
accesType !== undefined &&
filters.push(getFilterTerm('services.type', accesType))
type !== undefined && filters.push(getFilterTerm('metadata.type', type))
const baseQueryParams = {
chainIds,
filters,
sortOptions: {
sortBy: SortTermOptions.Created,
sortDirection: SortDirectionOptions.Descending
},
aggs: {
topPublishers: {
terms: {
field: 'nft.owner.keyword',
order: { totalSales: 'desc' }
},
aggs: {
totalSales: {
sum: {
field: SortTermOptions.Stats
}
}
}
}
},
esPaginationOptions: {
from: (Number(page) - 1 || 0) * 9,
size: 9
}
} as BaseQueryParams
const query = generateBaseQuery(baseQueryParams)
try {
const result = await queryMetadata(query, cancelToken)
return result
} catch (error) {
if (axios.isCancel(error)) {
LoggerInstance.log(error.message)
} else {
LoggerInstance.error(error.message)
}
}
}
export async function getDownloadAssets(
dtList: string[],
tokenOrders: OrdersData[],
chainIds: number[],
cancelToken: CancelToken
): Promise<DownloadedAsset[]> {
const baseQueryparams = {
chainIds,
filters: [
getFilterTerm('services.datatokenAddress', dtList),
getFilterTerm('services.type', 'access')
]
} as BaseQueryParams
const query = generateBaseQuery(baseQueryparams)
try {
const result = await queryMetadata(query, cancelToken)
const downloadedAssets: DownloadedAsset[] = result.results
.map((asset) => {
const order = tokenOrders.find(
2022-01-31 13:41:58 +01:00
({ datatoken }) =>
datatoken?.address.toLowerCase() ===
asset.services[0].datatokenAddress.toLowerCase()
)
return {
asset,
networkId: asset.chainId,
2022-01-31 13:41:58 +01:00
dtSymbol: order?.datatoken?.symbol,
timestamp: order?.createdTimestamp
}
})
.sort((a, b) => b.timestamp - a.timestamp)
return downloadedAssets
} catch (error) {
if (axios.isCancel(error)) {
LoggerInstance.log(error.message)
} else {
LoggerInstance.error(error.message)
}
}
}