-
Notifications
You must be signed in to change notification settings - Fork 0
/
quote.js
211 lines (168 loc) · 5.36 KB
/
quote.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
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
/*
* DOM Handles
*/
//dropdown lists
const fromTicker = document.querySelector('#fromTicker')
const toTicker = document.querySelector('#toTicker')
//quote info box
const spanFromLabel = document.querySelector('#fromLabel')
const spanToTokenAmount = document.querySelector('#toTokenAmount')
const spanToLabel = document.querySelector('#toLabel')
const spanFromTokenAmount = document.querySelector('#fromTokenAmount')
const spanEstimatedGas = document.querySelector('#estimatedGas')
/*
* Globals
*/
const rank = 50
const ETH_ADDRESS = '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee'
const ETH_DECIMALS = '18'
const USDC_ADDRESS = '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48'
const USDC_DECIMALS = '6'
let topERC20Tokens = []
let tickers = []
/*
* Fetch
*/
async function fetchTopTickers() {
try {
let response = await fetch(
`https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=${rank}&page=1`
)
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`)
}
let tokens = await response.json()
//keep a record of the top tickers
//.find() is case sensitive, 1inch symbols are upper case, so toUpperCase()
tickers = tokens.map(({ symbol }) => symbol.toUpperCase())
return tickers
} catch (e) {
console.log(`'ERROR: ' ${e}`)
}
}
async function fetchTopTokenInfo(tickers) {
try {
let response = await fetch('https://api.1inch.exchange/v3.0/1/Tokens')
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`)
}
let tokens = await response.json()
//1inch JSON hierarchy requires going 2 levels deep to get the value objects
let tokenList = Object.values(tokens.tokens)
// .includes works but does not preserve the market cap rank given by the tickers sort order
// topTokens = tokenList.filter((token) => tickers.includes(token.symbol))
//keep a record of the top ERC20 tokens
topERC20Tokens = generateTopERC20Tokens(tickers, tokenList)
return topERC20Tokens
} catch (e) {
console.log(`'ERROR: ' ${e}`)
}
}
function generateTopERC20Tokens(tickers, tokenList) {
let topERC20Tokens = []
tickers.forEach((ticker) => {
let foundToken = tokenList.find(({ symbol }) => {
return symbol === ticker
})
if (!(foundToken == null)) {
topERC20Tokens.push(foundToken)
}
})
return topERC20Tokens
}
async function fetchQuote(fromTokenAddress, toTokenAddress, fromCurrencyUnit) {
console.log(fromTokenAddress)
console.log(toTokenAddress)
console.log(fromCurrencyUnit)
try {
const response = await fetch(
`https://api.1inch.io/v4.0/1/quote?fromTokenAddress=${fromTokenAddress}&toTokenAddress=${toTokenAddress}&amount=${fromCurrencyUnit}`
)
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`)
}
const quote = await response.json()
return quote
} catch (e) {
console.log(`error: ${e}`)
}
}
/*
* Page Initialization
*/
fetchTopTickers().then(fetchTopTokenInfo).then(initializePage)
function initializePage() {
populateTickerLists()
setDefaultTickers()
displayDefaultQuote()
}
function populateTickerLists() {
let options = topERC20Tokens.map((token) => {
return `<option value='${token.decimals}-${token.address}'>${token.name} (${token.symbol})</option>`
})
let optionsList = options.join('')
fromTicker.innerHTML = optionsList
toTicker.innerHTML = optionsList
return
}
//Set ETH and USDC as the default tickers
function setDefaultTickers() {
const fromTickerDefault = document.querySelector(
`#fromTicker > [value = '${ETH_DECIMALS}-${ETH_ADDRESS}']`
)
//empty '' sets the attribute to true
fromTickerDefault.setAttribute('selected', '')
const toTickerDefault = document.querySelector(
`#toTicker > [value = '${USDC_DECIMALS}-${USDC_ADDRESS}']`
)
toTickerDefault.setAttribute('selected', '')
}
function displayDefaultQuote() {
getQuote()
return
}
/*
* Quote Functions
*/
async function getQuote() {
let tickers = getTickerSelection()
let fromCurrencyUnit = getFromCurrencyUnit(tickers.fromDecimals)
let quote = await fetchQuote(
tickers.fromAddress,
tickers.toAddress,
fromCurrencyUnit
)
displayQuoteInfo(quote, tickers)
return quote
}
function displayQuoteInfo(quote, tickers) {
exchangeRate =
(Number(quote.toTokenAmount) / Number(quote.fromTokenAmount)) *
tickers.decimalRatio
spanFromLabel.innerText = `1 ${quote.fromToken.symbol} costs approx.`
spanToTokenAmount.innerText = `${exchangeRate} ${quote.toToken.symbol}`
spanToLabel.innerText = `1 ${quote.toToken.symbol} costs approx.`
//take the inverse and round to fromDecimals
spanFromTokenAmount.innerText = `${(1 / exchangeRate).toFixed(
tickers.fromDecimals
)} ${quote.fromToken.symbol}`
spanEstimatedGas.innerText = `${quote.estimatedGas} GWEI??`
}
function getTickerSelection() {
let fromToken = document.querySelector('#fromTicker').value
let [fromDec, fromAddr] = fromToken.split('-')
let toToken = document.querySelector('#toTicker').value
let [toDec, toAddr] = toToken.split('-')
let decRatio = 10 ** (fromDec - toDec)
return {
fromAddress: fromAddr,
fromDecimals: fromDec,
toAddress: toAddr,
toDecimals: toDec,
decimalRatio: decRatio,
}
}
function getFromCurrencyUnit(decimals) {
let unit = 1
return unit.toString().padEnd(+decimals + 1, '0')
}