tornado-relayer/src/utils.js

63 lines
1.5 KiB
JavaScript
Raw Normal View History

2020-09-28 04:28:34 +02:00
const { instances, netId } = require('../config')
const { poseidon } = require('circomlib')
2020-10-01 18:37:25 +02:00
const { toBN, toChecksumAddress } = require('web3-utils')
2020-09-28 04:28:34 +02:00
2020-10-02 12:26:05 +02:00
const sleep = ms => new Promise(res => setTimeout(res, ms))
2020-09-29 05:17:42 +02:00
2020-09-28 04:28:34 +02:00
function getInstance(address) {
2020-10-01 18:37:25 +02:00
address = toChecksumAddress(address)
2020-09-28 04:28:34 +02:00
const inst = instances[`netId${netId}`]
for (const currency of Object.keys(inst)) {
for (const amount of Object.keys(inst[currency].instanceAddress)) {
if (inst[currency].instanceAddress[amount] === address) {
return { currency, amount }
2019-12-02 13:49:24 +01:00
}
2019-09-19 21:56:45 +02:00
}
}
2020-09-28 04:28:34 +02:00
return null
2019-12-18 20:25:09 +01:00
}
2020-09-28 04:28:34 +02:00
// async function setSafeInterval(func, interval) {
// try {
// await func()
// } catch (e) {
// console.error('Unhandled promise error:', e)
// } finally {
// setTimeout(() => setSafeInterval(func, interval), interval)
// }
// }
2020-08-04 09:39:56 +02:00
2020-10-02 12:26:05 +02:00
const poseidonHash = items => toBN(poseidon(items).toString())
2020-09-28 04:28:34 +02:00
const poseidonHash2 = (a, b) => poseidonHash([a, b])
2019-11-15 10:01:59 +01:00
2020-09-28 04:28:34 +02:00
function setSafeInterval(func, interval) {
2020-09-29 22:13:45 +02:00
func()
.catch(console.error)
.finally(() => {
setTimeout(() => setSafeInterval(func, interval), interval)
})
2019-12-02 13:49:24 +01:00
}
2020-09-29 05:17:42 +02:00
/**
* A promise that resolves when the source emits specified event
*/
function when(source, event) {
2020-09-29 22:13:45 +02:00
return new Promise((resolve, reject) => {
source
2020-10-02 12:26:05 +02:00
.once(event, payload => {
2020-09-29 22:13:45 +02:00
resolve(payload)
})
2020-10-02 12:26:05 +02:00
.on('error', error => {
2020-09-29 22:13:45 +02:00
reject(error)
})
2020-09-29 05:17:42 +02:00
})
}
2020-08-04 09:39:56 +02:00
module.exports = {
2020-09-28 04:28:34 +02:00
getInstance,
setSafeInterval,
poseidonHash2,
2020-09-29 05:17:42 +02:00
sleep,
when,
2020-08-04 09:39:56 +02:00
}