-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathfarcaster.ts
60 lines (49 loc) · 1.68 KB
/
farcaster.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import fetch from 'node-fetch';
import { getAddress } from '@ethersproject/address';
import { Address, resize } from '../utils';
import { max } from '../constants.json';
import { fetchHttpImage } from './utils';
const NEYNAR_API_URL = 'https://api.neynar.com/v2/farcaster/user/bulk-by-address';
const API_KEY = process.env.NEYNAR_API_KEY ?? '';
interface UserDetails {
pfp_url: string;
}
function withCache(url: string): string {
return url.includes('imgur.com')
? `https://wrpcd.net/cdn-cgi/image/fit=contain,f=auto,w=${max}/${encodeURIComponent(url)}`
: url;
}
function normalizeAddress(address: Address): Address | null {
try {
return getAddress(address);
} catch (e) {
return null;
}
}
async function fetchAddressImageUrl(normalizedAddress: string): Promise<string | null> {
try {
const response = await fetch(`${NEYNAR_API_URL}?addresses=${normalizedAddress}`, {
headers: { Accept: 'application/json', api_key: API_KEY }
});
if (!response.ok) {
throw new Error(`Invalid network response (${response.url} ${response.status})`);
}
const data: Record<Address, UserDetails[]> = await response.json();
return data[normalizedAddress.toLowerCase()]?.[0].pfp_url;
} catch (e) {
return null;
}
}
export default async function resolve(address: string): Promise<Buffer | false> {
const normalizedAddress = normalizeAddress(address);
if (!normalizedAddress) return false;
const url = await fetchAddressImageUrl(normalizedAddress);
if (!url) return false;
try {
const imageUrl = withCache(url);
const input = await fetchHttpImage(imageUrl);
return await resize(input, max, max);
} catch (e) {
return false;
}
}