diff --git a/.eslintrc.js b/.eslintrc.js index 4dbfa59c9..e2892bc8b 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -10,7 +10,7 @@ module.exports = { 'plugin:@typescript-eslint/recommended', 'prettier', 'prettier/@typescript-eslint', - 'plugin:nestjs/recommended' + 'plugin:nestjs/recommended', ], root: true, env: { @@ -24,6 +24,6 @@ module.exports = { '@typescript-eslint/no-use-before-define': 'off', 'nestjs/use-dependency-injection': 'error', 'nestjs/deprecated-api-modules': 'error', - '@typescript-eslint/quotes': ["warn", "single"] + '@typescript-eslint/quotes': ['warn', 'single'], }, }; diff --git a/package.json b/package.json index 72e568aa6..884ef48aa 100644 --- a/package.json +++ b/package.json @@ -30,7 +30,8 @@ "typeormTimescale": "ts-node --require ts-node/register ./node_modules/typeorm/cli.js -d src/common/persistence/timescaledb/typeorm.config.ts", "generate-migration-timescale": "npm run typeormTimescale -- migration:generate src/common/persistence/timescaledb/migrations/$npm_config_name", "run-migrations-timescale": "npm run typeormTimescale migration:run --transaction=each", - "revert-migrations-timescale": "npm run typeormTimescale migration:revert" + "revert-migrations-timescale": "npm run typeormTimescale migration:revert", + "pretty": "prettier --write \"./**/*.{js,jsx,ts,tsx,json}\"" }, "dependencies": { "@elastic/elasticsearch": "7.12.0", diff --git a/src/abis/nft-swap.abi.json b/src/abis/nft-swap.abi.json index 46c2bebae..eb382824f 100644 --- a/src/abis/nft-swap.abi.json +++ b/src/abis/nft-swap.abi.json @@ -1,625 +1,611 @@ { - "buildInfo": { - "rustc": { - "version": "1.64.0-nightly", - "commitHash": "23e21bdd25026e2839ebe946c2a937c1904887d2", - "commitDate": "2022-07-15", - "channel": "Nightly", - "short": "rustc 1.64.0-nightly (23e21bdd2 2022-07-15)" - }, - "contractCrate": { - "name": "nft-swap", - "version": "0.0.0" - }, - "framework": { - "name": "elrond-wasm", - "version": "0.29.3" - } - }, - "name": "NftSwap", - "constructor": { - "inputs": [ - { - "name": "bid_cut_percentage", - "type": "u64" - }, - { - "name": "swap_price", - "type": "BigUint" - } - ], - "outputs": [] - }, - "endpoints": [ - { - "name": "nftSwap", - "mutability": "mutable", - "payableInTokens": [ - "*" - ], - "inputs": [ - { - "name": "price", - "type": "BigUint" - }, - { - "name": "auction", - "type": "bool" - }, - { - "name": "deadline", - "type": "u64" - }, - { - "name": "opt_payment_token", - "type": "optional", - "multi_arg": true - } - ], - "outputs": [ - { - "type": "u64" - } - ] - }, + "buildInfo": { + "rustc": { + "version": "1.64.0-nightly", + "commitHash": "23e21bdd25026e2839ebe946c2a937c1904887d2", + "commitDate": "2022-07-15", + "channel": "Nightly", + "short": "rustc 1.64.0-nightly (23e21bdd2 2022-07-15)" + }, + "contractCrate": { + "name": "nft-swap", + "version": "0.0.0" + }, + "framework": { + "name": "elrond-wasm", + "version": "0.29.3" + } + }, + "name": "NftSwap", + "constructor": { + "inputs": [ + { + "name": "bid_cut_percentage", + "type": "u64" + }, + { + "name": "swap_price", + "type": "BigUint" + } + ], + "outputs": [] + }, + "endpoints": [ + { + "name": "nftSwap", + "mutability": "mutable", + "payableInTokens": ["*"], + "inputs": [ { - "name": "nftSwapUpdate", - "mutability": "mutable", - "inputs": [ - { - "name": "swap_id", - "type": "u64" - }, - { - "name": "min_bid", - "type": "BigUint" - } - ], - "outputs": [] + "name": "price", + "type": "BigUint" }, { - "name": "nftSwapExtend", - "mutability": "mutable", - "inputs": [ - { - "name": "swap_id", - "type": "u64" - }, - { - "name": "deadline", - "type": "u64" - } - ], - "outputs": [] + "name": "auction", + "type": "bool" }, { - "name": "withdrawProfits", - "onlyOwner": true, - "mutability": "mutable", - "inputs": [ - { - "name": "opt_payment_token", - "type": "optional", - "multi_arg": true - } - ], - "outputs": [] + "name": "deadline", + "type": "u64" }, { - "name": "emergencyWithdraw", - "onlyOwner": true, - "mutability": "mutable", - "inputs": [ - { - "name": "amount", - "type": "BigUint" - }, - { - "name": "opt_payment_token", - "type": "optional", - "multi_arg": true - } - ], - "outputs": [] - }, + "name": "opt_payment_token", + "type": "optional", + "multi_arg": true + } + ], + "outputs": [ { - "name": "setSwapCutAmount", - "onlyOwner": true, - "mutability": "mutable", - "inputs": [ - { - "name": "new_cut", - "type": "BigUint" - } - ], - "outputs": [] - }, + "type": "u64" + } + ] + }, + { + "name": "nftSwapUpdate", + "mutability": "mutable", + "inputs": [ { - "name": "setCutPercentage", - "onlyOwner": true, - "mutability": "mutable", - "inputs": [ - { - "name": "new_cut_percentage", - "type": "u64" - } - ], - "outputs": [] + "name": "swap_id", + "type": "u64" }, { - "name": "setNoCommissionToken", - "onlyOwner": true, - "mutability": "mutable", - "inputs": [ - { - "name": "token_id", - "type": "TokenIdentifier" - }, - { - "name": "active", - "type": "bool" - } - ], - "outputs": [] - }, + "name": "min_bid", + "type": "BigUint" + } + ], + "outputs": [] + }, + { + "name": "nftSwapExtend", + "mutability": "mutable", + "inputs": [ { - "name": "pause", - "onlyOwner": true, - "mutability": "mutable", - "inputs": [], - "outputs": [] + "name": "swap_id", + "type": "u64" }, { - "name": "resume", - "onlyOwner": true, - "mutability": "mutable", - "inputs": [], - "outputs": [] - }, + "name": "deadline", + "type": "u64" + } + ], + "outputs": [] + }, + { + "name": "withdrawProfits", + "onlyOwner": true, + "mutability": "mutable", + "inputs": [ + { + "name": "opt_payment_token", + "type": "optional", + "multi_arg": true + } + ], + "outputs": [] + }, + { + "name": "emergencyWithdraw", + "onlyOwner": true, + "mutability": "mutable", + "inputs": [ { - "name": "getActiveOffer", - "mutability": "readonly", - "inputs": [ - { - "name": "swap_id", - "type": "u64" - }, - { - "name": "address", - "type": "Address" - } - ], - "outputs": [ - { - "type": "bool" - } - ] + "name": "amount", + "type": "BigUint" }, { - "name": "getState", - "mutability": "readonly", - "inputs": [], - "outputs": [ - { - "type": "State" - } - ] - }, + "name": "opt_payment_token", + "type": "optional", + "multi_arg": true + } + ], + "outputs": [] + }, + { + "name": "setSwapCutAmount", + "onlyOwner": true, + "mutability": "mutable", + "inputs": [ + { + "name": "new_cut", + "type": "BigUint" + } + ], + "outputs": [] + }, + { + "name": "setCutPercentage", + "onlyOwner": true, + "mutability": "mutable", + "inputs": [ + { + "name": "new_cut_percentage", + "type": "u64" + } + ], + "outputs": [] + }, + { + "name": "setNoCommissionToken", + "onlyOwner": true, + "mutability": "mutable", + "inputs": [ { - "name": "getMarketplaceCutPercentage", - "mutability": "readonly", - "inputs": [], - "outputs": [ - { - "type": "BigUint" - } - ] + "name": "token_id", + "type": "TokenIdentifier" }, { - "name": "getMarketplaceSwapCut", - "mutability": "readonly", - "inputs": [], - "outputs": [ - { - "type": "BigUint" - } - ] - }, + "name": "active", + "type": "bool" + } + ], + "outputs": [] + }, + { + "name": "pause", + "onlyOwner": true, + "mutability": "mutable", + "inputs": [], + "outputs": [] + }, + { + "name": "resume", + "onlyOwner": true, + "mutability": "mutable", + "inputs": [], + "outputs": [] + }, + { + "name": "getActiveOffer", + "mutability": "readonly", + "inputs": [ { - "name": "getLastValidSwapId", - "mutability": "readonly", - "inputs": [], - "outputs": [ - { - "type": "u64" - } - ] + "name": "swap_id", + "type": "u64" }, { - "name": "getSwapById", - "mutability": "readonly", - "inputs": [ - { - "name": "swap_id", - "type": "u64" - } - ], - "outputs": [ - { - "type": "Swap" - } - ] - }, + "name": "address", + "type": "Address" + } + ], + "outputs": [ { - "name": "getOffersByAddress", - "mutability": "readonly", - "inputs": [ - { - "name": "swap_id", - "type": "u64" - }, - { - "name": "address", - "type": "Address" - } - ], - "outputs": [ - { - "type": "variadic", - "multi_result": true - } - ] + "type": "bool" + } + ] + }, + { + "name": "getState", + "mutability": "readonly", + "inputs": [], + "outputs": [ + { + "type": "State" + } + ] + }, + { + "name": "getMarketplaceCutPercentage", + "mutability": "readonly", + "inputs": [], + "outputs": [ + { + "type": "BigUint" + } + ] + }, + { + "name": "getMarketplaceSwapCut", + "mutability": "readonly", + "inputs": [], + "outputs": [ + { + "type": "BigUint" + } + ] + }, + { + "name": "getLastValidSwapId", + "mutability": "readonly", + "inputs": [], + "outputs": [ + { + "type": "u64" + } + ] + }, + { + "name": "getSwapById", + "mutability": "readonly", + "inputs": [ + { + "name": "swap_id", + "type": "u64" + } + ], + "outputs": [ + { + "type": "Swap" + } + ] + }, + { + "name": "getOffersByAddress", + "mutability": "readonly", + "inputs": [ + { + "name": "swap_id", + "type": "u64" }, { - "name": "getOfferAddressesById", - "mutability": "readonly", - "inputs": [ - { - "name": "swap_id", - "type": "u64" - } - ], - "outputs": [ - { - "type": "variadic
", - "multi_result": true - } - ] + "name": "address", + "type": "Address" + } + ], + "outputs": [ + { + "type": "variadic", + "multi_result": true + } + ] + }, + { + "name": "getOfferAddressesById", + "mutability": "readonly", + "inputs": [ + { + "name": "swap_id", + "type": "u64" + } + ], + "outputs": [ + { + "type": "variadic
", + "multi_result": true + } + ] + }, + { + "name": "getActiveOfferOfAddress", + "mutability": "readonly", + "inputs": [ + { + "name": "address", + "type": "Address" + } + ], + "outputs": [ + { + "type": "variadic", + "multi_result": true + } + ] + }, + { + "name": "getCommissionAmount", + "mutability": "readonly", + "inputs": [ + { + "name": "token_id", + "type": "TokenIdentifier" }, { - "name": "getActiveOfferOfAddress", - "mutability": "readonly", - "inputs": [ - { - "name": "address", - "type": "Address" - } - ], - "outputs": [ - { - "type": "variadic", - "multi_result": true - } - ] + "name": "token_nonce", + "type": "u64" + } + ], + "outputs": [ + { + "type": "BigUint" + } + ] + }, + { + "name": "getClaimableAmount", + "mutability": "readonly", + "inputs": [ + { + "name": "address", + "type": "Address" }, { - "name": "getCommissionAmount", - "mutability": "readonly", - "inputs": [ - { - "name": "token_id", - "type": "TokenIdentifier" - }, - { - "name": "token_nonce", - "type": "u64" - } - ], - "outputs": [ - { - "type": "BigUint" - } - ] + "name": "token_id", + "type": "TokenIdentifier" }, { - "name": "getClaimableAmount", - "mutability": "readonly", - "inputs": [ - { - "name": "address", - "type": "Address" - }, - { - "name": "token_id", - "type": "TokenIdentifier" - }, - { - "name": "token_nonce", - "type": "u64" - } - ], - "outputs": [ - { - "type": "BigUint" - } - ] + "name": "token_nonce", + "type": "u64" + } + ], + "outputs": [ + { + "type": "BigUint" + } + ] + }, + { + "name": "doesSwapExist", + "mutability": "readonly", + "inputs": [ + { + "name": "swap_id", + "type": "u64" + } + ], + "outputs": [ + { + "type": "bool" + } + ] + }, + { + "name": "getAuctionToken", + "mutability": "readonly", + "inputs": [ + { + "name": "swap_id", + "type": "u64" + } + ], + "outputs": [ + { + "type": "optional>", + "multi_result": true + } + ] + }, + { + "name": "totalCommission", + "mutability": "readonly", + "inputs": [], + "outputs": [ + { + "type": "BigUint" + } + ] + }, + { + "name": "addOffer", + "mutability": "mutable", + "payableInTokens": ["*"], + "inputs": [ + { + "name": "swap_id", + "type": "u64" + } + ], + "outputs": [] + }, + { + "name": "addMultiOffer", + "mutability": "mutable", + "payableInTokens": ["*"], + "inputs": [ + { + "name": "swap_id", + "type": "u64" + } + ], + "outputs": [] + }, + { + "name": "activateOffer", + "mutability": "mutable", + "payableInTokens": ["EGLD"], + "inputs": [ + { + "name": "swap_id", + "type": "u64" + } + ], + "outputs": [] + }, + { + "name": "bid", + "mutability": "mutable", + "payableInTokens": ["*"], + "inputs": [ + { + "name": "swap_id", + "type": "u64" + } + ], + "outputs": [] + }, + { + "name": "purchase", + "mutability": "mutable", + "payableInTokens": ["*"], + "inputs": [ + { + "name": "swap_id", + "type": "u64" }, { - "name": "doesSwapExist", - "mutability": "readonly", - "inputs": [ - { - "name": "swap_id", - "type": "u64" - } - ], - "outputs": [ - { - "type": "bool" - } - ] + "name": "amount", + "type": "BigUint" + } + ], + "outputs": [] + }, + { + "name": "acceptBid", + "mutability": "mutable", + "inputs": [ + { + "name": "swap_id", + "type": "u64" + } + ], + "outputs": [] + }, + { + "name": "acceptBidAsWinner", + "mutability": "mutable", + "inputs": [ + { + "name": "swap_id", + "type": "u64" + } + ], + "outputs": [] + }, + { + "name": "acceptOffer", + "mutability": "mutable", + "payableInTokens": ["EGLD"], + "inputs": [ + { + "name": "swap_id", + "type": "u64" }, { - "name": "getAuctionToken", - "mutability": "readonly", - "inputs": [ - { - "name": "swap_id", - "type": "u64" - } - ], - "outputs": [ - { - "type": "optional>", - "multi_result": true - } - ] + "name": "from_address", + "type": "Address" + } + ], + "outputs": [] + }, + { + "name": "withdrawOffer", + "mutability": "mutable", + "inputs": [ + { + "name": "swap_id", + "type": "u64" + } + ], + "outputs": [] + }, + { + "name": "withdrawSwap", + "mutability": "mutable", + "inputs": [ + { + "name": "swap_id", + "type": "u64" + } + ], + "outputs": [] + } + ], + "hasCallback": false, + "types": { + "EsdtToken": { + "type": "struct", + "fields": [ + { + "name": "token_type", + "type": "TokenIdentifier" }, { - "name": "totalCommission", - "mutability": "readonly", - "inputs": [], - "outputs": [ - { - "type": "BigUint" - } - ] + "name": "nonce", + "type": "u64" + } + ] + }, + "Offer": { + "type": "struct", + "fields": [ + { + "name": "token", + "type": "EsdtToken" }, { - "name": "addOffer", - "mutability": "mutable", - "payableInTokens": [ - "*" - ], - "inputs": [ - { - "name": "swap_id", - "type": "u64" - } - ], - "outputs": [] + "name": "nr_tokens", + "type": "BigUint" }, { - "name": "addMultiOffer", - "mutability": "mutable", - "payableInTokens": [ - "*" - ], - "inputs": [ - { - "name": "swap_id", - "type": "u64" - } - ], - "outputs": [] + "name": "original_owner", + "type": "Address" + } + ] + }, + "State": { + "type": "enum", + "variants": [ + { + "name": "Inactive", + "discriminant": 0 }, { - "name": "activateOffer", - "mutability": "mutable", - "payableInTokens": [ - "EGLD" - ], - "inputs": [ - { - "name": "swap_id", - "type": "u64" - } - ], - "outputs": [] + "name": "Active", + "discriminant": 1 + } + ] + }, + "Swap": { + "type": "struct", + "fields": [ + { + "name": "token", + "type": "EsdtToken" }, { - "name": "bid", - "mutability": "mutable", - "payableInTokens": [ - "*" - ], - "inputs": [ - { - "name": "swap_id", - "type": "u64" - } - ], - "outputs": [] + "name": "nr_tokens", + "type": "BigUint" }, { - "name": "purchase", - "mutability": "mutable", - "payableInTokens": [ - "*" - ], - "inputs": [ - { - "name": "swap_id", - "type": "u64" - }, - { - "name": "amount", - "type": "BigUint" - } - ], - "outputs": [] + "name": "min_bid", + "type": "BigUint" }, { - "name": "acceptBid", - "mutability": "mutable", - "inputs": [ - { - "name": "swap_id", - "type": "u64" - } - ], - "outputs": [] + "name": "swap_type", + "type": "SwapType" }, { - "name": "acceptBidAsWinner", - "mutability": "mutable", - "inputs": [ - { - "name": "swap_id", - "type": "u64" - } - ], - "outputs": [] + "name": "deadline", + "type": "u64" }, { - "name": "acceptOffer", - "mutability": "mutable", - "payableInTokens": [ - "EGLD" - ], - "inputs": [ - { - "name": "swap_id", - "type": "u64" - }, - { - "name": "from_address", - "type": "Address" - } - ], - "outputs": [] + "name": "payment_token", + "type": "EsdtToken" }, { - "name": "withdrawOffer", - "mutability": "mutable", - "inputs": [ - { - "name": "swap_id", - "type": "u64" - } - ], - "outputs": [] + "name": "original_owner", + "type": "Address" }, { - "name": "withdrawSwap", - "mutability": "mutable", - "inputs": [ - { - "name": "swap_id", - "type": "u64" - } - ], - "outputs": [] + "name": "creator_royalties_percentage", + "type": "BigUint" } - ], - "hasCallback": false, - "types": { - "EsdtToken": { - "type": "struct", - "fields": [ - { - "name": "token_type", - "type": "TokenIdentifier" - }, - { - "name": "nonce", - "type": "u64" - } - ] - }, - "Offer": { - "type": "struct", - "fields": [ - { - "name": "token", - "type": "EsdtToken" - }, - { - "name": "nr_tokens", - "type": "BigUint" - }, - { - "name": "original_owner", - "type": "Address" - } - ] - }, - "State": { - "type": "enum", - "variants": [ - { - "name": "Inactive", - "discriminant": 0 - }, - { - "name": "Active", - "discriminant": 1 - } - ] + ] + }, + "SwapType": { + "type": "enum", + "variants": [ + { + "name": "Auction", + "discriminant": 0 }, - "Swap": { - "type": "struct", - "fields": [ - { - "name": "token", - "type": "EsdtToken" - }, - { - "name": "nr_tokens", - "type": "BigUint" - }, - { - "name": "min_bid", - "type": "BigUint" - }, - { - "name": "swap_type", - "type": "SwapType" - }, - { - "name": "deadline", - "type": "u64" - }, - { - "name": "payment_token", - "type": "EsdtToken" - }, - { - "name": "original_owner", - "type": "Address" - }, - { - "name": "creator_royalties_percentage", - "type": "BigUint" - } - ] + { + "name": "Swap", + "discriminant": 1 }, - "SwapType": { - "type": "enum", - "variants": [ - { - "name": "Auction", - "discriminant": 0 - }, - { - "name": "Swap", - "discriminant": 1 - }, - { - "name": "Buy", - "discriminant": 2 - } - ] + { + "name": "Buy", + "discriminant": 2 } + ] } + } } diff --git a/src/analytics.indexer.ts b/src/analytics.indexer.ts index d1618ccd0..3e4072eab 100644 --- a/src/analytics.indexer.ts +++ b/src/analytics.indexer.ts @@ -7,10 +7,7 @@ export async function run(startDateUtc: string, endDateUtc: string) { BigNumber.config({ EXPONENTIAL_AT: [-100, 100] }); const app = await NestFactory.create(AnalyticsModule); const analyticsService = app.get(AnalyticsService); - await analyticsService.indexAnalyticsLogs( - parseInt(startDateUtc), - parseInt(endDateUtc), - ); + await analyticsService.indexAnalyticsLogs(parseInt(startDateUtc), parseInt(endDateUtc)); return process.exit(0); } diff --git a/src/common.module.ts b/src/common.module.ts index 2f2e844a9..347fa29f1 100644 --- a/src/common.module.ts +++ b/src/common.module.ts @@ -6,13 +6,7 @@ import { CacheModule } from './common/services/caching/caching.module'; import { ApiConfigModule } from './modules/common/api-config/api.config.module'; @Module({ - imports: [ - forwardRef(() => CacheModule), - ScheduleModule.forRoot(), - ConfigModule, - ApiConfigModule, - MxCommunicationModule, - ], + imports: [forwardRef(() => CacheModule), ScheduleModule.forRoot(), ConfigModule, ApiConfigModule, MxCommunicationModule], exports: [MxCommunicationModule, CacheModule, Logger, ApiConfigModule], providers: [Logger], }) diff --git a/src/common/persistence/persistence.module.ts b/src/common/persistence/persistence.module.ts index c20bc9aef..d31fecb72 100644 --- a/src/common/persistence/persistence.module.ts +++ b/src/common/persistence/persistence.module.ts @@ -7,18 +7,12 @@ import { TagsRepository } from 'src/db/auctions/tags.repository'; import { CampaignsRepository } from 'src/db/campaigns/campaigns.repository'; import { TiersRepository } from 'src/db/campaigns/tiers.repository'; import { CollectionStatsRepository } from 'src/db/collection-stats/collection-stats.repository'; -import { - FeaturedCollectionsRepository, - FeaturedNftsRepository, -} from 'src/db/featuredNfts/featured.repository'; +import { FeaturedCollectionsRepository, FeaturedNftsRepository } from 'src/db/featuredNfts/featured.repository'; import { MarketplaceCollectionsRepository } from 'src/db/marketplaces/marketplace-collections.repository'; import { MarketplaceRepository } from 'src/db/marketplaces/marketplaces.repository'; import { NftRarityRepository } from 'src/db/nft-rarity/nft-rarity.repository'; import { NftsFlagsRepository } from 'src/db/nftFlags/nft-flags.repository'; -import { - NotificationEntity, - NotificationsRepository, -} from 'src/db/notifications'; +import { NotificationEntity, NotificationsRepository } from 'src/db/notifications'; import { OfferEntity, OffersRepository } from 'src/db/offers'; import { OrderEntity, OrdersRepository } from 'src/db/orders'; import { ReportNftsRepository } from 'src/db/reports/report-nft.repository'; @@ -28,24 +22,14 @@ import { UsdPriceService } from 'src/modules/usdPrice/usd-price.service'; import { MxCommunicationModule } from '../services/mx-communication'; import { MarketplaceEventsRepository } from 'src/db/marketplaces/marketplace-events.repository'; import { BlacklistedCollectionsRepository } from 'src/db/blacklistedCollections/blacklisted.repository'; -import { - ReportCollectionEntity, - ReportCollectionsRepository, - ReportNftEntity, -} from 'src/db/reports'; +import { ReportCollectionEntity, ReportCollectionsRepository, ReportNftEntity } from 'src/db/reports'; import { AssetLikeEntity, AssetsLikesRepository } from 'src/db/assets'; import { BlacklistedCollectionEntity } from 'src/db/blacklistedCollections'; import { TierEntity } from 'src/db/campaigns/tiers.entity'; import { CampaignEntity } from 'src/db/campaigns'; import { TagEntity } from 'src/db/auctions/tags.entity'; -import { - FeaturedCollectionEntity, - FeaturedNftEntity, -} from 'src/db/featuredNfts'; -import { - MarketplaceCollectionEntity, - MarketplaceEntity, -} from 'src/db/marketplaces'; +import { FeaturedCollectionEntity, FeaturedNftEntity } from 'src/db/featuredNfts'; +import { MarketplaceCollectionEntity, MarketplaceEntity } from 'src/db/marketplaces'; import { NftFlagsEntity } from 'src/db/nftFlags'; import { NftRarityEntity } from 'src/db/nft-rarity'; import { MarketplaceEventsEntity } from 'src/db/marketplaces/marketplace-events.entity'; diff --git a/src/common/persistence/persistence.service.ts b/src/common/persistence/persistence.service.ts index 42bfa75ce..ecbc53199 100644 --- a/src/common/persistence/persistence.service.ts +++ b/src/common/persistence/persistence.service.ts @@ -10,28 +10,16 @@ import { AuctionWithStartBid } from 'src/db/auctions/auctionWithBidCount.dto'; import { PriceRange } from 'src/db/auctions/price-range'; import { TagEntity } from 'src/db/auctions/tags.entity'; import { TagsRepository } from 'src/db/auctions/tags.repository'; -import { - BlacklistedCollectionEntity, - BlacklistedCollectionsRepository, -} from 'src/db/blacklistedCollections'; +import { BlacklistedCollectionEntity, BlacklistedCollectionsRepository } from 'src/db/blacklistedCollections'; import { CampaignEntity } from 'src/db/campaigns/campaign.entity'; import { CampaignsRepository } from 'src/db/campaigns/campaigns.repository'; import { TierEntity } from 'src/db/campaigns/tiers.entity'; import { TiersRepository } from 'src/db/campaigns/tiers.repository'; import { CollectionStatsEntity } from 'src/db/collection-stats/collection-stats'; import { CollectionStatsRepository } from 'src/db/collection-stats/collection-stats.repository'; -import { - FeaturedCollectionEntity, - FeaturedNftEntity, -} from 'src/db/featuredNfts/featured.entity'; -import { - FeaturedCollectionsRepository, - FeaturedNftsRepository, -} from 'src/db/featuredNfts/featured.repository'; -import { - MarketplaceCollectionEntity, - MarketplaceEntity, -} from 'src/db/marketplaces'; +import { FeaturedCollectionEntity, FeaturedNftEntity } from 'src/db/featuredNfts/featured.entity'; +import { FeaturedCollectionsRepository, FeaturedNftsRepository } from 'src/db/featuredNfts/featured.repository'; +import { MarketplaceCollectionEntity, MarketplaceEntity } from 'src/db/marketplaces'; import { MarketplaceCollectionsRepository } from 'src/db/marketplaces/marketplace-collections.repository'; import { MarketplaceEventsEntity } from 'src/db/marketplaces/marketplace-events.entity'; import { MarketplaceEventsRepository } from 'src/db/marketplaces/marketplace-events.repository'; @@ -39,19 +27,11 @@ import { MarketplaceRepository } from 'src/db/marketplaces/marketplaces.reposito import { NftRarityEntity } from 'src/db/nft-rarity/nft-rarity.entity'; import { NftRarityRepository } from 'src/db/nft-rarity/nft-rarity.repository'; import { NftFlagsEntity, NftsFlagsRepository } from 'src/db/nftFlags'; -import { - NotificationEntity, - NotificationsRepository, -} from 'src/db/notifications'; +import { NotificationEntity, NotificationsRepository } from 'src/db/notifications'; import { OfferEntity, OffersRepository } from 'src/db/offers'; import { OffersFiltersForDb } from 'src/db/offers/offers.filter'; import { OrderEntity, OrdersRepository } from 'src/db/orders'; -import { - ReportCollectionEntity, - ReportCollectionsRepository, - ReportNftEntity, - ReportNftsRepository, -} from 'src/db/reports'; +import { ReportCollectionEntity, ReportCollectionsRepository, ReportNftEntity, ReportNftsRepository } from 'src/db/reports'; import { AuctionStatusEnum } from 'src/modules/auctions/models/AuctionStatus.enum'; import { QueryRequest } from 'src/modules/common/filters/QueryRequest'; import { FeaturedCollectionTypeEnum } from 'src/modules/featured/FeatureCollectionType.enum'; @@ -101,149 +81,75 @@ export class PersistenceService { } } - async getAssetsLiked( - limit: number = 20, - offset: number = 0, - address: string, - ): Promise<[AssetLikeEntity[], number]> { - return await this.execute( - this.getAssetsLiked.name, - this.assetsLikesRepository.getAssetsLiked(limit, offset, address), - ); + async getAssetsLiked(limit: number = 20, offset: number = 0, address: string): Promise<[AssetLikeEntity[], number]> { + return await this.execute(this.getAssetsLiked.name, this.assetsLikesRepository.getAssetsLiked(limit, offset, address)); } async isAssetLiked(identifier: string, address: string): Promise { - return await this.execute( - this.isAssetLiked.name, - this.assetsLikesRepository.isAssetLiked(identifier, address), - ); + return await this.execute(this.isAssetLiked.name, this.assetsLikesRepository.isAssetLiked(identifier, address)); } async getAssetLikesCount(identifier: string): Promise { - return await this.execute( - this.getAssetLikesCount.name, - this.assetsLikesRepository.getAssetLikesCount(identifier), - ); + return await this.execute(this.getAssetLikesCount.name, this.assetsLikesRepository.getAssetLikesCount(identifier)); } async getLikesCountForAddress(address: string): Promise { - return await this.execute( - this.getLikesCountForAddress.name, - this.assetsLikesRepository.getLikesCountForAddress(address), - ); + return await this.execute(this.getLikesCountForAddress.name, this.assetsLikesRepository.getLikesCountForAddress(address)); } async getBulkAssetLikesCount(identifiers: string[]): Promise { - return await this.execute( - this.getBulkAssetLikesCount.name, - this.assetsLikesRepository.getBulkAssetLikesCount(identifiers), - ); + return await this.execute(this.getBulkAssetLikesCount.name, this.assetsLikesRepository.getBulkAssetLikesCount(identifiers)); } async getIsLikedAsset(identifiers: string[]): Promise { - return await this.execute( - this.getIsLikedAsset.name, - this.assetsLikesRepository.getIsLikedAsset(identifiers), - ); + return await this.execute(this.getIsLikedAsset.name, this.assetsLikesRepository.getIsLikedAsset(identifiers)); } async addLike(assetLikeEntity: AssetLikeEntity): Promise { - return await this.execute( - this.addLike.name, - this.assetsLikesRepository.addLike(assetLikeEntity), - ); + return await this.execute(this.addLike.name, this.assetsLikesRepository.addLike(assetLikeEntity)); } async removeLike(identifier: string, address: string): Promise { - return await this.execute( - this.removeLike.name, - this.assetsLikesRepository.removeLike(identifier, address), - ); + return await this.execute(this.removeLike.name, this.assetsLikesRepository.removeLike(identifier, address)); } - async getPublicAccountStats( - address: string, - marketplaceKey: string = null, - ): Promise { - return await this.execute( - this.getPublicAccountStats.name, - this.accountStatsRepository.getPublicAccountStats( - address, - marketplaceKey, - ), - ); + async getPublicAccountStats(address: string, marketplaceKey: string = null): Promise { + return await this.execute(this.getPublicAccountStats.name, this.accountStatsRepository.getPublicAccountStats(address, marketplaceKey)); } - async getBiddingBalance( - address: string, - marketplaceKey: string = null, - ): Promise<[{ biddingBalance: string; priceToken: string }]> { - return await this.execute( - this.getBiddingBalance.name, - this.accountStatsRepository.getBiddingBalance(address, marketplaceKey), - ); + async getBiddingBalance(address: string, marketplaceKey: string = null): Promise<[{ biddingBalance: string; priceToken: string }]> { + return await this.execute(this.getBiddingBalance.name, this.accountStatsRepository.getBiddingBalance(address, marketplaceKey)); } - async getOwnerAccountStats( - address: string, - marketplaceKey: string = null, - ): Promise { - return await this.execute( - this.getOwnerAccountStats.name, - this.accountStatsRepository.getOwnerAccountStats(address, marketplaceKey), - ); + async getOwnerAccountStats(address: string, marketplaceKey: string = null): Promise { + return await this.execute(this.getOwnerAccountStats.name, this.accountStatsRepository.getOwnerAccountStats(address, marketplaceKey)); } - async getAccountClaimableCount( - address: string, - marketplaceKey: string = null, - ): Promise { + async getAccountClaimableCount(address: string, marketplaceKey: string = null): Promise { return await this.execute( this.getAccountClaimableCount.name, - this.accountStatsRepository.getAccountClaimableCount( - address, - marketplaceKey, - ), + this.accountStatsRepository.getAccountClaimableCount(address, marketplaceKey), ); } - async getTagsBySearchTerm( - searchTerm: string, - page: number = 0, - size: number = 10, - ): Promise { - return await this.execute( - this.getTagsBySearchTerm.name, - this.tagsRepository.getTagsBySearchTerm(searchTerm, page, size), - ); + async getTagsBySearchTerm(searchTerm: string, page: number = 0, size: number = 10): Promise { + return await this.execute(this.getTagsBySearchTerm.name, this.tagsRepository.getTagsBySearchTerm(searchTerm, page, size)); } async getTags(size: number): Promise { - return await this.execute( - this.getTags.name, - this.tagsRepository.getTags(size), - ); + return await this.execute(this.getTags.name, this.tagsRepository.getTags(size)); } async getTagsCount(): Promise { - return await this.execute( - this.getTagsCount.name, - this.tagsRepository.getTagsCount(), - ); + return await this.execute(this.getTagsCount.name, this.tagsRepository.getTagsCount()); } async getTagsBySearchTermCount(searchTerm: string): Promise { - return await this.execute( - this.getTagsBySearchTermCount.name, - this.tagsRepository.getTagsBySearchTermCount(searchTerm), - ); + return await this.execute(this.getTagsBySearchTermCount.name, this.tagsRepository.getTagsBySearchTermCount(searchTerm)); } async saveTags(tags: TagEntity[]): Promise { - return await this.execute( - this.saveTags.name, - this.tagsRepository.saveTags(tags), - ); + return await this.execute(this.saveTags.name, this.tagsRepository.saveTags(tags)); } async getCollectionStats( @@ -253,11 +159,7 @@ export class PersistenceService { ): Promise { return await this.execute( this.getCollectionStats.name, - this.collectionStatsRepository.getStats( - identifier, - marketplaceKey, - paymentToken, - ), + this.collectionStatsRepository.getStats(identifier, marketplaceKey, paymentToken), ); } @@ -268,208 +170,115 @@ export class PersistenceService { ): Promise { return await this.execute( this.getCollectionStats.name, - this.collectionStatsRepository.getFloorPriceForCollection( - identifier, - marketplaceKey, - paymentToken, - ), + this.collectionStatsRepository.getFloorPriceForCollection(identifier, marketplaceKey, paymentToken), ); } - async getCampaign( - campaignId: string, - minterAddress: string, - ): Promise { - return await this.execute( - this.getCampaign.name, - this.campaignsRepository.getCampaign(campaignId, minterAddress), - ); + async getCampaign(campaignId: string, minterAddress: string): Promise { + return await this.execute(this.getCampaign.name, this.campaignsRepository.getCampaign(campaignId, minterAddress)); } - async getCampaignByCollectionTicker( - collectionTicker: string, - ): Promise { + async getCampaignByCollectionTicker(collectionTicker: string): Promise { return await this.execute( this.getCampaignByCollectionTicker.name, this.campaignsRepository.getCampaignByCollectionTicker(collectionTicker), ); } - async getCampaignByMinterAddress( - minterAddress: string, - ): Promise { - return await this.execute( - this.getCampaignByMinterAddress.name, - this.campaignsRepository.getCampaignByMinterAddress(minterAddress), - ); + async getCampaignByMinterAddress(minterAddress: string): Promise { + return await this.execute(this.getCampaignByMinterAddress.name, this.campaignsRepository.getCampaignByMinterAddress(minterAddress)); } async getCampaigns(): Promise<[CampaignEntity[], number]> { - return await this.execute( - this.getCampaigns.name, - this.campaignsRepository.getCampaigns(), - ); + return await this.execute(this.getCampaigns.name, this.campaignsRepository.getCampaigns()); } async saveCampaign(campaign: CampaignEntity): Promise { - return await this.execute( - this.saveCampaign.name, - this.campaignsRepository.saveCampaign(campaign), - ); + return await this.execute(this.saveCampaign.name, this.campaignsRepository.saveCampaign(campaign)); } async getTier(campaignId: number, tierName: string): Promise { - return await this.execute( - this.getTier.name, - this.tiersRepository.getTier(campaignId, tierName), - ); + return await this.execute(this.getTier.name, this.tiersRepository.getTier(campaignId, tierName)); } async getTiersForCampaign(campaignId: number): Promise { - return await this.execute( - this.getTiersForCampaign.name, - this.tiersRepository.getTiersForCampaign(campaignId), - ); + return await this.execute(this.getTiersForCampaign.name, this.tiersRepository.getTiersForCampaign(campaignId)); } async saveTier(tier: TierEntity): Promise { - return await this.execute( - this.saveTier.name, - this.tiersRepository.saveTier(tier), - ); + return await this.execute(this.saveTier.name, this.tiersRepository.saveTier(tier)); } async saveTiers(tiers: TierEntity[]): Promise { - return await this.execute( - this.saveTiers.name, - this.tiersRepository.saveTiers(tiers), - ); + return await this.execute(this.saveTiers.name, this.tiersRepository.saveTiers(tiers)); } - async getFeaturedCollections( - limit: number = 20, - offset: number = 0, - ): Promise<[FeaturedCollectionEntity[], number]> { - return await this.execute( - this.getFeaturedCollections.name, - this.featuredCollectionsRepository.getFeaturedCollections(limit, offset), - ); + async getFeaturedCollections(limit: number = 20, offset: number = 0): Promise<[FeaturedCollectionEntity[], number]> { + return await this.execute(this.getFeaturedCollections.name, this.featuredCollectionsRepository.getFeaturedCollections(limit, offset)); } - async getFeaturedCollectionsByIdentifiers( - collections: string[], - ): Promise { + async getFeaturedCollectionsByIdentifiers(collections: string[]): Promise { return await this.execute( this.getFeaturedCollections.name, - this.featuredCollectionsRepository.getFeaturedCollectionsByIdentifiers( - collections, - ), + this.featuredCollectionsRepository.getFeaturedCollectionsByIdentifiers(collections), ); } - async getTicketCollectionsByIdentifiers( - collections: string[], - ): Promise { + async getTicketCollectionsByIdentifiers(collections: string[]): Promise { return await this.execute( this.getFeaturedCollections.name, - this.featuredCollectionsRepository.getTicketCollectionsByIdentifiers( - collections, - ), + this.featuredCollectionsRepository.getTicketCollectionsByIdentifiers(collections), ); } - async addFeaturedCollection( - collection: string, - type: FeaturedCollectionTypeEnum, - ): Promise { - return await this.execute( - this.addFeaturedCollection.name, - this.featuredCollectionsRepository.addFeaturedCollection( - collection, - type, - ), - ); + async addFeaturedCollection(collection: string, type: FeaturedCollectionTypeEnum): Promise { + return await this.execute(this.addFeaturedCollection.name, this.featuredCollectionsRepository.addFeaturedCollection(collection, type)); } - async removeFeaturedCollection( - collection: string, - type: FeaturedCollectionTypeEnum, - ): Promise { + async removeFeaturedCollection(collection: string, type: FeaturedCollectionTypeEnum): Promise { return await this.execute( this.removeFeaturedCollection.name, - this.featuredCollectionsRepository.removeFeaturedCollection( - collection, - type, - ), + this.featuredCollectionsRepository.removeFeaturedCollection(collection, type), ); } - async getFeaturedNfts( - limit: number = 20, - offset: number = 0, - ): Promise<[FeaturedNftEntity[], number]> { - return await this.execute( - this.getFeaturedNfts.name, - this.featuredNftsRepository.getFeaturedNfts(limit, offset), - ); + async getFeaturedNfts(limit: number = 20, offset: number = 0): Promise<[FeaturedNftEntity[], number]> { + return await this.execute(this.getFeaturedNfts.name, this.featuredNftsRepository.getFeaturedNfts(limit, offset)); } - async getMarketplaceByAddressAndCollection( - collection: string, - address: string, - ): Promise { + async getMarketplaceByAddressAndCollection(collection: string, address: string): Promise { return await this.execute( this.getMarketplaceByAddressAndCollection.name, - this.marketplaceCollectionsRepository.getMarketplaceByAddressAndCollection( - collection, - address, - ), + this.marketplaceCollectionsRepository.getMarketplaceByAddressAndCollection(collection, address), ); } async getAllMarketplaceCollections(): Promise { - return await this.execute( - this.getAllMarketplaceCollections.name, - this.marketplaceCollectionsRepository.getAllCollections(), - ); + return await this.execute(this.getAllMarketplaceCollections.name, this.marketplaceCollectionsRepository.getAllCollections()); } - async getMarketplaceByCollection( - collection: string, - ): Promise { + async getMarketplaceByCollection(collection: string): Promise { return await this.execute( this.getMarketplaceByCollection.name, - this.marketplaceCollectionsRepository.getMarketplaceByCollection( - collection, - ), + this.marketplaceCollectionsRepository.getMarketplaceByCollection(collection), ); } - async getMarketplaceByCollections( - collectionIdentifiers: string[], - ): Promise { + async getMarketplaceByCollections(collectionIdentifiers: string[]): Promise { return await this.execute( this.getMarketplaceByCollection.name, - this.marketplaceCollectionsRepository.getMarketplaceByCollections( - collectionIdentifiers, - ), + this.marketplaceCollectionsRepository.getMarketplaceByCollections(collectionIdentifiers), ); } - async getCollectionsByMarketplace( - marketplaceKey: string, - ): Promise { + async getCollectionsByMarketplace(marketplaceKey: string): Promise { return await this.execute( this.getCollectionsByMarketplace.name, - this.marketplaceCollectionsRepository.getCollectionsByMarketplace( - marketplaceKey, - ), + this.marketplaceCollectionsRepository.getCollectionsByMarketplace(marketplaceKey), ); } - async saveMarketplaceCollection( - entity: MarketplaceCollectionEntity, - ): Promise { + async saveMarketplaceCollection(entity: MarketplaceCollectionEntity): Promise { return await this.execute( this.getCollectionsByMarketplace.name, this.marketplaceCollectionsRepository.saveMarketplaceCollection(entity), @@ -477,264 +286,142 @@ export class PersistenceService { } async getMarketplaces(): Promise<[MarketplaceEntity[], number]> { - return await this.execute( - this.getMarketplaces.name, - this.marketplaceRepository.getMarketplaces(), - ); + return await this.execute(this.getMarketplaces.name, this.marketplaceRepository.getMarketplaces()); } async getMarketplaceByAddress(address: string): Promise { - return await this.execute( - this.getMarketplaceByAddress.name, - this.marketplaceRepository.getMarketplaceByAddress(address), - ); + return await this.execute(this.getMarketplaceByAddress.name, this.marketplaceRepository.getMarketplaceByAddress(address)); } - async getMarketplacesByKeys( - marketplaceKeys: string[], - ): Promise { - return await this.execute( - this.getMarketplacesByKeys.name, - this.marketplaceRepository.getMarketplacesByKeys(marketplaceKeys), - ); + async getMarketplacesByKeys(marketplaceKeys: string[]): Promise { + return await this.execute(this.getMarketplacesByKeys.name, this.marketplaceRepository.getMarketplacesByKeys(marketplaceKeys)); } - async getMarketplacesByAddresses( - addresses: string[], - ): Promise { - return await this.execute( - this.getMarketplacesByAddresses.name, - this.marketplaceRepository.getMarketplacesByAddresses(addresses), - ); + async getMarketplacesByAddresses(addresses: string[]): Promise { + return await this.execute(this.getMarketplacesByAddresses.name, this.marketplaceRepository.getMarketplacesByAddresses(addresses)); } - async updateMarketplaceLastIndexTimestampByAddress( - address: string, - lastIndexTimestamp: number, - ): Promise { + async updateMarketplaceLastIndexTimestampByAddress(address: string, lastIndexTimestamp: number): Promise { await this.execute( this.updateMarketplaceLastIndexTimestampByAddress.name, - this.marketplaceRepository.updateMarketplaceLastIndexTimestamp( - address, - lastIndexTimestamp, - ), + this.marketplaceRepository.updateMarketplaceLastIndexTimestamp(address, lastIndexTimestamp), ); } async isNftReportedBy(identifier: string, address: string): Promise { - return await this.execute( - this.isNftReportedBy.name, - this.reportNftsRepository.isReportedBy(identifier, address), - ); + return await this.execute(this.isNftReportedBy.name, this.reportNftsRepository.isReportedBy(identifier, address)); } async addNftReport(reportEntity: ReportNftEntity): Promise { - return await this.execute( - this.addNftReport.name, - this.reportNftsRepository.addReport(reportEntity), - ); + return await this.execute(this.addNftReport.name, this.reportNftsRepository.addReport(reportEntity)); } async clearNftReport(identifier: string): Promise { - return await this.execute( - this.clearNftReport.name, - this.reportNftsRepository.clearReport(identifier), - ); + return await this.execute(this.clearNftReport.name, this.reportNftsRepository.clearReport(identifier)); } async getNftReportCount(identifier: string): Promise { - return await this.execute( - this.getNftReportCount.name, - this.reportNftsRepository.getReportCount(identifier), - ); + return await this.execute(this.getNftReportCount.name, this.reportNftsRepository.getReportCount(identifier)); } - async isCollectionReportedBy( - identifier: string, - address: string, - ): Promise { - return await this.execute( - this.isCollectionReportedBy.name, - this.reportCollectionsRepository.isReportedBy(identifier, address), - ); + async isCollectionReportedBy(identifier: string, address: string): Promise { + return await this.execute(this.isCollectionReportedBy.name, this.reportCollectionsRepository.isReportedBy(identifier, address)); } - async addCollectionReport( - reportEntity: ReportCollectionEntity, - ): Promise { - return await this.execute( - this.addCollectionReport.name, - this.reportCollectionsRepository.addReport(reportEntity), - ); + async addCollectionReport(reportEntity: ReportCollectionEntity): Promise { + return await this.execute(this.addCollectionReport.name, this.reportCollectionsRepository.addReport(reportEntity)); } async clearCollectionReport(identifier: string): Promise { - return await this.execute( - this.clearCollectionReport.name, - this.reportCollectionsRepository.clearReport(identifier), - ); + return await this.execute(this.clearCollectionReport.name, this.reportCollectionsRepository.clearReport(identifier)); } async getCollectionReportCount(identifier: string): Promise { - return await this.execute( - this.getCollectionReportCount.name, - this.reportCollectionsRepository.getReportCount(identifier), - ); + return await this.execute(this.getCollectionReportCount.name, this.reportCollectionsRepository.getReportCount(identifier)); } async addFlag(flagEntity: NftFlagsEntity): Promise { - return await this.execute( - this.addFlag.name, - this.nftsFlagsRepository.addFlag(flagEntity), - ); + return await this.execute(this.addFlag.name, this.nftsFlagsRepository.addFlag(flagEntity)); } async batchGetFlags(identifiers: string[]): Promise> { - return await this.execute( - this.batchGetFlags.name, - this.nftsFlagsRepository.batchGetFlags(identifiers), - ); + return await this.execute(this.batchGetFlags.name, this.nftsFlagsRepository.batchGetFlags(identifiers)); } async upsertFlags(entities: NftFlagsEntity[]): Promise { - return await this.execute( - this.upsertFlags.name, - this.nftsFlagsRepository.upsertFlags(entities), - ); + return await this.execute(this.upsertFlags.name, this.nftsFlagsRepository.upsertFlags(entities)); } async updateFlag(flag: NftFlagsEntity): Promise { - return await this.execute( - this.updateFlag.name, - this.nftsFlagsRepository.updateFlag(flag), - ); + return await this.execute(this.updateFlag.name, this.nftsFlagsRepository.updateFlag(flag)); } - async saveOrUpdateBulkRarities( - nftRarities: NftRarityEntity[], - ): Promise { - return await this.execute( - this.saveOrUpdateBulkRarities.name, - this.nftRarityRepository.saveOrUpdateBulk(nftRarities), - ); + async saveOrUpdateBulkRarities(nftRarities: NftRarityEntity[]): Promise { + return await this.execute(this.saveOrUpdateBulkRarities.name, this.nftRarityRepository.saveOrUpdateBulk(nftRarities)); } async getCollectionIds(): Promise { - return await this.execute( - this.getCollectionIds.name, - this.nftRarityRepository.getCollectionIds(), - ); + return await this.execute(this.getCollectionIds.name, this.nftRarityRepository.getCollectionIds()); } async getBulkRarities(identifiers: string[]): Promise { - return await this.execute( - this.getBulkRarities.name, - this.nftRarityRepository.getBulkRarities(identifiers), - ); + return await this.execute(this.getBulkRarities.name, this.nftRarityRepository.getBulkRarities(identifiers)); } - async findNftRarityByCollection( - collectionTicker: string, - ): Promise { - return await this.execute( - this.findNftRarityByCollection.name, - this.nftRarityRepository.findNftRarityByCollection(collectionTicker), - ); + async findNftRarityByCollection(collectionTicker: string): Promise { + return await this.execute(this.findNftRarityByCollection.name, this.nftRarityRepository.findNftRarityByCollection(collectionTicker)); } async deleteNftRarity(identifier: string): Promise { - return await this.execute( - this.deleteNftRarity.name, - this.nftRarityRepository.deleteNftRarity(identifier), - ); + return await this.execute(this.deleteNftRarity.name, this.nftRarityRepository.deleteNftRarity(identifier)); } - async getNotificationsForAddress( - address: string, - marketplaceKey: string, - ): Promise<[NotificationEntity[], number]> { + async getNotificationsForAddress(address: string, marketplaceKey: string): Promise<[NotificationEntity[], number]> { return await this.execute( this.getNotificationsForAddress.name, - this.notificationRepository.getNotificationsForAddress( - address, - marketplaceKey, - ), + this.notificationRepository.getNotificationsForAddress(address, marketplaceKey), ); } - async getNotificationsByAuctionIds( - auctionIds: number[], - ): Promise { - return await this.execute( - this.getNotificationsByAuctionIds.name, - this.notificationRepository.getNotificationsByAuctionIds(auctionIds), - ); + async getNotificationsByAuctionIds(auctionIds: number[]): Promise { + return await this.execute(this.getNotificationsByAuctionIds.name, this.notificationRepository.getNotificationsByAuctionIds(auctionIds)); } - async getNotificationsByIdentifiersAndType( - identifiers: string[], - type: NotificationTypeEnum[], - ): Promise { + async getNotificationsByIdentifiersAndType(identifiers: string[], type: NotificationTypeEnum[]): Promise { return await this.execute( this.getNotificationsByIdentifiersAndType.name, - this.notificationRepository.getNotificationsByIdentifiersAndType( - identifiers, - type, - ), + this.notificationRepository.getNotificationsByIdentifiersAndType(identifiers, type), ); } - async getNotificationByIdAndOwner( - auctionId: number, - ownerAddress: string, - ): Promise { + async getNotificationByIdAndOwner(auctionId: number, ownerAddress: string): Promise { return await this.execute( this.getNotificationByIdAndOwner.name, - this.notificationRepository.getNotificationByIdAndOwner( - auctionId, - ownerAddress, - ), + this.notificationRepository.getNotificationByIdAndOwner(auctionId, ownerAddress), ); } async saveNotification(notification: NotificationEntity) { - return await this.execute( - this.saveNotification.name, - this.notificationRepository.saveNotification(notification), - ); + return await this.execute(this.saveNotification.name, this.notificationRepository.saveNotification(notification)); } async saveNotifications(notifications: NotificationEntity[]) { - return await this.execute( - this.saveNotifications.name, - this.notificationRepository.saveNotifications(notifications), - ); + return await this.execute(this.saveNotifications.name, this.notificationRepository.saveNotifications(notifications)); } async updateNotification(notification: NotificationEntity) { - return await this.execute( - this.updateNotification.name, - this.notificationRepository.updateNotification(notification), - ); + return await this.execute(this.updateNotification.name, this.notificationRepository.updateNotification(notification)); } async getActiveOrderForAuction(auctionId: number): Promise { - return await this.execute( - this.getActiveOrderForAuction.name, - this.ordersRepository.getActiveOrderForAuction(auctionId), - ); + return await this.execute(this.getActiveOrderForAuction.name, this.ordersRepository.getActiveOrderForAuction(auctionId)); } async getActiveOrdersForAuction(auctionId: number): Promise { - return await this.execute( - this.getActiveOrdersForAuction.name, - this.ordersRepository.getActiveOrdersForAuction(auctionId), - ); + return await this.execute(this.getActiveOrdersForAuction.name, this.ordersRepository.getActiveOrdersForAuction(auctionId)); } - async getOrdersByAuctionIdsOrderByPrice( - auctionIds: number[], - ): Promise { + async getOrdersByAuctionIdsOrderByPrice(auctionIds: number[]): Promise { return await this.execute( this.getOrdersByAuctionIdsOrderByPrice.name, this.ordersRepository.getOrdersByAuctionIdsOrderByPrice(auctionIds), @@ -742,102 +429,55 @@ export class PersistenceService { } async getOrdersByComposedKeys(auctionIds: string[]): Promise { - return await this.execute( - this.getOrdersByComposedKeys.name, - this.ordersRepository.getOrdersByComposedKeys(auctionIds), - ); + return await this.execute(this.getOrdersByComposedKeys.name, this.ordersRepository.getOrdersByComposedKeys(auctionIds)); } async getLastOrdersByAuctionIds(auctionIds: number[]): Promise { - return await this.execute( - this.getLastOrdersByAuctionIds.name, - this.ordersRepository.getLastOrdersByAuctionIds(auctionIds), - ); + return await this.execute(this.getLastOrdersByAuctionIds.name, this.ordersRepository.getLastOrdersByAuctionIds(auctionIds)); } async getOrdersByAuctionIds(auctionIds: number[]): Promise { - return await this.execute( - this.getOrdersByAuctionIds.name, - this.ordersRepository.getOrdersByAuctionIds(auctionIds), - ); + return await this.execute(this.getOrdersByAuctionIds.name, this.ordersRepository.getOrdersByAuctionIds(auctionIds)); } - async getOrders( - queryRequest: QueryRequest, - ): Promise<[OrderEntity[], number]> { - return await this.execute( - this.getOrders.name, - this.ordersRepository.getOrders(queryRequest), - ); + async getOrders(queryRequest: QueryRequest): Promise<[OrderEntity[], number]> { + return await this.execute(this.getOrders.name, this.ordersRepository.getOrders(queryRequest)); } async saveOrder(order: OrderEntity) { - return await this.execute( - this.saveOrder.name, - this.ordersRepository.saveOrder(order), - ); + return await this.execute(this.saveOrder.name, this.ordersRepository.saveOrder(order)); } async saveBulkOrders(orders: OrderEntity[]) { - return await this.execute( - this.saveBulkOrders.name, - this.ordersRepository.saveBulkOrders(orders), - ); + return await this.execute(this.saveBulkOrders.name, this.ordersRepository.saveBulkOrders(orders)); } async updateOrderWithStatus(order: OrderEntity, status: OrderStatusEnum) { - return await this.execute( - this.updateOrderWithStatus.name, - this.ordersRepository.updateOrderWithStatus(order, status), - ); + return await this.execute(this.updateOrderWithStatus.name, this.ordersRepository.updateOrderWithStatus(order, status)); } async rollbackOrdersByHash(blockHash: string) { - return await this.execute( - this.rollbackOrdersByHash.name, - this.ordersRepository.rollbackOrdersByHash(blockHash), - ); + return await this.execute(this.rollbackOrdersByHash.name, this.ordersRepository.rollbackOrdersByHash(blockHash)); } async deleteOrdersByAuctionId(auctionIds: number[]) { - return await this.execute( - this.deleteOrdersByAuctionId.name, - this.ordersRepository.deleteOrdersByAuctionId(auctionIds), - ); + return await this.execute(this.deleteOrdersByAuctionId.name, this.ordersRepository.deleteOrdersByAuctionId(auctionIds)); } - async getAuctions( - queryRequest: QueryRequest, - ): Promise<[AuctionEntity[], number, PriceRange]> { - return await this.execute( - this.getAuctions.name, - this.auctionsRepository.getAuctions(queryRequest), - ); + async getAuctions(queryRequest: QueryRequest): Promise<[AuctionEntity[], number, PriceRange]> { + return await this.execute(this.getAuctions.name, this.auctionsRepository.getAuctions(queryRequest)); } - async getAuctionsGroupBy( - queryRequest: QueryRequest, - ): Promise<[AuctionEntity[] | AuctionWithStartBid[], number, PriceRange]> { - return await this.execute( - this.getAuctionsGroupBy.name, - this.auctionsRepository.getAuctionsGroupBy(queryRequest), - ); + async getAuctionsGroupBy(queryRequest: QueryRequest): Promise<[AuctionEntity[] | AuctionWithStartBid[], number, PriceRange]> { + return await this.execute(this.getAuctionsGroupBy.name, this.auctionsRepository.getAuctionsGroupBy(queryRequest)); } - async getAuctionsForIdentifier( - queryRequest: QueryRequest, - ): Promise<[AuctionEntity[], number, PriceRange]> { - return await this.execute( - this.getAuctionsForIdentifier.name, - this.auctionsRepository.getAuctionsForIdentifier(queryRequest), - ); + async getAuctionsForIdentifier(queryRequest: QueryRequest): Promise<[AuctionEntity[], number, PriceRange]> { + return await this.execute(this.getAuctionsForIdentifier.name, this.auctionsRepository.getAuctionsForIdentifier(queryRequest)); } async getAuctionsForHash(blockHash: string): Promise { - return await this.execute( - this.getAuctionsForHash.name, - this.auctionsRepository.getAuctionsForHash(blockHash), - ); + return await this.execute(this.getAuctionsForHash.name, this.auctionsRepository.getAuctionsForHash(blockHash)); } async getClaimableAuctions( @@ -848,45 +488,27 @@ export class PersistenceService { ): Promise<[AuctionEntity[], number]> { return await this.execute( this.getClaimableAuctions.name, - this.auctionsRepository.getClaimableAuctions( - limit, - offset, - address, - marketplaceKey, - ), + this.auctionsRepository.getClaimableAuctions(limit, offset, address, marketplaceKey), ); } - async getAuctionsOrderByOrdersCountGroupByIdentifier( - queryRequest: QueryRequest, - ): Promise<[AuctionEntity[], number, PriceRange]> { + async getAuctionsOrderByOrdersCountGroupByIdentifier(queryRequest: QueryRequest): Promise<[AuctionEntity[], number, PriceRange]> { return await this.execute( this.getAuctionsOrderByOrdersCountGroupByIdentifier.name, - this.auctionsRepository.getAuctionsOrderByOrdersCountGroupByIdentifier( - queryRequest, - ), + this.auctionsRepository.getAuctionsOrderByOrdersCountGroupByIdentifier(queryRequest), ); } async getTrendingCollections(): Promise { - return await this.execute( - this.getTrendingCollections.name, - this.auctionsRepository.getTrendingCollections(), - ); + return await this.execute(this.getTrendingCollections.name, this.auctionsRepository.getTrendingCollections()); } async getTrendingCollectionsCount(): Promise { - return await this.execute( - this.getTrendingCollectionsCount.name, - this.auctionsRepository.getTrendingCollectionsCount(), - ); + return await this.execute(this.getTrendingCollectionsCount.name, this.auctionsRepository.getTrendingCollectionsCount()); } async getActiveCollectionsLast30Days(): Promise { - return await this.execute( - this.getActiveCollectionsLast30Days.name, - this.auctionsRepository.getActiveCollectionsFromLast30Days(), - ); + return await this.execute(this.getActiveCollectionsLast30Days.name, this.auctionsRepository.getActiveCollectionsFromLast30Days()); } async getActiveCollectionsLast30DaysCount(): Promise { @@ -896,32 +518,19 @@ export class PersistenceService { ); } - async getAuctionsOrderByOrdersCount( - queryRequest: QueryRequest, - ): Promise<[AuctionEntity[], number, PriceRange]> { - return await this.execute( - this.getAuctionsOrderByOrdersCount.name, - this.auctionsRepository.getAuctionsOrderByOrdersCount(queryRequest), - ); + async getAuctionsOrderByOrdersCount(queryRequest: QueryRequest): Promise<[AuctionEntity[], number, PriceRange]> { + return await this.execute(this.getAuctionsOrderByOrdersCount.name, this.auctionsRepository.getAuctionsOrderByOrdersCount(queryRequest)); } async getMinMax(token: string): Promise { - return await this.execute( - this.getMinMax.name, - this.auctionsRepository.getMinMax(token), - ); + return await this.execute(this.getMinMax.name, this.auctionsRepository.getMinMax(token)); } async getAuction(id: number): Promise { - return await this.execute( - this.getAuction.name, - this.auctionsRepository.getAuction(id), - ); + return await this.execute(this.getAuction.name, this.auctionsRepository.getAuction(id)); } - async getLastAuctionIdForMarketplace( - marketplaceKey: string, - ): Promise { + async getLastAuctionIdForMarketplace(marketplaceKey: string): Promise { return await this.execute( this.getLastAuctionIdForMarketplace.name, this.auctionsRepository.getLastAuctionIdForMarketplace(marketplaceKey), @@ -929,73 +538,38 @@ export class PersistenceService { } async getBulkAuctions(auctionsIds: number[]): Promise { - return await this.execute( - this.getBulkAuctions.name, - this.auctionsRepository.getBulkAuctions(auctionsIds), - ); + return await this.execute(this.getBulkAuctions.name, this.auctionsRepository.getBulkAuctions(auctionsIds)); } - async getBulkAuctionsByAuctionIdsAndMarketplace( - auctionsIds: number[], - marketplaceKey: string, - ): Promise { + async getBulkAuctionsByAuctionIdsAndMarketplace(auctionsIds: number[], marketplaceKey: string): Promise { return await this.execute( this.getBulkAuctionsByAuctionIdsAndMarketplace.name, - this.auctionsRepository.getBulkAuctionsByAuctionIdsAndMarketplace( - auctionsIds, - marketplaceKey, - ), + this.auctionsRepository.getBulkAuctionsByAuctionIdsAndMarketplace(auctionsIds, marketplaceKey), ); } - async getAuctionByMarketplace( - id: number, - marketplaceKey: string, - ): Promise { - return await this.execute( - this.getAuctionByMarketplace.name, - this.auctionsRepository.getAuctionByMarketplace(id, marketplaceKey), - ); + async getAuctionByMarketplace(id: number, marketplaceKey: string): Promise { + return await this.execute(this.getAuctionByMarketplace.name, this.auctionsRepository.getAuctionByMarketplace(id, marketplaceKey)); } - async getAuctionByIdentifierAndMarketplace( - identifier: string, - marketplaceKey: string, - ): Promise { + async getAuctionByIdentifierAndMarketplace(identifier: string, marketplaceKey: string): Promise { return await this.execute( this.getAuctionByIdentifierAndMarketplace.name, - this.auctionsRepository.getAuctionByIdentifierAndMarketplace( - identifier, - marketplaceKey, - ), + this.auctionsRepository.getAuctionByIdentifierAndMarketplace(identifier, marketplaceKey), ); } - async getAuctionCountForIdentifiers( - identifiers: string[], - ): Promise { - return await this.execute( - this.getAuctionCountForIdentifiers.name, - this.auctionsRepository.getAuctionCountForIdentifiers(identifiers), - ); + async getAuctionCountForIdentifiers(identifiers: string[]): Promise { + return await this.execute(this.getAuctionCountForIdentifiers.name, this.auctionsRepository.getAuctionCountForIdentifiers(identifiers)); } async getAuctionsForIdentifiers(identifiers: string[]): Promise { - return await this.execute( - this.getAuctionsForIdentifiers.name, - this.auctionsRepository.getAuctionsForIdentifiers(identifiers), - ); + return await this.execute(this.getAuctionsForIdentifiers.name, this.auctionsRepository.getAuctionsForIdentifiers(identifiers)); } - async getBulkAuctionsByIdentifierAndMarketplace( - identifiers: string[], - marletplaceKey: string, - ): Promise { + async getBulkAuctionsByIdentifierAndMarketplace(identifiers: string[], marletplaceKey: string): Promise { return await this.execute( this.getBulkAuctionsByIdentifierAndMarketplace.name, - this.auctionsRepository.getBulkAuctionsByIdentifiersAndMarketplace( - identifiers, - marletplaceKey, - ), + this.auctionsRepository.getBulkAuctionsByIdentifiersAndMarketplace(identifiers, marletplaceKey), ); } @@ -1020,22 +594,15 @@ export class PersistenceService { ); } - async getLowestAuctionForIdentifiersAndMarketplace( - identifiers: string[], - ): Promise { + async getLowestAuctionForIdentifiersAndMarketplace(identifiers: string[]): Promise { return await this.execute( this.getLowestAuctionForIdentifiersAndMarketplace.name, - this.auctionsRepository.getLowestAuctionForIdentifiersAndMarketplace( - identifiers, - ), + this.auctionsRepository.getLowestAuctionForIdentifiersAndMarketplace(identifiers), ); } async getAvailableTokensByAuctionId(id: number): Promise { - return await this.execute( - this.getAvailableTokensByAuctionId.name, - this.auctionsRepository.getAvailableTokensByAuctionId(id), - ); + return await this.execute(this.getAvailableTokensByAuctionId.name, this.auctionsRepository.getAvailableTokensByAuctionId(id)); } async getOnSaleAssetCountForCollections(identifiers: string[]): Promise { @@ -1046,49 +613,27 @@ export class PersistenceService { } async getAuctionsThatReachedDeadline(): Promise { - return await this.execute( - this.getAuctionsThatReachedDeadline.name, - this.auctionsRepository.getAuctionsThatReachedDeadline(), - ); + return await this.execute(this.getAuctionsThatReachedDeadline.name, this.auctionsRepository.getAuctionsThatReachedDeadline()); } async insertAuction(auction: AuctionEntity): Promise { - return await this.execute( - this.insertAuction.name, - this.auctionsRepository.insertAuction(auction), - ); + return await this.execute(this.insertAuction.name, this.auctionsRepository.insertAuction(auction)); } async saveBulkAuctions(auctions: AuctionEntity[]): Promise { - return await this.execute( - this.saveBulkAuctions.name, - this.auctionsRepository.saveBulkAuctions(auctions), - ); + return await this.execute(this.saveBulkAuctions.name, this.auctionsRepository.saveBulkAuctions(auctions)); } async rollbackAuctionAndOrdersByHash(blockHash: string): Promise { - return await this.execute( - this.rollbackAuctionAndOrdersByHash.name, - this.auctionsRepository.rollbackAuctionAndOrdersByHash(blockHash), - ); + return await this.execute(this.rollbackAuctionAndOrdersByHash.name, this.auctionsRepository.rollbackAuctionAndOrdersByHash(blockHash)); } async updateAuction(auction: AuctionEntity): Promise { - return await this.execute( - this.updateAuction.name, - this.auctionsRepository.updateAuction(auction), - ); + return await this.execute(this.updateAuction.name, this.auctionsRepository.updateAuction(auction)); } - async updateAuctionStatus( - auctionId: number, - status: AuctionStatusEnum, - hash: string, - ): Promise { - return await this.execute( - this.updateAuctionStatus.name, - this.auctionsRepository.updateAuctionStatus(auctionId, status, hash), - ); + async updateAuctionStatus(auctionId: number, status: AuctionStatusEnum, hash: string): Promise { + return await this.execute(this.updateAuctionStatus.name, this.auctionsRepository.updateAuctionStatus(auctionId, status, hash)); } async updateAuctionByMarketplace( @@ -1099,20 +644,12 @@ export class PersistenceService { ): Promise { return await this.execute( this.updateAuctionByMarketplace.name, - this.auctionsRepository.updateAuctionByMarketplace( - auctionId, - marketplaceKey, - status, - hash, - ), + this.auctionsRepository.updateAuctionByMarketplace(auctionId, marketplaceKey, status, hash), ); } async updateAuctions(auctions: AuctionEntity[]): Promise { - return await this.execute( - this.updateAuctions.name, - this.auctionsRepository.updateAuctions(auctions), - ); + return await this.execute(this.updateAuctions.name, this.auctionsRepository.updateAuctions(auctions)); } async getCurrentPaymentTokenIdsWithCounts( @@ -1121,98 +658,56 @@ export class PersistenceService { ): Promise<{ paymentToken: string; activeAuctions: number }[]> { return await this.execute( this.getCurrentPaymentTokenIdsWithCounts.name, - this.auctionsRepository.getCurrentPaymentTokenIds( - marketplaceKey, - collectionIdentifier, - ), + this.auctionsRepository.getCurrentPaymentTokenIds(marketplaceKey, collectionIdentifier), ); } async getOfferById(id: number): Promise { - return await this.execute( - this.getOfferById.name, - this.offersRepository.getOfferById(id), - ); + return await this.execute(this.getOfferById.name, this.offersRepository.getOfferById(id)); } - async getOffers( - filters?: OffersFiltersForDb, - offset: number = 0, - limit: number = 10, - ): Promise<[OfferEntity[], number]> { - return await this.execute( - this.getOffers.name, - this.offersRepository.getActiveOffers(filters, offset, limit), - ); + async getOffers(filters?: OffersFiltersForDb, offset: number = 0, limit: number = 10): Promise<[OfferEntity[], number]> { + return await this.execute(this.getOffers.name, this.offersRepository.getActiveOffers(filters, offset, limit)); } - async getOfferByIdAndMarketplace( - marketplaceOfferId: number, - marletplaceKey: string, - ): Promise { + async getOfferByIdAndMarketplace(marketplaceOfferId: number, marletplaceKey: string): Promise { return await this.execute( this.getOfferByIdAndMarketplace.name, - this.offersRepository.getOfferByIdAndMarketplaceKey( - marketplaceOfferId, - marletplaceKey, - ), + this.offersRepository.getOfferByIdAndMarketplaceKey(marketplaceOfferId, marletplaceKey), ); } async saveOffer(offer: OfferEntity): Promise { - return await this.execute( - this.saveOffer.name, - this.offersRepository.saveOffer(offer), - ); + return await this.execute(this.saveOffer.name, this.offersRepository.saveOffer(offer)); } async saveBulkOffers(offers: OfferEntity[]): Promise { - return await this.execute( - this.saveBulkOffers.name, - this.offersRepository.saveBulkOffers(offers), - ); + return await this.execute(this.saveBulkOffers.name, this.offersRepository.saveBulkOffers(offers)); } async getOffersThatReachedDeadline(): Promise { - return await this.execute( - this.getOffersThatReachedDeadline.name, - this.offersRepository.getOffersThatReachedDeadline(), - ); + return await this.execute(this.getOffersThatReachedDeadline.name, this.offersRepository.getOffersThatReachedDeadline()); } async updateOffers(offers: OfferEntity[]): Promise { - return await this.execute( - this.updateOffers.name, - this.offersRepository.updateOffers(offers), - ); + return await this.execute(this.updateOffers.name, this.offersRepository.updateOffers(offers)); } - async getBulkOffersByOfferIdsAndMarketplace( - offerIds: number[], - marketplaceKey: string, - ): Promise { + async getBulkOffersByOfferIdsAndMarketplace(offerIds: number[], marketplaceKey: string): Promise { return await this.execute( this.getBulkOffersByOfferIdsAndMarketplace.name, - this.offersRepository.getBulkOffersByOfferIdsAndMarketplace( - offerIds, - marketplaceKey, - ), + this.offersRepository.getBulkOffersByOfferIdsAndMarketplace(offerIds, marketplaceKey), ); } - async getMostLikedAssetsIdentifiers( - offset?: number, - limit?: number, - ): Promise { + async getMostLikedAssetsIdentifiers(offset?: number, limit?: number): Promise { return await this.execute( this.getMostLikedAssetsIdentifiers.name, this.assetsLikesRepository.getMostLikedAssetsIdentifiers(offset, limit), ); } - async saveOrIgnoreMarketplacesBulk( - events: MarketplaceEventsEntity[], - ): Promise { + async saveOrIgnoreMarketplacesBulk(events: MarketplaceEventsEntity[]): Promise { return await this.marketplaceEventsRepository.saveOrIgnoreBulk(events); } @@ -1221,51 +716,32 @@ export class PersistenceService { afterTimestamp?: number, beforeTimestamp?: number, ): Promise { - return await this.marketplaceEventsRepository.getEventsByMarketplaceAndTimestampsAsc( - marketplaceKey, - afterTimestamp, - beforeTimestamp, - ); + return await this.marketplaceEventsRepository.getEventsByMarketplaceAndTimestampsAsc(marketplaceKey, afterTimestamp, beforeTimestamp); } - async getBlacklistedCollections(): Promise< - [BlacklistedCollectionEntity[], number] - > { - return await this.execute( - this.getBlacklistedCollections.name, - this.blacklistedCollectionsRepository.getBlacklistedCollections(), - ); + async getBlacklistedCollections(): Promise<[BlacklistedCollectionEntity[], number]> { + return await this.execute(this.getBlacklistedCollections.name, this.blacklistedCollectionsRepository.getBlacklistedCollections()); } async addBlacklistedCollection(collection: string): Promise { return await this.execute( this.addBlacklistedCollection.name, - this.blacklistedCollectionsRepository.addBlacklistedCollection( - collection, - ), + this.blacklistedCollectionsRepository.addBlacklistedCollection(collection), ); } async removeBlacklistedCollection(collection: string): Promise { return await this.execute( this.removeBlacklistedCollection.name, - this.blacklistedCollectionsRepository.removeBlacklistedCollection( - collection, - ), + this.blacklistedCollectionsRepository.removeBlacklistedCollection(collection), ); } async saveMinter(minter: MinterEntity): Promise { - return await this.execute( - this.saveMinter.name, - this.mintersRepository.saveMinter(minter), - ); + return await this.execute(this.saveMinter.name, this.mintersRepository.saveMinter(minter)); } async getMinters(): Promise { - return await this.execute( - this.getMinters.name, - this.mintersRepository.getMinters(), - ); + return await this.execute(this.getMinters.name, this.mintersRepository.getMinters()); } } diff --git a/src/common/persistence/timescaledb/analytics-data.getter.service.ts b/src/common/persistence/timescaledb/analytics-data.getter.service.ts index e83c796a5..5d37c40e4 100644 --- a/src/common/persistence/timescaledb/analytics-data.getter.service.ts +++ b/src/common/persistence/timescaledb/analytics-data.getter.service.ts @@ -32,28 +32,15 @@ export class AnalyticsDataGetterService { if (series) { query.andWhere('series = :series', { series }); } - const [response, count] = await Promise.all([ - query.offset(offset).limit(limit).getRawMany(), - query.getCount(), - ]); + const [response, count] = await Promise.all([query.offset(offset).limit(limit).getRawMany(), query.getCount()]); if (series && count === 0) { return [[new AnalyticsAggregateValue({ value: 0, series: series })], 1]; } - return [ - response?.map((row) => - AnalyticsAggregateValue.fromTimescaleObjext(row), - ) ?? [], - count ?? 0, - ]; + return [response?.map((row) => AnalyticsAggregateValue.fromTimescaleObjext(row)) ?? [], count ?? 0]; } - async getVolumeData({ - time, - series, - metric, - start, - }: AnalyticsArgs): Promise { + async getVolumeData({ time, series, metric, start }: AnalyticsArgs): Promise { const [startDate, endDate] = computeTimeInterval(time, start); const query = await this.sumDaily .createQueryBuilder() @@ -61,26 +48,15 @@ export class AnalyticsDataGetterService { .addSelect('sum(sum) as value') .where('key = :metric', { metric }) .andWhere('series = :series', { series }) - .andWhere( - endDate ? 'time BETWEEN :startDate AND :endDate' : 'time >= :startDate', - { startDate, endDate }, - ) + .andWhere(endDate ? 'time BETWEEN :startDate AND :endDate' : 'time >= :startDate', { startDate, endDate }) .orderBy('timestamp', 'ASC') .groupBy('timestamp') .getRawMany(); - return ( - query?.map((row) => AnalyticsAggregateValue.fromTimescaleObjext(row)) ?? - [] - ); + return query?.map((row) => AnalyticsAggregateValue.fromTimescaleObjext(row)) ?? []; } - async getFloorPriceData({ - time, - series, - metric, - start, - }: AnalyticsArgs): Promise { + async getFloorPriceData({ time, series, metric, start }: AnalyticsArgs): Promise { const [startDate, endDate] = computeTimeInterval(time, start); const query = await this.floorPriceDaily .createQueryBuilder() @@ -88,17 +64,11 @@ export class AnalyticsDataGetterService { .addSelect('locf(min(min)) as value') .where('key = :metric', { metric }) .andWhere('series = :series', { series }) - .andWhere( - endDate ? 'time BETWEEN :startDate AND :endDate' : 'time >= :startDate', - { startDate, endDate }, - ) + .andWhere(endDate ? 'time BETWEEN :startDate AND :endDate' : 'time >= :startDate', { startDate, endDate }) .orderBy('timestamp', 'ASC') .groupBy('timestamp') .getRawMany(); - return ( - query?.map((row) => AnalyticsAggregateValue.fromTimescaleObjext(row)) ?? - [] - ); + return query?.map((row) => AnalyticsAggregateValue.fromTimescaleObjext(row)) ?? []; } } diff --git a/src/common/persistence/timescaledb/analytics-data.setter.service.ts b/src/common/persistence/timescaledb/analytics-data.setter.service.ts index 177756863..2b7c172f5 100644 --- a/src/common/persistence/timescaledb/analytics-data.setter.service.ts +++ b/src/common/persistence/timescaledb/analytics-data.setter.service.ts @@ -35,9 +35,7 @@ export class AnalyticsDataSetterService { this.pendingRecords = []; } catch (error) { - this.logger.error( - `Could not insert ${this.pendingRecords.length} records into TimescaleDb, ${error}, ${timestamp}`, - ); + this.logger.error(`Could not insert ${this.pendingRecords.length} records into TimescaleDb, ${error}, ${timestamp}`); throw error; } } @@ -55,9 +53,7 @@ export class AnalyticsDataSetterService { await query.execute(); } catch (error) { - this.logger.error( - `Could not insert ${data} records into TimescaleDb, ${error}}`, - ); + this.logger.error(`Could not insert ${data} records into TimescaleDb, ${error}}`); throw error; } } diff --git a/src/common/persistence/timescaledb/entities/analytics.entity.ts b/src/common/persistence/timescaledb/entities/analytics.entity.ts index 12aae68ec..67477ba28 100644 --- a/src/common/persistence/timescaledb/entities/analytics.entity.ts +++ b/src/common/persistence/timescaledb/entities/analytics.entity.ts @@ -30,23 +30,14 @@ export class XNftsAnalyticsEntity { Object.assign(this, init); } - public static fromObject( - timestamp: Date, - object: Record>, - ): XNftsAnalyticsEntity[] { + public static fromObject(timestamp: Date, object: Record>): XNftsAnalyticsEntity[] { const entities = Object.entries(object) - .map(([series, record]: [string, Record]) => - XNftsAnalyticsEntity.fromRecord(timestamp, record, series), - ) + .map(([series, record]: [string, Record]) => XNftsAnalyticsEntity.fromRecord(timestamp, record, series)) .flat(1); return entities; } - private static fromRecord( - timestamp: Date, - record: Record, - series?: string, - ): XNftsAnalyticsEntity[] { + private static fromRecord(timestamp: Date, record: Record, series?: string): XNftsAnalyticsEntity[] { const entities = Object.entries(record).map(([key, value]) => { const entity = new XNftsAnalyticsEntity(); entity.timestamp = timestamp; diff --git a/src/common/persistence/timescaledb/tests/analytics-data.getter.spec.ts b/src/common/persistence/timescaledb/tests/analytics-data.getter.spec.ts index f1f7814ec..922fe2629 100644 --- a/src/common/persistence/timescaledb/tests/analytics-data.getter.spec.ts +++ b/src/common/persistence/timescaledb/tests/analytics-data.getter.spec.ts @@ -31,9 +31,7 @@ describe('Analytics Data Getter Service', () => { ], }).compile(); - service = module.get( - AnalyticsDataGetterService, - ); + service = module.get(AnalyticsDataGetterService); }); it('should be defined', () => { @@ -44,9 +42,7 @@ describe('Analytics Data Getter Service', () => { it('returns empty list when no data and no key present', async () => { const getRawMany = jest.fn().mockReturnValueOnce([]); const getCount = jest.fn().mockReturnValueOnce(0); - const sumDailyRepository = module.get( - getRepositoryToken(SumDaily, 'timescaledb'), - ); + const sumDailyRepository = module.get(getRepositoryToken(SumDaily, 'timescaledb')); sumDailyRepository.createQueryBuilder = jest.fn(() => ({ select, offset, @@ -67,9 +63,7 @@ describe('Analytics Data Getter Service', () => { it('returns list with one item when no data and the searched key', async () => { const getRawMany = jest.fn().mockReturnValueOnce([]); const getCount = jest.fn().mockReturnValueOnce(0); - const sumDailyRepository = module.get( - getRepositoryToken(SumDaily, 'timescaledb'), - ); + const sumDailyRepository = module.get(getRepositoryToken(SumDaily, 'timescaledb')); sumDailyRepository.createQueryBuilder = jest.fn(() => ({ select, offset, @@ -85,10 +79,7 @@ describe('Analytics Data Getter Service', () => { metric: 'test', series: 'test', }); - const expectedResult = [ - [new AnalyticsAggregateValue({ value: 0, series: 'test' })], - 1, - ]; + const expectedResult = [[new AnalyticsAggregateValue({ value: 0, series: 'test' })], 1]; expect(result).toMatchObject(expectedResult); }); @@ -99,9 +90,7 @@ describe('Analytics Data Getter Service', () => { { value: 121, series: 'test2' }, ]); const getCount = jest.fn().mockReturnValueOnce(2); - const sumDailyRepository = module.get( - getRepositoryToken(SumDaily, 'timescaledb'), - ); + const sumDailyRepository = module.get(getRepositoryToken(SumDaily, 'timescaledb')); sumDailyRepository.createQueryBuilder = jest.fn(() => ({ select, offset, @@ -115,16 +104,12 @@ describe('Analytics Data Getter Service', () => { getCount, })); - const [responseList, responseCount] = - await service.getTopCollectionsDaily({ - metric: 'test', - }); + const [responseList, responseCount] = await service.getTopCollectionsDaily({ + metric: 'test', + }); const [expectedList, expectedCount] = [ - [ - new AnalyticsAggregateValue({ value: 2, series: 'test' }), - new AnalyticsAggregateValue({ value: 121, series: 'test2' }), - ], + [new AnalyticsAggregateValue({ value: 2, series: 'test' }), new AnalyticsAggregateValue({ value: 121, series: 'test2' })], 2, ]; @@ -136,9 +121,7 @@ describe('Analytics Data Getter Service', () => { describe('getFloorPriceData', () => { it('returns empty list when no data for specific collection', async () => { const getRawMany = jest.fn().mockReturnValueOnce([]); - const floorPriceRepository = module.get( - getRepositoryToken(FloorPriceDaily, 'timescaledb'), - ); + const floorPriceRepository = module.get(getRepositoryToken(FloorPriceDaily, 'timescaledb')); floorPriceRepository.createQueryBuilder = jest.fn(() => ({ select, offset, @@ -169,9 +152,7 @@ describe('Analytics Data Getter Service', () => { new AnalyticsAggregateValue({ value: 2, series: 'test' }), new AnalyticsAggregateValue({ value: 121, series: 'test' }), ]; - const floorPriceRepository = module.get( - getRepositoryToken(FloorPriceDaily, 'timescaledb'), - ); + const floorPriceRepository = module.get(getRepositoryToken(FloorPriceDaily, 'timescaledb')); floorPriceRepository.createQueryBuilder = jest.fn(() => ({ select, offset, @@ -197,9 +178,7 @@ describe('Analytics Data Getter Service', () => { describe('getVolumeData', () => { it('returns empty list when no data for specific collection', async () => { const getRawMany = jest.fn().mockReturnValueOnce([]); - const sumDailyRepository = module.get( - getRepositoryToken(SumDaily, 'timescaledb'), - ); + const sumDailyRepository = module.get(getRepositoryToken(SumDaily, 'timescaledb')); sumDailyRepository.createQueryBuilder = jest.fn(() => ({ select, offset, @@ -230,9 +209,7 @@ describe('Analytics Data Getter Service', () => { new AnalyticsAggregateValue({ value: 2, series: 'test' }), new AnalyticsAggregateValue({ value: 121, series: 'test' }), ]; - const sumDailyRepository = module.get( - getRepositoryToken(SumDaily, 'timescaledb'), - ); + const sumDailyRepository = module.get(getRepositoryToken(SumDaily, 'timescaledb')); sumDailyRepository.createQueryBuilder = jest.fn(() => ({ select, offset, diff --git a/src/common/persistence/timescaledb/timescaledb.module.ts b/src/common/persistence/timescaledb/timescaledb.module.ts index 92313b28b..cdb06828b 100644 --- a/src/common/persistence/timescaledb/timescaledb.module.ts +++ b/src/common/persistence/timescaledb/timescaledb.module.ts @@ -34,10 +34,7 @@ import { SumWeekly } from './entities/sum-weekly.entity'; }), inject: [ApiConfigService], }), - TypeOrmModule.forFeature( - [XNftsAnalyticsEntity, SumDaily, SumWeekly, FloorPriceDaily], - 'timescaledb', - ), + TypeOrmModule.forFeature([XNftsAnalyticsEntity, SumDaily, SumWeekly, FloorPriceDaily], 'timescaledb'), ], providers: [AnalyticsDataGetterService, AnalyticsDataSetterService], exports: [AnalyticsDataGetterService, AnalyticsDataSetterService], diff --git a/src/common/services/caching/caching.controller.ts b/src/common/services/caching/caching.controller.ts index 5c59b2c0c..ee8539e03 100644 --- a/src/common/services/caching/caching.controller.ts +++ b/src/common/services/caching/caching.controller.ts @@ -1,13 +1,4 @@ -import { - Body, - Controller, - Delete, - Get, - HttpStatus, - Post, - Res, - UseGuards, -} from '@nestjs/common'; +import { Body, Controller, Delete, Get, HttpStatus, Post, Res, UseGuards } from '@nestjs/common'; import { Response } from 'express'; import { DeleteCacheKeysInput } from './entities/deleteCacheInput'; import { SetCacheKeyInput } from './entities/setCacheInput'; @@ -15,25 +6,16 @@ import { GetCacheKeysInput } from './entities/getCacheInput'; import { JwtOrNativeAuthGuard } from 'src/modules/auth/jwt.or.native.auth-guard'; import { GqlAdminAuthGuard } from 'src/modules/auth/gql-admin.auth-guard'; import { CacheEventsPublisherService } from 'src/modules/rabbitmq/cache-invalidation/cache-invalidation-publisher/change-events-publisher.service'; -import { - CacheEventTypeEnum, - ChangedEvent, -} from 'src/modules/rabbitmq/cache-invalidation/events/changed.event'; +import { CacheEventTypeEnum, ChangedEvent } from 'src/modules/rabbitmq/cache-invalidation/events/changed.event'; import { CachingService } from '@multiversx/sdk-nestjs'; @Controller() export class CachingController { - constructor( - private readonly cachingService: CachingService, - private readonly cacheEventsPublisherService: CacheEventsPublisherService, - ) {} + constructor(private readonly cachingService: CachingService, private readonly cacheEventsPublisherService: CacheEventsPublisherService) {} @UseGuards(JwtOrNativeAuthGuard, GqlAdminAuthGuard) @Get('/caching') - async getCacheKeys( - @Body() input: GetCacheKeysInput, - @Res() res: Response, - ): Promise { + async getCacheKeys(@Body() input: GetCacheKeysInput, @Res() res: Response): Promise { try { let values: any[] = []; @@ -48,10 +30,7 @@ export class CachingController { @UseGuards(JwtOrNativeAuthGuard, GqlAdminAuthGuard) @Post('/caching') - async setCacheKey( - @Body() input: SetCacheKeyInput, - @Res() res: Response, - ): Promise { + async setCacheKey(@Body() input: SetCacheKeyInput, @Res() res: Response): Promise { try { await this.publishSetCacheKeyForClientEvent(input); return res.status(HttpStatus.CREATED).send(); @@ -62,10 +41,7 @@ export class CachingController { @UseGuards(JwtOrNativeAuthGuard, GqlAdminAuthGuard) @Delete('/caching') - async deleteCacheKeys( - @Body() input: DeleteCacheKeysInput, - @Res() res: Response, - ): Promise { + async deleteCacheKeys(@Body() input: DeleteCacheKeysInput, @Res() res: Response): Promise { try { await this.publishDeleteCacheKeysFromClientEvent(input); return res.status(HttpStatus.OK).send(); @@ -74,9 +50,7 @@ export class CachingController { } } - private async publishDeleteCacheKeysFromClientEvent( - input: DeleteCacheKeysInput, - ) { + private async publishDeleteCacheKeysFromClientEvent(input: DeleteCacheKeysInput) { await this.cacheEventsPublisherService.publish( new ChangedEvent({ id: input.keys, diff --git a/src/common/services/caching/caching.module.ts b/src/common/services/caching/caching.module.ts index f8cadc340..d0bcadd0d 100644 --- a/src/common/services/caching/caching.module.ts +++ b/src/common/services/caching/caching.module.ts @@ -5,11 +5,7 @@ import { LocalRedisCacheService } from './local-redis-cache.service'; @Global() @Module({ - imports: [ - forwardRef(() => CommonModule), - DynamicModuleUtils.getRedisModule(), - DynamicModuleUtils.getCachingModule(), - ], + imports: [forwardRef(() => CommonModule), DynamicModuleUtils.getRedisModule(), DynamicModuleUtils.getCachingModule()], providers: [LocalRedisCacheService], exports: [LocalRedisCacheService, DynamicModuleUtils.getRedisModule()], }) diff --git a/src/common/services/caching/local-redis-cache.service.ts b/src/common/services/caching/local-redis-cache.service.ts index a11c9bccb..44473c5dd 100644 --- a/src/common/services/caching/local-redis-cache.service.ts +++ b/src/common/services/caching/local-redis-cache.service.ts @@ -3,15 +3,9 @@ import { Injectable, Logger } from '@nestjs/common'; import { isNil } from '@nestjs/common/utils/shared.utils'; @Injectable() export class LocalRedisCacheService { - constructor( - private readonly logger: Logger, - private readonly redisCacheService: RedisCacheService, - ) {} + constructor(private readonly logger: Logger, private readonly redisCacheService: RedisCacheService) {} - async getOrSetWithDifferentTtl( - key: string, - createValueFunc: () => any, - ): Promise { + async getOrSetWithDifferentTtl(key: string, createValueFunc: () => any): Promise { const cachedData = await this.redisCacheService.get(key); if (!isNil(cachedData)) { return cachedData; @@ -22,10 +16,7 @@ export class LocalRedisCacheService { return value; } - private async buildInternalCreateValueFunc( - key: string, - createValueFunc: () => any, - ): Promise { + private async buildInternalCreateValueFunc(key: string, createValueFunc: () => any): Promise { try { let data = createValueFunc(); if (data instanceof Promise) { diff --git a/src/common/services/mx-communication/api.service.ts b/src/common/services/mx-communication/api.service.ts index e64268da9..27522412e 100644 --- a/src/common/services/mx-communication/api.service.ts +++ b/src/common/services/mx-communication/api.service.ts @@ -61,11 +61,7 @@ export class ApiService { }; } - async get( - url: string, - settings: ApiSettings = new ApiSettings(), - errorHandler?: (error: any) => Promise, - ): Promise { + async get(url: string, settings: ApiSettings = new ApiSettings(), errorHandler?: (error: any) => Promise): Promise { try { return await axios.get(url, this.getConfig(settings)); } catch (error: any) { @@ -122,10 +118,7 @@ export class ApiService { } } finally { profiler.stop(); - MetricsCollector.setExternalCall( - this.getHostname(url), - profiler.duration, - ); + MetricsCollector.setExternalCall(this.getHostname(url), profiler.duration); } } @@ -161,10 +154,7 @@ export class ApiService { } } finally { profiler.stop(); - MetricsCollector.setExternalCall( - this.getHostname(url), - profiler.duration, - ); + MetricsCollector.setExternalCall(this.getHostname(url), profiler.duration); } } diff --git a/src/common/services/mx-communication/mx-api.service.mock.ts b/src/common/services/mx-communication/mx-api.service.mock.ts index 5c0c6a1a8..c215ebe74 100644 --- a/src/common/services/mx-communication/mx-api.service.mock.ts +++ b/src/common/services/mx-communication/mx-api.service.mock.ts @@ -3,10 +3,7 @@ export class MxApiServiceMock { return Promise.resolve(4); } - async getNftsCountForCollection( - _query: string = '', - _collection: string = '', - ): Promise<{ value: string; key: string }> { + async getNftsCountForCollection(_query: string = '', _collection: string = ''): Promise<{ value: string; key: string }> { return Promise.resolve({ key: 'identifier', value: '4' }); } diff --git a/src/common/services/mx-communication/mx-data.service.ts b/src/common/services/mx-communication/mx-data.service.ts index 7b19c1d67..4db4cd69e 100644 --- a/src/common/services/mx-communication/mx-data.service.ts +++ b/src/common/services/mx-communication/mx-data.service.ts @@ -22,13 +22,10 @@ export class MxDataApiService { let response = await this.apiService.get(requestUrl, this.getHeaders()); return response.data.price; } catch (error) { - this.logger.error( - `An error occurred while calling the mx data service on url ${requestUrl}`, - { - path: this.getCexPrice.name, - exception: error, - }, - ); + this.logger.error(`An error occurred while calling the mx data service on url ${requestUrl}`, { + path: this.getCexPrice.name, + exception: error, + }); return; } } @@ -40,13 +37,10 @@ export class MxDataApiService { return response?.data?.map((x) => x.identifier); } catch (error) { - this.logger.error( - `An error occurred while calling the mx data service on url ${requestUrl}`, - { - path: this.getCexTokens.name, - exception: error, - }, - ); + this.logger.error(`An error occurred while calling the mx data service on url ${requestUrl}`, { + path: this.getCexTokens.name, + exception: error, + }); return; } } @@ -57,34 +51,25 @@ export class MxDataApiService { let response = await this.apiService.get(requestUrl); return response?.data?.map((x) => x.identifier); } catch (error) { - this.logger.error( - `An error occurred while calling the mx data service on url ${requestUrl}`, - { - path: this.getXexchangeTokens.name, - exception: error, - }, - ); + this.logger.error(`An error occurred while calling the mx data service on url ${requestUrl}`, { + path: this.getXexchangeTokens.name, + exception: error, + }); return; } } - async getXechangeTokenPrice( - token: string, - isoDateOnly: string, - ): Promise { + async getXechangeTokenPrice(token: string, isoDateOnly: string): Promise { const requestUrl = `${this.url}/v1/quotes/xexchange/${token}?date=${isoDateOnly}&fields=price`; try { let response = await this.apiService.get(requestUrl, this.getHeaders()); return response.data.price; } catch (error) { - this.logger.error( - `An error occurred while calling the mx data service on url ${requestUrl}`, - { - path: this.getCexPrice.name, - exception: error, - }, - ); + this.logger.error(`An error occurred while calling the mx data service on url ${requestUrl}`, { + path: this.getCexPrice.name, + exception: error, + }); return; } } diff --git a/src/common/services/mx-communication/mx-feed.service.ts b/src/common/services/mx-communication/mx-feed.service.ts index 479b40d57..a4615bbbf 100644 --- a/src/common/services/mx-communication/mx-feed.service.ts +++ b/src/common/services/mx-communication/mx-feed.service.ts @@ -7,10 +7,7 @@ import { SubscriptionFeed } from './models/subscription-feed.dto'; @Injectable() export class MxFeedService { - constructor( - private readonly logger: Logger, - private readonly apiService: ApiService, - ) {} + constructor(private readonly logger: Logger, private readonly apiService: ApiService) {} async subscribe(identifier: string, authKey?: string): Promise { if (process.env.ENABLE_FEED_EVENTS === 'true') { @@ -28,16 +25,11 @@ export class MxFeedService { ); return response.data; } catch (error) { - this.logger.error( - `An error occurred while calling the mx feed api on url ${removeCredentialsFromUrl( - url, - )}`, - { - path: `${MxFeedService.name}.${this.subscribe.name}`, - identifier, - exception: error, - }, - ); + this.logger.error(`An error occurred while calling the mx feed api on url ${removeCredentialsFromUrl(url)}`, { + path: `${MxFeedService.name}.${this.subscribe.name}`, + identifier, + exception: error, + }); return; } } @@ -61,16 +53,11 @@ export class MxFeedService { ); return response.data; } catch (error) { - this.logger.error( - `An error occurred while calling the mx feed api on url ${removeCredentialsFromUrl( - url, - )}`, - { - path: `${MxFeedService.name}.${this.unsubscribe.name}`, - reference, - exception: error, - }, - ); + this.logger.error(`An error occurred while calling the mx feed api on url ${removeCredentialsFromUrl(url)}`, { + path: `${MxFeedService.name}.${this.unsubscribe.name}`, + reference, + exception: error, + }); return; } } @@ -82,23 +69,14 @@ export class MxFeedService { const url = `${process.env.ELROND_FEED}v1/feed/item`; try { - const response = await this.apiService.post( - url, - feed, - new ApiSettings({ apiKey: process.env.ELROND_FEED_API_KEY }), - ); + const response = await this.apiService.post(url, feed, new ApiSettings({ apiKey: process.env.ELROND_FEED_API_KEY })); return response.data; } catch (error) { - this.logger.error( - `An error occurred while calling the mx feed api on url ${removeCredentialsFromUrl( - url, - )}`, - { - path: `${MxFeedService.name}.${this.addFeed.name}`, - feed: feed, - exception: error, - }, - ); + this.logger.error(`An error occurred while calling the mx feed api on url ${removeCredentialsFromUrl(url)}`, { + path: `${MxFeedService.name}.${this.addFeed.name}`, + feed: feed, + exception: error, + }); return; } } diff --git a/src/common/services/mx-communication/mx-identity.service.ts b/src/common/services/mx-communication/mx-identity.service.ts index 5ffb335cf..6a180075a 100644 --- a/src/common/services/mx-communication/mx-identity.service.ts +++ b/src/common/services/mx-communication/mx-identity.service.ts @@ -6,10 +6,7 @@ import { AccountIdentity } from './models/account.identity'; @Injectable() export class MxIdentityService { - constructor( - private readonly logger: Logger, - private readonly apiService: ApiService, - ) {} + constructor(private readonly logger: Logger, private readonly apiService: ApiService) {} async getProfiles(addresses: string[]): Promise { const url = `${process.env.ELROND_IDENTITY}api/v1/users/multiple`; @@ -26,16 +23,11 @@ export class MxIdentityService { return accounts[key]; }); } catch (error) { - this.logger.error( - `An error occurred while calling the mx identity service on url ${removeCredentialsFromUrl( - url, - )}`, - { - path: this.getProfiles.name, - addresses: addresses, - exception: error, - }, - ); + this.logger.error(`An error occurred while calling the mx identity service on url ${removeCredentialsFromUrl(url)}`, { + path: this.getProfiles.name, + addresses: addresses, + exception: error, + }); return; } } @@ -56,39 +48,27 @@ export class MxIdentityService { privacy: Privacy.private, }); } - this.logger.error( - `An error occurred while calling the mx identity service on url ${removeCredentialsFromUrl( - url, - )}`, - { - path: this.getProfile.name, - address: address, - exception: error, - }, - ); + this.logger.error(`An error occurred while calling the mx identity service on url ${removeCredentialsFromUrl(url)}`, { + path: this.getProfile.name, + address: address, + exception: error, + }); return; } } - async getFollowersCount( - address: string, - ): Promise<{ address: string; count: number }> { + async getFollowersCount(address: string): Promise<{ address: string; count: number }> { const url = `${process.env.ELROND_IDENTITY}api/v1/followers/${address}/count`; try { let response = await this.apiService.get(url); return response?.data; } catch (error) { - this.logger.error( - `An error occurred while calling the mx identity service on url ${removeCredentialsFromUrl( - url, - )}`, - { - path: this.getFollowersCount.name, - address: address, - exception: error, - }, - ); + this.logger.error(`An error occurred while calling the mx identity service on url ${removeCredentialsFromUrl(url)}`, { + path: this.getFollowersCount.name, + address: address, + exception: error, + }); return { address, count: 0 }; } } @@ -107,16 +87,11 @@ export class MxIdentityService { privacy: Privacy.private, }); } - this.logger.error( - `An error occurred while calling the mx identity service on url ${removeCredentialsFromUrl( - url, - )}`, - { - path: this.getAcountsByHerotag.name, - address: searchTerm, - exception: error, - }, - ); + this.logger.error(`An error occurred while calling the mx identity service on url ${removeCredentialsFromUrl(url)}`, { + path: this.getAcountsByHerotag.name, + address: searchTerm, + exception: error, + }); return; } } @@ -138,25 +113,18 @@ export class MxIdentityService { privacy: Privacy.private, }); } - this.logger.error( - `An error occurred while calling the mx identity service on url ${removeCredentialsFromUrl( - url, - )}`, - { - path: this.getAddressByHerotag.name, - herotag: herotag, - exception: error, - }, - ); + this.logger.error(`An error occurred while calling the mx identity service on url ${removeCredentialsFromUrl(url)}`, { + path: this.getAddressByHerotag.name, + herotag: herotag, + exception: error, + }); return; } } async getAccountsForAddresses(keys: string[]): Promise { const uniqueAddresses = [...new Set(keys)]; - const accountsPromises = uniqueAddresses.map((address) => - this.getProfile(address), - ); + const accountsPromises = uniqueAddresses.map((address) => this.getProfile(address)); const accountResponse = await Promise.all(accountsPromises); return accountResponse; diff --git a/src/common/services/mx-communication/mx-private-api.service.ts b/src/common/services/mx-communication/mx-private-api.service.ts index a2c4cd5af..a0250e0b6 100644 --- a/src/common/services/mx-communication/mx-private-api.service.ts +++ b/src/common/services/mx-communication/mx-private-api.service.ts @@ -19,39 +19,28 @@ export class MxPrivateApiService { const httpAgent = new Agent(keepAliveOptions); const httpsAgent = new Agent.HttpsAgent(keepAliveOptions); - this.privateApiProvider = new ApiNetworkProvider( - process.env.ELROND_PRIVATE_API, - { - timeout: mxConfig.proxyTimeout, - httpAgent: mxConfig.keepAlive ? httpAgent : null, - httpsAgent: mxConfig.keepAlive ? httpsAgent : null, - headers: { - origin: 'NftService', - }, + this.privateApiProvider = new ApiNetworkProvider(process.env.ELROND_PRIVATE_API, { + timeout: mxConfig.proxyTimeout, + httpAgent: mxConfig.keepAlive ? httpAgent : null, + httpsAgent: mxConfig.keepAlive ? httpsAgent : null, + headers: { + origin: 'NftService', }, - ); + }); } getPrivateService(): ApiNetworkProvider { return this.privateApiProvider; } - async doPostGeneric( - name: string, - resourceUrl: string, - payload: any, - ): Promise { + async doPostGeneric(name: string, resourceUrl: string, payload: any): Promise { try { const profiler = new PerformanceProfiler(`${name} ${resourceUrl}`); const service = this.getPrivateService(); const response = await service.doPostGeneric(resourceUrl, payload); profiler.stop(); - MetricsCollector.setExternalCall( - MxPrivateApiService.name, - profiler.duration, - name, - ); + MetricsCollector.setExternalCall(MxPrivateApiService.name, profiler.duration, name); return response; } catch (error) { @@ -66,13 +55,10 @@ export class MxPrivateApiService { message: error.message, name: error.name, }; - this.logger.error( - `An error occurred while calling the mx private-api service on url ${resourceUrl}`, - { - path: `${MxPrivateApiService.name}.${this.doPostGeneric.name}`, - error: customError, - }, - ); + this.logger.error(`An error occurred while calling the mx private-api service on url ${resourceUrl}`, { + path: `${MxPrivateApiService.name}.${this.doPostGeneric.name}`, + error: customError, + }); } } } diff --git a/src/common/services/mx-communication/mx-stats.service.ts b/src/common/services/mx-communication/mx-stats.service.ts index 8b2b0ae05..34f83b6e0 100644 --- a/src/common/services/mx-communication/mx-stats.service.ts +++ b/src/common/services/mx-communication/mx-stats.service.ts @@ -5,10 +5,7 @@ import { NftViewsCount } from './models/nft-views.dto'; @Injectable() export class MxStatsService { - constructor( - private readonly logger: Logger, - private readonly apiService: ApiService, - ) {} + constructor(private readonly logger: Logger, private readonly apiService: ApiService) {} async getTrending(dimension: 'identifier' | 'collection'): Promise { const url = `${process.env.ELROND_STATS}api/v1/trending/${dimension}`; @@ -17,16 +14,11 @@ export class MxStatsService { const response = await this.apiService.get(url); return response.data; } catch (error) { - this.logger.error( - `An error occurred while calling the mx stats service on url ${removeCredentialsFromUrl( - url, - )}`, - { - path: `${MxStatsService.name}.${this.getTrending.name}`, - dimension, - exception: error, - }, - ); + this.logger.error(`An error occurred while calling the mx stats service on url ${removeCredentialsFromUrl(url)}`, { + path: `${MxStatsService.name}.${this.getTrending.name}`, + dimension, + exception: error, + }); return; } } @@ -38,16 +30,11 @@ export class MxStatsService { const response = await this.apiService.get(url); return response.data; } catch (error) { - this.logger.error( - `An error occurred while calling the mx stats service on url ${removeCredentialsFromUrl( - url, - )}`, - { - path: `${MxStatsService.name}.${this.getNftsViewsCount.name}`, - identifier, - exception: error, - }, - ); + this.logger.error(`An error occurred while calling the mx stats service on url ${removeCredentialsFromUrl(url)}`, { + path: `${MxStatsService.name}.${this.getNftsViewsCount.name}`, + identifier, + exception: error, + }); return new NftViewsCount({ identifier: identifier, viewsCount: 0 }); } } diff --git a/src/common/services/mx-communication/mx-tools.service.ts b/src/common/services/mx-communication/mx-tools.service.ts index 7179d955f..aca7c3836 100644 --- a/src/common/services/mx-communication/mx-tools.service.ts +++ b/src/common/services/mx-communication/mx-tools.service.ts @@ -26,15 +26,11 @@ export class MxToolsService { }); } - async getNftsCount( - input: AnalyticsInput, - ): Promise { + async getNftsCount(input: AnalyticsInput): Promise { try { const query = this.getNftsCountQuery(input); const res = await this.doPost(this.getActiveNftsStats.name, query); - return res.data?.nfts?.count.map((x) => - AnalyticsAggregateValue.fromDataApi(x), - ); + return res.data?.nfts?.count.map((x) => AnalyticsAggregateValue.fromDataApi(x)); } catch (error) { this.logger.error(`An error occurred while mapping data api response`, { path: this.getNftsCount.name, @@ -45,15 +41,11 @@ export class MxToolsService { } } - async getActiveNftsStats( - input: AnalyticsInput, - ): Promise { + async getActiveNftsStats(input: AnalyticsInput): Promise { try { const query = this.getLatestListingNumber(input); const res = await this.doPost(this.getActiveNftsStats.name, query); - return res.data?.nfts?.active_nfts.map((x) => - AnalyticsAggregateValue.fromDataApi(x), - ); + return res.data?.nfts?.active_nfts.map((x) => AnalyticsAggregateValue.fromDataApi(x)); } catch (error) { this.logger.error(`An error occurred while mapping data api response`, { path: this.getActiveNftsStats.name, @@ -64,15 +56,11 @@ export class MxToolsService { } } - async getLast24HActive( - input: AnalyticsInput, - ): Promise { + async getLast24HActive(input: AnalyticsInput): Promise { try { const query = this.getNftsCountLast24h(input); const res = await this.doPost(this.getActiveNftsStats.name, query); - return res.data?.nfts?.count24h.map((x) => - AnalyticsAggregateValue.fromDataApi(x), - ); + return res.data?.nfts?.count24h.map((x) => AnalyticsAggregateValue.fromDataApi(x)); } catch (error) { this.logger.error(`An error occurred while mapping data api response`, { path: this.getLast24HActive.name, diff --git a/src/common/services/mx-communication/slack-report.service.ts b/src/common/services/mx-communication/slack-report.service.ts index b9d9ee896..d7dc97e89 100644 --- a/src/common/services/mx-communication/slack-report.service.ts +++ b/src/common/services/mx-communication/slack-report.service.ts @@ -5,20 +5,11 @@ import { ApiSettings } from './models/api-settings'; @Injectable() export class SlackReportService { - constructor( - private readonly logger: Logger, - private readonly apiService: ApiService, - ) {} + constructor(private readonly logger: Logger, private readonly apiService: ApiService) {} - async sendReport( - identifier: string, - count: number, - type: 'nfts' | 'collections' = 'nfts', - ): Promise { + async sendReport(identifier: string, count: number, type: 'nfts' | 'collections' = 'nfts'): Promise { const url = process.env.SLACK_API; - const marketplaceUrl = new URL( - `${process.env.ELROND_MARKETPLACE}\\${type}\\${identifier}`, - ); + const marketplaceUrl = new URL(`${process.env.ELROND_MARKETPLACE}\\${type}\\${identifier}`); try { const response = await this.apiService.post( url, @@ -32,16 +23,11 @@ export class SlackReportService { ); return response.data; } catch (error) { - this.logger.error( - `An error occurred while calling the slack report service on url ${removeCredentialsFromUrl( - url, - )}`, - { - path: 'SlackReportService.sendReport', - identifier, - exception: error, - }, - ); + this.logger.error(`An error occurred while calling the slack report service on url ${removeCredentialsFromUrl(url)}`, { + path: 'SlackReportService.sendReport', + identifier, + exception: error, + }); return; } } @@ -61,9 +47,7 @@ export class SlackReportService { ); } catch (error) { this.logger.error( - `An error occurred while sending slack notification for marketplace SCUpgrade event url ${removeCredentialsFromUrl( - url, - )}`, + `An error occurred while sending slack notification for marketplace SCUpgrade event url ${removeCredentialsFromUrl(url)}`, { path: 'SlackReportService.sendScUpgradeNotification', marketplaceAddress, diff --git a/src/config/env_load.ts b/src/config/env_load.ts index 542d734b6..542a4ed6d 100644 --- a/src/config/env_load.ts +++ b/src/config/env_load.ts @@ -1,8 +1,6 @@ import * as dotenv from 'dotenv'; -const nodeEnv: string = process.env.NODE_ENV - ? process.env.NODE_ENV.trim() - : 'production'; +const nodeEnv: string = process.env.NODE_ENV ? process.env.NODE_ENV.trim() : 'production'; export const envload = () => { switch (nodeEnv) { diff --git a/src/datasource.ts b/src/datasource.ts index ce15728a1..0930df3a3 100644 --- a/src/datasource.ts +++ b/src/datasource.ts @@ -13,9 +13,7 @@ const db: MysqlConnectionCredentialsOptions = { database: process.env.DB_NAME, }; -const dbSlaves = process.env.DB_SLAVES - ? JSON.parse(process.env.DB_SLAVES) - : [db]; +const dbSlaves = process.env.DB_SLAVES ? JSON.parse(process.env.DB_SLAVES) : [db]; const connectionSource = new DataSource({ migrationsTableName: 'migrations', type: 'mysql', @@ -30,10 +28,7 @@ const connectionSource = new DataSource({ master: db, slaves: dbSlaves, }, - entities: - process.env.NODE_ENV === 'test-e2e' - ? ['src/db/**/*.entity.js'] - : ['dist/db/**/*.entity.js'], + entities: process.env.NODE_ENV === 'test-e2e' ? ['src/db/**/*.entity.js'] : ['dist/db/**/*.entity.js'], migrations: ['dist/db/migrations/*.js'], extra: { connectionLimit: process.env.DB_CONNECTION_LIMIT, diff --git a/src/db/orders/order.entity.ts b/src/db/orders/order.entity.ts index 6a44d3a3d..5826fbe1f 100644 --- a/src/db/orders/order.entity.ts +++ b/src/db/orders/order.entity.ts @@ -4,10 +4,7 @@ import { AuctionEntity } from '../auctions'; import { BaseEntity } from '../base-entity'; @Entity('orders') -@Index('orders_price_token_amount_denominated', [ - 'priceAmount', - 'priceAmountDenominated', -]) +@Index('orders_price_token_amount_denominated', ['priceAmount', 'priceAmountDenominated']) export class OrderEntity extends BaseEntity { @Column({ length: 20 }) @Index('orders_price_token') diff --git a/src/main.ts b/src/main.ts index ac43f1ed7..b742e1798 100644 --- a/src/main.ts +++ b/src/main.ts @@ -39,10 +39,7 @@ async function bootstrap() { if (process.env.ENABLE_PRIVATE_API === 'true') { const privateApp = await NestFactory.create(PrivateAppModule); - await privateApp.listen( - parseInt(process.env.PRIVATE_PORT), - process.env.PRIVATE_LISTEN_ADDRESS, - ); + await privateApp.listen(parseInt(process.env.PRIVATE_PORT), process.env.PRIVATE_LISTEN_ADDRESS); } if (process.env.ENABLE_CACHE_INVALIDATION === 'true') { @@ -85,54 +82,33 @@ async function bootstrap() { await processorApp.listen(ports.scamInfo); } if (process.env.ENABLE_CACHE_INVALIDATION !== 'true') { - const pubSubApp = await NestFactory.createMicroservice( - PubSubListenerModule, - { - transport: Transport.REDIS, - options: { - host: apiConfigService.getRedisUrl(), - port: apiConfigService.getRedisPort(), - retryAttempts: 100, - retryDelay: 1000, - retryStrategy: () => 1000, - }, + const pubSubApp = await NestFactory.createMicroservice(PubSubListenerModule, { + transport: Transport.REDIS, + options: { + host: apiConfigService.getRedisUrl(), + port: apiConfigService.getRedisPort(), + retryAttempts: 100, + retryDelay: 1000, + retryStrategy: () => 1000, }, - ); + }); pubSubApp.listen(); } logger.log(`Public API active: ${process.env.ENABLE_PUBLIC_API}`); logger.log(`Private API active: ${process.env.ENABLE_PRIVATE_API}`); - logger.log( - `Claimable job is active: ${process.env.ENABLE_CLAIMABLE_AUCTIONS}`, - ); + logger.log(`Claimable job is active: ${process.env.ENABLE_CLAIMABLE_AUCTIONS}`); logger.log(`Cache warmer active: ${process.env.ENABLE_CACHE_WARMER}`); logger.log(`Rabbit is active: ${process.env.ENABLE_RABBITMQ}`); - logger.log( - `Cache invalidation is active: ${process.env.ENABLE_CACHE_INVALIDATION}`, - ); - logger.log( - `Account batch get is active: ${process.env.ENABLE_BATCH_ACCOUNT_GET}`, - ); + logger.log(`Cache invalidation is active: ${process.env.ENABLE_CACHE_INVALIDATION}`); + logger.log(`Account batch get is active: ${process.env.ENABLE_BATCH_ACCOUNT_GET}`); logger.log(`NSFW cron job is active: ${process.env.ENABLE_NSFW_CRONJOBS}`); - logger.log( - `Elastic updates are active: ${process.env.ENABLE_ELASTIC_UPDATES}`, - ); - logger.log( - `Elastic nft traits are active: ${process.env.ENABLE_TRAITS_CRONJOBS}`, - ); - logger.log( - `Elastic nft rarities are active: ${process.env.ENABLE_RARITY_CRONJOBS}`, - ); - logger.log( - `Elastic nft scams are active: ${process.env.ENABLE_SCAM_CRONJOBS}`, - ); - logger.log( - `Marketplace events indexing is active: ${process.env.ENABLE_MARKETPLACE_EVENTS}`, - ); - logger.log( - `Trending by volume is active: ${process.env.ENABLE_TRENDING_BY_VOLUME}`, - ); + logger.log(`Elastic updates are active: ${process.env.ENABLE_ELASTIC_UPDATES}`); + logger.log(`Elastic nft traits are active: ${process.env.ENABLE_TRAITS_CRONJOBS}`); + logger.log(`Elastic nft rarities are active: ${process.env.ENABLE_RARITY_CRONJOBS}`); + logger.log(`Elastic nft scams are active: ${process.env.ENABLE_SCAM_CRONJOBS}`); + logger.log(`Marketplace events indexing is active: ${process.env.ENABLE_MARKETPLACE_EVENTS}`); + logger.log(`Trending by volume is active: ${process.env.ENABLE_TRENDING_BY_VOLUME}`); } bootstrap(); @@ -158,9 +134,7 @@ async function startPublicApp() { app.useGlobalInterceptors(new LoggingInterceptor()); const httpServer = httpAdapterHostService.httpAdapter.getHttpServer(); - httpServer.keepAliveTimeout = parseInt( - process.env.KEEPALIVE_TIMEOUT_UPSTREAM, - ); + httpServer.keepAliveTimeout = parseInt(process.env.KEEPALIVE_TIMEOUT_UPSTREAM); await app.listen(process.env.PORT); } diff --git a/src/modules/account-stats/models/Account.dto.ts b/src/modules/account-stats/models/Account.dto.ts index ac86fe640..e5dfe8ce4 100644 --- a/src/modules/account-stats/models/Account.dto.ts +++ b/src/modules/account-stats/models/Account.dto.ts @@ -33,9 +33,7 @@ export class Account { cover: account?.cover?.url, herotag: account?.herotag, privacy: account.privacy, - socialLinks: account?.socialLinks?.map( - (elem) => new SocialLink({ type: elem?.type, url: elem?.url }), - ), + socialLinks: account?.socialLinks?.map((elem) => new SocialLink({ type: elem?.type, url: elem?.url })), }) : new Account({ address: address }); } diff --git a/src/modules/asset-history/assets-history-caching.service.ts b/src/modules/asset-history/assets-history-caching.service.ts index 00cd2c7ed..96344df44 100644 --- a/src/modules/asset-history/assets-history-caching.service.ts +++ b/src/modules/asset-history/assets-history-caching.service.ts @@ -15,31 +15,11 @@ export class AssetsHistoryCachingService { timestamp: string | number, getOrSetHistoryLog: () => any, ): Promise { - const cacheKey = this.getAssetHistoryCacheKey( - collection, - nonce, - limit, - timestamp, - ); - return await this.redisCacheService.getOrSet( - cacheKey, - getOrSetHistoryLog, - CacheInfo.AssetHistory.ttl, - ); + const cacheKey = this.getAssetHistoryCacheKey(collection, nonce, limit, timestamp); + return await this.redisCacheService.getOrSet(cacheKey, getOrSetHistoryLog, CacheInfo.AssetHistory.ttl); } - getAssetHistoryCacheKey( - collection: string, - nonce: string, - limit?: number, - timestamp?: string | number, - ) { - return generateCacheKeyFromParams( - CacheInfo.AssetHistory.key, - collection, - nonce, - limit, - timestamp, - ); + getAssetHistoryCacheKey(collection: string, nonce: string, limit?: number, timestamp?: string | number) { + return generateCacheKeyFromParams(CacheInfo.AssetHistory.key, collection, nonce, limit, timestamp); } } diff --git a/src/modules/asset-history/assets-history-elastic.service.ts b/src/modules/asset-history/assets-history-elastic.service.ts index fa43adbec..de8cc8ae9 100644 --- a/src/modules/asset-history/assets-history-elastic.service.ts +++ b/src/modules/asset-history/assets-history-elastic.service.ts @@ -1,23 +1,13 @@ import { Injectable } from '@nestjs/common'; import { MxElasticService } from 'src/common'; -import { - ElasticQuery, - ElasticSortOrder, - QueryType, - RangeLowerThan, -} from '@multiversx/sdk-nestjs'; +import { ElasticQuery, ElasticSortOrder, QueryType, RangeLowerThan } from '@multiversx/sdk-nestjs'; import { constants } from 'src/config'; @Injectable() export class AssetsHistoryElasticService { constructor(private readonly mxElasticService: MxElasticService) {} - async getHistoryLog( - collection: string, - nonce: string, - limit: number, - beforeTimestamp: number, - ): Promise { + async getHistoryLog(collection: string, nonce: string, limit: number, beforeTimestamp: number): Promise { let elasticLogs = []; const encodedCollection = Buffer.from(collection).toString('base64'); const encodedNonce = Buffer.from(nonce, 'hex').toString('base64'); @@ -40,27 +30,18 @@ export class AssetsHistoryElasticService { size: constants.getLogsFromElasticBatchSize, }); - await this.mxElasticService.getScrollableList( - 'logs', - 'identifier', - query, - async (logs) => { - logs.map((log) => { - const anyMatchingEvent = log.events.find( - (event) => - event.topics?.[0] === encodedCollection && - event.topics?.[1] === encodedNonce, - ); - if (anyMatchingEvent) { - elasticLogs.push(log); - } - }); - - if (elasticLogs.length >= limit) { - return false; + await this.mxElasticService.getScrollableList('logs', 'identifier', query, async (logs) => { + logs.map((log) => { + const anyMatchingEvent = log.events.find((event) => event.topics?.[0] === encodedCollection && event.topics?.[1] === encodedNonce); + if (anyMatchingEvent) { + elasticLogs.push(log); } - }, - ); + }); + + if (elasticLogs.length >= limit) { + return false; + } + }); return [...new Set(elasticLogs)]; } diff --git a/src/modules/asset-history/assets-history.resolver.ts b/src/modules/asset-history/assets-history.resolver.ts index ad7c1fdad..b598a5444 100644 --- a/src/modules/asset-history/assets-history.resolver.ts +++ b/src/modules/asset-history/assets-history.resolver.ts @@ -5,10 +5,7 @@ import { AssetsHistoryService } from '.'; import { getCollectionAndNonceFromIdentifier } from 'src/utils/helpers'; import { AssetHistoryLogResponse } from './models'; import { DateUtils } from 'src/utils/date-utils'; -import { - HistoryPagination, - HistoryEdge, -} from '../common/filters/ConnectionArgs'; +import { HistoryPagination, HistoryEdge } from '../common/filters/ConnectionArgs'; import { AssetHistoryFilter } from '../common/filters/filtersTypes'; @Resolver(() => AssetHistoryLogResponse) @@ -24,28 +21,13 @@ export class AssetsHistoryResolver extends BaseResolver(AssetHistoryLog) { @Args({ name: 'pagination', type: () => HistoryPagination, nullable: true }) pagination: HistoryPagination, ): Promise { - const { collection, nonce } = getCollectionAndNonceFromIdentifier( - filters.identifier, - ); - const historyLog = await this.assetsHistoryService.getOrSetHistoryLog( - collection, - nonce, - pagination.first, - pagination.timestamp, - ); + const { collection, nonce } = getCollectionAndNonceFromIdentifier(filters.identifier); + const historyLog = await this.assetsHistoryService.getOrSetHistoryLog(collection, nonce, pagination.first, pagination.timestamp); return this.mapResponse(historyLog, pagination.timestamp, pagination.first); } - private mapResponse( - returnList: AssetHistoryLog[], - offset: number, - limit: number, - ) { - const startTimestamp = offset - ? offset - : returnList.length > 0 - ? returnList[0]?.actionDate - : DateUtils.getCurrentTimestamp(); + private mapResponse(returnList: AssetHistoryLog[], offset: number, limit: number) { + const startTimestamp = offset ? offset : returnList.length > 0 ? returnList[0]?.actionDate : DateUtils.getCurrentTimestamp(); return { edges: returnList?.map( diff --git a/src/modules/asset-history/assets-history.service.ts b/src/modules/asset-history/assets-history.service.ts index f495fa884..8d04adb0b 100644 --- a/src/modules/asset-history/assets-history.service.ts +++ b/src/modules/asset-history/assets-history.service.ts @@ -29,21 +29,9 @@ export class AssetsHistoryService { private readonly assetsHistoryElasticService: AssetsHistoryElasticService, ) {} - async getOrSetHistoryLog( - collection: string, - nonce: string, - limit: number, - beforeTimestamp: number, - ): Promise { - const getOrSetHistoryLog = async () => - await this.getAndMapHistoryLog(collection, nonce, limit, beforeTimestamp); - return await this.assetsHistoryCachingService.getOrSetHistoryLog( - collection, - nonce, - limit, - beforeTimestamp, - getOrSetHistoryLog, - ); + async getOrSetHistoryLog(collection: string, nonce: string, limit: number, beforeTimestamp: number): Promise { + const getOrSetHistoryLog = async () => await this.getAndMapHistoryLog(collection, nonce, limit, beforeTimestamp); + return await this.assetsHistoryCachingService.getOrSetHistoryLog(collection, nonce, limit, beforeTimestamp, getOrSetHistoryLog); } private async getAndMapHistoryLog( @@ -53,12 +41,7 @@ export class AssetsHistoryService { beforeTimestamp: number, historyLog: AssetHistoryLog[] = [], ): Promise { - const elasticLogs = await this.assetsHistoryElasticService.getHistoryLog( - collection, - nonce, - limit, - beforeTimestamp, - ); + const elasticLogs = await this.assetsHistoryElasticService.getHistoryLog(collection, nonce, limit, beforeTimestamp); for (let index = 0; index < elasticLogs.length; index++) { if (historyLog.length === limit) { @@ -71,12 +54,7 @@ export class AssetsHistoryService { return historyLog; } - private mapLogs( - nonce: string, - res: any, - index: number, - historyLog: AssetHistoryLog[], - ) { + private mapLogs(nonce: string, res: any, index: number, historyLog: AssetHistoryLog[]) { const [eventCategory, eventType, mainEvent] = this.getEventType(res, index); if (!eventCategory) { @@ -85,81 +63,39 @@ export class AssetsHistoryService { switch (eventCategory) { case NftEventTypeEnum.NftEventEnum: { - this.addHistoryLog( - historyLog, - this.assetsHistoryNftEventService.mapNftEventLog( - nonce, - eventType, - mainEvent, - ), - ); + this.addHistoryLog(historyLog, this.assetsHistoryNftEventService.mapNftEventLog(nonce, eventType, mainEvent)); break; } case NftEventTypeEnum.AuctionEventEnum: { - this.addHistoryLog( - historyLog, - this.assetsHistoryAuctionService.mapAuctionEventLog( - eventType, - mainEvent, - ), - ); + this.addHistoryLog(historyLog, this.assetsHistoryAuctionService.mapAuctionEventLog(eventType, mainEvent)); break; } case NftEventTypeEnum.ExternalAuctionEventEnum: { - this.addHistoryLog( - historyLog, - this.assetsHistoryExternalAuctionService.mapExternalAuctionEventLog( - nonce, - eventType, - mainEvent, - ), - ); + this.addHistoryLog(historyLog, this.assetsHistoryExternalAuctionService.mapExternalAuctionEventLog(nonce, eventType, mainEvent)); break; } case NftEventTypeEnum.ElrondNftsSwapAuctionEventEnum: { - this.addHistoryLog( - historyLog, - this.assetsHistoryElrondNftsSwapEventsService.mapElrondNftsSwapEventLog( - eventType, - mainEvent, - ), - ); + this.addHistoryLog(historyLog, this.assetsHistoryElrondNftsSwapEventsService.mapElrondNftsSwapEventLog(eventType, mainEvent)); break; } } } - private addHistoryLog( - historyLog: AssetHistoryLog[], - input: AssetHistoryInput, - ): void { + private addHistoryLog(historyLog: AssetHistoryLog[], input: AssetHistoryInput): void { if (!input) { return; } - const minPrice = input.price - ? Buffer.from(input.price, 'base64') - .toString('hex') - .hexBigNumberToString() - : undefined; - const itemCountString = input.itemsCount - ? Buffer.from(input.itemsCount, 'base64') - .toString('hex') - .hexBigNumberToString() - : undefined; - const totalPrice = - minPrice && itemCountString - ? new BigNumber(minPrice).multipliedBy(itemCountString) - : undefined; + const minPrice = input.price ? Buffer.from(input.price, 'base64').toString('hex').hexBigNumberToString() : undefined; + const itemCountString = input.itemsCount ? Buffer.from(input.itemsCount, 'base64').toString('hex').hexBigNumberToString() : undefined; + const totalPrice = minPrice && itemCountString ? new BigNumber(minPrice).multipliedBy(itemCountString) : undefined; historyLog.push( new AssetHistoryLog({ action: input.action, address: input.address, senderAddress: input.sender, - transactionHash: input.event.originalTxHash - ? input.event.originalTxHash - : input.event.identifier, + transactionHash: input.event.originalTxHash ? input.event.originalTxHash : input.event.identifier, actionDate: input.event.timestamp || '', itemCount: itemCountString ? itemCountString.toString() : undefined, price: totalPrice @@ -181,11 +117,7 @@ export class AssetsHistoryService { const eventId = res[index].identifier; - const relatedEvents = res.filter( - (eventObject) => - eventObject.identifier === eventId || - eventObject.originalTxHash === eventId, - ); + const relatedEvents = res.filter((eventObject) => eventObject.identifier === eventId || eventObject.originalTxHash === eventId); for (let i = 0; i < relatedEvents?.length; i++) { const events = relatedEvents[i].events; @@ -197,42 +129,20 @@ export class AssetsHistoryService { eventIdentifier !== NftEventEnum.MultiESDTNFTTransfer && Object.values(NftEventEnum).includes(eventIdentifier) ) { - return [ - NftEventTypeEnum.NftEventEnum, - eventIdentifier, - relatedEvents[i], - ]; + return [NftEventTypeEnum.NftEventEnum, eventIdentifier, relatedEvents[i]]; } if (Object.values(AuctionEventEnum).includes(eventIdentifier)) { - return [ - NftEventTypeEnum.AuctionEventEnum, - eventIdentifier, - relatedEvents[i], - ]; + return [NftEventTypeEnum.AuctionEventEnum, eventIdentifier, relatedEvents[i]]; } if (Object.values(ExternalAuctionEventEnum).includes(eventIdentifier)) { - return [ - NftEventTypeEnum.ExternalAuctionEventEnum, - eventIdentifier, - relatedEvents[i], - ]; + return [NftEventTypeEnum.ExternalAuctionEventEnum, eventIdentifier, relatedEvents[i]]; } - if ( - Object.values(KroganSwapAuctionEventEnum).includes(eventIdentifier) - ) { - return [ - NftEventTypeEnum.ElrondNftsSwapAuctionEventEnum, - eventIdentifier, - relatedEvents[i], - ]; + if (Object.values(KroganSwapAuctionEventEnum).includes(eventIdentifier)) { + return [NftEventTypeEnum.ElrondNftsSwapAuctionEventEnum, eventIdentifier, relatedEvents[i]]; } } } - return [ - NftEventTypeEnum.NftEventEnum, - res[index].events[0].identifier, - res[index], - ]; + return [NftEventTypeEnum.NftEventEnum, res[index].events[0].identifier, res[index]]; } } diff --git a/src/modules/asset-history/models/AssetHistoryResponse.ts b/src/modules/asset-history/models/AssetHistoryResponse.ts index 4239e586c..b8ae0de9b 100644 --- a/src/modules/asset-history/models/AssetHistoryResponse.ts +++ b/src/modules/asset-history/models/AssetHistoryResponse.ts @@ -3,6 +3,4 @@ import relayTypes from 'src/modules/common/Relay.types'; import { AssetHistoryLog } from '.'; @ObjectType() -export class AssetHistoryLogResponse extends relayTypes( - AssetHistoryLog, -) {} +export class AssetHistoryLogResponse extends relayTypes(AssetHistoryLog) {} diff --git a/src/modules/asset-history/services/assets-history.auction.service.ts b/src/modules/asset-history/services/assets-history.auction.service.ts index b7f4cb470..7dc34aac4 100644 --- a/src/modules/asset-history/services/assets-history.auction.service.ts +++ b/src/modules/asset-history/services/assets-history.auction.service.ts @@ -7,9 +7,7 @@ export class AssetsHistoryAuctionService { constructor() {} mapAuctionEventLog(eventType: string, mainEvent: any): AssetHistoryLogInput { - const event = mainEvent.events.find( - (event) => event.identifier === eventType, - ); + const event = mainEvent.events.find((event) => event.identifier === eventType); switch (eventType) { case AuctionEventEnum.AuctionTokenEvent: { return new AssetHistoryLogInput({ diff --git a/src/modules/asset-history/services/assets-history.external-auction.service.ts b/src/modules/asset-history/services/assets-history.external-auction.service.ts index 0d59dc952..14af0ce97 100644 --- a/src/modules/asset-history/services/assets-history.external-auction.service.ts +++ b/src/modules/asset-history/services/assets-history.external-auction.service.ts @@ -1,28 +1,17 @@ import { Injectable } from '@nestjs/common'; -import { - AssetActionEnum, - ExternalAuctionEventEnum, - NftEventEnum, -} from 'src/modules/assets/models'; +import { AssetActionEnum, ExternalAuctionEventEnum, NftEventEnum } from 'src/modules/assets/models'; import { AssetHistoryInput as AssetHistoryLogInput } from '../models/asset-history-log-input'; @Injectable() export class AssetsHistoryExternalAuctionService { constructor() {} - mapExternalAuctionEventLog( - nonce: string, - eventType: string, - mainEvent: any, - ): AssetHistoryLogInput { - const event = mainEvent.events.find( - (event) => event.identifier === eventType, - ); + mapExternalAuctionEventLog(nonce: string, eventType: string, mainEvent: any): AssetHistoryLogInput { + const event = mainEvent.events.find((event) => event.identifier === eventType); const encodedNonce = Buffer.from(nonce, 'hex').toString('base64'); const transferEvent = mainEvent.events.find( (event) => - (event.identifier === NftEventEnum.ESDTNFTTransfer || - event.identifier === NftEventEnum.MultiESDTNFTTransfer) && + (event.identifier === NftEventEnum.ESDTNFTTransfer || event.identifier === NftEventEnum.MultiESDTNFTTransfer) && event.topics[1] === encodedNonce, ); @@ -38,10 +27,7 @@ export class AssetsHistoryExternalAuctionService { } case ExternalAuctionEventEnum.Buy: { const senderAddress = event.address; - const addresses = this.getAddressesFromTopics( - event.topics, - senderAddress, - ); + const addresses = this.getAddressesFromTopics(event.topics, senderAddress); return new AssetHistoryLogInput({ event: mainEvent, action: AssetActionEnum.Bought, @@ -52,12 +38,8 @@ export class AssetsHistoryExternalAuctionService { } case ExternalAuctionEventEnum.BuyNft: { const senderAddress = event.address; - const addresses = this.getAddressesFromTopics( - event.topics, - senderAddress, - ); - const quantity = - event.topics.length === 7 ? event.topics[4] : event.topics[7]; + const addresses = this.getAddressesFromTopics(event.topics, senderAddress); + const quantity = event.topics.length === 7 ? event.topics[4] : event.topics[7]; return new AssetHistoryLogInput({ event: mainEvent, action: AssetActionEnum.Bought, @@ -67,15 +49,9 @@ export class AssetsHistoryExternalAuctionService { }); } case ExternalAuctionEventEnum.BulkBuy: { - const buyNftEvent = mainEvent.events.find( - (event) => - event.identifier === eventType && event.topics[2] === encodedNonce, - ); + const buyNftEvent = mainEvent.events.find((event) => event.identifier === eventType && event.topics[2] === encodedNonce); const senderAddress = buyNftEvent.address; - const addresses = this.getAddressesFromTopics( - buyNftEvent.topics, - senderAddress, - ); + const addresses = this.getAddressesFromTopics(buyNftEvent.topics, senderAddress); return new AssetHistoryLogInput({ event: mainEvent, action: AssetActionEnum.Bought, @@ -87,10 +63,7 @@ export class AssetsHistoryExternalAuctionService { } } - private getAddressesFromTopics( - topics: string[], - differentThanAddress?: string, - ): string[] { + private getAddressesFromTopics(topics: string[], differentThanAddress?: string): string[] { const addresses: string[] = []; const possibleAddresses = topics?.filter((topic) => topic.length === 44); diff --git a/src/modules/asset-history/services/assets-history.nft-events.service.ts b/src/modules/asset-history/services/assets-history.nft-events.service.ts index 15658e531..34a5c47ae 100644 --- a/src/modules/asset-history/services/assets-history.nft-events.service.ts +++ b/src/modules/asset-history/services/assets-history.nft-events.service.ts @@ -7,19 +7,12 @@ import { AssetHistoryInput as AssetHistoryLogInput } from '../models/asset-histo export class AssetsHistoryNftEventService { constructor() {} - mapNftEventLog( - nonce: string, - eventType: string, - mainEvent: any, - ): AssetHistoryLogInput { - const event = mainEvent.events.find( - (event) => event.identifier === eventType, - ); + mapNftEventLog(nonce: string, eventType: string, mainEvent: any): AssetHistoryLogInput { + const event = mainEvent.events.find((event) => event.identifier === eventType); const encodedNonce = Buffer.from(nonce, 'hex').toString('base64'); const transferEvent = mainEvent.events.find( (event) => - (event.identifier === NftEventEnum.ESDTNFTTransfer || - event.identifier === NftEventEnum.MultiESDTNFTTransfer) && + (event.identifier === NftEventEnum.ESDTNFTTransfer || event.identifier === NftEventEnum.MultiESDTNFTTransfer) && event.topics[1] === encodedNonce, ); @@ -44,8 +37,7 @@ export class AssetsHistoryNftEventService { case NftEventEnum.ESDTNFTTransfer: { if ( mainEvent.address === mainEvent?.events[0].address && - transferEvent.topics[3].base64ToBech32() !== - mxConfig.nftMarketplaceAddress + transferEvent.topics[3].base64ToBech32() !== mxConfig.nftMarketplaceAddress ) { return new AssetHistoryLogInput({ event: mainEvent, diff --git a/src/modules/asset-history/services/assets-history.nfts-swap-auction.service.ts b/src/modules/asset-history/services/assets-history.nfts-swap-auction.service.ts index aff3f5dc8..86a326450 100644 --- a/src/modules/asset-history/services/assets-history.nfts-swap-auction.service.ts +++ b/src/modules/asset-history/services/assets-history.nfts-swap-auction.service.ts @@ -1,18 +1,12 @@ import { Injectable } from '@nestjs/common'; -import { - AssetActionEnum, - KroganSwapAuctionEventEnum, -} from 'src/modules/assets/models'; +import { AssetActionEnum, KroganSwapAuctionEventEnum } from 'src/modules/assets/models'; import { AssetHistoryInput as AssetHistoryLogInput } from '../models/asset-history-log-input'; @Injectable() export class AssetsHistoryElrondNftsSwapEventsService { constructor() {} - mapElrondNftsSwapEventLog( - eventType: string, - mainEvent: any, - ): AssetHistoryLogInput { + mapElrondNftsSwapEventLog(eventType: string, mainEvent: any): AssetHistoryLogInput { switch (eventType) { case KroganSwapAuctionEventEnum.NftSwap: { return new AssetHistoryLogInput({ @@ -24,9 +18,7 @@ export class AssetsHistoryElrondNftsSwapEventsService { }); } case KroganSwapAuctionEventEnum.WithdrawSwap: { - const withdrawSwap = mainEvent.events.find( - (event) => event.identifier === eventType, - ); + const withdrawSwap = mainEvent.events.find((event) => event.identifier === eventType); const quantity = withdrawSwap.topics[4]; const txSender = withdrawSwap.topics[5].base64ToBech32(); return new AssetHistoryLogInput({ @@ -38,9 +30,7 @@ export class AssetsHistoryElrondNftsSwapEventsService { }); } case KroganSwapAuctionEventEnum.Purchase: { - const purchaseEvent = mainEvent.events.find( - (event) => event.identifier === eventType, - ); + const purchaseEvent = mainEvent.events.find((event) => event.identifier === eventType); return new AssetHistoryLogInput({ event: mainEvent, action: AssetActionEnum.Bought, diff --git a/src/modules/auctions/auctions-queries.resolver.ts b/src/modules/auctions/auctions-queries.resolver.ts index bf66361ab..773e3eb14 100644 --- a/src/modules/auctions/auctions-queries.resolver.ts +++ b/src/modules/auctions/auctions-queries.resolver.ts @@ -1,11 +1,4 @@ -import { - Resolver, - Query, - Args, - ResolveField, - Parent, - Int, -} from '@nestjs/graphql'; +import { Resolver, Query, Args, ResolveField, Parent, Int } from '@nestjs/graphql'; import { BaseResolver } from '../common/base.resolver'; import { Auction, AuctionTypeEnum, AuctionResponse } from './models'; import { Asset, Price } from '../assets/models'; @@ -14,11 +7,7 @@ import { AccountsProvider } from '../account-stats/loaders/accounts.loader'; import { AssetsProvider } from '../assets/loaders/assets.loader'; import { Account } from '../account-stats/models'; import ConnectionArgs from '../common/filters/ConnectionArgs'; -import { - FiltersExpression, - Sorting, - Grouping, -} from '../common/filters/filtersTypes'; +import { FiltersExpression, Sorting, Grouping } from '../common/filters/filtersTypes'; import { AuctionCustomFilter } from '../common/filters/AuctionCustomFilters'; import PageResponse from '../common/PageResponse'; import { QueryRequest } from '../common/filters/QueryRequest'; @@ -58,16 +47,14 @@ export class AuctionsQueriesResolver extends BaseResolver(Auction) { name: 'filters', type: () => FiltersExpression, nullable: true, - description: - 'The values that can be used for this filters fields are the entity properties', + description: 'The values that can be used for this filters fields are the entity properties', }) filters, @Args({ name: 'sorting', type: () => [Sorting], nullable: true, - description: - 'The values that can be used for this sorting fields are the entity properties', + description: 'The values that can be used for this sorting fields are the entity properties', }) sorting, @Args({ name: 'grouping', type: () => Grouping, nullable: true }) @@ -82,33 +69,21 @@ export class AuctionsQueriesResolver extends BaseResolver(Auction) { pagination: ConnectionArgs, ) { const { limit, offset } = pagination.pagingParams(); - const [auctions, count, priceRange] = - await this.auctionsGetterService.getAuctions( - new QueryRequest({ - limit, - offset, - filters, - sorting, - groupByOption: groupBy, - customFilters, - }), - ); + const [auctions, count, priceRange] = await this.auctionsGetterService.getAuctions( + new QueryRequest({ + limit, + offset, + filters, + sorting, + groupByOption: groupBy, + customFilters, + }), + ); return { - ...PageResponse.mapResponse( - auctions, - pagination, - count, - offset, - limit, - ), + ...PageResponse.mapResponse(auctions, pagination, count, offset, limit), priceRange: priceRange - ? PriceRange.fromEntity( - priceRange?.minBid, - priceRange?.maxBid, - priceRange?.paymentToken, - priceRange?.paymentDecimals, - ) + ? PriceRange.fromEntity(priceRange?.minBid, priceRange?.maxBid, priceRange?.paymentToken, priceRange?.paymentDecimals) : null, }; } @@ -124,25 +99,12 @@ export class AuctionsQueriesResolver extends BaseResolver(Auction) { ) { const { limit, offset } = pagination.pagingParams(); - const [auctions, count, priceRange] = - await this.auctionsGetterService.getAuctionsOrderByNoBids( - new QueryRequest({ limit, offset, filters, groupByOption: groupBy }), - ); + const [auctions, count, priceRange] = await this.auctionsGetterService.getAuctionsOrderByNoBids( + new QueryRequest({ limit, offset, filters, groupByOption: groupBy }), + ); return { - ...PageResponse.mapResponse( - auctions, - pagination, - count, - offset, - limit, - ), - priceRange: priceRange - ? PriceRange.fromEntity( - priceRange?.minBid, - priceRange?.maxBid, - priceRange?.paymentToken, - ) - : null, + ...PageResponse.mapResponse(auctions, pagination, count, offset, limit), + priceRange: priceRange ? PriceRange.fromEntity(priceRange?.minBid, priceRange?.maxBid, priceRange?.paymentToken) : null, }; } @@ -155,9 +117,7 @@ export class AuctionsQueriesResolver extends BaseResolver(Auction) { }) filters: TokenFilter, ) { - const { minBid, maxBid } = await this.auctionsGetterService.getMinMaxPrice( - filters?.token ?? mxConfig.egld, - ); + const { minBid, maxBid } = await this.auctionsGetterService.getMinMaxPrice(filters?.token ?? mxConfig.egld); return PriceRange.fromEntity(minBid, maxBid); } @@ -175,20 +135,8 @@ export class AuctionsQueriesResolver extends BaseResolver(Auction) { pagination: ConnectionArgs, ) { const { limit, offset } = pagination.pagingParams(); - const [auctions, count] = - await this.auctionsGetterService.getClaimableAuctions( - limit, - offset, - user.address, - filters?.marketplaceKey, - ); - return PageResponse.mapResponse( - auctions, - pagination, - count, - offset, - limit, - ); + const [auctions, count] = await this.auctionsGetterService.getClaimableAuctions(limit, offset, user.address, filters?.marketplaceKey); + return PageResponse.mapResponse(auctions, pagination, count, offset, limit); } @ResolveField('asset', () => Asset) @@ -208,23 +156,16 @@ export class AuctionsQueriesResolver extends BaseResolver(Auction) { if (type === AuctionTypeEnum.SftOnePerPayment) return null; const activeOrders = await this.lastOrderProvider.load(id); const activeOrdersValue = activeOrders?.value; - return activeOrdersValue?.length > 0 - ? Price.fromEntity(activeOrdersValue[0]) - : null; + return activeOrdersValue?.length > 0 ? Price.fromEntity(activeOrdersValue[0]) : null; } @ResolveField('topBidder', () => Account) - async topBidder( - @Parent() auction: Auction, - @Fields('topBidder', ['*.']) fields: string[], - ) { + async topBidder(@Parent() auction: Auction, @Fields('topBidder', ['*.']) fields: string[]) { const { id, type } = auction; if (type === AuctionTypeEnum.SftOnePerPayment) return null; const activeOrders = await this.lastOrderProvider.load(id); const activeOrdersValue = activeOrders?.value; - return activeOrdersValue && activeOrdersValue?.length > 0 - ? await this.getAccount(fields, activeOrdersValue[0].ownerAddress) - : null; + return activeOrdersValue && activeOrdersValue?.length > 0 ? await this.getAccount(fields, activeOrdersValue[0].ownerAddress) : null; } @ResolveField('availableTokens', () => Int) @@ -238,10 +179,7 @@ export class AuctionsQueriesResolver extends BaseResolver(Auction) { } @ResolveField('owner', () => Account) - async owner( - @Parent() auction: Auction, - @Fields('owner', ['*.']) fields: string[], - ) { + async owner(@Parent() auction: Auction, @Fields('owner', ['*.']) fields: string[]) { const { ownerAddress } = auction; if (!ownerAddress) return null; @@ -262,13 +200,7 @@ export class AuctionsQueriesResolver extends BaseResolver(Auction) { } return marketplaceValue?.length > 0 - ? Marketplace.fromEntity( - marketplaceValue[0], - identifier, - id, - marketplaceAuctionId, - asset?.type, - ) + ? Marketplace.fromEntity(marketplaceValue[0], identifier, id, marketplaceAuctionId, asset?.type) : null; } @@ -287,28 +219,19 @@ export class AuctionsQueriesResolver extends BaseResolver(Auction) { private hasToResolveAsset(fields: string[]) { return ( fields.filter( - (x) => - x !== 'totalAvailableTokens' && - x !== 'totalRunningAuctions' && - x !== 'identifier' && - x !== 'hasAvailableAuctions', + (x) => x !== 'totalAvailableTokens' && x !== 'totalRunningAuctions' && x !== 'identifier' && x !== 'hasAvailableAuctions', ).length > 0 ); } private async getAccount(fields: string[], ownerAddress: any) { const account = this.hasToResolveAccount(fields) - ? Account.fromEntity( - (await this.accountsProvider.load(ownerAddress)).value, - ownerAddress, - ) + ? Account.fromEntity((await this.accountsProvider.load(ownerAddress)).value, ownerAddress) : Account.fromEntity(null, ownerAddress); return account; } private hasToResolveAccount(fields: string[]) { - return ( - fields.length > 1 || (fields.length === 1 && fields[0] !== 'address') - ); + return fields.length > 1 || (fields.length === 1 && fields[0] !== 'address'); } } diff --git a/src/modules/common/base.loader.ts b/src/modules/common/base.loader.ts index fe6400849..65bb5c8a8 100644 --- a/src/modules/common/base.loader.ts +++ b/src/modules/common/base.loader.ts @@ -5,9 +5,7 @@ import { RedisValueDataloaderHandler } from './redis-value-dataloader.handler'; @Injectable({ scope: Scope.REQUEST }) export abstract class BaseProvider { constructor( - private redisHandler: - | RedisKeyValueDataloaderHandler - | RedisValueDataloaderHandler, + private redisHandler: RedisKeyValueDataloaderHandler | RedisValueDataloaderHandler, private dataLoader: { load: (arg0: T) => any; clear: (arg0: T) => any; diff --git a/src/modules/notifications/notifications.resolver.ts b/src/modules/notifications/notifications.resolver.ts index c73ce08eb..67e19541e 100644 --- a/src/modules/notifications/notifications.resolver.ts +++ b/src/modules/notifications/notifications.resolver.ts @@ -26,11 +26,7 @@ export class NotificationsResolver extends BaseResolver(Notification) { @AuthUser() user: UserAuthResult, ) { const { limit, offset } = pagination.pagingParams(); - const [notifications, count] = - await this.notificationsService.getNotifications( - user.address, - filters?.marketplaceKey, - ); + const [notifications, count] = await this.notificationsService.getNotifications(user.address, filters?.marketplaceKey); const page = connectionFromArraySlice(notifications, pagination, { arrayLength: count, sliceStart: offset || 0, diff --git a/src/modules/tags/tags.service.ts b/src/modules/tags/tags.service.ts index a36c1c966..35ff88d53 100644 --- a/src/modules/tags/tags.service.ts +++ b/src/modules/tags/tags.service.ts @@ -9,17 +9,9 @@ import { CachingService, Constants } from '@multiversx/sdk-nestjs'; @Injectable() export class TagsService { - constructor( - private apiService: MxApiService, - private persistenceService: PersistenceService, - private cacheService: CachingService, - ) {} + constructor(private apiService: MxApiService, private persistenceService: PersistenceService, private cacheService: CachingService) {} - async getTags( - offset: number = 0, - limit: number = 10, - filters: TagsFilter, - ): Promise<[Tag[], number]> { + async getTags(offset: number = 0, limit: number = 10, filters: TagsFilter): Promise<[Tag[], number]> { if (filters.tagType === TagTypeEnum.Nft) { const [tagsApi, count] = await this.getNftTags(filters, offset, limit); const tags = tagsApi?.map((element) => Tag.fromApiTag(element)); @@ -30,11 +22,7 @@ export class TagsService { return [tags, count]; } - private async getNftTags( - filters: TagsFilter, - offset: number, - limit: number, - ): Promise<[Tag[], number]> { + private async getNftTags(filters: TagsFilter, offset: number, limit: number): Promise<[Tag[], number]> { let [tagsApi, count] = [[], 0]; if (filters?.searchTerm) { [tagsApi, count] = await Promise.all([ @@ -48,27 +36,16 @@ export class TagsService { return [tagsApi, count]; } - private async getCachedNftTags( - offset: number, - limit: number, - filters: TagsFilter, - ): Promise<[NftTag[], number]> { + private async getCachedNftTags(offset: number, limit: number, filters: TagsFilter): Promise<[NftTag[], number]> { return await this.cacheService.getOrSetCache( `${CacheInfo.NftTags.key}_${limit}_${offset}`, async () => - Promise.all([ - this.apiService.getTags(offset, limit, filters.searchTerm), - this.apiService.getTagsCount(filters.searchTerm), - ]), + Promise.all([this.apiService.getTags(offset, limit, filters.searchTerm), this.apiService.getTagsCount(filters.searchTerm)]), 5 * Constants.oneMinute(), ); } - private async getAuctionTags( - filters: TagsFilter, - offset: number, - limit: number, - ): Promise<[Tag[], number]> { + private async getAuctionTags(filters: TagsFilter, offset: number, limit: number): Promise<[Tag[], number]> { if (filters?.searchTerm) { return await this.getAuctionTagsWithSearch(filters, offset, limit); } else { @@ -81,25 +58,14 @@ export class TagsService { } async getAuctionTagsFromDb(limit: number = 100): Promise<[Tag[], number]> { - const [tagsApi, count] = await Promise.all([ - this.persistenceService.getTags(limit), - this.persistenceService.getTagsCount(), - ]); + const [tagsApi, count] = await Promise.all([this.persistenceService.getTags(limit), this.persistenceService.getTagsCount()]); const tags = tagsApi?.map((element) => Tag.fromApiTag(element)); return [tags, count]; } - async getAuctionTagsWithSearch( - filters: TagsFilter, - offset: number, - limit: number, - ): Promise<[Tag[], number]> { + async getAuctionTagsWithSearch(filters: TagsFilter, offset: number, limit: number): Promise<[Tag[], number]> { const [tagsApi, count] = await Promise.all([ - this.persistenceService.getTagsBySearchTerm( - filters.searchTerm, - offset, - limit, - ), + this.persistenceService.getTagsBySearchTerm(filters.searchTerm, offset, limit), this.persistenceService.getTagsBySearchTermCount(filters.searchTerm), ]); const tags = tagsApi?.map((element) => Tag.fromApiTag(element)); diff --git a/src/modules/trending/trending.service.ts b/src/modules/trending/trending.service.ts index 506be6d1f..5f99fb830 100644 --- a/src/modules/trending/trending.service.ts +++ b/src/modules/trending/trending.service.ts @@ -4,11 +4,7 @@ import { Asset } from '../assets/models'; @Injectable() export class TrendingService { - constructor( - private apiService: MxApiService, - private statsService: MxStatsService, - private readonly logger: Logger, - ) {} + constructor(private apiService: MxApiService, private statsService: MxStatsService, private readonly logger: Logger) {} async getTrendingAssets(): Promise<[Asset[], number]> { try { diff --git a/src/modules/usdPrice/usd-price.module.ts b/src/modules/usdPrice/usd-price.module.ts index 9e90d20b8..70448e03f 100644 --- a/src/modules/usdPrice/usd-price.module.ts +++ b/src/modules/usdPrice/usd-price.module.ts @@ -6,12 +6,7 @@ import { UsdTokenPriceResolver } from './usd-token-price.resolver'; import { CommonModule } from 'src/common.module'; @Module({ - providers: [ - UsdPriceResolver, - UsdTokenPriceResolver, - UsdPriceRedisHandler, - UsdPriceService, - ], + providers: [UsdPriceResolver, UsdTokenPriceResolver, UsdPriceRedisHandler, UsdPriceService], imports: [CommonModule], exports: [UsdPriceService], }) diff --git a/src/modules/usdPrice/usd-price.redis-handler.ts b/src/modules/usdPrice/usd-price.redis-handler.ts index 60a672750..95b8fc916 100644 --- a/src/modules/usdPrice/usd-price.redis-handler.ts +++ b/src/modules/usdPrice/usd-price.redis-handler.ts @@ -11,17 +11,11 @@ export class UsdPriceRedisHandler extends RedisKeyValueDataloaderHandler super(redisCacheService, 'priceUSD'); } - mapValues( - returnValues: { key: number; value: any }[], - assetsIdentifiers: { [key: number]: any[] }, - ) { + mapValues(returnValues: { key: number; value: any }[], assetsIdentifiers: { [key: number]: any[] }) { const redisValues = []; for (const item of returnValues) { if (item.value === null) { - item.value = - assetsIdentifiers && assetsIdentifiers[item.key] - ? assetsIdentifiers[item.key][0] - : null; + item.value = assetsIdentifiers && assetsIdentifiers[item.key] ? assetsIdentifiers[item.key][0] : null; redisValues.push(item); } } @@ -30,9 +24,6 @@ export class UsdPriceRedisHandler extends RedisKeyValueDataloaderHandler } getCacheKey(key: number) { - return generateCacheKeyFromParams( - 'priceUSD', - DateUtils.getDateFromTimestampWithoutTime(key), - ); + return generateCacheKeyFromParams('priceUSD', DateUtils.getDateFromTimestampWithoutTime(key)); } } diff --git a/src/utils/LoggerService.ts b/src/utils/LoggerService.ts index e10af3ce9..c264c3a5d 100644 --- a/src/utils/LoggerService.ts +++ b/src/utils/LoggerService.ts @@ -2,10 +2,7 @@ import { LoggerService as LS } from '@nestjs/common'; import * as winston from 'winston'; const { combine, timestamp, printf } = winston.format; import * as Transport from 'winston-transport'; -import { - utilities as nestWinstonModuleUtilities, - WinstonModule, -} from 'nest-winston'; +import { utilities as nestWinstonModuleUtilities, WinstonModule } from 'nest-winston'; export class LoggerService implements LS { private logger: LS; @@ -57,10 +54,7 @@ export class LoggerService implements LS { const logFile = process.env.LOG_FILE ?? false; const logLevel = !!process.env.LOG_LEVEL ? process.env.LOG_LEVEL : 'error'; - const format = combine( - timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }), - nestWinstonModuleUtilities.format.nestLike(), - ); + const format = combine(timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }), nestWinstonModuleUtilities.format.nestLike()); const logTransports: Transport[] = [ new winston.transports.Console({ @@ -77,12 +71,7 @@ export class LoggerService implements LS { level: logLevel, format: combine( timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }), - printf( - (info) => - `[${info.timestamp}] ${info.level}: ${ - info.message - } ${JSON.stringify(info)}`, - ), + printf((info) => `[${info.timestamp}] ${info.level}: ${info.message} ${JSON.stringify(info)}`), ), }), ); diff --git a/src/utils/helpers.ts b/src/utils/helpers.ts index 5b238aae1..fedfe6848 100644 --- a/src/utils/helpers.ts +++ b/src/utils/helpers.ts @@ -56,25 +56,13 @@ export const removeCredentialsFromUrl = (url: string): string => { return url; }; -export const computeUsdAmount = ( - tokenPriceUsd: string, - tokenAmount: string, - tokenDecimals: number, -): string => { - const amountUsd: BigNumber = new BigNumber(tokenAmount) - .multipliedBy(tokenPriceUsd) - .dividedBy(Math.pow(10, tokenDecimals)); +export const computeUsdAmount = (tokenPriceUsd: string, tokenAmount: string, tokenDecimals: number): string => { + const amountUsd: BigNumber = new BigNumber(tokenAmount).multipliedBy(tokenPriceUsd).dividedBy(Math.pow(10, tokenDecimals)); return amountUsd.toString(); }; -export const computeUsd = ( - tokenPriceUsd: string, - tokenAmount: string, - tokenDecimals: number, -): BigNumber => { - const amountUsd = new BigNumber(tokenAmount) - .multipliedBy(tokenPriceUsd) - .dividedBy(Math.pow(10, tokenDecimals)); +export const computeUsd = (tokenPriceUsd: string, tokenAmount: string, tokenDecimals: number): BigNumber => { + const amountUsd = new BigNumber(tokenAmount).multipliedBy(tokenPriceUsd).dividedBy(Math.pow(10, tokenDecimals)); return amountUsd; }; @@ -92,8 +80,7 @@ export function timestampToEpochAndRound( milisecondsPerRound: number, ): [number, number] { const currentTimestamp = new Date(); - const timeDiffInMs = - +currentTimestamp.getTime() - +new Date(timestamp).getTime() * 1000; + const timeDiffInMs = +currentTimestamp.getTime() - +new Date(timestamp).getTime() * 1000; const roundDiff = timeDiffInMs / milisecondsPerRound; const epochDiff = roundDiff / roundsPerEpoch; @@ -109,8 +96,5 @@ export async function sleep(ms: number) { } export function getFilePathFromDist(filename: string): string { - return `${__dirname.substring( - 0, - __dirname.lastIndexOf('dist/') + 5, - )}${filename}`; + return `${__dirname.substring(0, __dirname.lastIndexOf('dist/') + 5)}${filename}`; } diff --git a/test/accounts-stats.e2e-spec.ts b/test/accounts-stats.e2e-spec.ts index 5452cb715..91089d79f 100644 --- a/test/accounts-stats.e2e-spec.ts +++ b/test/accounts-stats.e2e-spec.ts @@ -30,22 +30,18 @@ describe('AccountStatsResolver', () => { `; it('get stats for account', async () => { - const accountStatsService = - app.get(AccountsStatsService); + const accountStatsService = app.get(AccountsStatsService); jest.spyOn(accountStatsService, 'getStats').mockResolvedValue( new AccountStatsEntity({ auctions: '2', orders: '0', biddingBalance: '0', - address: - 'erd1dc3yzxxeq69wvf583gw0h67td226gu2ahpk3k50qdgzzym8npltq7ndgha', + address: 'erd1dc3yzxxeq69wvf583gw0h67td226gu2ahpk3k50qdgzzym8npltq7ndgha', }), ); jest.spyOn(accountStatsService, 'getClaimableCount').mockResolvedValue(5); jest.spyOn(accountStatsService, 'getCollectedCount').mockResolvedValue(5); - jest - .spyOn(accountStatsService, 'getCollectionsCount') - .mockResolvedValue(5); + jest.spyOn(accountStatsService, 'getCollectionsCount').mockResolvedValue(5); return request(app.getHttpServer()) .post('/graphql') @@ -56,8 +52,7 @@ describe('AccountStatsResolver', () => { expect(res.body).toEqual({ data: { accountStats: { - address: - 'erd1dc3yzxxeq69wvf583gw0h67td226gu2ahpk3k50qdgzzym8npltq7ndgha', + address: 'erd1dc3yzxxeq69wvf583gw0h67td226gu2ahpk3k50qdgzzym8npltq7ndgha', auctions: '2', biddingBalance: '0', claimable: '5', diff --git a/test/collection-stats.e2e-spec.ts b/test/collection-stats.e2e-spec.ts index 279a93088..f1e0aa22b 100644 --- a/test/collection-stats.e2e-spec.ts +++ b/test/collection-stats.e2e-spec.ts @@ -30,9 +30,7 @@ describe('CollectionStatsResolver', () => { `; it('get stats for collection', async () => { - const collectionStatsService = app.get( - CollectionsStatsService, - ); + const collectionStatsService = app.get(CollectionsStatsService); jest.spyOn(collectionStatsService, 'getStats').mockResolvedValue( new CollectionStatsEntity({ activeAuctions: 2, @@ -43,9 +41,7 @@ describe('CollectionStatsResolver', () => { volumeTraded: '21', }), ); - jest - .spyOn(collectionStatsService, 'getItemsCount') - .mockResolvedValue({ key: 'test', value: '4' }); + jest.spyOn(collectionStatsService, 'getItemsCount').mockResolvedValue({ key: 'test', value: '4' }); return request(app.getHttpServer()) .post('/graphql')