From c30391f86213c92d6c28ff6b3903c8ccfdf5125c Mon Sep 17 00:00:00 2001 From: Rodrigo Branas Date: Wed, 25 Sep 2024 10:51:11 -0300 Subject: [PATCH] feat: creating a cache for verified assets (#586) --- .../src/graphql/resolvers/PublicResolver.ts | 13 ++++---- .../graphql/src/infra/cache/VerifiedAssets.ts | 31 +++++++++++++++++++ 2 files changed, 37 insertions(+), 7 deletions(-) create mode 100644 packages/graphql/src/infra/cache/VerifiedAssets.ts diff --git a/packages/graphql/src/graphql/resolvers/PublicResolver.ts b/packages/graphql/src/graphql/resolvers/PublicResolver.ts index d6be7591..7935510a 100644 --- a/packages/graphql/src/graphql/resolvers/PublicResolver.ts +++ b/packages/graphql/src/graphql/resolvers/PublicResolver.ts @@ -1,5 +1,6 @@ import { Provider } from 'fuels'; import { env } from '~/config'; +import VerifiedAssets from '~/infra/cache/VerifiedAssets'; import AssetDAO from '~/infra/dao/AssetDAO'; type Params = { @@ -20,10 +21,8 @@ export class PublicResolver { const assetDAO = new AssetDAO(); const provider = await Provider.create(env.get('FUEL_PROVIDER')); const chainId = provider.getChainId(); - const response = await fetch( - 'https://verified-assets.fuel.network/assets.json', - ); - const verifiedAssets = await response.json(); + const nonVerifiedAsset = await assetDAO.getByAssetId(_params.assetId); + const verifiedAssets = await VerifiedAssets.getInstance().fetch(); for (const verifiedAsset of verifiedAssets) { for (const network of verifiedAsset.networks) { if (network.type === 'fuel') { @@ -43,6 +42,7 @@ export class PublicResolver { const asset = Object.assign(verifiedAsset, { assetId: _params.assetId, contractId: network.contractId, + subId: nonVerifiedAsset?.subId, decimals: network.decimals, verified: true, }); @@ -50,9 +50,8 @@ export class PublicResolver { } } } - const asset = await assetDAO.getByAssetId(_params.assetId); - if (!asset) return; - return Object.assign(asset, { + if (!nonVerifiedAsset) return; + return Object.assign(nonVerifiedAsset, { verified: false, }); } diff --git a/packages/graphql/src/infra/cache/VerifiedAssets.ts b/packages/graphql/src/infra/cache/VerifiedAssets.ts new file mode 100644 index 00000000..c2faef9f --- /dev/null +++ b/packages/graphql/src/infra/cache/VerifiedAssets.ts @@ -0,0 +1,31 @@ +export default class VerifiedAssets { + static instance: VerifiedAssets; + private lastDate?: Date; + private assets: any; + + private constructor() {} + + async fetch() { + const now = new Date(); + if ( + !this.lastDate || + !this.assets || + now.getTime() - this.lastDate.getTime() > 60000 + ) { + this.lastDate = new Date(); + const response = await fetch( + 'https://verified-assets.fuel.network/assets.json', + ); + this.assets = await response.json(); + return this.assets; + } + return this.assets; + } + + static getInstance() { + if (!VerifiedAssets.instance) { + VerifiedAssets.instance = new VerifiedAssets(); + } + return VerifiedAssets.instance; + } +}