-
Notifications
You must be signed in to change notification settings - Fork 49
feat: add token metadata proxy endpoint #1265
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
bd02d80
feat: add token metadata proxy endpoint
0xApotheosis 70c0f9d
fix: harden token metadata proxy input and rate limiting
0xApotheosis 7288545
refactor: simplify token metadata proxy to true pass-through
0xApotheosis 5b2e3b8
fix: graceful degradation and cache headers for token metadata proxy
0xApotheosis 539475e
refactor: remove unnecessary ALCHEMY_SOLANA_RPC_URL env override
0xApotheosis 7ceaf03
address review comments, update to server side cache and add chain co…
kaladinlight 658cd58
lint fix
kaladinlight 0cf3377
add solana web3 package
kaladinlight File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -12,3 +12,4 @@ generated | |
| *.yaml | ||
| *.xml | ||
| *.go | ||
| .yarn | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,180 @@ | ||
| import { PublicKey } from '@solana/web3.js' | ||
| import axios, { isAxiosError } from 'axios' | ||
| import type { Request, Response } from 'express' | ||
| import { isAddress } from 'viem' | ||
|
|
||
| const ALCHEMY_API_KEY = process.env.ALCHEMY_API_KEY | ||
|
|
||
| if (!ALCHEMY_API_KEY) throw new Error('ALCHEMY_API_KEY env var not set') | ||
|
|
||
| interface EvmResult { | ||
| name: string | ||
| symbol: string | ||
| decimals: number | ||
| logo: string | ||
| } | ||
|
|
||
| interface SolanaResult { | ||
| content?: { | ||
| metadata?: { name?: string; symbol?: string } | ||
| links?: { image?: string } | ||
| files?: Array<{ uri?: string; mime?: string }> | ||
| } | ||
| token_info?: { symbol?: string; decimals?: number } | ||
| } | ||
|
|
||
| interface TokenMetadataPayload { | ||
| name: string | ||
| symbol: string | ||
| decimals: number | null | ||
| logo: string | null | ||
| } | ||
|
|
||
| interface ChainConfig { | ||
| url: string | ||
| method: string | ||
| params: (tokenAddress: string) => unknown | ||
| parse: (r: unknown) => TokenMetadataPayload | ||
| validateAddress: (tokenAddress: string) => boolean | ||
| } | ||
|
|
||
| const CACHE_TTL_MS = 24 * 60 * 60 * 1000 | ||
|
|
||
| const parseEvm = (r: unknown): TokenMetadataPayload => { | ||
| const { name, symbol, decimals, logo } = r as EvmResult | ||
| return { name, symbol, decimals: decimals ?? null, logo: logo ?? null } | ||
| } | ||
|
|
||
| const parseSolana = (r: unknown): TokenMetadataPayload => { | ||
| const { content, token_info } = r as SolanaResult | ||
| return { | ||
| name: content?.metadata?.name ?? '', | ||
| symbol: content?.metadata?.symbol ?? token_info?.symbol ?? '', | ||
| decimals: token_info?.decimals ?? null, | ||
| logo: content?.links?.image ?? content?.files?.find((f) => f.mime?.startsWith('image/'))?.uri ?? null, | ||
| } | ||
| } | ||
|
|
||
| const isValidSolanaAddress = (address: string): boolean => { | ||
| try { | ||
| new PublicKey(address) | ||
| return true | ||
| } catch { | ||
| return false | ||
| } | ||
| } | ||
|
|
||
| const CHAIN_CONFIGS: Record<string, ChainConfig> = { | ||
| 'eip155:1': { | ||
| url: `https://eth-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY}`, | ||
| method: 'alchemy_getTokenMetadata', | ||
| params: (a) => [a], | ||
| parse: parseEvm, | ||
| validateAddress: isAddress, | ||
| }, | ||
| 'eip155:10': { | ||
| url: `https://opt-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY}`, | ||
| method: 'alchemy_getTokenMetadata', | ||
| params: (a) => [a], | ||
| parse: parseEvm, | ||
| validateAddress: isAddress, | ||
| }, | ||
| 'eip155:137': { | ||
| url: `https://polygon-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY}`, | ||
| method: 'alchemy_getTokenMetadata', | ||
| params: (a) => [a], | ||
| parse: parseEvm, | ||
| validateAddress: isAddress, | ||
| }, | ||
| 'eip155:8453': { | ||
| url: `https://base-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY}`, | ||
| method: 'alchemy_getTokenMetadata', | ||
| params: (a) => [a], | ||
| parse: parseEvm, | ||
| validateAddress: isAddress, | ||
| }, | ||
| 'eip155:42161': { | ||
| url: `https://arb-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY}`, | ||
| method: 'alchemy_getTokenMetadata', | ||
| params: (a) => [a], | ||
| parse: parseEvm, | ||
| validateAddress: isAddress, | ||
| }, | ||
| 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp': { | ||
| url: `https://solana-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY}`, | ||
| method: 'getAsset', | ||
| params: (a) => ({ id: a }), | ||
| parse: parseSolana, | ||
| validateAddress: isValidSolanaAddress, | ||
| }, | ||
| } | ||
|
|
||
| export class TokenMetadata { | ||
| private axiosInstance = axios.create({ timeout: 10_000 }) | ||
| private requestCache: Partial<Record<string, TokenMetadataPayload>> = {} | ||
|
|
||
| async handler(req: Request, res: Response): Promise<void> { | ||
| const { chainId, tokenAddress } = req.query | ||
|
|
||
| if (typeof chainId !== 'string' || !chainId) { | ||
| res.status(400).json({ error: 'chainId is required' }) | ||
| return | ||
| } | ||
|
|
||
| if (typeof tokenAddress !== 'string' || !tokenAddress) { | ||
| res.status(400).json({ error: 'tokenAddress is required' }) | ||
| return | ||
| } | ||
|
|
||
| const config = CHAIN_CONFIGS[chainId] | ||
| if (!config) { | ||
| res.status(422).json({ error: 'Unsupported chainId', supported: Object.keys(CHAIN_CONFIGS) }) | ||
| return | ||
| } | ||
|
|
||
| if (!config.validateAddress(tokenAddress)) { | ||
| res.status(422).json({ error: 'Invalid tokenAddress' }) | ||
| return | ||
| } | ||
|
|
||
| const cacheKey = `${chainId}:${tokenAddress}` | ||
| const cached = this.requestCache[cacheKey] | ||
| if (cached) { | ||
| res.set('X-Cache', 'HIT').json({ chainId, tokenAddress, ...cached }) | ||
| return | ||
| } | ||
|
|
||
| try { | ||
kaladinlight marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| const { data } = await this.axiosInstance.post(config.url, { | ||
| jsonrpc: '2.0', | ||
| id: crypto.randomUUID(), | ||
| method: config.method, | ||
| params: config.params(tokenAddress), | ||
| }) | ||
|
|
||
| if (data.error?.message) { | ||
| res.status(502).json({ error: data.error.message }) | ||
| return | ||
| } | ||
|
|
||
| const metadata = config.parse(data.result) | ||
| if (!metadata.name && !metadata.symbol) { | ||
| res.status(404).json({ error: 'Token not found' }) | ||
| return | ||
| } | ||
|
|
||
| this.requestCache[cacheKey] = metadata | ||
| setTimeout(() => delete this.requestCache[cacheKey], CACHE_TTL_MS) | ||
|
|
||
| res.set('X-Cache', 'MISS').json({ chainId, tokenAddress, ...metadata }) | ||
| } catch (err) { | ||
| if (isAxiosError(err)) { | ||
| res.status(502).json({ error: err.message || 'Upstream request failed' }) | ||
| } else if (err instanceof Error) { | ||
| res.status(500).json({ error: err.message || 'Internal server error' }) | ||
| } else { | ||
| res.status(500).json({ error: 'Internal server error' }) | ||
| } | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.