tornado-relayer/src/utils.js

63 lines
1.5 KiB
JavaScript
Raw Normal View History

2020-09-28 05:28:34 +03:00
const { instances, netId } = require('../config')
const { poseidon } = require('circomlib')
2020-10-01 19:37:25 +03:00
const { toBN, toChecksumAddress } = require('web3-utils')
2020-09-28 05:28:34 +03:00
2020-09-29 23:13:45 +03:00
const sleep = (ms) => new Promise((res) => setTimeout(res, ms))
2020-09-29 06:17:42 +03:00
2020-09-28 05:28:34 +03:00
function getInstance(address) {
2020-10-01 19:37:25 +03:00
address = toChecksumAddress(address)
2020-09-28 05:28:34 +03: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 15:49:24 +03:00
}
2019-09-19 22:56:45 +03:00
}
}
2020-09-28 05:28:34 +03:00
return null
2019-12-18 22:25:09 +03:00
}
2020-09-28 05:28:34 +03: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 10:39:56 +03:00
2020-09-28 05:28:34 +03:00
const poseidonHash = (items) => toBN(poseidon(items).toString())
const poseidonHash2 = (a, b) => poseidonHash([a, b])
2019-11-15 12:01:59 +03:00
2020-09-28 05:28:34 +03:00
function setSafeInterval(func, interval) {
2020-09-29 23:13:45 +03:00
func()
.catch(console.error)
.finally(() => {
setTimeout(() => setSafeInterval(func, interval), interval)
})
2019-12-02 15:49:24 +03:00
}
2020-09-29 06:17:42 +03:00
/**
* A promise that resolves when the source emits specified event
*/
function when(source, event) {
2020-09-29 23:13:45 +03:00
return new Promise((resolve, reject) => {
source
.once(event, (payload) => {
resolve(payload)
})
.on('error', (error) => {
reject(error)
})
2020-09-29 06:17:42 +03:00
})
}
2020-08-04 10:39:56 +03:00
module.exports = {
2020-09-28 05:28:34 +03:00
getInstance,
setSafeInterval,
poseidonHash2,
2020-09-29 06:17:42 +03:00
sleep,
when,
2020-08-04 10:39:56 +03:00
}