-
Notifications
You must be signed in to change notification settings - Fork 138
/
client.ts
90 lines (79 loc) · 2.72 KB
/
client.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import { PERMISSIONED_LIST, PERMISSIONLESS_LIST, DEFAULT_TESTNET_LIST, RawCoinInfo } from "./list";
import fetch from 'cross-fetch';
export type NetworkType = 'testnet' | 'mainnet';
export class CoinListClient {
fullnameToCoinInfo: Record<string, RawCoinInfo>;
indexToCoinInfo: Map<number, RawCoinInfo>;
symbolToCoinInfo: Record<string, RawCoinInfo[]>;
private coinList: RawCoinInfo[];
private isUpdated: boolean
constructor(
public readonly permissioned: boolean,
public readonly network: NetworkType = 'mainnet',
list: RawCoinInfo[] | undefined = undefined
) {
this.fullnameToCoinInfo = {};
this.indexToCoinInfo = new Map();
this.symbolToCoinInfo = {};
this.isUpdated = false;
if (list){
this.coinList = list
} else {
this.coinList = network === 'mainnet' ? (permissioned ? PERMISSIONED_LIST : PERMISSIONLESS_LIST) : DEFAULT_TESTNET_LIST;
}
this.buildCache();
}
getCoinInfoList() {
return this.coinList.concat([]).sort((a, b) => (a.unique_index || 0) - (b.unique_index || 0));
}
getCoinInfoBySymbol(symbol: string): RawCoinInfo[] {
return this.symbolToCoinInfo[symbol] || [];
}
getCoinInfoByFullName(fullname: string): RawCoinInfo | undefined {
return this.fullnameToCoinInfo[fullname];
}
getCoinInfoByIndex(index: number): RawCoinInfo | undefined {
return this.indexToCoinInfo.get(index);
}
async update() {
if (this.isUpdated){
return this.coinList;
}
return await this.updateDirect();
}
async updateDirect() {
let url = this.permissioned ?
"https://raw.githubusercontent.com/hippospace/aptos-coin-list/main/src/permissioned.json" :
"https://raw.githubusercontent.com/hippospace/aptos-coin-list/main/src/permissionless.json";
let response = await fetch(url + '?t='+Math.floor(Date.now() / 120 / 1000));
this.coinList = await response.json()
this.buildCache();
this.isUpdated = true
return this.coinList;
}
private clearCache(){
if (this.indexToCoinInfo.size > 0){
this.indexToCoinInfo = new Map()
this.fullnameToCoinInfo = {}
this.symbolToCoinInfo = {}
}
}
private buildCache() {
this.clearCache()
for (const coinInfo of this.coinList) {
this.fullnameToCoinInfo[coinInfo.token_type.type] = coinInfo;
const index = coinInfo.unique_index;
if (index) {
if (this.indexToCoinInfo.has(index)) {
throw new Error(`${index} is used by multiple coins`);
}
this.indexToCoinInfo.set(index, coinInfo);
}
const symbol = coinInfo.symbol;
if (!this.symbolToCoinInfo[symbol]) {
this.symbolToCoinInfo[symbol] = [];
}
this.symbolToCoinInfo[coinInfo.symbol].push(coinInfo);
}
}
}