Extend line width to 120 (#174)

* Extend line width to 120

* Lint fixes
This commit is contained in:
Przemyslaw Rzad 2019-08-01 15:10:22 +02:00 committed by GitHub
parent a2e9dae43d
commit 40be5a5f8e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
68 changed files with 225 additions and 740 deletions

@ -1,6 +1,6 @@
{ {
"semi": false, "semi": false,
"singleQuote": true, "singleQuote": true,
"printWidth": 100, "printWidth": 120,
"bracketSpacing": true "bracketSpacing": true
} }

@ -1,12 +1,9 @@
const HOME_NATIVE_TO_ERC_ABI = require('../contracts/build/contracts/HomeBridgeNativeToErc').abi const HOME_NATIVE_TO_ERC_ABI = require('../contracts/build/contracts/HomeBridgeNativeToErc').abi
const FOREIGN_NATIVE_TO_ERC_ABI = require('../contracts/build/contracts/ForeignBridgeNativeToErc') const FOREIGN_NATIVE_TO_ERC_ABI = require('../contracts/build/contracts/ForeignBridgeNativeToErc').abi
.abi
const HOME_ERC_TO_ERC_ABI = require('../contracts/build/contracts/HomeBridgeErcToErc').abi const HOME_ERC_TO_ERC_ABI = require('../contracts/build/contracts/HomeBridgeErcToErc').abi
const FOREIGN_ERC_TO_ERC_ABI = require('../contracts/build/contracts/ForeignBridgeErc677ToErc677') const FOREIGN_ERC_TO_ERC_ABI = require('../contracts/build/contracts/ForeignBridgeErc677ToErc677').abi
.abi
const HOME_ERC_TO_NATIVE_ABI = require('../contracts/build/contracts/HomeBridgeErcToNative').abi const HOME_ERC_TO_NATIVE_ABI = require('../contracts/build/contracts/HomeBridgeErcToNative').abi
const FOREIGN_ERC_TO_NATIVE_ABI = require('../contracts/build/contracts/ForeignBridgeErcToNative') const FOREIGN_ERC_TO_NATIVE_ABI = require('../contracts/build/contracts/ForeignBridgeErcToNative').abi
.abi
const ERC20_ABI = require('../contracts/build/contracts/ERC20').abi const ERC20_ABI = require('../contracts/build/contracts/ERC20').abi
const ERC677_ABI = require('../contracts/build/contracts/ERC677').abi const ERC677_ABI = require('../contracts/build/contracts/ERC677').abi
const ERC677_BRIDGE_TOKEN_ABI = require('../contracts/build/contracts/ERC677BridgeToken').abi const ERC677_BRIDGE_TOKEN_ABI = require('../contracts/build/contracts/ERC677BridgeToken').abi

@ -30,25 +30,15 @@ async function main() {
) )
logger.debug('extracting most recent transactionHash') logger.debug('extracting most recent transactionHash')
const { transactionHash: xSignaturesMostRecentTxHash = '' } = const { transactionHash: xSignaturesMostRecentTxHash = '' } = xSignatures.sort(sortEvents).reverse()[0] || {}
xSignatures.sort(sortEvents).reverse()[0] || {} const { transactionHash: xAffirmationsMostRecentTxHash = '' } = xAffirmations.sort(sortEvents).reverse()[0] || {}
const { transactionHash: xAffirmationsMostRecentTxHash = '' } =
xAffirmations.sort(sortEvents).reverse()[0] || {}
logger.debug('building transaction objects') logger.debug('building transaction objects')
const foreignValidators = await Promise.all( const foreignValidators = await Promise.all(xSignatures.map(event => findTxSender(web3Foreign)(event)))
xSignatures.map(event => findTxSender(web3Foreign)(event)) const homeValidators = await Promise.all(xAffirmations.map(event => findTxSender(web3Home)(event)))
)
const homeValidators = await Promise.all(
xAffirmations.map(event => findTxSender(web3Home)(event))
)
const xSignaturesTxs = xSignatures const xSignaturesTxs = xSignatures.map(normalizeEventInformation).reduce(buildTxList(foreignValidators), {})
.map(normalizeEventInformation) const xAffirmationsTxs = xAffirmations.map(normalizeEventInformation).reduce(buildTxList(homeValidators), {})
.reduce(buildTxList(foreignValidators), {})
const xAffirmationsTxs = xAffirmations
.map(normalizeEventInformation)
.reduce(buildTxList(homeValidators), {})
logger.debug('Done') logger.debug('Done')
@ -166,9 +156,7 @@ const findDifferences = src => dest => {
return ( return (
src src
.map(normalizeEventInformation) .map(normalizeEventInformation)
.filter( .filter(a => a.referenceTx === b.referenceTx && a.recipient === b.recipient && a.value === b.value).length === 0
a => a.referenceTx === b.referenceTx && a.recipient === b.recipient && a.value === b.value
).length === 0
) )
} }

@ -26,18 +26,12 @@ async function checkWorker() {
const foreign = Object.assign({}, balances.foreign, events.foreign) const foreign = Object.assign({}, balances.foreign, events.foreign)
const status = Object.assign({}, balances, events, { home }, { foreign }) const status = Object.assign({}, balances, events, { home }, { foreign })
if (!status) throw new Error('status is empty: ' + JSON.stringify(status)) if (!status) throw new Error('status is empty: ' + JSON.stringify(status))
fs.writeFileSync( fs.writeFileSync(path.join(__dirname, '/responses/getBalances.json'), JSON.stringify(status, null, 4))
path.join(__dirname, '/responses/getBalances.json'),
JSON.stringify(status, null, 4)
)
logger.debug('calling validators()') logger.debug('calling validators()')
const vBalances = await validators(bridgeMode) const vBalances = await validators(bridgeMode)
if (!vBalances) throw new Error('vBalances is empty: ' + JSON.stringify(vBalances)) if (!vBalances) throw new Error('vBalances is empty: ' + JSON.stringify(vBalances))
fs.writeFileSync( fs.writeFileSync(path.join(__dirname, '/responses/validators.json'), JSON.stringify(vBalances, null, 4))
path.join(__dirname, '/responses/validators.json'),
JSON.stringify(vBalances, null, 4)
)
logger.debug('Done') logger.debug('Done')
} catch (e) { } catch (e) {
logger.error(e) logger.error(e)

@ -9,17 +9,11 @@ async function checkWorker2() {
logger.debug('calling eventsStats()') logger.debug('calling eventsStats()')
const evStats = await eventsStats() const evStats = await eventsStats()
if (!evStats) throw new Error('evStats is empty: ' + JSON.stringify(evStats)) if (!evStats) throw new Error('evStats is empty: ' + JSON.stringify(evStats))
fs.writeFileSync( fs.writeFileSync(path.join(__dirname, '/responses/eventsStats.json'), JSON.stringify(evStats, null, 4))
path.join(__dirname, '/responses/eventsStats.json'),
JSON.stringify(evStats, null, 4)
)
logger.debug('calling alerts()') logger.debug('calling alerts()')
const _alerts = await alerts() const _alerts = await alerts()
if (!_alerts) throw new Error('alerts is empty: ' + JSON.stringify(_alerts)) if (!_alerts) throw new Error('alerts is empty: ' + JSON.stringify(_alerts))
fs.writeFileSync( fs.writeFileSync(path.join(__dirname, '/responses/alerts.json'), JSON.stringify(_alerts, null, 4))
path.join(__dirname, '/responses/alerts.json'),
JSON.stringify(_alerts, null, 4)
)
logger.debug('Done x2') logger.debug('Done x2')
} catch (e) { } catch (e) {
logger.error(e) logger.error(e)

@ -9,10 +9,7 @@ async function checkWorker3() {
const transfers = await stuckTransfers() const transfers = await stuckTransfers()
// console.log(transfers) // console.log(transfers)
if (!transfers) throw new Error('transfers is empty: ' + JSON.stringify(transfers)) if (!transfers) throw new Error('transfers is empty: ' + JSON.stringify(transfers))
fs.writeFileSync( fs.writeFileSync(path.join(__dirname, '/responses/stuckTransfers.json'), JSON.stringify(transfers, null, 4))
path.join(__dirname, '/responses/stuckTransfers.json'),
JSON.stringify(transfers, null, 4)
)
logger.debug('Done') logger.debug('Done')
} catch (e) { } catch (e) {
logger.error('checkWorker3.js', e) logger.error('checkWorker3.js', e)

@ -57,18 +57,10 @@ function compareTransferForeign(home) {
} }
async function main() { async function main() {
const { const { foreignDeposits, homeDeposits, homeWithdrawals, foreignWithdrawals, isExternalErc20 } = await eventsInfo()
foreignDeposits,
homeDeposits,
homeWithdrawals,
foreignWithdrawals,
isExternalErc20
} = await eventsInfo()
const onlyInHomeDeposits = homeDeposits.filter(compareDepositsHome(foreignDeposits)) const onlyInHomeDeposits = homeDeposits.filter(compareDepositsHome(foreignDeposits))
const onlyInForeignDeposits = foreignDeposits const onlyInForeignDeposits = foreignDeposits.concat([]).filter(compareDepositsForeign(homeDeposits))
.concat([])
.filter(compareDepositsForeign(homeDeposits))
const onlyInHomeWithdrawals = isExternalErc20 const onlyInHomeWithdrawals = isExternalErc20
? homeWithdrawals.filter(compareTransferHome(foreignWithdrawals)) ? homeWithdrawals.filter(compareTransferHome(foreignWithdrawals))

@ -27,10 +27,7 @@ const {
async function main(bridgeMode) { async function main(bridgeMode) {
if (bridgeMode === BRIDGE_MODES.ERC_TO_ERC) { if (bridgeMode === BRIDGE_MODES.ERC_TO_ERC) {
const foreignBridge = new web3Foreign.eth.Contract( const foreignBridge = new web3Foreign.eth.Contract(FOREIGN_ERC_TO_ERC_ABI, FOREIGN_BRIDGE_ADDRESS)
FOREIGN_ERC_TO_ERC_ABI,
FOREIGN_BRIDGE_ADDRESS
)
const erc20Address = await foreignBridge.methods.erc20token().call() const erc20Address = await foreignBridge.methods.erc20token().call()
const erc20Contract = new web3Foreign.eth.Contract(ERC20_ABI, erc20Address) const erc20Contract = new web3Foreign.eth.Contract(ERC20_ABI, erc20Address)
logger.debug('calling erc20Contract.methods.balanceOf') logger.debug('calling erc20Contract.methods.balanceOf')
@ -55,15 +52,9 @@ async function main(bridgeMode) {
balanceDiff: Number(Web3Utils.fromWei(diff)), balanceDiff: Number(Web3Utils.fromWei(diff)),
lastChecked: Math.floor(Date.now() / 1000) lastChecked: Math.floor(Date.now() / 1000)
} }
} else if ( } else if (bridgeMode === BRIDGE_MODES.NATIVE_TO_ERC || bridgeMode === BRIDGE_MODES.NATIVE_TO_ERC_V1) {
bridgeMode === BRIDGE_MODES.NATIVE_TO_ERC ||
bridgeMode === BRIDGE_MODES.NATIVE_TO_ERC_V1
) {
logger.debug('calling web3Home.eth.getBalance') logger.debug('calling web3Home.eth.getBalance')
const foreignBridge = new web3Foreign.eth.Contract( const foreignBridge = new web3Foreign.eth.Contract(FOREIGN_NATIVE_TO_ERC_ABI, FOREIGN_BRIDGE_ADDRESS)
FOREIGN_NATIVE_TO_ERC_ABI,
FOREIGN_BRIDGE_ADDRESS
)
const erc20Address = await foreignBridge.methods.erc677token().call() const erc20Address = await foreignBridge.methods.erc677token().call()
const homeBalance = await web3Home.eth.getBalance(HOME_BRIDGE_ADDRESS) const homeBalance = await web3Home.eth.getBalance(HOME_BRIDGE_ADDRESS)
const tokenContract = new web3Foreign.eth.Contract(ERC20_ABI, erc20Address) const tokenContract = new web3Foreign.eth.Contract(ERC20_ABI, erc20Address)
@ -84,10 +75,7 @@ async function main(bridgeMode) {
lastChecked: Math.floor(Date.now() / 1000) lastChecked: Math.floor(Date.now() / 1000)
} }
} else if (bridgeMode === BRIDGE_MODES.ERC_TO_NATIVE) { } else if (bridgeMode === BRIDGE_MODES.ERC_TO_NATIVE) {
const foreignBridge = new web3Foreign.eth.Contract( const foreignBridge = new web3Foreign.eth.Contract(FOREIGN_ERC_TO_NATIVE_ABI, FOREIGN_BRIDGE_ADDRESS)
FOREIGN_ERC_TO_NATIVE_ABI,
FOREIGN_BRIDGE_ADDRESS
)
const erc20Address = await foreignBridge.methods.erc20token().call() const erc20Address = await foreignBridge.methods.erc20token().call()
const erc20Contract = new web3Foreign.eth.Contract(ERC20_ABI, erc20Address) const erc20Contract = new web3Foreign.eth.Contract(ERC20_ABI, erc20Address)
logger.debug('calling erc20Contract.methods.balanceOf') logger.debug('calling erc20Contract.methods.balanceOf')

@ -2,9 +2,7 @@ require('dotenv').config()
const eventsInfo = require('./utils/events') const eventsInfo = require('./utils/events')
async function main(bridgeMode) { async function main(bridgeMode) {
const { foreignDeposits, homeDeposits, homeWithdrawals, foreignWithdrawals } = await eventsInfo( const { foreignDeposits, homeDeposits, homeWithdrawals, foreignWithdrawals } = await eventsInfo(bridgeMode)
bridgeMode
)
return { return {
depositsDiff: homeDeposits.length - foreignDeposits.length, depositsDiff: homeDeposits.length - foreignDeposits.length,

@ -91,8 +91,7 @@ app.get('/eventsStats', async (req, res, next) => {
app.get('/alerts', async (req, res, next) => { app.get('/alerts', async (req, res, next) => {
try { try {
const results = await readFile('./responses/alerts.json') const results = await readFile('./responses/alerts.json')
results.ok = results.ok = !results.executeAffirmations.mostRecentTxHash && !results.executeSignatures.mostRecentTxHash
!results.executeAffirmations.mostRecentTxHash && !results.executeSignatures.mostRecentTxHash
res.json(results) res.json(results)
} catch (e) { } catch (e) {
next(e) next(e)

@ -3,12 +3,7 @@ module.exports = function logger(name) {
function log(...args) { function log(...args) {
const now = new Date() const now = new Date()
console.log( console.log(now.toISOString(), `(+${lastlog ? now.getTime() - lastlog : 0}ms)`, `[${name}]`, ...args)
now.toISOString(),
`(+${lastlog ? now.getTime() - lastlog : 0}ms)`,
`[${name}]`,
...args
)
lastlog = now.getTime() lastlog = now.getTime()
} }

@ -32,8 +32,7 @@ async function main(mode) {
const homeBridge = new web3Home.eth.Contract(HOME_ABI, HOME_BRIDGE_ADDRESS) const homeBridge = new web3Home.eth.Contract(HOME_ABI, HOME_BRIDGE_ADDRESS)
const foreignBridge = new web3Foreign.eth.Contract(FOREIGN_ABI, FOREIGN_BRIDGE_ADDRESS) const foreignBridge = new web3Foreign.eth.Contract(FOREIGN_ABI, FOREIGN_BRIDGE_ADDRESS)
const v1Bridge = bridgeMode === BRIDGE_MODES.NATIVE_TO_ERC_V1 const v1Bridge = bridgeMode === BRIDGE_MODES.NATIVE_TO_ERC_V1
const erc20MethodName = const erc20MethodName = bridgeMode === BRIDGE_MODES.NATIVE_TO_ERC || v1Bridge ? 'erc677token' : 'erc20token'
bridgeMode === BRIDGE_MODES.NATIVE_TO_ERC || v1Bridge ? 'erc677token' : 'erc20token'
const erc20Address = await foreignBridge.methods[erc20MethodName]().call() const erc20Address = await foreignBridge.methods[erc20MethodName]().call()
const tokenType = await getTokenType( const tokenType = await getTokenType(
new web3Foreign.eth.Contract(ERC677_BRIDGE_TOKEN_ABI, erc20Address), new web3Foreign.eth.Contract(ERC677_BRIDGE_TOKEN_ABI, erc20Address),

@ -72,20 +72,14 @@ async function main(bridgeMode) {
const homeBridge = new web3Home.eth.Contract(HOME_ABI, HOME_BRIDGE_ADDRESS) const homeBridge = new web3Home.eth.Contract(HOME_ABI, HOME_BRIDGE_ADDRESS)
const foreignBridge = new web3Foreign.eth.Contract(FOREIGN_ABI, FOREIGN_BRIDGE_ADDRESS) const foreignBridge = new web3Foreign.eth.Contract(FOREIGN_ABI, FOREIGN_BRIDGE_ADDRESS)
const homeValidatorsAddress = await homeBridge.methods.validatorContract().call() const homeValidatorsAddress = await homeBridge.methods.validatorContract().call()
const homeBridgeValidators = new web3Home.eth.Contract( const homeBridgeValidators = new web3Home.eth.Contract(BRIDGE_VALIDATORS_ABI, homeValidatorsAddress)
BRIDGE_VALIDATORS_ABI,
homeValidatorsAddress
)
logger.debug('getting last block numbers') logger.debug('getting last block numbers')
const [homeBlockNumber, foreignBlockNumber] = await getBlockNumber(web3Home, web3Foreign) const [homeBlockNumber, foreignBlockNumber] = await getBlockNumber(web3Home, web3Foreign)
logger.debug('calling foreignBridge.methods.validatorContract().call()') logger.debug('calling foreignBridge.methods.validatorContract().call()')
const foreignValidatorsAddress = await foreignBridge.methods.validatorContract().call() const foreignValidatorsAddress = await foreignBridge.methods.validatorContract().call()
const foreignBridgeValidators = new web3Foreign.eth.Contract( const foreignBridgeValidators = new web3Foreign.eth.Contract(BRIDGE_VALIDATORS_ABI, foreignValidatorsAddress)
BRIDGE_VALIDATORS_ABI,
foreignValidatorsAddress
)
logger.debug('calling foreignBridgeValidators getValidatorList()') logger.debug('calling foreignBridgeValidators getValidatorList()')
const foreignValidators = await getValidatorList( const foreignValidators = await getValidatorList(

@ -16,10 +16,7 @@ const { toBN } = foreignWeb3.utils
homeWeb3.eth.accounts.wallet.add(user.privateKey) homeWeb3.eth.accounts.wallet.add(user.privateKey)
foreignWeb3.eth.accounts.wallet.add(user.privateKey) foreignWeb3.eth.accounts.wallet.add(user.privateKey)
const erc20Token = new foreignWeb3.eth.Contract( const erc20Token = new foreignWeb3.eth.Contract(ERC677_BRIDGE_TOKEN_ABI, ercToErcBridge.foreignToken)
ERC677_BRIDGE_TOKEN_ABI,
ercToErcBridge.foreignToken
)
const erc677Token = new homeWeb3.eth.Contract(ERC677_BRIDGE_TOKEN_ABI, ercToErcBridge.homeToken) const erc677Token = new homeWeb3.eth.Contract(ERC677_BRIDGE_TOKEN_ABI, ercToErcBridge.homeToken)
describe('erc to erc', () => { describe('erc to erc', () => {

@ -16,10 +16,7 @@ const { toBN } = foreignWeb3.utils
homeWeb3.eth.accounts.wallet.add(user.privateKey) homeWeb3.eth.accounts.wallet.add(user.privateKey)
foreignWeb3.eth.accounts.wallet.add(user.privateKey) foreignWeb3.eth.accounts.wallet.add(user.privateKey)
const erc20Token = new foreignWeb3.eth.Contract( const erc20Token = new foreignWeb3.eth.Contract(ERC677_BRIDGE_TOKEN_ABI, ercToNativeBridge.foreignToken)
ERC677_BRIDGE_TOKEN_ABI,
ercToNativeBridge.foreignToken
)
describe('erc to native', () => { describe('erc to native', () => {
it('should convert tokens in foreign to coins in home', async () => { it('should convert tokens in foreign to coins in home', async () => {

@ -21,8 +21,7 @@ if (baseConfig.id === 'erc-erc' && initialChecks.foreignERC === ERC_TYPES.ERC677
const id = `${baseConfig.id}-affirmation-request` const id = `${baseConfig.id}-affirmation-request`
module.exports = module.exports =
(baseConfig.id === 'erc-erc' && initialChecks.foreignERC === ERC_TYPES.ERC20) || (baseConfig.id === 'erc-erc' && initialChecks.foreignERC === ERC_TYPES.ERC20) || baseConfig.id === 'erc-native'
baseConfig.id === 'erc-native'
? { ? {
...baseConfig.bridgeConfig, ...baseConfig.bridgeConfig,
...baseConfig.foreignConfig, ...baseConfig.foreignConfig,

@ -49,8 +49,7 @@ let maxProcessingTime = null
if (String(process.env.MAX_PROCESSING_TIME) === '0') { if (String(process.env.MAX_PROCESSING_TIME) === '0') {
maxProcessingTime = 0 maxProcessingTime = 0
} else if (!process.env.MAX_PROCESSING_TIME) { } else if (!process.env.MAX_PROCESSING_TIME) {
maxProcessingTime = maxProcessingTime = 4 * Math.max(process.env.HOME_POLLING_INTERVAL, process.env.FOREIGN_POLLING_INTERVAL)
4 * Math.max(process.env.HOME_POLLING_INTERVAL, process.env.FOREIGN_POLLING_INTERVAL)
} else { } else {
maxProcessingTime = Number(process.env.MAX_PROCESSING_TIME) maxProcessingTime = Number(process.env.MAX_PROCESSING_TIME)
} }

@ -61,10 +61,7 @@ async function main() {
console.log('Signature Requests') console.log('Signature Requests')
console.log(signatureRequestsStats) console.log(signatureRequestsStats)
const collectedSignaturesStats = computeCollectedSignaturesStats( const collectedSignaturesStats = computeCollectedSignaturesStats(collectedSignatures, senderForeign)
collectedSignatures,
senderForeign
)
console.log('Collected Signatures') console.log('Collected Signatures')
console.log(collectedSignaturesStats) console.log(collectedSignaturesStats)
} }

@ -14,8 +14,7 @@ const {
HOME_TEST_TX_GAS_PRICE HOME_TEST_TX_GAS_PRICE
} = process.env } = process.env
const NUMBER_OF_WITHDRAWALS_TO_SEND = const NUMBER_OF_WITHDRAWALS_TO_SEND = process.argv[2] || process.env.NUMBER_OF_WITHDRAWALS_TO_SEND || 1
process.argv[2] || process.env.NUMBER_OF_WITHDRAWALS_TO_SEND || 1
const BRIDGEABLE_TOKEN_ABI = [ const BRIDGEABLE_TOKEN_ABI = [
{ {

@ -17,10 +17,7 @@ async function getStartBlock(rpcUrl, bridgeAddress, bridgeAbi) {
const deployedAtBlock = await bridgeContract.methods.deployedAtBlock().call() const deployedAtBlock = await bridgeContract.methods.deployedAtBlock().call()
const validatorContractAddress = await bridgeContract.methods.validatorContract().call() const validatorContractAddress = await bridgeContract.methods.validatorContract().call()
const validatorContract = new web3Instance.eth.Contract( const validatorContract = new web3Instance.eth.Contract(BRIDGE_VALIDATORS_ABI, validatorContractAddress)
BRIDGE_VALIDATORS_ABI,
validatorContractAddress
)
const validatorDeployedAtBlock = await validatorContract.methods.deployedAtBlock().call() const validatorDeployedAtBlock = await validatorContract.methods.deployedAtBlock().call()

@ -8,10 +8,7 @@ async function initialChecks() {
if (BRIDGE_MODE === 'ERC_TO_ERC') { if (BRIDGE_MODE === 'ERC_TO_ERC') {
const foreignWeb3 = new Web3(new Web3.providers.HttpProvider(FOREIGN_RPC_URL)) const foreignWeb3 = new Web3(new Web3.providers.HttpProvider(FOREIGN_RPC_URL))
const bridgeTokenContract = new foreignWeb3.eth.Contract( const bridgeTokenContract = new foreignWeb3.eth.Contract(ERC677_BRIDGE_TOKEN_ABI, ERC20_TOKEN_ADDRESS)
ERC677_BRIDGE_TOKEN_ABI,
ERC20_TOKEN_ADDRESS
)
result.foreignERC = await getTokenType(bridgeTokenContract, FOREIGN_BRIDGE_ADDRESS) result.foreignERC = await getTokenType(bridgeTokenContract, FOREIGN_BRIDGE_ADDRESS)
} }

@ -13,8 +13,7 @@ const {
FOREIGN_TEST_TX_GAS_PRICE FOREIGN_TEST_TX_GAS_PRICE
} = process.env } = process.env
const NUMBER_OF_WITHDRAWALS_TO_SEND = const NUMBER_OF_WITHDRAWALS_TO_SEND = process.argv[2] || process.env.NUMBER_OF_WITHDRAWALS_TO_SEND || 1
process.argv[2] || process.env.NUMBER_OF_WITHDRAWALS_TO_SEND || 1
const ERC677_ABI = [ const ERC677_ABI = [
{ {

@ -1,26 +1,12 @@
const { HttpListProviderError } = require('http-list-provider') const { HttpListProviderError } = require('http-list-provider')
const { const { AlreadyProcessedError, AlreadySignedError, InvalidValidatorError } = require('../../utils/errors')
AlreadyProcessedError,
AlreadySignedError,
InvalidValidatorError
} = require('../../utils/errors')
const logger = require('../../services/logger').child({ const logger = require('../../services/logger').child({
module: 'processAffirmationRequests:estimateGas' module: 'processAffirmationRequests:estimateGas'
}) })
async function estimateGas({ async function estimateGas({ web3, homeBridge, validatorContract, recipient, value, txHash, address }) {
web3,
homeBridge,
validatorContract,
recipient,
value,
txHash,
address
}) {
try { try {
const gasEstimate = await homeBridge.methods const gasEstimate = await homeBridge.methods.executeAffirmation(recipient, value, txHash).estimateGas({
.executeAffirmation(recipient, value, txHash)
.estimateGas({
from: address from: address
}) })
@ -36,9 +22,7 @@ async function estimateGas({
// Check if minimum number of validations was already reached // Check if minimum number of validations was already reached
logger.debug('Check if minimum number of validations was already reached') logger.debug('Check if minimum number of validations was already reached')
const numAffirmationsSigned = await homeBridge.methods.numAffirmationsSigned(messageHash).call() const numAffirmationsSigned = await homeBridge.methods.numAffirmationsSigned(messageHash).call()
const alreadyProcessed = await homeBridge.methods const alreadyProcessed = await homeBridge.methods.isAlreadyProcessed(numAffirmationsSigned).call()
.isAlreadyProcessed(numAffirmationsSigned)
.call()
if (alreadyProcessed) { if (alreadyProcessed) {
throw new AlreadyProcessedError(e.message) throw new AlreadyProcessedError(e.message)

@ -7,11 +7,7 @@ const { web3Home } = require('../../services/web3')
const { BRIDGE_VALIDATORS_ABI } = require('../../../../commons') const { BRIDGE_VALIDATORS_ABI } = require('../../../../commons')
const { EXIT_CODES, MAX_CONCURRENT_EVENTS } = require('../../utils/constants') const { EXIT_CODES, MAX_CONCURRENT_EVENTS } = require('../../utils/constants')
const estimateGas = require('./estimateGas') const estimateGas = require('./estimateGas')
const { const { AlreadyProcessedError, AlreadySignedError, InvalidValidatorError } = require('../../utils/errors')
AlreadyProcessedError,
AlreadySignedError,
InvalidValidatorError
} = require('../../utils/errors')
const limit = promiseLimit(MAX_CONCURRENT_EVENTS) const limit = promiseLimit(MAX_CONCURRENT_EVENTS)
@ -40,10 +36,7 @@ function processAffirmationRequestsBuilder(config) {
eventTransactionHash: affirmationRequest.transactionHash eventTransactionHash: affirmationRequest.transactionHash
}) })
logger.info( logger.info({ sender: recipient, value }, `Processing affirmationRequest ${affirmationRequest.transactionHash}`)
{ sender: recipient, value },
`Processing affirmationRequest ${affirmationRequest.transactionHash}`
)
let gasEstimate let gasEstimate
try { try {
@ -60,9 +53,7 @@ function processAffirmationRequestsBuilder(config) {
logger.debug({ gasEstimate }, 'Gas estimated') logger.debug({ gasEstimate }, 'Gas estimated')
} catch (e) { } catch (e) {
if (e instanceof HttpListProviderError) { if (e instanceof HttpListProviderError) {
throw new Error( throw new Error('RPC Connection Error: submitSignature Gas Estimate cannot be obtained.')
'RPC Connection Error: submitSignature Gas Estimate cannot be obtained.'
)
} else if (e instanceof InvalidValidatorError) { } else if (e instanceof InvalidValidatorError) {
logger.fatal({ address: config.validatorAddress }, 'Invalid validator') logger.fatal({ address: config.validatorAddress }, 'Invalid validator')
process.exit(EXIT_CODES.INCOMPATIBILITY) process.exit(EXIT_CODES.INCOMPATIBILITY)
@ -71,9 +62,7 @@ function processAffirmationRequestsBuilder(config) {
return return
} else if (e instanceof AlreadyProcessedError) { } else if (e instanceof AlreadyProcessedError) {
logger.info( logger.info(
`affirmationRequest ${ `affirmationRequest ${affirmationRequest.transactionHash} was already processed by other validators`
affirmationRequest.transactionHash
} was already processed by other validators`
) )
return return
} else { } else {

@ -1,10 +1,6 @@
const Web3 = require('web3') const Web3 = require('web3')
const { HttpListProviderError } = require('http-list-provider') const { HttpListProviderError } = require('http-list-provider')
const { const { AlreadyProcessedError, IncompatibleContractError, InvalidValidatorError } = require('../../utils/errors')
AlreadyProcessedError,
IncompatibleContractError,
InvalidValidatorError
} = require('../../utils/errors')
const { parseMessage } = require('../../utils/message') const { parseMessage } = require('../../utils/message')
const logger = require('../../services/logger').child({ const logger = require('../../services/logger').child({
module: 'processCollectedSignatures:estimateGas' module: 'processCollectedSignatures:estimateGas'
@ -13,19 +9,9 @@ const logger = require('../../services/logger').child({
const web3 = new Web3() const web3 = new Web3()
const { toBN } = Web3.utils const { toBN } = Web3.utils
async function estimateGas({ async function estimateGas({ foreignBridge, validatorContract, message, numberOfCollectedSignatures, v, r, s }) {
foreignBridge,
validatorContract,
message,
numberOfCollectedSignatures,
v,
r,
s
}) {
try { try {
const gasEstimate = await foreignBridge.methods const gasEstimate = await foreignBridge.methods.executeSignatures(v, r, s, message).estimateGas()
.executeSignatures(v, r, s, message)
.estimateGas()
return gasEstimate return gasEstimate
} catch (e) { } catch (e) {
if (e instanceof HttpListProviderError) { if (e instanceof HttpListProviderError) {

@ -6,11 +6,7 @@ const rootLogger = require('../../services/logger')
const { web3Home, web3Foreign } = require('../../services/web3') const { web3Home, web3Foreign } = require('../../services/web3')
const { signatureToVRS } = require('../../utils/message') const { signatureToVRS } = require('../../utils/message')
const estimateGas = require('./estimateGas') const estimateGas = require('./estimateGas')
const { const { AlreadyProcessedError, IncompatibleContractError, InvalidValidatorError } = require('../../utils/errors')
AlreadyProcessedError,
IncompatibleContractError,
InvalidValidatorError
} = require('../../utils/errors')
const { MAX_CONCURRENT_EVENTS } = require('../../utils/constants') const { MAX_CONCURRENT_EVENTS } = require('../../utils/constants')
const limit = promiseLimit(MAX_CONCURRENT_EVENTS) const limit = promiseLimit(MAX_CONCURRENT_EVENTS)
@ -20,10 +16,7 @@ let validatorContract = null
function processCollectedSignaturesBuilder(config) { function processCollectedSignaturesBuilder(config) {
const homeBridge = new web3Home.eth.Contract(config.homeBridgeAbi, config.homeBridgeAddress) const homeBridge = new web3Home.eth.Contract(config.homeBridgeAbi, config.homeBridgeAddress)
const foreignBridge = new web3Foreign.eth.Contract( const foreignBridge = new web3Foreign.eth.Contract(config.foreignBridgeAbi, config.foreignBridgeAddress)
config.foreignBridgeAbi,
config.foreignBridgeAddress
)
return async function processCollectedSignatures(signatures) { return async function processCollectedSignatures(signatures) {
const txToSend = [] const txToSend = []
@ -33,28 +26,19 @@ function processCollectedSignaturesBuilder(config) {
const validatorContractAddress = await foreignBridge.methods.validatorContract().call() const validatorContractAddress = await foreignBridge.methods.validatorContract().call()
rootLogger.debug({ validatorContractAddress }, 'Validator contract address obtained') rootLogger.debug({ validatorContractAddress }, 'Validator contract address obtained')
validatorContract = new web3Foreign.eth.Contract( validatorContract = new web3Foreign.eth.Contract(BRIDGE_VALIDATORS_ABI, validatorContractAddress)
BRIDGE_VALIDATORS_ABI,
validatorContractAddress
)
} }
rootLogger.debug(`Processing ${signatures.length} CollectedSignatures events`) rootLogger.debug(`Processing ${signatures.length} CollectedSignatures events`)
const callbacks = signatures.map(colSignature => const callbacks = signatures.map(colSignature =>
limit(async () => { limit(async () => {
const { const { authorityResponsibleForRelay, messageHash, NumberOfCollectedSignatures } = colSignature.returnValues
authorityResponsibleForRelay,
messageHash,
NumberOfCollectedSignatures
} = colSignature.returnValues
const logger = rootLogger.child({ const logger = rootLogger.child({
eventTransactionHash: colSignature.transactionHash eventTransactionHash: colSignature.transactionHash
}) })
if ( if (authorityResponsibleForRelay === web3Home.utils.toChecksumAddress(config.validatorAddress)) {
authorityResponsibleForRelay === web3Home.utils.toChecksumAddress(config.validatorAddress)
) {
logger.info(`Processing CollectedSignatures ${colSignature.transactionHash}`) logger.info(`Processing CollectedSignatures ${colSignature.transactionHash}`)
const message = await homeBridge.methods.message(messageHash).call() const message = await homeBridge.methods.message(messageHash).call()
@ -90,16 +74,11 @@ function processCollectedSignaturesBuilder(config) {
logger.debug({ gasEstimate }, 'Gas estimated') logger.debug({ gasEstimate }, 'Gas estimated')
} catch (e) { } catch (e) {
if (e instanceof HttpListProviderError) { if (e instanceof HttpListProviderError) {
throw new Error( throw new Error('RPC Connection Error: submitSignature Gas Estimate cannot be obtained.')
'RPC Connection Error: submitSignature Gas Estimate cannot be obtained.'
)
} else if (e instanceof AlreadyProcessedError) { } else if (e instanceof AlreadyProcessedError) {
logger.info(`Already processed CollectedSignatures ${colSignature.transactionHash}`) logger.info(`Already processed CollectedSignatures ${colSignature.transactionHash}`)
return return
} else if ( } else if (e instanceof IncompatibleContractError || e instanceof InvalidValidatorError) {
e instanceof IncompatibleContractError ||
e instanceof InvalidValidatorError
) {
logger.error(`The message couldn't be processed; skipping: ${e.message}`) logger.error(`The message couldn't be processed; skipping: ${e.message}`)
return return
} else { } else {
@ -115,11 +94,7 @@ function processCollectedSignaturesBuilder(config) {
to: config.foreignBridgeAddress to: config.foreignBridgeAddress
}) })
} else { } else {
logger.info( logger.info(`Validator not responsible for relaying CollectedSignatures ${colSignature.transactionHash}`)
`Validator not responsible for relaying CollectedSignatures ${
colSignature.transactionHash
}`
)
} }
}) })
) )

@ -1,9 +1,5 @@
const { HttpListProviderError } = require('http-list-provider') const { HttpListProviderError } = require('http-list-provider')
const { const { AlreadyProcessedError, AlreadySignedError, InvalidValidatorError } = require('../../utils/errors')
AlreadyProcessedError,
AlreadySignedError,
InvalidValidatorError
} = require('../../utils/errors')
const logger = require('../../services/logger').child({ const logger = require('../../services/logger').child({
module: 'processSignatureRequests:estimateGas' module: 'processSignatureRequests:estimateGas'
}) })

@ -6,11 +6,7 @@ const rootLogger = require('../../services/logger')
const { web3Home } = require('../../services/web3') const { web3Home } = require('../../services/web3')
const { createMessage } = require('../../utils/message') const { createMessage } = require('../../utils/message')
const estimateGas = require('./estimateGas') const estimateGas = require('./estimateGas')
const { const { AlreadyProcessedError, AlreadySignedError, InvalidValidatorError } = require('../../utils/errors')
AlreadyProcessedError,
AlreadySignedError,
InvalidValidatorError
} = require('../../utils/errors')
const { EXIT_CODES, MAX_CONCURRENT_EVENTS } = require('../../utils/constants') const { EXIT_CODES, MAX_CONCURRENT_EVENTS } = require('../../utils/constants')
const { VALIDATOR_ADDRESS_PRIVATE_KEY } = process.env const { VALIDATOR_ADDRESS_PRIVATE_KEY } = process.env
@ -47,10 +43,7 @@ function processSignatureRequestsBuilder(config) {
eventTransactionHash: signatureRequest.transactionHash eventTransactionHash: signatureRequest.transactionHash
}) })
logger.info( logger.info({ sender: recipient, value }, `Processing signatureRequest ${signatureRequest.transactionHash}`)
{ sender: recipient, value },
`Processing signatureRequest ${signatureRequest.transactionHash}`
)
const message = createMessage({ const message = createMessage({
recipient, recipient,
@ -76,9 +69,7 @@ function processSignatureRequestsBuilder(config) {
logger.debug({ gasEstimate }, 'Gas estimated') logger.debug({ gasEstimate }, 'Gas estimated')
} catch (e) { } catch (e) {
if (e instanceof HttpListProviderError) { if (e instanceof HttpListProviderError) {
throw new Error( throw new Error('RPC Connection Error: submitSignature Gas Estimate cannot be obtained.')
'RPC Connection Error: submitSignature Gas Estimate cannot be obtained.'
)
} else if (e instanceof InvalidValidatorError) { } else if (e instanceof InvalidValidatorError) {
logger.fatal({ address: config.validatorAddress }, 'Invalid validator') logger.fatal({ address: config.validatorAddress }, 'Invalid validator')
process.exit(EXIT_CODES.INCOMPATIBILITY) process.exit(EXIT_CODES.INCOMPATIBILITY)
@ -87,9 +78,7 @@ function processSignatureRequestsBuilder(config) {
return return
} else if (e instanceof AlreadyProcessedError) { } else if (e instanceof AlreadyProcessedError) {
logger.info( logger.info(
`signatureRequest ${ `signatureRequest ${signatureRequest.transactionHash} was already processed by other validators`
signatureRequest.transactionHash
} was already processed by other validators`
) )
return return
} else { } else {

@ -4,11 +4,7 @@ const { HttpListProviderError } = require('http-list-provider')
const { BRIDGE_VALIDATORS_ABI } = require('../../../../commons') const { BRIDGE_VALIDATORS_ABI } = require('../../../../commons')
const rootLogger = require('../../services/logger') const rootLogger = require('../../services/logger')
const { web3Home } = require('../../services/web3') const { web3Home } = require('../../services/web3')
const { const { AlreadyProcessedError, AlreadySignedError, InvalidValidatorError } = require('../../utils/errors')
AlreadyProcessedError,
AlreadySignedError,
InvalidValidatorError
} = require('../../utils/errors')
const { EXIT_CODES, MAX_CONCURRENT_EVENTS } = require('../../utils/constants') const { EXIT_CODES, MAX_CONCURRENT_EVENTS } = require('../../utils/constants')
const estimateGas = require('../processAffirmationRequests/estimateGas') const estimateGas = require('../processAffirmationRequests/estimateGas')
@ -56,9 +52,7 @@ function processTransfersBuilder(config) {
logger.debug({ gasEstimate }, 'Gas estimated') logger.debug({ gasEstimate }, 'Gas estimated')
} catch (e) { } catch (e) {
if (e instanceof HttpListProviderError) { if (e instanceof HttpListProviderError) {
throw new Error( throw new Error('RPC Connection Error: submitSignature Gas Estimate cannot be obtained.')
'RPC Connection Error: submitSignature Gas Estimate cannot be obtained.'
)
} else if (e instanceof InvalidValidatorError) { } else if (e instanceof InvalidValidatorError) {
logger.fatal({ address: config.validatorAddress }, 'Invalid validator') logger.fatal({ address: config.validatorAddress }, 'Invalid validator')
process.exit(EXIT_CODES.INCOMPATIBILITY) process.exit(EXIT_CODES.INCOMPATIBILITY)
@ -66,9 +60,7 @@ function processTransfersBuilder(config) {
logger.info(`Already signed transfer ${transfer.transactionHash}`) logger.info(`Already signed transfer ${transfer.transactionHash}`)
return return
} else if (e instanceof AlreadyProcessedError) { } else if (e instanceof AlreadyProcessedError) {
logger.info( logger.info(`transfer ${transfer.transactionHash} was already processed by other validators`)
`transfer ${transfer.transactionHash} was already processed by other validators`
)
return return
} else { } else {
logger.error(e, 'Unknown error while processing transaction') logger.error(e, 'Unknown error while processing transaction')

@ -63,9 +63,7 @@ async function initialize() {
} }
function resume(newBalance) { function resume(newBalance) {
logger.info( logger.info(`Validator balance changed. New balance is ${newBalance}. Resume messages processing.`)
`Validator balance changed. New balance is ${newBalance}. Resume messages processing.`
)
initialize() initialize()
} }
@ -164,9 +162,7 @@ async function main({ msg, ackMsg, nackMsg, channel, scheduleForRetry }) {
logger.debug(`Finished processing msg`) logger.debug(`Finished processing msg`)
if (insufficientFunds) { if (insufficientFunds) {
logger.warn( logger.warn('Insufficient funds. Stop sending transactions until the account has the minimum balance')
'Insufficient funds. Stop sending transactions until the account has the minimum balance'
)
channel.close() channel.close()
waitForFunds(web3Instance, VALIDATOR_ADDRESS, minimumBalance, resume, logger) waitForFunds(web3Instance, VALIDATOR_ADDRESS, minimumBalance, resume, logger)
} }

@ -59,14 +59,7 @@ function connectSenderToQueue({ queueName, cb }) {
}) })
} }
async function generateRetry({ async function generateRetry({ data, msgRetries, channelWrapper, channel, queueName, deadLetterExchange }) {
data,
msgRetries,
channelWrapper,
channel,
queueName,
deadLetterExchange
}) {
const retries = msgRetries + 1 const retries = msgRetries + 1
const delay = getRetrySequence(retries) * 1000 const delay = getRetrySequence(retries) * 1000
const retryQueue = `${queueName}-retry-${delay}` const retryQueue = `${queueName}-retry-${delay}`

@ -7,11 +7,7 @@ const logger = require('../services/logger').child({
module: 'gasPrice' module: 'gasPrice'
}) })
const { setIntervalAndRun } = require('../utils/utils') const { setIntervalAndRun } = require('../utils/utils')
const { const { DEFAULT_UPDATE_INTERVAL, GAS_PRICE_BOUNDARIES, DEFAULT_GAS_PRICE_FACTOR } = require('../utils/constants')
DEFAULT_UPDATE_INTERVAL,
GAS_PRICE_BOUNDARIES,
DEFAULT_GAS_PRICE_FACTOR
} = require('../utils/constants')
const HomeABI = bridgeConfig.homeBridgeAbi const HomeABI = bridgeConfig.homeBridgeAbi
const ForeignABI = bridgeConfig.foreignBridgeAbi const ForeignABI = bridgeConfig.foreignBridgeAbi

@ -1,8 +1,7 @@
const pino = require('pino') const pino = require('pino')
const path = require('path') const path = require('path')
const config = const config = process.env.NODE_ENV !== 'test' ? require(path.join('../../config/', process.argv[2])) : {}
process.env.NODE_ENV !== 'test' ? require(path.join('../../config/', process.argv[2])) : {}
const logger = pino({ const logger = pino({
enabled: process.env.NODE_ENV !== 'test', enabled: process.env.NODE_ENV !== 'test',

@ -3,18 +3,7 @@ const fetch = require('node-fetch')
const rpcUrlsManager = require('../services/getRpcUrlsManager') const rpcUrlsManager = require('../services/getRpcUrlsManager')
// eslint-disable-next-line consistent-return // eslint-disable-next-line consistent-return
async function sendTx({ async function sendTx({ chain, privateKey, data, nonce, gasPrice, amount, gasLimit, to, chainId, web3 }) {
chain,
privateKey,
data,
nonce,
gasPrice,
amount,
gasLimit,
to,
chainId,
web3
}) {
const serializedTx = await web3.eth.accounts.signTransaction( const serializedTx = await web3.eth.accounts.signTransaction(
{ {
nonce: Number(nonce), nonce: Number(nonce),

@ -47,10 +47,7 @@ async function getRequiredBlockConfirmations(contract) {
const contractAddress = contract.options.address const contractAddress = contract.options.address
logger.debug({ contractAddress }, 'Getting required block confirmations') logger.debug({ contractAddress }, 'Getting required block confirmations')
const requiredBlockConfirmations = await contract.methods.requiredBlockConfirmations().call() const requiredBlockConfirmations = await contract.methods.requiredBlockConfirmations().call()
logger.debug( logger.debug({ contractAddress, requiredBlockConfirmations }, 'Required block confirmations obtained')
{ contractAddress, requiredBlockConfirmations },
'Required block confirmations obtained'
)
return requiredBlockConfirmations return requiredBlockConfirmations
} catch (e) { } catch (e) {
throw new Error(`Required block confirmations cannot be obtained`) throw new Error(`Required block confirmations cannot be obtained`)

@ -6,13 +6,7 @@ function strip0x(input) {
return input.replace(/^0x/, '') return input.replace(/^0x/, '')
} }
function createMessage({ function createMessage({ recipient, value, transactionHash, bridgeAddress, expectedMessageLength }) {
recipient,
value,
transactionHash,
bridgeAddress,
expectedMessageLength
}) {
recipient = strip0x(recipient) recipient = strip0x(recipient)
assert.strictEqual(recipient.length, 20 * 2) assert.strictEqual(recipient.length, 20 * 2)
@ -50,10 +44,7 @@ function parseMessage(message) {
const contractAddressStart = txHashStart + txHashLength const contractAddressStart = txHashStart + txHashLength
const contractAddressLength = 32 * 2 const contractAddressLength = 32 * 2
const contractAddress = `0x${message.slice( const contractAddress = `0x${message.slice(contractAddressStart, contractAddressStart + contractAddressLength)}`
contractAddressStart,
contractAddressStart + contractAddressLength
)}`
return { return {
recipient, recipient,

@ -5,9 +5,7 @@ const Web3 = require('web3')
const retrySequence = [1, 2, 3, 5, 8, 13, 21, 34, 55, 60] const retrySequence = [1, 2, 3, 5, 8, 13, 21, 34, 55, 60]
function getRetrySequence(count) { function getRetrySequence(count) {
return count > retrySequence.length return count > retrySequence.length ? retrySequence[retrySequence.length - 1] : retrySequence[count - 1]
? retrySequence[retrySequence.length - 1]
: retrySequence[count - 1]
} }
async function syncForEach(array, callback) { async function syncForEach(array, callback) {
@ -23,9 +21,7 @@ function checkHTTPS(ALLOW_HTTP, logger) {
if (ALLOW_HTTP !== 'yes') { if (ALLOW_HTTP !== 'yes') {
throw new Error(`http is not allowed: ${url}`) throw new Error(`http is not allowed: ${url}`)
} else { } else {
logger.warn( logger.warn(`You are using http (${url}) on ${network} network. In production https must be used instead.`)
`You are using http (${url}) on ${network} network. In production https must be used instead.`
)
} }
} }
} }
@ -38,16 +34,10 @@ async function waitForFunds(web3, address, minimumBalance, cb, logger) {
logger.debug('Getting balance of validator account') logger.debug('Getting balance of validator account')
const newBalance = web3.utils.toBN(await web3.eth.getBalance(address)) const newBalance = web3.utils.toBN(await web3.eth.getBalance(address))
if (newBalance.gte(minimumBalance)) { if (newBalance.gte(minimumBalance)) {
logger.debug( logger.debug({ balance: newBalance, minimumBalance }, 'Validator has minimum necessary balance')
{ balance: newBalance, minimumBalance },
'Validator has minimum necessary balance'
)
cb(newBalance) cb(newBalance)
} else { } else {
logger.debug( logger.debug({ balance: newBalance, minimumBalance }, 'Balance of validator is still less than the minimum')
{ balance: newBalance, minimumBalance },
'Balance of validator is still less than the minimum'
)
retry() retry()
} }
}, },
@ -99,9 +89,7 @@ function add0xPrefix(s) {
} }
function privateKeyToAddress(privateKey) { function privateKeyToAddress(privateKey) {
return privateKey return privateKey ? new Web3().eth.accounts.privateKeyToAccount(add0xPrefix(privateKey)).address : null
? new Web3().eth.accounts.privateKeyToAccount(add0xPrefix(privateKey)).address
: null
} }
function nonceError(e) { function nonceError(e) {

@ -72,10 +72,7 @@ async function runMain({ sendToQueue }) {
async function getLastProcessedBlock() { async function getLastProcessedBlock() {
const result = await redis.get(lastBlockRedisKey) const result = await redis.get(lastBlockRedisKey)
logger.debug( logger.debug({ fromRedis: result, fromConfig: lastProcessedBlock.toString() }, 'Last Processed block obtained')
{ fromRedis: result, fromConfig: lastProcessedBlock.toString() },
'Last Processed block obtained'
)
lastProcessedBlock = result ? toBN(result) : lastProcessedBlock lastProcessedBlock = result ? toBN(result) : lastProcessedBlock
} }
@ -146,10 +143,7 @@ async function main({ sendToQueue }) {
} }
} }
logger.debug( logger.debug({ lastProcessedBlock: lastBlockToProcess.toString() }, 'Updating last processed block')
{ lastProcessedBlock: lastBlockToProcess.toString() },
'Updating last processed block'
)
await updateLastProcessedBlock(lastBlockToProcess) await updateLastProcessedBlock(lastBlockToProcess)
} catch (e) { } catch (e) {
logger.error(e) logger.error(e)

@ -2,11 +2,7 @@ const sinon = require('sinon')
const { expect } = require('chai') const { expect } = require('chai')
const proxyquire = require('proxyquire').noPreserveCache() const proxyquire = require('proxyquire').noPreserveCache()
const Web3Utils = require('web3-utils') const Web3Utils = require('web3-utils')
const { const { fetchGasPrice, gasPriceWithinLimits, normalizeGasPrice } = require('../src/services/gasPrice')
fetchGasPrice,
gasPriceWithinLimits,
normalizeGasPrice
} = require('../src/services/gasPrice')
const { DEFAULT_UPDATE_INTERVAL, GAS_PRICE_BOUNDARIES } = require('../src/utils/constants') const { DEFAULT_UPDATE_INTERVAL, GAS_PRICE_BOUNDARIES } = require('../src/utils/constants')
describe('gasPrice', () => { describe('gasPrice', () => {
@ -94,12 +90,8 @@ describe('gasPrice', () => {
// then // then
expect(process.env.HOME_GAS_PRICE_UPDATE_INTERVAL).to.equal('15000') expect(process.env.HOME_GAS_PRICE_UPDATE_INTERVAL).to.equal('15000')
expect(process.env.HOME_GAS_PRICE_UPDATE_INTERVAL).to.not.equal( expect(process.env.HOME_GAS_PRICE_UPDATE_INTERVAL).to.not.equal(DEFAULT_UPDATE_INTERVAL.toString())
DEFAULT_UPDATE_INTERVAL.toString() expect(utils.setIntervalAndRun.args[0][1]).to.equal(process.env.HOME_GAS_PRICE_UPDATE_INTERVAL.toString())
)
expect(utils.setIntervalAndRun.args[0][1]).to.equal(
process.env.HOME_GAS_PRICE_UPDATE_INTERVAL.toString()
)
}) })
it('should call setIntervalAndRun with FOREIGN_GAS_PRICE_UPDATE_INTERVAL interval value on Foreign', async () => { it('should call setIntervalAndRun with FOREIGN_GAS_PRICE_UPDATE_INTERVAL interval value on Foreign', async () => {
// given // given
@ -111,12 +103,8 @@ describe('gasPrice', () => {
// then // then
expect(process.env.FOREIGN_GAS_PRICE_UPDATE_INTERVAL).to.equal('15000') expect(process.env.FOREIGN_GAS_PRICE_UPDATE_INTERVAL).to.equal('15000')
expect(process.env.HOME_GAS_PRICE_UPDATE_INTERVAL).to.not.equal( expect(process.env.HOME_GAS_PRICE_UPDATE_INTERVAL).to.not.equal(DEFAULT_UPDATE_INTERVAL.toString())
DEFAULT_UPDATE_INTERVAL.toString() expect(utils.setIntervalAndRun.args[0][1]).to.equal(process.env.FOREIGN_GAS_PRICE_UPDATE_INTERVAL.toString())
)
expect(utils.setIntervalAndRun.args[0][1]).to.equal(
process.env.FOREIGN_GAS_PRICE_UPDATE_INTERVAL.toString()
)
}) })
it('should call setIntervalAndRun with default interval value on Home', async () => { it('should call setIntervalAndRun with default interval value on Home', async () => {
// given // given

@ -148,8 +148,7 @@ describe('message utils', () => {
const transactionHash = '0x4a298455c1ccb17de77718fc045a876e1b4e063afaad361dcdef142a8ee48d5a' const transactionHash = '0x4a298455c1ccb17de77718fc045a876e1b4e063afaad361dcdef142a8ee48d5a'
// when // when
const messageThunk = () => const messageThunk = () => createMessage({ recipient, value, transactionHash, expectedMessageLength })
createMessage({ recipient, value, transactionHash, expectedMessageLength })
// then // then
expect(messageThunk).to.throw() expect(messageThunk).to.throw()
@ -162,8 +161,7 @@ describe('message utils', () => {
const transactionHash = '0x4a298455c1ccb17de77718fc045a876e1b4e063afaad361dcdef142a8ee48d5a' const transactionHash = '0x4a298455c1ccb17de77718fc045a876e1b4e063afaad361dcdef142a8ee48d5a'
// when // when
const messageThunk = () => const messageThunk = () => createMessage({ recipient, value, transactionHash, expectedMessageLength })
createMessage({ recipient, value, transactionHash, expectedMessageLength })
// then // then
expect(messageThunk).to.throw() expect(messageThunk).to.throw()
@ -176,8 +174,7 @@ describe('message utils', () => {
const transactionHash = '0x4a298455c1ccb17de77718fc045a876e1b4e063afaad361dcdef142a8ee48d5' const transactionHash = '0x4a298455c1ccb17de77718fc045a876e1b4e063afaad361dcdef142a8ee48d5'
// when // when
const messageThunk = () => const messageThunk = () => createMessage({ recipient, value, transactionHash, expectedMessageLength })
createMessage({ recipient, value, transactionHash, expectedMessageLength })
// then // then
expect(messageThunk).to.throw() expect(messageThunk).to.throw()
@ -190,8 +187,7 @@ describe('message utils', () => {
const transactionHash = '0x4a298455c1ccb17de77718fc045a876e1b4e063afaad361dcdef142a8ee48d5aa' const transactionHash = '0x4a298455c1ccb17de77718fc045a876e1b4e063afaad361dcdef142a8ee48d5aa'
// when // when
const messageThunk = () => const messageThunk = () => createMessage({ recipient, value, transactionHash, expectedMessageLength })
createMessage({ recipient, value, transactionHash, expectedMessageLength })
// then // then
expect(messageThunk).to.throw() expect(messageThunk).to.throw()
@ -232,8 +228,7 @@ describe('message utils', () => {
// given // given
const originalRecipient = '0xe3D952Ad4B96A756D65790393128FA359a7CD888' const originalRecipient = '0xe3D952Ad4B96A756D65790393128FA359a7CD888'
const originalValue = '0x2a' const originalValue = '0x2a'
const originalTransactionHash = const originalTransactionHash = '0x4a298455c1ccb17de77718fc045a876e1b4e063afaad361dcdef142a8ee48d5a'
'0x4a298455c1ccb17de77718fc045a876e1b4e063afaad361dcdef142a8ee48d5a'
const originalBridgeAddress = '0xfA79875FB0828c1FBD438583ED23fF5a956D80a1' const originalBridgeAddress = '0xfA79875FB0828c1FBD438583ED23fF5a956D80a1'
// when // when

@ -74,9 +74,7 @@ class MetaMask extends Page {
await this.setNetwork(user.networkID) await this.setNetwork(user.networkID)
await super.clickWithWait(popupAccount) await super.clickWithWait(popupAccount)
await this.driver.executeScript( await this.driver.executeScript(
"document.getElementsByClassName('dropdown-menu-item')[" + "document.getElementsByClassName('dropdown-menu-item')[" + user.accountOrderInMetamask + '].click();'
user.accountOrderInMetamask +
'].click();'
) )
await this.switchToNextPage() await this.switchToNextPage()
return true return true
@ -89,9 +87,7 @@ class MetaMask extends Page {
try { try {
await super.clickWithWait(popupAccount) await super.clickWithWait(popupAccount)
await this.driver.executeScript( await this.driver.executeScript(
"document.getElementsByClassName('dropdown-menu-item')[" + "document.getElementsByClassName('dropdown-menu-item')[" + (accountOrderNumber + 1) + '].click();'
(accountOrderNumber + 1) +
'].click();'
) )
accountOrderNumber++ accountOrderNumber++
return true return true
@ -121,8 +117,7 @@ class MetaMask extends Page {
try { try {
await super.clickWithWait(popupNetwork) await super.clickWithWait(popupNetwork)
const orderNumber = networks.indexOf(provider) const orderNumber = networks.indexOf(provider)
const script = const script = "document.getElementsByClassName('dropdown-menu-item')[" + orderNumber + '].click();'
"document.getElementsByClassName('dropdown-menu-item')[" + orderNumber + '].click();'
if (orderNumber < 0) await this.addNetwork(provider) if (orderNumber < 0) await this.addNetwork(provider)
else await this.driver.executeScript(script) else await this.driver.executeScript(script)
return true return true

@ -59,22 +59,14 @@ test.describe('e2e-test for bridge.poa, version 1.5.0', async function() {
foreignBalanceBefore = await mainPage.getForeignPOABalance() foreignBalanceBefore = await mainPage.getForeignPOABalance()
console.log('foreignBalanceBefore = ' + foreignBalanceBefore) console.log('foreignBalanceBefore = ' + foreignBalanceBefore)
const result = foreignBalanceBefore === 0 const result = foreignBalanceBefore === 0
return await assert.strictEqual( return await assert.strictEqual(result, true, 'Test FAILED.Foreign POA balance is zero or not displayed ')
result,
true,
'Test FAILED.Foreign POA balance is zero or not displayed '
)
}) })
test.it('Main page: home POA balance is displayed', async () => { test.it('Main page: home POA balance is displayed', async () => {
homeBalanceBefore = await mainPage.getHomePOABalance() homeBalanceBefore = await mainPage.getHomePOABalance()
console.log('homeBalanceBefore = ' + homeBalanceBefore) console.log('homeBalanceBefore = ' + homeBalanceBefore)
const result = homeBalanceBefore !== 0 const result = homeBalanceBefore !== 0
return await assert.strictEqual( return await assert.strictEqual(result, true, 'Test FAILED.Home POA balance is zero or not displayed ')
result,
true,
'Test FAILED.Home POA balance is zero or not displayed '
)
}) })
test.it('User is able to send tokens from Home account to Foreign account', async () => { test.it('User is able to send tokens from Home account to Foreign account', async () => {
@ -93,16 +85,10 @@ test.describe('e2e-test for bridge.poa, version 1.5.0', async function() {
console.log('shouldBe = ' + shouldBe) console.log('shouldBe = ' + shouldBe)
const result = Math.abs(shouldBe - newHomeBalance) < maxAmountPerTransactionLimit / 100 const result = Math.abs(shouldBe - newHomeBalance) < maxAmountPerTransactionLimit / 100
homeBalanceBefore = newHomeBalance homeBalanceBefore = newHomeBalance
return await assert.strictEqual( return await assert.strictEqual(result, true, 'Test FAILED.Home POA balance is not correct after transaction')
result,
true,
'Test FAILED.Home POA balance is not correct after transaction'
)
}) })
test.it( test.it('Foreign account has received correct amount of tokens after transaction ', async () => {
'Foreign account has received correct amount of tokens after transaction ',
async () => {
const newForeignBalance = await mainPage.getForeignPOABalance() const newForeignBalance = await mainPage.getForeignPOABalance()
const shouldBe = foreignBalanceBefore + maxAmountPerTransactionLimit const shouldBe = foreignBalanceBefore + maxAmountPerTransactionLimit
@ -110,13 +96,8 @@ test.describe('e2e-test for bridge.poa, version 1.5.0', async function() {
console.log('shouldBe = ' + shouldBe) console.log('shouldBe = ' + shouldBe)
const result = Math.abs(shouldBe - newForeignBalance) < maxAmountPerTransactionLimit / 100 const result = Math.abs(shouldBe - newForeignBalance) < maxAmountPerTransactionLimit / 100
return await assert.strictEqual( return await assert.strictEqual(result, true, 'Test FAILED. Foreign POA balance is not correct after transaction')
result, })
true,
'Test FAILED. Foreign POA balance is not correct after transaction'
)
}
)
test.it('User is able to send tokens from Foreign account to Home account', async () => { test.it('User is able to send tokens from Foreign account to Home account', async () => {
await foreignAccount.setMetaMaskNetwork() await foreignAccount.setMetaMaskNetwork()
@ -135,11 +116,7 @@ test.describe('e2e-test for bridge.poa, version 1.5.0', async function() {
console.log('newForeignBalance = ' + newForeignBalance) console.log('newForeignBalance = ' + newForeignBalance)
console.log('shouldBe = ' + shouldBe) console.log('shouldBe = ' + shouldBe)
const result = Math.abs(shouldBe - newForeignBalance) < maxAmountPerTransactionLimit / 100 const result = Math.abs(shouldBe - newForeignBalance) < maxAmountPerTransactionLimit / 100
return await assert.strictEqual( return await assert.strictEqual(result, true, 'Test FAILED.Foreign POA balance is not correct after transaction')
result,
true,
'Test FAILED.Foreign POA balance is not correct after transaction'
)
}) })
test.it('Home account has received correct amount of tokens after transaction', async () => { test.it('Home account has received correct amount of tokens after transaction', async () => {
@ -148,11 +125,7 @@ test.describe('e2e-test for bridge.poa, version 1.5.0', async function() {
console.log('newHomeBalance = ' + newHomeBalance) console.log('newHomeBalance = ' + newHomeBalance)
console.log('shouldBe = ' + shouldBe) console.log('shouldBe = ' + shouldBe)
const result = Math.abs(shouldBe - newHomeBalance) < maxAmountPerTransactionLimit / 100 const result = Math.abs(shouldBe - newHomeBalance) < maxAmountPerTransactionLimit / 100
return await assert.strictEqual( return await assert.strictEqual(result, true, 'Test FAILED.Home POA balance is not correct after transaction')
result,
true,
'Test FAILED.Home POA balance is not correct after transaction'
)
}) })
}) })
@ -173,22 +146,14 @@ test.describe('e2e-test for bridge.poa, version 1.5.0', async function() {
foreignBalanceBefore = await mainPage.getForeignPOABalance() foreignBalanceBefore = await mainPage.getForeignPOABalance()
console.log('foreignBalanceBefore = ' + foreignBalanceBefore) console.log('foreignBalanceBefore = ' + foreignBalanceBefore)
const result = foreignBalanceBefore === 0 const result = foreignBalanceBefore === 0
return await assert.strictEqual( return await assert.strictEqual(result, true, 'Test FAILED. Foreign erc20 balance is not zero')
result,
true,
'Test FAILED. Foreign erc20 balance is not zero'
)
}) })
test.it('Main page: home erc20 balance is displayed', async () => { test.it('Main page: home erc20 balance is displayed', async () => {
homeBalanceBefore = await mainPage.getHomePOABalance() homeBalanceBefore = await mainPage.getHomePOABalance()
console.log('homeBalanceBefore = ' + homeBalanceBefore) console.log('homeBalanceBefore = ' + homeBalanceBefore)
const result = homeBalanceBefore !== 0 const result = homeBalanceBefore !== 0
return await assert.strictEqual( return await assert.strictEqual(result, true, 'Test FAILED. Home erc20 balance is zero or not displayed ')
result,
true,
'Test FAILED. Home erc20 balance is zero or not displayed '
)
}) })
test.it('User is able to send tokens from Foreign account to Home account ', async () => { test.it('User is able to send tokens from Foreign account to Home account ', async () => {
@ -208,11 +173,7 @@ test.describe('e2e-test for bridge.poa, version 1.5.0', async function() {
console.log('newForeignBalance = ' + newForeignBalance) console.log('newForeignBalance = ' + newForeignBalance)
console.log('shouldBe = ' + shouldBe) console.log('shouldBe = ' + shouldBe)
const result = Math.abs(shouldBe - newForeignBalance) < maxAmountPerTransactionLimit / 100 const result = Math.abs(shouldBe - newForeignBalance) < maxAmountPerTransactionLimit / 100
return await assert.strictEqual( return await assert.strictEqual(result, true, 'Test FAILED.Foreign POA balance is not correct after transaction')
result,
true,
'Test FAILED.Foreign POA balance is not correct after transaction'
)
}) })
test.it('Home account has received correct amount of tokens after transaction ', async () => { test.it('Home account has received correct amount of tokens after transaction ', async () => {
@ -221,11 +182,7 @@ test.describe('e2e-test for bridge.poa, version 1.5.0', async function() {
console.log('newHomeBalance = ' + newHomeBalance) console.log('newHomeBalance = ' + newHomeBalance)
console.log('shouldBe = ' + shouldBe) console.log('shouldBe = ' + shouldBe)
const result = Math.abs(shouldBe - newHomeBalance) < maxAmountPerTransactionLimit / 100 const result = Math.abs(shouldBe - newHomeBalance) < maxAmountPerTransactionLimit / 100
return await assert.strictEqual( return await assert.strictEqual(result, true, 'Test FAILED.Home POA balance is not correct after transaction')
result,
true,
'Test FAILED.Home POA balance is not correct after transaction'
)
}) })
test.it('User is able to send tokens from Home account to Foreign account ', async () => { test.it('User is able to send tokens from Home account to Foreign account ', async () => {
await homeAccount.setMetaMaskNetwork() await homeAccount.setMetaMaskNetwork()
@ -246,16 +203,10 @@ test.describe('e2e-test for bridge.poa, version 1.5.0', async function() {
console.log('shouldBe = ' + shouldBe) console.log('shouldBe = ' + shouldBe)
const result = Math.abs(shouldBe - newHomeBalance) < maxAmountPerTransactionLimit / 100 const result = Math.abs(shouldBe - newHomeBalance) < maxAmountPerTransactionLimit / 100
homeBalanceBefore = newHomeBalance homeBalanceBefore = newHomeBalance
return await assert.strictEqual( return await assert.strictEqual(result, true, 'Test FAILED.Home POA balance is not correct after transaction')
result,
true,
'Test FAILED.Home POA balance is not correct after transaction'
)
}) })
test.it( test.it('Foreign account has received correct amount of tokens after transaction ', async () => {
'Foreign account has received correct amount of tokens after transaction ',
async () => {
const newForeignBalance = await mainPage.getForeignPOABalance() const newForeignBalance = await mainPage.getForeignPOABalance()
const shouldBe = foreignBalanceBefore + maxAmountPerTransactionLimit const shouldBe = foreignBalanceBefore + maxAmountPerTransactionLimit
@ -263,13 +214,8 @@ test.describe('e2e-test for bridge.poa, version 1.5.0', async function() {
console.log('shouldBe = ' + shouldBe) console.log('shouldBe = ' + shouldBe)
const result = Math.abs(shouldBe - newForeignBalance) < maxAmountPerTransactionLimit / 100 const result = Math.abs(shouldBe - newForeignBalance) < maxAmountPerTransactionLimit / 100
return await assert.strictEqual( return await assert.strictEqual(result, true, 'Test FAILED. Foreign POA balance is not correct after transaction')
result, })
true,
'Test FAILED. Foreign POA balance is not correct after transaction'
)
}
)
}) })
test.describe('ERC TO NATIVE', async () => { test.describe('ERC TO NATIVE', async () => {
@ -297,11 +243,7 @@ test.describe('e2e-test for bridge.poa, version 1.5.0', async function() {
homeBalanceBefore = await mainPage.getHomePOABalance() homeBalanceBefore = await mainPage.getHomePOABalance()
console.log('homeBalanceBefore = ' + homeBalanceBefore) console.log('homeBalanceBefore = ' + homeBalanceBefore)
const result = homeBalanceBefore !== 0 const result = homeBalanceBefore !== 0
return await assert.strictEqual( return await assert.strictEqual(result, true, 'Test FAILED. Home erc20 balance is zero or not displayed ')
result,
true,
'Test FAILED. Home erc20 balance is zero or not displayed '
)
}) })
test.it('User is able to send tokens from Foreign account to Home account', async () => { test.it('User is able to send tokens from Foreign account to Home account', async () => {
@ -321,11 +263,7 @@ test.describe('e2e-test for bridge.poa, version 1.5.0', async function() {
console.log('newForeignBalance = ' + newForeignBalance) console.log('newForeignBalance = ' + newForeignBalance)
console.log('shouldBe = ' + shouldBe) console.log('shouldBe = ' + shouldBe)
const result = Math.abs(shouldBe - newForeignBalance) < maxAmountPerTransactionLimit / 100 const result = Math.abs(shouldBe - newForeignBalance) < maxAmountPerTransactionLimit / 100
return await assert.strictEqual( return await assert.strictEqual(result, true, 'Test FAILED.Foreign POA balance is not correct after transaction')
result,
true,
'Test FAILED.Foreign POA balance is not correct after transaction'
)
}) })
test.it('Home account has received correct amount of tokens after transaction', async () => { test.it('Home account has received correct amount of tokens after transaction', async () => {
@ -334,11 +272,7 @@ test.describe('e2e-test for bridge.poa, version 1.5.0', async function() {
console.log('newHomeBalance = ' + newHomeBalance) console.log('newHomeBalance = ' + newHomeBalance)
console.log('shouldBe = ' + shouldBe) console.log('shouldBe = ' + shouldBe)
const result = Math.abs(shouldBe - newHomeBalance) < maxAmountPerTransactionLimit / 100 const result = Math.abs(shouldBe - newHomeBalance) < maxAmountPerTransactionLimit / 100
return await assert.strictEqual( return await assert.strictEqual(result, true, 'Test FAILED.Home POA balance is not correct after transaction')
result,
true,
'Test FAILED.Home POA balance is not correct after transaction'
)
}) })
test.it('User is able to send tokens from Home account to Foreign account', async () => { test.it('User is able to send tokens from Home account to Foreign account', async () => {
await homeAccount.setMetaMaskNetwork() await homeAccount.setMetaMaskNetwork()
@ -359,11 +293,7 @@ test.describe('e2e-test for bridge.poa, version 1.5.0', async function() {
console.log('shouldBe = ' + shouldBe) console.log('shouldBe = ' + shouldBe)
const result = Math.abs(shouldBe - newHomeBalance) < maxAmountPerTransactionLimit / 100 const result = Math.abs(shouldBe - newHomeBalance) < maxAmountPerTransactionLimit / 100
homeBalanceBefore = newHomeBalance homeBalanceBefore = newHomeBalance
return await assert.strictEqual( return await assert.strictEqual(result, true, 'Test FAILED.Home POA balance is not correct after transaction')
result,
true,
'Test FAILED.Home POA balance is not correct after transaction'
)
}) })
test.it('Foreign account has received correct amount of tokens after transaction', async () => { test.it('Foreign account has received correct amount of tokens after transaction', async () => {
@ -374,11 +304,7 @@ test.describe('e2e-test for bridge.poa, version 1.5.0', async function() {
console.log('shouldBe = ' + shouldBe) console.log('shouldBe = ' + shouldBe)
const result = Math.abs(shouldBe - newForeignBalance) < maxAmountPerTransactionLimit / 100 const result = Math.abs(shouldBe - newForeignBalance) < maxAmountPerTransactionLimit / 100
return await assert.strictEqual( return await assert.strictEqual(result, true, 'Test FAILED. Foreign POA balance is not correct after transaction')
result,
true,
'Test FAILED. Foreign POA balance is not correct after transaction'
)
}) })
}) })
}) })

@ -2,9 +2,7 @@ const { addDecoratorsLegacy, disableEsLint, override } = require('customize-cra'
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin') const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin')
const disableModuleScopePlugin = () => config => { const disableModuleScopePlugin = () => config => {
config.resolve.plugins = config.resolve.plugins.filter( config.resolve.plugins = config.resolve.plugins.filter(plugin => !(plugin instanceof ModuleScopePlugin))
plugin => !(plugin instanceof ModuleScopePlugin)
)
return config return config
} }

@ -1,14 +1,5 @@
import React from 'react' import React from 'react'
import { import { Header, Bridge, RelayEvents, Footer, SweetAlert, Loading, StatusPage, StatisticsPage } from './components'
Header,
Bridge,
RelayEvents,
Footer,
SweetAlert,
Loading,
StatusPage,
StatisticsPage
} from './components'
import { Route } from 'react-router-dom' import { Route } from 'react-router-dom'
import './assets/stylesheets/application.css' import './assets/stylesheets/application.css'
import { Disclaimer } from './components' import { Disclaimer } from './components'
@ -45,11 +36,7 @@ export class App extends React.Component {
<div className={showMobileMenu ? 'mobile-menu-is-open' : ''}> <div className={showMobileMenu ? 'mobile-menu-is-open' : ''}>
<Route component={Loading} /> <Route component={Loading} />
<Route component={SweetAlert} /> <Route component={SweetAlert} />
<Route <Route render={() => <Header onMenuToggle={this.toggleMobileMenu} showMobileMenu={showMobileMenu} />} />
render={() => (
<Header onMenuToggle={this.toggleMobileMenu} showMobileMenu={showMobileMenu} />
)}
/>
<div className="app-container"> <div className="app-container">
{showMobileMenu && <Route render={() => <div className="mobile-menu-open" />} />} {showMobileMenu && <Route render={() => <div className="mobile-menu-open" />} />}
<Route exact path="/" component={Bridge} /> <Route exact path="/" component={Bridge} />

@ -87,9 +87,9 @@ export class Bridge extends React.Component {
} }
if (isGreaterThan(amount, homeStore.maxCurrentDeposit)) { if (isGreaterThan(amount, homeStore.maxCurrentDeposit)) {
alertStore.pushError( alertStore.pushError(
`The amount is above current daily limit.\nThe max deposit today: ${ `The amount is above current daily limit.\nThe max deposit today: ${homeStore.maxCurrentDeposit} ${
homeStore.maxCurrentDeposit homeStore.symbol
} ${homeStore.symbol}` }`
) )
return return
} }
@ -140,24 +140,22 @@ export class Bridge extends React.Component {
} }
if (!isExternalErc20 && isGreaterThan(amount, foreignStore.maxPerTx)) { if (!isExternalErc20 && isGreaterThan(amount, foreignStore.maxPerTx)) {
alertStore.pushError( alertStore.pushError(
`The amount is above maximum amount per transaction.\nThe max per transaction is: ${ `The amount is above maximum amount per transaction.\nThe max per transaction is: ${foreignStore.maxPerTx} ${
foreignStore.maxPerTx foreignStore.symbol
} ${foreignStore.symbol}` }`
) )
return return
} }
if (!isExternalErc20 && isGreaterThan(amount, foreignStore.maxCurrentDeposit)) { if (!isExternalErc20 && isGreaterThan(amount, foreignStore.maxCurrentDeposit)) {
alertStore.pushError( alertStore.pushError(
`The amount is above current daily limit.\nThe max withdrawal today: ${ `The amount is above current daily limit.\nThe max withdrawal today: ${foreignStore.maxCurrentDeposit} ${
foreignStore.maxCurrentDeposit foreignStore.symbol
} ${foreignStore.symbol}` }`
) )
return return
} }
if (isGreaterThan(amount, foreignStore.balance)) { if (isGreaterThan(amount, foreignStore.balance)) {
alertStore.pushError( alertStore.pushError(`Insufficient token balance. Your balance is ${foreignStore.balance} ${foreignStore.symbol}`)
`Insufficient token balance. Your balance is ${foreignStore.balance} ${foreignStore.symbol}`
)
} else { } else {
try { try {
alertStore.setLoading(true) alertStore.setLoading(true)
@ -262,8 +260,7 @@ export class Bridge extends React.Component {
loadHomeDetails = () => { loadHomeDetails = () => {
const { web3Store, homeStore, bridgeMode } = this.props.RootStore const { web3Store, homeStore, bridgeMode } = this.props.RootStore
const isErcToErcMode = bridgeMode === BRIDGE_MODES.ERC_TO_ERC const isErcToErcMode = bridgeMode === BRIDGE_MODES.ERC_TO_ERC
const isExternalErc20 = const isExternalErc20 = bridgeMode === BRIDGE_MODES.ERC_TO_ERC || bridgeMode === BRIDGE_MODES.ERC_TO_NATIVE
bridgeMode === BRIDGE_MODES.ERC_TO_ERC || bridgeMode === BRIDGE_MODES.ERC_TO_NATIVE
const modalData = { const modalData = {
isHome: true, isHome: true,

@ -2,11 +2,7 @@ import React from 'react'
export const BridgeAddress = ({ isHome, reverse }) => { export const BridgeAddress = ({ isHome, reverse }) => {
const getAddress = () => const getAddress = () =>
isHome ? ( isHome ? <div className="home-address-container" /> : <div className="foreign-address-container" />
<div className="home-address-container" />
) : (
<div className="foreign-address-container" />
)
return isHome ? ( return isHome ? (
<div className="bridge-home"> <div className="bridge-home">

@ -2,15 +2,7 @@ import React from 'react'
import numeral from 'numeral' import numeral from 'numeral'
import { InfoIcon } from './icons/InfoIcon' import { InfoIcon } from './icons/InfoIcon'
export const BridgeNetwork = ({ export const BridgeNetwork = ({ balance, currency, isHome, networkSubtitle, networkTitle, showModal, side }) => {
balance,
currency,
isHome,
networkSubtitle,
networkTitle,
showModal,
side
}) => {
const containerName = isHome ? 'home' : 'foreign' const containerName = isHome ? 'home' : 'foreign'
const formattedBalance = isNaN(numeral(balance).format('0.00', Math.floor)) const formattedBalance = isNaN(numeral(balance).format('0.00', Math.floor))
? numeral(0).format('0,0.00', Math.floor) ? numeral(0).format('0,0.00', Math.floor)

@ -2,19 +2,9 @@ import React from 'react'
import numeral from 'numeral' import numeral from 'numeral'
import { DataBlock } from './DataBlock' import { DataBlock } from './DataBlock'
export const Configuration = ({ export const Configuration = ({ requiredSignatures, authorities, symbol, maxSingleDeposit, maxTotalBalance }) => (
requiredSignatures,
authorities,
symbol,
maxSingleDeposit,
maxTotalBalance
}) => (
<div className="status-configuration-data"> <div className="status-configuration-data">
<DataBlock <DataBlock description="Required Signatures" value={numeral(requiredSignatures).format('0')} type="" />
description="Required Signatures"
value={numeral(requiredSignatures).format('0')}
type=""
/>
<div className="separator" /> <div className="separator" />
<DataBlock description="Authorities" value={numeral(authorities).format('0')} type="" /> <DataBlock description="Authorities" value={numeral(authorities).format('0')} type="" />
{maxSingleDeposit && {maxSingleDeposit &&

@ -12,22 +12,18 @@ export const Disclaimer = ({ onConfirmation }) => (
<br /> TokenBridge UI App Beta+ <br /> TokenBridge UI App Beta+
</span> </span>
<p className="disclaimer-description"> <p className="disclaimer-description">
Were launching our TokenBridge and our UI App on a beta-testing basis. While weve worked Were launching our TokenBridge and our UI App on a beta-testing basis. While weve worked long and hard to
long and hard to develop the core features of the software, we expect that our users may develop the core features of the software, we expect that our users may detect bugs and other issues. Help us
detect bugs and other issues. Help us improve by posting any difficulties to our improve by posting any difficulties to our
<a <a href="https://forum.poa.network/c/support/tokenbridge-support" target="_blank" rel="noopener noreferrer">
href="https://forum.poa.network/c/support/tokenbridge-support"
target="_blank"
rel="noopener noreferrer"
>
{' '} {' '}
support page support page
</a> </a>
.<br /> .<br />
<br /> <br />
Use of this app and the TokenBridge is at your own risk. Users may experience unexpected Use of this app and the TokenBridge is at your own risk. Users may experience unexpected delays, unexpected
delays, unexpected visual artifacts, unexpected loss of tokens or funds from improper app visual artifacts, unexpected loss of tokens or funds from improper app configuration, or other negative
configuration, or other negative outcomes. outcomes.
<br /> <br />
<br /> <br />
By hitting the "continue" button, you are representing that youve read our By hitting the "continue" button, you are representing that youve read our

@ -16,8 +16,7 @@ export const FeeStatistics = ({ depositFeeCollected, withdrawFeeCollected }) =>
dataTestid="deposit-fees-block" dataTestid="deposit-fees-block"
/> />
)} )}
{depositFeeCollected.shouldDisplay && {depositFeeCollected.shouldDisplay && withdrawFeeCollected.shouldDisplay && <div className="separator" />}
withdrawFeeCollected.shouldDisplay && <div className="separator" />}
{withdrawFeeCollected.shouldDisplay && ( {withdrawFeeCollected.shouldDisplay && (
<DataBlock <DataBlock
description="Withdrawal Fees" description="Withdrawal Fees"

@ -16,18 +16,12 @@ export class Header extends React.Component {
onMenuToggle, onMenuToggle,
RootStore: { alertStore, web3Store } RootStore: { alertStore, web3Store }
} = this.props } = this.props
const { const { REACT_APP_HOME_WITHOUT_EVENTS: HOME, REACT_APP_FOREIGN_WITHOUT_EVENTS: FOREIGN } = process.env
REACT_APP_HOME_WITHOUT_EVENTS: HOME, const withoutEvents = web3Store.metamaskNet.id === web3Store.homeNet.id.toString() ? yn(HOME) : yn(FOREIGN)
REACT_APP_FOREIGN_WITHOUT_EVENTS: FOREIGN
} = process.env
const withoutEvents =
web3Store.metamaskNet.id === web3Store.homeNet.id.toString() ? yn(HOME) : yn(FOREIGN)
return ( return (
<header className="header"> <header className="header">
{showMobileMenu ? ( {showMobileMenu ? <MobileMenu withoutEvents={withoutEvents} onMenuToggle={onMenuToggle} /> : null}
<MobileMenu withoutEvents={withoutEvents} onMenuToggle={onMenuToggle} />
) : null}
<div className="container"> <div className="container">
<Link to="/" onClick={showMobileMenu ? onMenuToggle : null} className="header-logo" /> <Link to="/" onClick={showMobileMenu ? onMenuToggle : null} className="header-logo" />
<HeaderMenu withoutEvents={withoutEvents} onMenuToggle={onMenuToggle} /> <HeaderMenu withoutEvents={withoutEvents} onMenuToggle={onMenuToggle} />

@ -13,10 +13,7 @@ export class Loading extends React.Component {
const progress = loadingStepIndex === 3 ? 100 : loadingStepIndex * 25 + blockConfirmations * 4 const progress = loadingStepIndex === 3 ? 100 : loadingStepIndex * 25 + blockConfirmations * 4
return ( return (
<div <div className={`loading-container ${loadingStepIndex > 0 ? 'mobile-container' : ''}`} style={style}>
className={`loading-container ${loadingStepIndex > 0 ? 'mobile-container' : ''}`}
style={style}
>
{loadingStepIndex > 0 && ( {loadingStepIndex > 0 && (
<ProgressRing <ProgressRing
confirmationNumber={blockConfirmations} confirmationNumber={blockConfirmations}
@ -28,9 +25,7 @@ export class Loading extends React.Component {
)} )}
{loadingStepIndex === 0 && <div className="loading-logo" />} {loadingStepIndex === 0 && <div className="loading-logo" />}
{loadingStepIndex === 0 && <div className="loading-i" />} {loadingStepIndex === 0 && <div className="loading-i" />}
{loadingStepIndex > 0 && ( {loadingStepIndex > 0 && <div className="loading-text">{loadingSteps[loadingStepIndex]}</div>}
<div className="loading-text">{loadingSteps[loadingStepIndex]}</div>
)}
{alertStore.showLoading && <PreventExit />} {alertStore.showLoading && <PreventExit />}
</div> </div>
) )

@ -48,11 +48,7 @@ export const NetworkDetails = ({
<p className="details-data-container"> <p className="details-data-container">
<span className="details-label">{networkTitle} Address</span> <span className="details-label">{networkTitle} Address</span>
<span className="details-description details-copy"> <span className="details-description details-copy">
<a <a className="details-description" href={getExplorerAddressUrl(address)} target="_blank">
className="details-description"
href={getExplorerAddressUrl(address)}
target="_blank"
>
{address.slice(0, 27).concat('...')} {address.slice(0, 27).concat('...')}
</a> </a>
<CopyToClipboard text={address}> <CopyToClipboard text={address}>
@ -90,11 +86,7 @@ export const NetworkDetails = ({
<p className="details-data-container"> <p className="details-data-container">
<span className="details-label">Token Address</span> <span className="details-label">Token Address</span>
<span className="details-description details-copy"> <span className="details-description details-copy">
<a <a className="details-description" href={getExplorerAddressUrl(tokenAddress)} target="_blank">
className="details-description"
href={getExplorerAddressUrl(tokenAddress)}
target="_blank"
>
{tokenAddress.slice(0, 27).concat('...')} {tokenAddress.slice(0, 27).concat('...')}
</a> </a>
<CopyToClipboard text={tokenAddress}> <CopyToClipboard text={tokenAddress}>

@ -34,12 +34,11 @@ export class NoWallet extends Component {
<div className="noWallet-alert-container"> <div className="noWallet-alert-container">
<h2 className="noWallet-title">Wallet not found</h2> <h2 className="noWallet-title">Wallet not found</h2>
<p className="noWallet-description"> <p className="noWallet-description">
A wallet is not installed. Before continue, please install one (AlphaWallet, Metamask A wallet is not installed. Before continue, please install one (AlphaWallet, Metamask or Nifty Wallet) and
or Nifty Wallet) and return to this page to continue using the application. return to this page to continue using the application.
</p> </p>
<p className="noWallet-description"> <p className="noWallet-description">
For further information on how to install any of both wallets, please click the For further information on how to install any of both wallets, please click the buttons below.
buttons below.
</p> </p>
<div className="noWallet-buttons"> <div className="noWallet-buttons">
<a <a

@ -107,9 +107,7 @@ export class RelayEvents extends React.Component {
} }
getHomeEvents = homeStore => { getHomeEvents = homeStore => {
return homeStore.events return homeStore.events.slice().map(({ event, transactionHash, blockNumber, returnValues }) => ({
.slice()
.map(({ event, transactionHash, blockNumber, returnValues }) => ({
color: this.colors[event], color: this.colors[event],
eventName: event, eventName: event,
transactionHash, transactionHash,
@ -120,9 +118,7 @@ export class RelayEvents extends React.Component {
} }
getForeignEvents = foreignStore => { getForeignEvents = foreignStore => {
return foreignStore.events return foreignStore.events.slice().map(({ event, transactionHash, signedTxHash, blockNumber, returnValues }) => {
.slice()
.map(({ event, transactionHash, signedTxHash, blockNumber, returnValues }) => {
return { return {
color: this.colors[event], color: this.colors[event],
eventName: event, eventName: event,
@ -143,12 +139,8 @@ export class RelayEvents extends React.Component {
const { selectedList } = this.state const { selectedList } = this.state
const home = this.getHomeEvents(homeStore, foreignStore) const home = this.getHomeEvents(homeStore, foreignStore)
const foreign = this.getForeignEvents(foreignStore, homeStore) const foreign = this.getForeignEvents(foreignStore, homeStore)
const { const { REACT_APP_HOME_WITHOUT_EVENTS: HOME, REACT_APP_FOREIGN_WITHOUT_EVENTS: FOREIGN } = process.env
REACT_APP_HOME_WITHOUT_EVENTS: HOME, const withoutEvents = web3Store.metamaskNet.id === web3Store.homeNet.id.toString() ? yn(HOME) : yn(FOREIGN)
REACT_APP_FOREIGN_WITHOUT_EVENTS: FOREIGN
} = process.env
const withoutEvents =
web3Store.metamaskNet.id === web3Store.homeNet.id.toString() ? yn(HOME) : yn(FOREIGN)
return withoutEvents ? ( return withoutEvents ? (
<Redirect to="/" /> <Redirect to="/" />
@ -156,12 +148,8 @@ export class RelayEvents extends React.Component {
<div className="events-page"> <div className="events-page">
<div className="events-container"> <div className="events-container">
<EventsListHeader <EventsListHeader
handleChange={ handleChange={selectedList === this.homeValue ? this.handleChangeHome : this.handleChangeForeign}
selectedList === this.homeValue ? this.handleChangeHome : this.handleChangeForeign handleKeyDown={selectedList === this.homeValue ? this.handleKeyDownHome : this.handleKeyDownForeign}
}
handleKeyDown={
selectedList === this.homeValue ? this.handleKeyDownHome : this.handleKeyDownForeign
}
onChangeList={this.onChangeList} onChangeList={this.onChangeList}
selected={selectedList} selected={selectedList}
homeName={homeStore.networkName} homeName={homeStore.networkName}

@ -15,12 +15,8 @@ export class StatisticsPage extends React.Component {
const isNativeToErc = bridgeMode === BRIDGE_MODES.NATIVE_TO_ERC const isNativeToErc = bridgeMode === BRIDGE_MODES.NATIVE_TO_ERC
const leftTitle = isNativeToErc ? 'Deposits' : 'Withdraws' const leftTitle = isNativeToErc ? 'Deposits' : 'Withdraws'
const rightTitle = isNativeToErc ? 'Withdraws' : 'Deposits' const rightTitle = isNativeToErc ? 'Withdraws' : 'Deposits'
const { const { REACT_APP_HOME_WITHOUT_EVENTS: HOME, REACT_APP_FOREIGN_WITHOUT_EVENTS: FOREIGN } = process.env
REACT_APP_HOME_WITHOUT_EVENTS: HOME, const withoutEvents = web3Store.metamaskNet.id === web3Store.homeNet.id.toString() ? yn(HOME) : yn(FOREIGN)
REACT_APP_FOREIGN_WITHOUT_EVENTS: FOREIGN
} = process.env
const withoutEvents =
web3Store.metamaskNet.id === web3Store.homeNet.id.toString() ? yn(HOME) : yn(FOREIGN)
return withoutEvents ? ( return withoutEvents ? (
<Redirect to="/" /> <Redirect to="/" />
@ -32,9 +28,7 @@ export class StatisticsPage extends React.Component {
<span className="statistics-bridge-title statistics-title">Bridge Statistics</span> <span className="statistics-bridge-title statistics-title">Bridge Statistics</span>
<BridgeStatistics <BridgeStatistics
users={homeStore.statistics.finished ? homeStore.statistics.users.size : ''} users={homeStore.statistics.finished ? homeStore.statistics.users.size : ''}
totalBridged={ totalBridged={homeStore.statistics.finished ? homeStore.statistics.totalBridged.toString() : ''}
homeStore.statistics.finished ? homeStore.statistics.totalBridged.toString() : ''
}
homeBalance={homeStore.balance} homeBalance={homeStore.balance}
homeSymbol={homeStore.symbol} homeSymbol={homeStore.symbol}
homeNativeSupplyTitle={isNativeToErc} homeNativeSupplyTitle={isNativeToErc}
@ -44,8 +38,7 @@ export class StatisticsPage extends React.Component {
</div> </div>
{homeStore.depositFeeCollected.finished && {homeStore.depositFeeCollected.finished &&
homeStore.withdrawFeeCollected.finished && homeStore.withdrawFeeCollected.finished &&
(homeStore.depositFeeCollected.shouldDisplay || (homeStore.depositFeeCollected.shouldDisplay || homeStore.withdrawFeeCollected.shouldDisplay) && (
homeStore.withdrawFeeCollected.shouldDisplay) && (
<FeeStatistics <FeeStatistics
depositFeeCollected={homeStore.depositFeeCollected} depositFeeCollected={homeStore.depositFeeCollected}
withdrawFeeCollected={homeStore.withdrawFeeCollected} withdrawFeeCollected={homeStore.withdrawFeeCollected}
@ -61,9 +54,7 @@ export class StatisticsPage extends React.Component {
/> />
</div> </div>
<div className="statistics-withdraw-container"> <div className="statistics-withdraw-container">
<span className="statistics-withdraw-title statistics-title"> <span className="statistics-withdraw-title statistics-title">Tokens {rightTitle}</span>
Tokens {rightTitle}
</span>
<TransactionsStatistics <TransactionsStatistics
txNumber={homeStore.statistics.finished ? homeStore.statistics.withdraws : ''} txNumber={homeStore.statistics.finished ? homeStore.statistics.withdraws : ''}
type={foreignStore.symbol} type={foreignStore.symbol}

@ -10,20 +10,14 @@ export class StatusPage extends React.Component {
render() { render() {
const { homeStore, foreignStore, web3Store } = this.props.RootStore const { homeStore, foreignStore, web3Store } = this.props.RootStore
const isHome = web3Store.metamaskNet.id.toString() === web3Store.homeNet.id.toString() const isHome = web3Store.metamaskNet.id.toString() === web3Store.homeNet.id.toString()
const requiredSignatures = isHome const requiredSignatures = isHome ? homeStore.requiredSignatures : foreignStore.requiredSignatures
? homeStore.requiredSignatures
: foreignStore.requiredSignatures
const authorities = isHome ? homeStore.validatorsCount : foreignStore.validatorsCount const authorities = isHome ? homeStore.validatorsCount : foreignStore.validatorsCount
const symbol = isHome ? homeStore.symbol : foreignStore.symbol const symbol = isHome ? homeStore.symbol : foreignStore.symbol
const maxSingleDeposit = isHome ? homeStore.maxPerTx : foreignStore.maxPerTx const maxSingleDeposit = isHome ? homeStore.maxPerTx : foreignStore.maxPerTx
const maxTotalBalance = isHome ? homeStore.maxCurrentDeposit : foreignStore.maxCurrentDeposit const maxTotalBalance = isHome ? homeStore.maxCurrentDeposit : foreignStore.maxCurrentDeposit
const validatorsList = isHome ? homeStore.validators : foreignStore.validators const validatorsList = isHome ? homeStore.validators : foreignStore.validators
const { const { REACT_APP_HOME_WITHOUT_EVENTS: HOME, REACT_APP_FOREIGN_WITHOUT_EVENTS: FOREIGN } = process.env
REACT_APP_HOME_WITHOUT_EVENTS: HOME, const withoutEvents = web3Store.metamaskNet.id === web3Store.homeNet.id.toString() ? yn(HOME) : yn(FOREIGN)
REACT_APP_FOREIGN_WITHOUT_EVENTS: FOREIGN
} = process.env
const withoutEvents =
web3Store.metamaskNet.id === web3Store.homeNet.id.toString() ? yn(HOME) : yn(FOREIGN)
return ( return (
<div className="status-page"> <div className="status-page">

@ -6,10 +6,6 @@ export const TransactionsStatistics = ({ txNumber, value, type }) => (
<div className="statistics-bridge-data"> <div className="statistics-bridge-data">
<DataBlock description="Transactions" value={numeral(txNumber).format('0,0 a')} type="" /> <DataBlock description="Transactions" value={numeral(txNumber).format('0,0 a')} type="" />
<div className="separator" /> <div className="separator" />
<DataBlock <DataBlock description="Total Value" value={numeral(value).format('0,0.00 a', Math.floor)} type={type} />
description="Total Value"
value={numeral(value).format('0,0.00 a', Math.floor)}
type={type}
/>
</div> </div>
) )

@ -42,9 +42,8 @@ export const TransferAlert = ({
<p className="transfer-description" data-testid="transfer-description"> <p className="transfer-description" data-testid="transfer-description">
<strong>{fee && `Fee: ${fee.toString()}%`}</strong> <strong>{fee && `Fee: ${fee.toString()}%`}</strong>
<br /> <br />
Please confirm that you would like to send <strong>{formattedFromAmount}</strong>{' '} Please confirm that you would like to send <strong>{formattedFromAmount}</strong> {fromCurrency} from {from}{' '}
{fromCurrency} from {from} to receive <strong>{formattedToAmount}</strong> {toCurrency} on{' '} to receive <strong>{formattedToAmount}</strong> {toCurrency} on {to}.
{to}.
</p> </p>
<div className="transfer-buttons"> <div className="transfer-buttons">
<button className="transfer-confirm" onClick={onConfirmation}> <button className="transfer-confirm" onClick={onConfirmation}>

@ -12,9 +12,7 @@ export class Wallet extends React.Component {
const explorerAddressUrl = isHome const explorerAddressUrl = isHome
? homeStore.getExplorerAddressUrl(address) ? homeStore.getExplorerAddressUrl(address)
: foreignStore.getExplorerAddressUrl(address) : foreignStore.getExplorerAddressUrl(address)
const completed = isHome const completed = isHome ? homeStore.getDailyQuotaCompleted() : foreignStore.getDailyQuotaCompleted()
? homeStore.getDailyQuotaCompleted()
: foreignStore.getDailyQuotaCompleted()
const width = `${completed}%` const width = `${completed}%`
const wallet = const wallet =

@ -23,10 +23,7 @@ describe('FeeStatistics', () => {
// When // When
const { queryByTestId } = render( const { queryByTestId } = render(
<FeeStatistics <FeeStatistics depositFeeCollected={depositFeeCollected} withdrawFeeCollected={withdrawFeeCollected} />
depositFeeCollected={depositFeeCollected}
withdrawFeeCollected={withdrawFeeCollected}
/>
) )
// Then // Then
@ -61,10 +58,7 @@ describe('FeeStatistics', () => {
// When // When
const { queryByTestId } = render( const { queryByTestId } = render(
<FeeStatistics <FeeStatistics depositFeeCollected={depositFeeCollected} withdrawFeeCollected={withdrawFeeCollected} />
depositFeeCollected={depositFeeCollected}
withdrawFeeCollected={withdrawFeeCollected}
/>
) )
// Then // Then
@ -96,10 +90,7 @@ describe('FeeStatistics', () => {
// When // When
const { queryByTestId } = render( const { queryByTestId } = render(
<FeeStatistics <FeeStatistics depositFeeCollected={depositFeeCollected} withdrawFeeCollected={withdrawFeeCollected} />
depositFeeCollected={depositFeeCollected}
withdrawFeeCollected={withdrawFeeCollected}
/>
) )
// Then // Then
@ -131,10 +122,7 @@ describe('FeeStatistics', () => {
// When // When
const { queryByTestId } = render( const { queryByTestId } = render(
<FeeStatistics <FeeStatistics depositFeeCollected={depositFeeCollected} withdrawFeeCollected={withdrawFeeCollected} />
depositFeeCollected={depositFeeCollected}
withdrawFeeCollected={withdrawFeeCollected}
/>
) )
// Then // Then

@ -4,16 +4,7 @@ import numeral from 'numeral'
import { CopyIcon } from '../icons/CopyIcon' import { CopyIcon } from '../icons/CopyIcon'
import { CopyToClipboard } from 'react-copy-to-clipboard' import { CopyToClipboard } from 'react-copy-to-clipboard'
export const Event = ({ export const Event = ({ color, eventName, transactionHash, recipient, value, blockNumber, txUrl, accountUrl }) => (
color,
eventName,
transactionHash,
recipient,
value,
blockNumber,
txUrl,
accountUrl
}) => (
<div> <div>
<div className="event"> <div className="event">
<div className="event-tx-container txhash-column"> <div className="event-tx-container txhash-column">

@ -186,28 +186,18 @@ class ForeignStore {
this.rootStore.bridgeMode === BRIDGE_MODES.ERC_TO_NATIVE this.rootStore.bridgeMode === BRIDGE_MODES.ERC_TO_NATIVE
? await getErc20TokenAddress(this.foreignBridge) ? await getErc20TokenAddress(this.foreignBridge)
: await getErc677TokenAddress(this.foreignBridge) : await getErc677TokenAddress(this.foreignBridge)
this.tokenContract = new this.foreignWeb3.eth.Contract( this.tokenContract = new this.foreignWeb3.eth.Contract(ERC677_BRIDGE_TOKEN_ABI, this.tokenAddress)
ERC677_BRIDGE_TOKEN_ABI,
this.tokenAddress
)
this.tokenType = await getTokenType(this.tokenContract, this.FOREIGN_BRIDGE_ADDRESS) this.tokenType = await getTokenType(this.tokenContract, this.FOREIGN_BRIDGE_ADDRESS)
const alternativeContract = new this.foreignWeb3.eth.Contract( const alternativeContract = new this.foreignWeb3.eth.Contract(ERC20_BYTES32_ABI, this.tokenAddress)
ERC20_BYTES32_ABI,
this.tokenAddress
)
try { try {
this.symbol = await getSymbol(this.tokenContract) this.symbol = await getSymbol(this.tokenContract)
} catch (e) { } catch (e) {
this.symbol = this.foreignWeb3.utils this.symbol = this.foreignWeb3.utils.hexToAscii(await getSymbol(alternativeContract)).replace(/\u0000*$/, '')
.hexToAscii(await getSymbol(alternativeContract))
.replace(/\u0000*$/, '')
} }
try { try {
this.tokenName = await getName(this.tokenContract) this.tokenName = await getName(this.tokenContract)
} catch (e) { } catch (e) {
this.tokenName = this.foreignWeb3.utils this.tokenName = this.foreignWeb3.utils.hexToAscii(await getName(alternativeContract)).replace(/\u0000*$/, '')
.hexToAscii(await getName(alternativeContract))
.replace(/\u0000*$/, '')
} }
this.tokenDecimals = await getDecimals(this.tokenContract) this.tokenDecimals = await getDecimals(this.tokenContract)
@ -269,17 +259,11 @@ class ForeignStore {
if (this.waitingForConfirmation.size) { if (this.waitingForConfirmation.size) {
const confirmationEvents = foreignEvents.filter( const confirmationEvents = foreignEvents.filter(
event => event =>
event.event === 'RelayedMessage' && event.event === 'RelayedMessage' && this.waitingForConfirmation.has(event.returnValues.transactionHash)
this.waitingForConfirmation.has(event.returnValues.transactionHash)
) )
confirmationEvents.forEach(async event => { confirmationEvents.forEach(async event => {
const TxReceipt = await this.getTxReceipt(event.transactionHash) const TxReceipt = await this.getTxReceipt(event.transactionHash)
if ( if (TxReceipt && TxReceipt.logs && TxReceipt.logs.length > 1 && this.waitingForConfirmation.size) {
TxReceipt &&
TxReceipt.logs &&
TxReceipt.logs.length > 1 &&
this.waitingForConfirmation.size
) {
this.alertStore.setLoadingStepIndex(3) this.alertStore.setLoadingStepIndex(3)
const urlExplorer = this.getExplorerTxUrl(event.transactionHash) const urlExplorer = this.getExplorerTxUrl(event.transactionHash)
const unitReceived = getUnit(this.rootStore.bridgeMode).unitForeign const unitReceived = getUnit(this.rootStore.bridgeMode).unitForeign
@ -397,10 +381,7 @@ class ForeignStore {
async getValidators() { async getValidators() {
try { try {
const foreignValidatorsAddress = await getValidatorContract(this.foreignBridge) const foreignValidatorsAddress = await getValidatorContract(this.foreignBridge)
this.foreignBridgeValidators = new this.foreignWeb3.eth.Contract( this.foreignBridgeValidators = new this.foreignWeb3.eth.Contract(BRIDGE_VALIDATORS_ABI, foreignValidatorsAddress)
BRIDGE_VALIDATORS_ABI,
foreignValidatorsAddress
)
this.requiredSignatures = await getRequiredSignatures(this.foreignBridgeValidators) this.requiredSignatures = await getRequiredSignatures(this.foreignBridgeValidators)
this.validatorsCount = await getValidatorCount(this.foreignBridgeValidators) this.validatorsCount = await getValidatorCount(this.foreignBridgeValidators)

@ -193,29 +193,19 @@ class HomeStore {
async getTokenInfo() { async getTokenInfo() {
try { try {
this.tokenAddress = await getErc677TokenAddress(this.homeBridge) this.tokenAddress = await getErc677TokenAddress(this.homeBridge)
this.tokenContract = new this.homeWeb3.eth.Contract( this.tokenContract = new this.homeWeb3.eth.Contract(ERC677_BRIDGE_TOKEN_ABI, this.tokenAddress)
ERC677_BRIDGE_TOKEN_ABI,
this.tokenAddress
)
this.symbol = await getSymbol(this.tokenContract) this.symbol = await getSymbol(this.tokenContract)
this.tokenName = await getName(this.tokenContract) this.tokenName = await getName(this.tokenContract)
const alternativeContract = new this.homeWeb3.eth.Contract( const alternativeContract = new this.homeWeb3.eth.Contract(ERC20_BYTES32_ABI, this.tokenAddress)
ERC20_BYTES32_ABI,
this.tokenAddress
)
try { try {
this.symbol = await getSymbol(this.tokenContract) this.symbol = await getSymbol(this.tokenContract)
} catch (e) { } catch (e) {
this.symbol = this.homeWeb3.utils this.symbol = this.homeWeb3.utils.hexToAscii(await getSymbol(alternativeContract)).replace(/\u0000*$/, '')
.hexToAscii(await getSymbol(alternativeContract))
.replace(/\u0000*$/, '')
} }
try { try {
this.tokenName = await getName(this.tokenContract) this.tokenName = await getName(this.tokenContract)
} catch (e) { } catch (e) {
this.tokenName = this.homeWeb3.utils this.tokenName = this.homeWeb3.utils.hexToAscii(await getName(alternativeContract)).replace(/\u0000*$/, '')
.hexToAscii(await getName(alternativeContract))
.replace(/\u0000*$/, '')
} }
this.tokenDecimals = await getDecimals(this.tokenContract) this.tokenDecimals = await getDecimals(this.tokenContract)
} catch (e) { } catch (e) {
@ -256,17 +246,11 @@ class HomeStore {
if (this.rootStore.bridgeMode === BRIDGE_MODES.ERC_TO_ERC) { if (this.rootStore.bridgeMode === BRIDGE_MODES.ERC_TO_ERC) {
this.balance = await getTotalSupply(this.tokenContract) this.balance = await getTotalSupply(this.tokenContract)
this.web3Store.getWeb3Promise.then(async () => { this.web3Store.getWeb3Promise.then(async () => {
this.userBalance = await getBalanceOf( this.userBalance = await getBalanceOf(this.tokenContract, this.web3Store.defaultAccount.address)
this.tokenContract,
this.web3Store.defaultAccount.address
)
balanceLoaded() balanceLoaded()
}) })
} else if (this.rootStore.bridgeMode === BRIDGE_MODES.ERC_TO_NATIVE) { } else if (this.rootStore.bridgeMode === BRIDGE_MODES.ERC_TO_NATIVE) {
const mintedCoins = await mintedTotallyByBridge( const mintedCoins = await mintedTotallyByBridge(this.blockRewardContract, this.HOME_BRIDGE_ADDRESS)
this.blockRewardContract,
this.HOME_BRIDGE_ADDRESS
)
const burntCoins = await totalBurntCoins(this.homeBridge) const burntCoins = await totalBurntCoins(this.homeBridge)
this.balance = fromDecimals(mintedCoins.minus(burntCoins).toString(10), this.tokenDecimals) this.balance = fromDecimals(mintedCoins.minus(burntCoins).toString(10), this.tokenDecimals)
} else { } else {
@ -388,14 +372,8 @@ class HomeStore {
async filterByTxHash(transactionHash) { async filterByTxHash(transactionHash) {
const events = await this.getEvents(1, 'latest') const events = await this.getEvents(1, 'latest')
this.events = events.filter(event => event.transactionHash === transactionHash) this.events = events.filter(event => event.transactionHash === transactionHash)
if ( if (this.events.length > 0 && this.events[0].returnValues && this.events[0].returnValues.transactionHash) {
this.events.length > 0 && await this.rootStore.foreignStore.filterByTxHashInReturnValues(this.events[0].returnValues.transactionHash)
this.events[0].returnValues &&
this.events[0].returnValues.transactionHash
) {
await this.rootStore.foreignStore.filterByTxHashInReturnValues(
this.events[0].returnValues.transactionHash
)
} }
} }
@ -432,10 +410,7 @@ class HomeStore {
async getValidators() { async getValidators() {
try { try {
const homeValidatorsAddress = await getValidatorContract(this.homeBridge) const homeValidatorsAddress = await getValidatorContract(this.homeBridge)
this.homeBridgeValidators = new this.homeWeb3.eth.Contract( this.homeBridgeValidators = new this.homeWeb3.eth.Contract(BRIDGE_VALIDATORS_ABI, homeValidatorsAddress)
BRIDGE_VALIDATORS_ABI,
homeValidatorsAddress
)
this.requiredSignatures = await getRequiredSignatures(this.homeBridgeValidators) this.requiredSignatures = await getRequiredSignatures(this.homeBridgeValidators)
this.validatorsCount = await getValidatorCount(this.homeBridgeValidators) this.validatorsCount = await getValidatorCount(this.homeBridgeValidators)
@ -455,9 +430,7 @@ class HomeStore {
const events = await getPastEvents(contract, deployedAtBlock, 'latest') const events = await getPastEvents(contract, deployedAtBlock, 'latest')
processLargeArrayAsync(events, this.processEvent, () => { processLargeArrayAsync(events, this.processEvent, () => {
this.statistics.finished = true this.statistics.finished = true
this.statistics.totalBridged = this.statistics.depositsValue.plus( this.statistics.totalBridged = this.statistics.depositsValue.plus(this.statistics.withdrawsValue)
this.statistics.withdrawsValue
)
}) })
} catch (e) { } catch (e) {
console.error(e) console.error(e)
@ -505,10 +478,8 @@ class HomeStore {
const data = getRewardableData(this.feeManager, this.rootStore.foreignStore.feeManager) const data = getRewardableData(this.feeManager, this.rootStore.foreignStore.feeManager)
this.depositFeeCollected.type = this.depositFeeCollected.type = data.depositSymbol === 'home' ? this.symbol : this.rootStore.foreignStore.symbol
data.depositSymbol === 'home' ? this.symbol : this.rootStore.foreignStore.symbol this.withdrawFeeCollected.type = data.withdrawSymbol === 'home' ? this.symbol : this.rootStore.foreignStore.symbol
this.withdrawFeeCollected.type =
data.withdrawSymbol === 'home' ? this.symbol : this.rootStore.foreignStore.symbol
this.depositFeeCollected.shouldDisplay = data.displayDeposit this.depositFeeCollected.shouldDisplay = data.displayDeposit
this.withdrawFeeCollected.shouldDisplay = data.displayWithdraw this.withdrawFeeCollected.shouldDisplay = data.displayWithdraw

@ -23,10 +23,7 @@ class RootStore {
@action @action
async setBridgeMode() { async setBridgeMode() {
const homeWeb3 = getWeb3Instance(process.env.REACT_APP_HOME_HTTP_PARITY_URL) const homeWeb3 = getWeb3Instance(process.env.REACT_APP_HOME_HTTP_PARITY_URL)
const homeBridge = new homeWeb3.eth.Contract( const homeBridge = new homeWeb3.eth.Contract(HOME_ERC_TO_ERC_ABI, process.env.REACT_APP_HOME_BRIDGE_ADDRESS)
HOME_ERC_TO_ERC_ABI,
process.env.REACT_APP_HOME_BRIDGE_ADDRESS
)
const bridgeModeHash = await homeBridge.methods.getBridgeMode().call() const bridgeModeHash = await homeBridge.methods.getBridgeMode().call()
this.bridgeMode = decodeBridgeMode(bridgeModeHash) this.bridgeMode = decodeBridgeMode(bridgeModeHash)
this.bridgeModeInitialized = true this.bridgeModeInitialized = true

@ -112,10 +112,7 @@ class Web3Store {
await this.rootStore.homeStore.getBalance() await this.rootStore.homeStore.getBalance()
this.alertStore.setLoading(false) this.alertStore.setLoading(false)
} }
if ( if (this.rootStore.bridgeModeInitialized && this.rootStore.bridgeMode !== BRIDGE_MODES.ERC_TO_ERC) {
this.rootStore.bridgeModeInitialized &&
this.rootStore.bridgeMode !== BRIDGE_MODES.ERC_TO_ERC
) {
balanceLoaded() balanceLoaded()
} }
} catch (e) { } catch (e) {
@ -132,10 +129,7 @@ class Web3Store {
}, 1000) }, 1000)
return return
} }
if ( if (this.metamaskNet.name !== this.homeNet.name && this.metamaskNet.name !== this.foreignNet.name) {
this.metamaskNet.name !== this.homeNet.name &&
this.metamaskNet.name !== this.foreignNet.name
) {
this.metamaskNotSetted = true this.metamaskNotSetted = true
this.alertStore.pushError( this.alertStore.pushError(
`You are on an unknown network on your wallet. Please select ${this.homeNet.name} or ${ `You are on an unknown network on your wallet. Please select ${this.homeNet.name} or ${

@ -24,22 +24,16 @@ describe('HomeStore', () => {
// Other mocks // Other mocks
contract.totalBurntCoins = jest.fn(() => Promise.resolve(new BN(0))) contract.totalBurntCoins = jest.fn(() => Promise.resolve(new BN(0)))
contract.getBlockRewardContract = jest.fn(() => contract.getBlockRewardContract = jest.fn(() => Promise.resolve('0xCecBE80Ed3548dE11D7d2D922a36576eA40C4c26'))
Promise.resolve('0xCecBE80Ed3548dE11D7d2D922a36576eA40C4c26')
)
contract.getPastEvents = jest.fn(() => Promise.resolve([])) contract.getPastEvents = jest.fn(() => Promise.resolve([]))
web3StoreUtils.getBlockNumber = jest.fn(() => Promise.resolve(10)) web3StoreUtils.getBlockNumber = jest.fn(() => Promise.resolve(10))
contract.getMinPerTxLimit = jest.fn(() => Promise.resolve(100000000)) contract.getMinPerTxLimit = jest.fn(() => Promise.resolve(100000000))
contract.getMaxPerTxLimit = jest.fn(() => Promise.resolve(10000000000)) contract.getMaxPerTxLimit = jest.fn(() => Promise.resolve(10000000000))
contract.getCurrentLimit = jest.fn(() => Promise.resolve({})) contract.getCurrentLimit = jest.fn(() => Promise.resolve({}))
contract.getValidatorContract = jest.fn(() => contract.getValidatorContract = jest.fn(() => Promise.resolve('0xcDF12C376F43A70a07d7Ad2fD3449634717C9235'))
Promise.resolve('0xcDF12C376F43A70a07d7Ad2fD3449634717C9235')
)
contract.getRequiredSignatures = jest.fn(() => Promise.resolve(1)) contract.getRequiredSignatures = jest.fn(() => Promise.resolve(1))
contract.getValidatorCount = jest.fn(() => Promise.resolve(1)) contract.getValidatorCount = jest.fn(() => Promise.resolve(1))
contract.getValidatorList = jest.fn(() => contract.getValidatorList = jest.fn(() => Promise.resolve(['0x52576e0cCaA0C9157142Fbf1d1c6DbfAc5e4E33e']))
Promise.resolve(['0x52576e0cCaA0C9157142Fbf1d1c6DbfAc5e4E33e'])
)
// When // When
new HomeStore(rootStore) new HomeStore(rootStore)

@ -16,10 +16,7 @@ export const toDecimals = (number, decimals) => {
} }
const isBigNumber = object => { const isBigNumber = object => {
return ( return object && (object instanceof BN || (object.constructor && object.constructor.name === 'BigNumber'))
object &&
(object instanceof BN || (object.constructor && object.constructor.name === 'BigNumber'))
)
} }
const toBigNumber = number => { const toBigNumber = number => {
@ -33,8 +30,5 @@ const toBigNumber = number => {
} }
const isString = object => { const isString = object => {
return ( return typeof object === 'string' || (object && object.constructor && object.constructor.name === 'String')
typeof object === 'string' ||
(object && object.constructor && object.constructor.name === 'String')
)
} }