|
1 | 1 | import { CHAIN_IDS, type Asset, type NetworkFuel } from 'fuels'; |
2 | | -import { promises as fs } from 'fs'; |
3 | | -import { join } from 'path'; |
4 | | -import os from 'os'; |
5 | | -import { fileURLToPath } from 'url'; |
6 | | -import { dirname } from 'path'; |
7 | | - |
8 | | -// Get project root directory (will try to save the the dev's project root) |
9 | | -const CACHE_DIR = join(process.cwd(), '.fuel-agent-kit'); // change name or dir maybe? |
10 | | -const CACHE_FILE = join(CACHE_DIR, 'verified-assets.json'); |
11 | | -const CACHE_TTL = 1000 * 60 * 60; // 1 hour in milliseconds |
12 | 2 |
|
13 | 3 | interface CacheData { |
14 | 4 | timestamp: number; |
15 | 5 | data: Asset[]; |
16 | 6 | } |
17 | 7 |
|
18 | | -export const getVerifiedAssets = async () => { |
19 | | - try { |
20 | | - // Try to read from cache first |
21 | | - const cacheExists = await fs |
22 | | - .access(CACHE_FILE) |
23 | | - .then(() => true) |
24 | | - .catch(() => false); |
25 | | - |
26 | | - if (cacheExists) { |
27 | | - const cacheContent = await fs.readFile(CACHE_FILE, 'utf-8'); |
28 | | - const cache = JSON.parse(cacheContent) as CacheData; |
| 8 | +// In-memory cache |
| 9 | +let assetsCache: CacheData | null = null; |
| 10 | +const CACHE_TTL = 1000 * 60 * 60; // 1 hour in milliseconds |
29 | 11 |
|
30 | | - // Check if cache is still valid |
31 | | - if (Date.now() - cache.timestamp < CACHE_TTL) { |
32 | | - return cache.data; |
33 | | - } |
34 | | - } else { |
35 | | - } |
36 | | - } catch (error) {} |
| 12 | +export const getVerifiedAssets = async () => { |
| 13 | + // Check if we have valid cache |
| 14 | + if (assetsCache && Date.now() - assetsCache.timestamp < CACHE_TTL) { |
| 15 | + return assetsCache.data; |
| 16 | + } |
37 | 17 |
|
| 18 | + // Fetch fresh data |
38 | 19 | const allAssets = (await fetch( |
39 | 20 | 'https://verified-assets.fuel.network/assets.json', |
40 | 21 | ).then((res) => res.json())) as Asset[]; |
41 | | - // Save to cache |
42 | | - try { |
43 | | - await fs.mkdir(CACHE_DIR, { recursive: true }); |
44 | | - await fs.writeFile( |
45 | | - CACHE_FILE, |
46 | | - JSON.stringify({ |
47 | | - timestamp: Date.now(), |
48 | | - data: allAssets, |
49 | | - }), |
50 | | - ); |
51 | | - } catch (error) {} |
| 22 | + |
| 23 | + // Update cache |
| 24 | + assetsCache = { |
| 25 | + timestamp: Date.now(), |
| 26 | + data: allAssets, |
| 27 | + }; |
52 | 28 |
|
53 | 29 | return allAssets; |
54 | 30 | }; |
|
0 commit comments