refactor + coingecko
This commit is contained in:
parent
db35a0cbcc
commit
b5609c30c5
@ -1,17 +0,0 @@
|
|||||||
[
|
|
||||||
{
|
|
||||||
"constant": true,
|
|
||||||
"inputs": [],
|
|
||||||
"name": "getMedianPrice",
|
|
||||||
"outputs": [
|
|
||||||
{
|
|
||||||
"internalType": "uint256",
|
|
||||||
"name": "",
|
|
||||||
"type": "uint256"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"payable": false,
|
|
||||||
"stateMutability": "view",
|
|
||||||
"type": "function"
|
|
||||||
}
|
|
||||||
]
|
|
@ -14,6 +14,7 @@ module.exports = {
|
|||||||
} ],
|
} ],
|
||||||
defaultGasPrice: 2,
|
defaultGasPrice: 2,
|
||||||
gasOracleUrls: ['https://www.etherchain.org/api/gasPriceOracle', 'https://gasprice.poa.network/'],
|
gasOracleUrls: ['https://www.etherchain.org/api/gasPriceOracle', 'https://gasprice.poa.network/'],
|
||||||
ethdaiAddress: '0x7Ef645705cb7D401C5CD91a395cfcc3Db3C93689',
|
port: process.env.APP_PORT,
|
||||||
port: process.env.APP_PORT
|
//dai
|
||||||
|
tokens: ['0x6b175474e89094c44da98b954eedeac495271d0f']
|
||||||
}
|
}
|
@ -4,13 +4,14 @@
|
|||||||
"description": "Relayer for Tornado mixer. https://tornado.cash",
|
"description": "Relayer for Tornado mixer. https://tornado.cash",
|
||||||
"main": "index.js",
|
"main": "index.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"start": "node index.js",
|
"start": "node src/index.js",
|
||||||
"eslint": "npx eslint --ignore-path .gitignore .",
|
"eslint": "npx eslint --ignore-path .gitignore .",
|
||||||
"test": "echo \"Error: no test specified\" && exit 1"
|
"test": "echo \"Error: no test specified\" && exit 1"
|
||||||
},
|
},
|
||||||
"author": "Alexey Pertsev <alexey@peppersec.com> (https://peppersec.com)",
|
"author": "tornado.cash",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"coingecko-api": "^1.0.6",
|
||||||
"dotenv": "^8.2.0",
|
"dotenv": "^8.2.0",
|
||||||
"express": "^4.17.1",
|
"express": "^4.17.1",
|
||||||
"node-fetch": "^2.6.0",
|
"node-fetch": "^2.6.0",
|
||||||
|
69
src/Fetcher.js
Normal file
69
src/Fetcher.js
Normal file
@ -0,0 +1,69 @@
|
|||||||
|
const CoinGecko = require('coingecko-api')
|
||||||
|
const fetch = require('node-fetch')
|
||||||
|
const { gasOracleUrls, defaultGasPrice } = require('../config')
|
||||||
|
const { toWei } = require('web3-utils')
|
||||||
|
const { tokens } = require('../config')
|
||||||
|
|
||||||
|
|
||||||
|
class Fetcher {
|
||||||
|
constructor(web3) {
|
||||||
|
this.web3 = web3
|
||||||
|
this.ethPrices = {
|
||||||
|
dai: '6700000000000000' // 0.0067
|
||||||
|
}
|
||||||
|
this.gasPrices = {
|
||||||
|
fast: defaultGasPrice
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async fetchPrices() {
|
||||||
|
try {
|
||||||
|
const CoinGeckoClient = new CoinGecko()
|
||||||
|
const price = await CoinGeckoClient.simple.fetchTokenPrice({
|
||||||
|
contract_addresses: tokens,
|
||||||
|
vs_currencies: 'eth',
|
||||||
|
assetPlatform: 'ethereum'
|
||||||
|
})
|
||||||
|
const addressToSymbol = {
|
||||||
|
'0x6b175474e89094c44da98b954eedeac495271d0f': 'dai'
|
||||||
|
}
|
||||||
|
this.ethPrices = Object.entries(price.data).reduce((acc, token) => {
|
||||||
|
if (token[1].eth) {
|
||||||
|
acc[addressToSymbol[token[0]]] = toWei(token[1].eth.toString())
|
||||||
|
}
|
||||||
|
return acc
|
||||||
|
}, {})
|
||||||
|
setTimeout(() => this.fetchPrices(), 1000 * 30)
|
||||||
|
} catch(e) {
|
||||||
|
setTimeout(() => this.fetchPrices(), 1000 * 30)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async fetchGasPrice({ oracleIndex = 0 } = {}) {
|
||||||
|
oracleIndex = (oracleIndex + 1) % gasOracleUrls.length
|
||||||
|
try {
|
||||||
|
const response = await fetch(gasOracleUrls[oracleIndex])
|
||||||
|
if (response.status === 200) {
|
||||||
|
const json = await response.json()
|
||||||
|
|
||||||
|
if (json.slow) {
|
||||||
|
this.gasPrices.low = Number(json.slow)
|
||||||
|
}
|
||||||
|
if (json.safeLow) {
|
||||||
|
this.gasPrices.low = Number(json.safeLow)
|
||||||
|
}
|
||||||
|
if (json.standard) {
|
||||||
|
this.gasPrices.standard = Number(json.standard)
|
||||||
|
}
|
||||||
|
if (json.fast) {
|
||||||
|
this.gasPrices.fast = Number(json.fast)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
throw Error('Fetch gasPrice failed')
|
||||||
|
}
|
||||||
|
setTimeout(() => this.fetchGasPrice({ oracleIndex }), 15000)
|
||||||
|
} catch (e) {
|
||||||
|
setTimeout(() => this.fetchGasPrice({ oracleIndex }), 15000)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = Fetcher
|
49
src/index.js
Normal file
49
src/index.js
Normal file
@ -0,0 +1,49 @@
|
|||||||
|
const express = require('express')
|
||||||
|
const { netId, mixers, port } = require('../config')
|
||||||
|
const relayController = require('./relayController')
|
||||||
|
const { fetcher, web3 } = require('./instances')
|
||||||
|
|
||||||
|
const app = express()
|
||||||
|
app.use(express.json())
|
||||||
|
|
||||||
|
app.use((err, req, res, next) => {
|
||||||
|
if (err) {
|
||||||
|
console.log('Invalid Request data')
|
||||||
|
res.send('Invalid Request data')
|
||||||
|
} else {
|
||||||
|
next()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
app.use(function(req, res, next) {
|
||||||
|
res.header('Access-Control-Allow-Origin', '*')
|
||||||
|
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')
|
||||||
|
next()
|
||||||
|
})
|
||||||
|
|
||||||
|
app.get('/', function (req, res) {
|
||||||
|
// just for testing purposes
|
||||||
|
res.send('This is <a href=https://tornado.cash>tornado.cash</a> Relayer service. Check the /status for settings')
|
||||||
|
})
|
||||||
|
|
||||||
|
app.get('/status', function (req, res) {
|
||||||
|
const { ethPrices, gasPrices } = fetcher
|
||||||
|
res.json({ relayerAddress: web3.eth.defaultAccount, mixers, gasPrices, netId, ethPrices })
|
||||||
|
})
|
||||||
|
|
||||||
|
app.post('/relay', relayController)
|
||||||
|
|
||||||
|
app.listen(port || 8000)
|
||||||
|
|
||||||
|
if (Number(netId) === 1) {
|
||||||
|
console.log('Gas price oracle started.')
|
||||||
|
fetcher.fetchGasPrice()
|
||||||
|
fetcher.fetchPrices()
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('Relayer started on port', port || 8000)
|
||||||
|
console.log(`relayerAddress: ${web3.eth.defaultAccount}`)
|
||||||
|
console.log(`mixers: ${JSON.stringify(mixers)}`)
|
||||||
|
console.log(`gasPrices: ${JSON.stringify(fetcher.gasPrices)}`)
|
||||||
|
console.log(`netId: ${netId}`)
|
||||||
|
console.log(`ethPrices: ${JSON.stringify(fetcher.ethPrices)}`)
|
8
src/instances.js
Normal file
8
src/instances.js
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
const Fetcher = require('./Fetcher')
|
||||||
|
const web3 = require('./setupWeb3')
|
||||||
|
const fetcher = new Fetcher(web3)
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
fetcher,
|
||||||
|
web3
|
||||||
|
}
|
@ -1,47 +1,15 @@
|
|||||||
const { numberToHex, toWei, toHex, toBN, toChecksumAddress } = require('web3-utils')
|
const { numberToHex, toWei, toHex, toBN, toChecksumAddress } = require('web3-utils')
|
||||||
const { netId, rpcUrl, privateKey, mixers, defaultGasPrice, port } = require('./config')
|
const mixerABI = require('../abis/mixerABI.json')
|
||||||
const { fetchGasPrice, isValidProof, isValidArgs, fetchDAIprice, isKnownContract, isEnoughFee } = require('./utils')
|
const {
|
||||||
const Web3 = require('web3')
|
isValidProof, isValidArgs, isKnownContract, isEnoughFee
|
||||||
const express = require('express')
|
} = require('./utils')
|
||||||
|
|
||||||
const app = express()
|
const { web3, fetcher } = require('./instances')
|
||||||
app.use(express.json())
|
|
||||||
|
|
||||||
app.use((err, req, res, next) => {
|
async function relay (req, resp) {
|
||||||
if (err) {
|
|
||||||
console.log('Invalid Request data')
|
|
||||||
res.send('Invalid Request data')
|
|
||||||
} else {
|
|
||||||
next()
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
app.use(function(req, res, next) {
|
|
||||||
res.header('Access-Control-Allow-Origin', '*')
|
|
||||||
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')
|
|
||||||
next()
|
|
||||||
})
|
|
||||||
|
|
||||||
const web3 = new Web3(rpcUrl, null, { transactionConfirmationBlocks: 1 })
|
|
||||||
const account = web3.eth.accounts.privateKeyToAccount('0x' + privateKey)
|
|
||||||
web3.eth.accounts.wallet.add('0x' + privateKey)
|
|
||||||
web3.eth.defaultAccount = account.address
|
|
||||||
|
|
||||||
const mixerABI = require('./abis/mixerABI.json')
|
|
||||||
const gasPrices = { fast: defaultGasPrice }
|
|
||||||
const ethPriceInDai = toWei('200')
|
|
||||||
|
|
||||||
app.get('/', function (req, res) {
|
|
||||||
// just for testing purposes
|
|
||||||
res.send('This is <a href=https://tornado.cash>tornado.cash</a> Relayer service. Check the /status for settings')
|
|
||||||
})
|
|
||||||
|
|
||||||
app.get('/status', function (req, res) {
|
|
||||||
res.json({ relayerAddress: web3.eth.defaultAccount, mixers, gasPrices, netId, ethPriceInDai })
|
|
||||||
})
|
|
||||||
|
|
||||||
app.post('/relay', async (req, resp) => {
|
|
||||||
const { proof, args, contract } = req.body
|
const { proof, args, contract } = req.body
|
||||||
|
console.log(proof, args, contract)
|
||||||
|
const gasPrices = fetcher.gasPrices
|
||||||
let { valid , reason } = isValidProof(proof)
|
let { valid , reason } = isValidProof(proof)
|
||||||
if (!valid) {
|
if (!valid) {
|
||||||
console.log('Proof is invalid:', reason)
|
console.log('Proof is invalid:', reason)
|
||||||
@ -69,7 +37,7 @@ app.post('/relay', async (req, resp) => {
|
|||||||
toBN(args[4]),
|
toBN(args[4]),
|
||||||
toBN(args[5])
|
toBN(args[5])
|
||||||
]
|
]
|
||||||
|
console.log('root, nullifierHash, recipient, relayer, fee, refund', fee.toString(), refund)
|
||||||
if (currency === 'eth' && !refund.isZero()) {
|
if (currency === 'eth' && !refund.isZero()) {
|
||||||
return resp.status(400).json({ error: 'Cannot send refund for eth currency.' })
|
return resp.status(400).json({ error: 'Cannot send refund for eth currency.' })
|
||||||
}
|
}
|
||||||
@ -105,8 +73,8 @@ app.post('/relay', async (req, resp) => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
gas += 50000
|
gas += 50000
|
||||||
|
const ethPrices = fetcher.ethPrices
|
||||||
const { isEnough, reason } = isEnoughFee({ gas, gasPrices, currency, refund, ethPriceInDai, fee })
|
const { isEnough, reason } = isEnoughFee({ gas, gasPrices, currency, refund, ethPrices, fee })
|
||||||
if (!isEnough) {
|
if (!isEnough) {
|
||||||
console.log(`Wrong fee: ${reason}`)
|
console.log(`Wrong fee: ${reason}`)
|
||||||
return resp.status(400).json({ error: reason })
|
return resp.status(400).json({ error: reason })
|
||||||
@ -130,19 +98,6 @@ app.post('/relay', async (req, resp) => {
|
|||||||
console.log(e)
|
console.log(e)
|
||||||
return resp.status(400).json({ error: 'Proof is malformed or spent.' })
|
return resp.status(400).json({ error: 'Proof is malformed or spent.' })
|
||||||
}
|
}
|
||||||
})
|
|
||||||
|
|
||||||
app.listen(port || 8000)
|
|
||||||
|
|
||||||
if (Number(netId) === 1) {
|
|
||||||
fetchGasPrice({ gasPrices })
|
|
||||||
fetchDAIprice({ ethPriceInDai, web3 })
|
|
||||||
console.log('Gas price oracle started.')
|
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log('Relayer started on port', port || 8000)
|
module.exports = relay
|
||||||
console.log(`relayerAddress: ${web3.eth.defaultAccount}`)
|
|
||||||
console.log(`mixers: ${JSON.stringify(mixers)}`)
|
|
||||||
console.log(`gasPrices: ${JSON.stringify(gasPrices)}`)
|
|
||||||
console.log(`netId: ${netId}`)
|
|
||||||
console.log(`ethPriceInDai: ${ethPriceInDai}`)
|
|
16
src/setupWeb3.js
Normal file
16
src/setupWeb3.js
Normal file
@ -0,0 +1,16 @@
|
|||||||
|
const Web3 = require('web3')
|
||||||
|
const { rpcUrl, privateKey } = require('../config')
|
||||||
|
|
||||||
|
function setup() {
|
||||||
|
try {
|
||||||
|
const web3 = new Web3(rpcUrl, null, { transactionConfirmationBlocks: 1 })
|
||||||
|
const account = web3.eth.accounts.privateKeyToAccount('0x' + privateKey)
|
||||||
|
web3.eth.accounts.wallet.add('0x' + privateKey)
|
||||||
|
web3.eth.defaultAccount = account.address
|
||||||
|
return web3
|
||||||
|
} catch(e) {
|
||||||
|
console.error('web3 failed')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const web3 = setup()
|
||||||
|
module.exports = web3
|
@ -1,46 +1,5 @@
|
|||||||
const fetch = require('node-fetch')
|
const { isHexStrict, toBN, toWei } = require('web3-utils')
|
||||||
const { isHexStrict, hexToNumberString, toBN, toWei } = require('web3-utils')
|
const { mixers } = require('../config')
|
||||||
const { gasOracleUrls, ethdaiAddress, mixers } = require('./config')
|
|
||||||
const oracleABI = require('./abis/ETHDAIOracle.json')
|
|
||||||
|
|
||||||
async function fetchGasPrice({ gasPrices, oracleIndex = 0 }) {
|
|
||||||
oracleIndex = (oracleIndex + 1) % gasOracleUrls.length
|
|
||||||
try {
|
|
||||||
const response = await fetch(gasOracleUrls[oracleIndex])
|
|
||||||
if (response.status === 200) {
|
|
||||||
const json = await response.json()
|
|
||||||
|
|
||||||
if (json.slow) {
|
|
||||||
gasPrices.low = Number(json.slow)
|
|
||||||
}
|
|
||||||
if (json.safeLow) {
|
|
||||||
gasPrices.low = Number(json.safeLow)
|
|
||||||
}
|
|
||||||
if (json.standard) {
|
|
||||||
gasPrices.standard = Number(json.standard)
|
|
||||||
}
|
|
||||||
if (json.fast) {
|
|
||||||
gasPrices.fast = Number(json.fast)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
throw Error('Fetch gasPrice failed')
|
|
||||||
}
|
|
||||||
setTimeout(() => fetchGasPrice({ gasPrices, oracleIndex }), 15000)
|
|
||||||
} catch (e) {
|
|
||||||
setTimeout(() => fetchGasPrice({ gasPrices, oracleIndex }), 15000)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function fetchDAIprice({ ethPriceInDai, web3 }) {
|
|
||||||
try {
|
|
||||||
const ethDaiInstance = web3.eth.Contract(oracleABI, ethdaiAddress)
|
|
||||||
const price = await ethDaiInstance.methods.getMedianPrice().call()
|
|
||||||
ethPriceInDai = hexToNumberString(price)
|
|
||||||
setTimeout(() => fetchDAIprice({ ethPriceInDai, web3 }), 1000 * 30)
|
|
||||||
} catch(e) {
|
|
||||||
setTimeout(() => fetchDAIprice({ ethPriceInDai, web3 }), 1000 * 30)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function isValidProof(proof) {
|
function isValidProof(proof) {
|
||||||
// validator expects `websnarkUtils.toSolidityInput(proof)` output
|
// validator expects `websnarkUtils.toSolidityInput(proof)` output
|
||||||
@ -97,7 +56,7 @@ function sleep(ms) {
|
|||||||
return new Promise(resolve => setTimeout(resolve, ms))
|
return new Promise(resolve => setTimeout(resolve, ms))
|
||||||
}
|
}
|
||||||
|
|
||||||
function isEnoughFee({ gas, gasPrices, currency, refund, ethPriceInDai, fee }) {
|
function isEnoughFee({ gas, gasPrices, currency, refund, ethPrices, fee }) {
|
||||||
const expense = toBN(toWei(gasPrices.fast.toString(), 'gwei')).mul(toBN(gas))
|
const expense = toBN(toWei(gasPrices.fast.toString(), 'gwei')).mul(toBN(gas))
|
||||||
let desiredFee
|
let desiredFee
|
||||||
switch (currency) {
|
switch (currency) {
|
||||||
@ -106,14 +65,15 @@ function isEnoughFee({ gas, gasPrices, currency, refund, ethPriceInDai, fee }) {
|
|||||||
break
|
break
|
||||||
}
|
}
|
||||||
case 'dai': {
|
case 'dai': {
|
||||||
desiredFee = expense.add(refund).mul(toBN(ethPriceInDai)).div(toBN(10 ** 18))
|
desiredFee = expense.add(refund).mul(toBN(ethPrices.dai)).div(toBN(10 ** 18))
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
console.log('desired fee', desiredFee)
|
||||||
if (fee.lt(desiredFee)) {
|
if (fee.lt(desiredFee)) {
|
||||||
return { isEnough: false, reason: 'Not enough fee' }
|
return { isEnough: false, reason: 'Not enough fee' }
|
||||||
}
|
}
|
||||||
return { isEnough: true }
|
return { isEnough: true }
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = { fetchGasPrice, isValidProof, isValidArgs, sleep, fetchDAIprice, isKnownContract, isEnoughFee }
|
module.exports = { isValidProof, isValidArgs, sleep, isKnownContract, isEnoughFee }
|
Loading…
Reference in New Issue
Block a user