-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcoinbase.js
executable file
·60 lines (55 loc) · 1.85 KB
/
coinbase.js
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 {Record} from '@resolverworks/enson';
import {log} from '../src/utils.js';
import {ethers} from 'ethers';
import {SmartCache} from '../src/SmartCache.js';
const cache = new SmartCache();
const RATES_URL = 'https://api.coinbase.com/v2/exchange-rates';
async function fetch_rates() {
log('coinbase: fetch_rates()');
let {data: {rates}} = await fetch(RATES_URL).then(r => r.json());
let map = new Map();
map.t = new Date().toISOString();
for (let [k, v] of Object.entries(rates)) {
try {
map.set(ethers.ensNormalize(k), 1 / parseFloat(v));
} catch (err) {
//console.log('coinbase: invalid ticker:', k, err); // rare
}
}
return map;
}
export default {
slug: 'coinbase',
async resolve(name) {
let rates = await cache.get('RATES', fetch_rates);
if (!name) {
return Record.from({
name: 'Coinbase API over ENS',
notice: `${rates.size.toLocaleString()} symbols`,
description: [...rates.keys()].join(' '),
url: RATES_URL,
});
}
let price = rates.get(name);
let rel = name === 'eth' ? 'BTC' : 'ETH';
if (price) {
return Record.from({
name: `$${format_price(price)} — ${format_price(price / rates.get(rel.toLowerCase()))} per ${rel}`,
description: `As of ${rates.t}`,
avatar: `https://raw.githubusercontent.com/spothq/cryptocurrency-icons/master/32%402x/color/${name}@2x.png`,
url: `https://www.coinbase.com/price/${name}`,
});
}
}
}
// make fancy degen price
export function format_price(p, n = 4) {
if (p > 100) n = 2;
if (p >= 1) return p.toLocaleString(undefined, {minimumFractionDigits: n, maximumFractionDigits: n});
let [dec, exp] = p.toExponential(n-1).split('e-');
exp = parseInt(exp);
return exp >= 4 ? `0.0${sub_digit(exp)}${dec.replace('.', '')}` : p.toFixed(exp+n-1);
}
function sub_digit(i) {
return (i < 10 ? '' : sub_digit(Math.floor(i / 10))) + String.fromCodePoint(0x2080 + (i % 10));
}