Skip to content

Commit 4959df1

Browse files
committed
add error handling to tokenlist loading
1 parent bfb762f commit 4959df1

16 files changed

+3450
-3649
lines changed

src/common/utils/tokenList.ts

Lines changed: 41 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -42,38 +42,58 @@ const loadTokenlistsFromFiles = () => {
4242
) as TokenListItem[]
4343
}
4444
}
45-
;(function buildCache() {
45+
46+
const writeTokenListsToFiles = () => {
47+
let dir = `${__dirname}/../tokenLists`
48+
try {
49+
fs.readdirSync(dir)
50+
} catch {
51+
dir = `${__dirname}/../../../tokenLists`
52+
}
53+
for (const [chainId, tokenlist] of Object.entries(cache)) {
54+
fs.writeFileSync(
55+
`${dir}/tokenList_${chainId}.json`,
56+
JSON.stringify(tokenlist, null, 2),
57+
)
58+
}
59+
}
60+
61+
export async function buildCache() {
4662
const tokenlistURL = process.env.TOKENLIST_URL
4763
if (!tokenlistURL) {
4864
console.warn(
4965
"Missing TOKENLIST_URL configuration. Falling back to static files",
5066
)
5167
loadTokenlistsFromFiles()
52-
return
68+
return cache
5369
}
5470

55-
Promise.all(
71+
await Promise.all(
5672
Object.keys(RPC_URLS).map(async (chainId) => {
5773
const response = await fetch(`${tokenlistURL}?chainId=${chainId}`)
74+
5875
if (!response.ok) {
59-
cache[Number(chainId)] = []
60-
return
76+
throw new Error(`${response.status} ${response.statusText}`)
6177
}
6278
const res = await response.json()
6379
if (res.success === "false") {
64-
cache[Number(chainId)] = []
65-
return
80+
throw new Error(JSON.stringify(res))
6681
}
6782

6883
cache[Number(chainId)] = res as TokenListItem[]
6984
}),
70-
)
85+
).catch((err) => {
86+
console.log(`Error fetching tokenlists ${err}`)
87+
loadTokenlistsFromFiles()
88+
})
7189

72-
setTimeout(
73-
buildCache,
74-
Number(process.env.TOKENLIST_CACHE_TIMEOUT_SECONDS || 5 * 60) * 1000,
75-
)
76-
})()
90+
try {
91+
writeTokenListsToFiles()
92+
} catch (err) {
93+
console.log(`Error writing tokenlists, ${err}`)
94+
}
95+
return cache
96+
}
7797

7898
export default function getTokenList(chainId: number): TokenListItem[] {
7999
return cache[chainId] || []
@@ -82,3 +102,11 @@ export default function getTokenList(chainId: number): TokenListItem[] {
82102
export function getAllTokenLists() {
83103
return cache
84104
}
105+
106+
export function initTokenlistCache() {
107+
buildCache()
108+
setInterval(
109+
buildCache,
110+
Number(process.env.TOKENLIST_CACHE_TIMEOUT_SECONDS || 5 * 60) * 1000,
111+
)
112+
}

src/index.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
11
import { app, logger } from "@/server"
2+
import { initTokenlistCache } from "./common/utils/tokenList"
3+
4+
initTokenlistCache()
25

36
const server = app.listen(process.env.PORT, () => {
47
const { NODE_ENV, PORT } = process.env

0 commit comments

Comments
 (0)