feat: updated gasOracle library

This commit is contained in:
Danil Kovtonyuk 2022-07-11 20:53:13 +10:00 committed by GitHub
commit 767541ef61
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
15 changed files with 117 additions and 406 deletions

View File

@ -28,7 +28,6 @@
<div v-show="isEnabledSaveFile" class="note"> <div v-show="isEnabledSaveFile" class="note">
{{ $t('saveAsFile') }} <span class="has-text-primary">{{ filename }}</span> {{ $t('saveAsFile') }} <span class="has-text-primary">{{ filename }}</span>
</div> </div>
<gas-price-slider v-if="!eipSupported" v-model="gasPrice" @validate="onGasPriceValidate" />
<template v-if="!isSetupAccount"> <template v-if="!isSetupAccount">
<i18n tag="div" path="yourDontHaveAccount" class="notice"> <i18n tag="div" path="yourDontHaveAccount" class="notice">
<template v-slot:account> <template v-slot:account>
@ -57,7 +56,7 @@
<b-button <b-button
v-else v-else
type="is-primary is-fullwidth" type="is-primary is-fullwidth"
:disabled="disableButton || (!isValidGasPrice && !eipSupported)" :disabled="disableButton"
data-test="send_deposit_button" data-test="send_deposit_button"
@click="_sendDeposit" @click="_sendDeposit"
> >
@ -70,27 +69,22 @@
import { mapActions, mapState, mapGetters } from 'vuex' import { mapActions, mapState, mapGetters } from 'vuex'
import { sliceAddress } from '@/utils' import { sliceAddress } from '@/utils'
import GasPriceSlider from '@/components/GasPriceSlider'
import { ConnectButton } from '@/components/web3Connect' import { ConnectButton } from '@/components/web3Connect'
export default { export default {
components: { components: {
ConnectButton, ConnectButton
GasPriceSlider
}, },
data() { data() {
return { return {
isBackuped: false, isBackuped: false,
tooltipCopy: this.$t('clickToCopy'), tooltipCopy: this.$t('clickToCopy'),
gasPrice: undefined,
isValidGasPrice: false,
isEncrypted: false, isEncrypted: false,
copyTimer: null copyTimer: null
} }
}, },
computed: { computed: {
...mapGetters('metamask', ['isLoggedIn']), ...mapGetters('metamask', ['isLoggedIn']),
...mapGetters('gasPrices', ['eipSupported']),
...mapGetters('txHashKeeper', ['addressExplorerUrl']), ...mapGetters('txHashKeeper', ['addressExplorerUrl']),
...mapGetters('encryptedNote', ['isSetupAccount', 'accounts', 'isEnabledSaveFile']), ...mapGetters('encryptedNote', ['isSetupAccount', 'accounts', 'isEnabledSaveFile']),
...mapState('application', ['note', 'prefix']), ...mapState('application', ['note', 'prefix']),
@ -135,13 +129,10 @@ export default {
}, },
async _sendDeposit() { async _sendDeposit() {
this.$store.dispatch('loading/enable', { message: this.$t('preparingTransactionData') }) this.$store.dispatch('loading/enable', { message: this.$t('preparingTransactionData') })
await this.sendDeposit({ gasPrice: this.gasPrice, isEncrypted: this.isEncrypted }) await this.sendDeposit({ isEncrypted: this.isEncrypted })
this.$store.dispatch('loading/disable') this.$store.dispatch('loading/disable')
this.$parent.close() this.$parent.close()
}, },
onGasPriceValidate(value) {
this.isValidGasPrice = value
},
async copyNoteAccount() { async copyNoteAccount() {
await this.$copyText(this.accounts.encrypt) await this.$copyText(this.accounts.encrypt)
this.onCopy() this.onCopy()

View File

@ -1,132 +0,0 @@
<template>
<div class="field field-slider">
<div class="label">
Gas Price
<b-field :class="hasError ? 'is-warning' : ''">
<b-input
ref="gasPriceInput"
v-model.number="input"
type="number"
:min="0"
custom-class="hide-spinner"
:use-html5-validation="false"
expanded
:style="{ width: reactiveWidth }"
></b-input>
<div class="control has-text" @click="$refs.gasPriceInput.focus()">
<span>Gwei</span>
</div>
</b-field>
</div>
<b-slider
v-model="slider"
:min="0"
:max="2"
:custom-formatter="tooltipFormat"
bigger-slider-focus
lazy
rounded
@change="onChange"
>
<template v-for="(val, index) of Object.keys(gasPrices).filter((k) => k !== 'instant')">
<b-slider-tick :key="val" :value="index">{{ $t(`gasPriceSlider.${val}`) }}</b-slider-tick>
</template>
</b-slider>
</div>
</template>
<script>
import { mapGetters } from 'vuex'
import { debounce } from '@/utils'
const { toWei, toHex } = require('web3-utils')
export default {
inheritAttrs: false,
data() {
return {
input: null,
slider: 2,
hasError: false,
reactiveWidth: ''
}
},
computed: {
...mapGetters('gasPrices', ['gasPrices'])
},
watch: {
input: {
handler(gasPrice) {
this.setWidth(gasPrice)
debounce(this.validateGasPrice, gasPrice)
}
}
},
mounted() {
this.input = this.gasPrices.fast
this.setWidth(this.input)
},
methods: {
onChange(index) {
this.input = this.getValueFromIndex(index)
},
tooltipFormat(index) {
return this.getValueFromIndex(index)
},
getValueFromIndex(index) {
switch (Number(index)) {
case 2:
return this.gasPrices.fast
case 1:
return this.gasPrices.standard
case 0:
return this.gasPrices.low
}
},
validateGasPrice(gasPrice) {
try {
let speed = ''
this.hasError = false
if (gasPrice === '') {
throw new Error('must not be an empty')
}
if (gasPrice <= 0) {
throw new Error('must be greater than zero')
}
if (gasPrice < this.gasPrices.standard) {
speed = 'low'
this.slider = 0
} else if (gasPrice === this.gasPrices.standard) {
this.slider = 1
speed = 'standard'
} else {
this.slider = 2
speed = 'fast'
}
if (gasPrice) {
gasPrice = {
speed,
value: toHex(toWei(gasPrice.toString(), 'gwei'))
}
}
this.$emit('input', gasPrice)
} catch (e) {
// eslint-disable-next-line no-console
console.error('Invalid gas price:', e.message)
this.hasError = true
} finally {
this.$emit('validate', !this.hasError)
}
},
setWidth(value) {
if (!value) {
value = 0
}
this.reactiveWidth = `${Math.min(75, Math.max(35, 19 + value && value.toString().length * 12))}px`
}
}
}
</script>

View File

@ -133,8 +133,8 @@
:class="{ 'slide-animation-active': isLoading }" :class="{ 'slide-animation-active': isLoading }"
:disabled="isWithdrawalButtonDisable" :disabled="isWithdrawalButtonDisable"
:loading="isLoadingRelayers || isLoading" :loading="isLoadingRelayers || isLoading"
@click="onWithdraw"
data-test="button_start_withdraw" data-test="button_start_withdraw"
@click="onWithdraw"
> >
{{ $t('withdrawButton') }} {{ $t('withdrawButton') }}
</b-button> </b-button>
@ -189,7 +189,7 @@ export default {
} }
}, },
computed: { computed: {
...mapState('application', ['note', 'errors', 'withdrawType', 'ethToReceive']), ...mapState('application', ['note', 'withdrawType', 'ethToReceive']),
...mapState('relayer', ['isLoadingRelayers']), ...mapState('relayer', ['isLoadingRelayers']),
...mapGetters('txHashKeeper', ['txExplorerUrl']), ...mapGetters('txHashKeeper', ['txExplorerUrl']),
...mapGetters('application', ['isNotEnoughTokens', 'selectedStatisticCurrency']), ...mapGetters('application', ['isNotEnoughTokens', 'selectedStatisticCurrency']),
@ -291,24 +291,6 @@ export default {
} }
} }
}, },
errors: {
handler(errors) {
console.log('error', errors)
this.error = {
type: errors.length ? this.$t('error') : null,
message: errors[errors.length - 1]
}
if (this.error.message) {
this.$store.dispatch('notice/addNoticeWithInterval', {
notice: {
untranslatedTitle: this.error.message,
type: 'warning'
}
})
}
},
deep: true
},
withdrawNote: { withdrawNote: {
async handler(withdrawNote) { async handler(withdrawNote) {
this.error = { this.error = {
@ -382,6 +364,8 @@ export default {
}, },
activeTab(newTab, oldTab) { activeTab(newTab, oldTab) {
if (newTab !== oldTab && newTab === 1) { if (newTab !== oldTab && newTab === 1) {
this.withdrawAddress = ''
this.withdrawNote = ''
this.error = { this.error = {
type: '', type: '',
message: '' message: ''
@ -448,7 +432,7 @@ export default {
console.log(`Get logs: ${err.message}`) console.log(`Get logs: ${err.message}`)
} }
}, },
onWithdraw() { async onWithdraw() {
const note = this.withdrawNote.split('-')[4] const note = this.withdrawNote.split('-')[4]
if (note.length !== 126) { if (note.length !== 126) {
this.error = { this.error = {
@ -457,14 +441,26 @@ export default {
} }
return return
} }
try { try {
this.withdrawAddress = toChecksumAddress(this.withdrawAddress) this.withdrawAddress = toChecksumAddress(this.withdrawAddress)
this.$store.dispatch('application/prepareWithdraw', { } catch {
this.error = {
type: this.$t('validationError'),
message: this.$t('recipientAddressIsInvalid')
}
return
}
try {
this.$store.dispatch('loading/enable', { message: this.$t('generatingProof') })
await this.$store.dispatch('application/prepareWithdraw', {
note: this.withdrawNote, note: this.withdrawNote,
recipient: this.withdrawAddress recipient: this.withdrawAddress
}) })
this.error.type = null
this.currentModal = this.$buefy.modal.open({ this.$buefy.modal.open({
parent: this, parent: this,
component: WithdrawModalBox, component: WithdrawModalBox,
hasModalCard: true, hasModalCard: true,
@ -474,12 +470,20 @@ export default {
withdrawType: this.withdrawType withdrawType: this.withdrawType
} }
}) })
} catch (e) { } catch (err) {
this.error = { this.error = {
type: this.$t('validationError'), type: this.$t('error'),
message: this.$t('recipientAddressIsInvalid') message: err.message
} }
console.error('error', e)
this.$store.dispatch('notice/addNoticeWithInterval', {
notice: {
untranslatedTitle: err.message,
type: 'warning'
}
})
} finally {
this.$store.dispatch('loading/disable')
} }
}, },
onSettings() { onSettings() {

View File

@ -5,7 +5,7 @@
<button type="button" class="delete" @click="$emit('close')" /> <button type="button" class="delete" @click="$emit('close')" />
</header> </header>
<div class="note" data-test="withdrawal_confirmation_text"> <div class="note" data-test="withdrawal_confirmation_text">
{{ message }} {{ $t('yourZkSnarkProofHasBeenSuccesfullyGenerated') }}
</div> </div>
<b-button type="is-primary is-fullwidth" data-test="withdrawal_confirm_button" @click="_sendWithdraw"> <b-button type="is-primary is-fullwidth" data-test="withdrawal_confirm_button" @click="_sendWithdraw">
{{ $t('confirm') }} {{ $t('confirm') }}
@ -14,7 +14,6 @@
</template> </template>
<script> <script>
/* eslint-disable no-console */ /* eslint-disable no-console */
import { mapState } from 'vuex'
export default { export default {
props: { props: {
@ -27,13 +26,7 @@ export default {
required: true required: true
} }
}, },
data() {
return {
message: ''
}
},
computed: { computed: {
...mapState('application', ['notes', 'errors']),
withdrawalMethod() { withdrawalMethod() {
if (this.withdrawType === 'wallet') { if (this.withdrawType === 'wallet') {
return 'application/withdraw' return 'application/withdraw'
@ -42,24 +35,6 @@ export default {
return 'relayer/relayTornadoWithdraw' return 'relayer/relayTornadoWithdraw'
} }
}, },
watch: {
notes(newNotes) {
if (newNotes[this.note]) {
this.$store.dispatch('loading/disable')
this.message = this.$t('yourZkSnarkProofHasBeenSuccesfullyGenerated')
}
},
errors: {
handler(type) {
this.$store.dispatch('loading/disable')
this.$parent.close()
},
deep: true
}
},
beforeCreate() {
this.$store.dispatch('loading/enable', { message: this.$t('generatingProof') })
},
methods: { methods: {
async _sendWithdraw() { async _sendWithdraw() {
this.$store.dispatch('loading/enable', { message: this.$t('preparingTransactionData') }) this.$store.dispatch('loading/enable', { message: this.$t('preparingTransactionData') })

View File

@ -13,7 +13,8 @@
</div> </div>
<div v-if="withdrawType === 'relayer'" class="withdraw-data-item"> <div v-if="withdrawType === 'relayer'" class="withdraw-data-item">
{{ $t('gasPrice') }} {{ $t('gasPrice') }}
<span>{{ gasPrices.fast }} Gwei</span>
<span>{{ gasPriceInGwei }} Gwei</span>
</div> </div>
<div v-if="withdrawType === 'relayer'" class="withdraw-data-item"> <div v-if="withdrawType === 'relayer'" class="withdraw-data-item">
{{ $t('networkFee') }} {{ $t('networkFee') }}
@ -72,7 +73,7 @@ export default {
...mapGetters('metamask', { ...mapGetters('metamask', {
networkCurrency: 'currency' networkCurrency: 'currency'
}), }),
...mapGetters('gasPrices', ['gasPrices']), ...mapGetters('gasPrices', ['gasPriceInGwei']),
...mapGetters('token', ['toDecimals', 'fromDecimals']), ...mapGetters('token', ['toDecimals', 'fromDecimals']),
...mapGetters('application', ['networkFee']), ...mapGetters('application', ['networkFee']),
...mapGetters('price', ['tokenRate']), ...mapGetters('price', ['tokenRate']),

View File

@ -80,7 +80,7 @@ export default {
await this.selectRpc({ netId: 1, action: this.preselectRpc }) await this.selectRpc({ netId: 1, action: this.preselectRpc })
} }
this.$store.dispatch('gasPrices/fetchGasPrice', {}) this.$store.dispatch('gasPrices/fetchGasPrice')
this.$store.dispatch('price/fetchTokenPrice', {}, { root: true }) this.$store.dispatch('price/fetchTokenPrice', {}, { root: true })
try { try {
this.$store.dispatch('application/loadAllNotesData') this.$store.dispatch('application/loadAllNotesData')

View File

@ -114,7 +114,7 @@ export default {
} }
}, },
ensSubdomainKey: 'mainnet-tornado', ensSubdomainKey: 'mainnet-tornado',
pollInterval: 30, pollInterval: 15,
constants: { constants: {
NOTE_ACCOUNT_BLOCK: 11842486, NOTE_ACCOUNT_BLOCK: 11842486,
ENCRYPTED_NOTES_BLOCK: 14248730, ENCRYPTED_NOTES_BLOCK: 14248730,
@ -276,7 +276,7 @@ export default {
} }
}, },
ensSubdomainKey: 'optimism-tornado', ensSubdomainKey: 'optimism-tornado',
pollInterval: 20, pollInterval: 15,
constants: { constants: {
NOTE_ACCOUNT_BLOCK: 2243694, NOTE_ACCOUNT_BLOCK: 2243694,
ENCRYPTED_NOTES_BLOCK: 2243694 ENCRYPTED_NOTES_BLOCK: 2243694
@ -331,7 +331,7 @@ export default {
} }
}, },
ensSubdomainKey: 'arbitrum-tornado', ensSubdomainKey: 'arbitrum-tornado',
pollInterval: 20, pollInterval: 15,
constants: { constants: {
NOTE_ACCOUNT_BLOCK: 3430605, NOTE_ACCOUNT_BLOCK: 3430605,
ENCRYPTED_NOTES_BLOCK: 3430605 ENCRYPTED_NOTES_BLOCK: 3430605
@ -378,7 +378,7 @@ export default {
} }
}, },
ensSubdomainKey: 'gnosis-tornado', ensSubdomainKey: 'gnosis-tornado',
pollInterval: 20, pollInterval: 15,
constants: { constants: {
NOTE_ACCOUNT_BLOCK: 17754564, NOTE_ACCOUNT_BLOCK: 17754564,
ENCRYPTED_NOTES_BLOCK: 17754564 ENCRYPTED_NOTES_BLOCK: 17754564
@ -532,7 +532,7 @@ export default {
} }
}, },
ensSubdomainKey: 'goerli-tornado', ensSubdomainKey: 'goerli-tornado',
pollInterval: 30, pollInterval: 15,
constants: { constants: {
NOTE_ACCOUNT_BLOCK: 4131375, NOTE_ACCOUNT_BLOCK: 4131375,
ENCRYPTED_NOTES_BLOCK: 4131375, ENCRYPTED_NOTES_BLOCK: 4131375,

View File

@ -38,7 +38,7 @@
"file-saver": "^2.0.5", "file-saver": "^2.0.5",
"fixed-merkle-tree": "^0.7.3", "fixed-merkle-tree": "^0.7.3",
"form-data": "^3.0.0", "form-data": "^3.0.0",
"gas-price-oracle": "^0.4.6", "gas-price-oracle": "^0.5.0",
"graphql": "^15.5.1", "graphql": "^15.5.1",
"idb": "^6.0.0", "idb": "^6.0.0",
"jspdf": "^1.5.3", "jspdf": "^1.5.3",

View File

@ -5,7 +5,7 @@ export default ({ store, isHMR, app }, inject) => {
function main() { function main() {
const whiteListedDomains = ['localhost:3000', 'tornadocash.eth.link', 'tornadocash.eth.limo'] const whiteListedDomains = ['localhost:3000', 'tornadocash.eth.link', 'tornadocash.eth.limo']
const NETLIFY_REGEXP = /https:\/\/deploy-preview-(\d+)--tornadocash\.netlify\.app/ const NETLIFY_REGEXP = /deploy-preview-(\d+)--tornadocash\.netlify\.app/
if (NETLIFY_REGEXP.test(window.location.host)) { if (NETLIFY_REGEXP.test(window.location.host)) {
return false return false

View File

@ -36,10 +36,10 @@ class EventService {
} }
return cachedEvents return cachedEvents
} }
async updateEvents(type) { async updateEvents(type, cachedEvents) {
const { deployedBlock } = networkConfig[`netId${this.netId}`] const { deployedBlock } = networkConfig[`netId${this.netId}`]
const savedEvents = await this.getEvents(type) const savedEvents = cachedEvents || (await this.getEvents(type))
let fromBlock = deployedBlock let fromBlock = deployedBlock
if (savedEvents) { if (savedEvents) {
@ -157,8 +157,17 @@ class EventService {
} }
} }
async getStatisticsRpc({ fromBlock, eventsCount }) { async getStatisticsRpc({ eventsCount }) {
const { deployedBlock } = networkConfig[`netId${this.netId}`]
const savedEvents = await this.getEvents(eventsType.DEPOSIT)
if (savedEvents.events.length) {
const { events } = await this.updateEvents(eventsType.DEPOSIT, savedEvents)
return events
}
const blockRange = 4950 const blockRange = 4950
const fromBlock = deployedBlock
const { blockDifference, currentBlockNumber } = await this.getBlocksDiff({ fromBlock }) const { blockDifference, currentBlockNumber } = await this.getBlocksDiff({ fromBlock })
let numberParts = blockDifference === 0 ? 1 : Math.ceil(blockDifference / blockRange) let numberParts = blockDifference === 0 ? 1 : Math.ceil(blockDifference / blockRange)
@ -225,6 +234,15 @@ class EventService {
async getEventsPartFromRpc({ fromBlock, toBlock, type }) { async getEventsPartFromRpc({ fromBlock, toBlock, type }) {
try { try {
const { currentBlockNumber } = await this.getBlocksDiff({ fromBlock })
if (fromBlock > currentBlockNumber) {
return {
events: [],
lastBlock: fromBlock
}
}
const events = await this.contract.getPastEvents(capitalizeFirstLetter(type), { const events = await this.contract.getPastEvents(capitalizeFirstLetter(type), {
fromBlock, fromBlock,
toBlock toBlock

View File

@ -55,7 +55,6 @@ const state = () => {
note: null, note: null,
commitment: null, commitment: null,
prefix: null, prefix: null,
errors: [],
notes: {}, notes: {},
statistic: defaultStatistics, statistic: defaultStatistics,
ip: {}, ip: {},
@ -80,12 +79,6 @@ const mutations = {
REMOVE_PROOF(state, { note }) { REMOVE_PROOF(state, { note }) {
this._vm.$delete(state.notes, note) this._vm.$delete(state.notes, note)
}, },
SAVE_ERROR(state, message) {
state.errors.push(message)
},
REMOVE_ERRORS(state) {
this._vm.$set(state, 'errors', [])
},
SAVE_LAST_INDEX(state, { nextDepositIndex, anonymitySet, currency, amount }) { SAVE_LAST_INDEX(state, { nextDepositIndex, anonymitySet, currency, amount }) {
const currentState = state.statistic[currency][amount] const currentState = state.statistic[currency][amount]
this._vm.$set(state.statistic[currency], `${amount}`, { ...currentState, nextDepositIndex, anonymitySet }) this._vm.$set(state.statistic[currency], `${amount}`, { ...currentState, nextDepositIndex, anonymitySet })
@ -166,7 +159,7 @@ const getters = {
return ACTION_GAS[action] return ACTION_GAS[action]
}, },
networkFee: (state, getters, rootState, rootGetters) => { networkFee: (state, getters, rootState, rootGetters) => {
const gasPrice = rootGetters['gasPrices/fastGasPrice'] const gasPrice = rootGetters['gasPrices/gasPrice']
const networkFee = toBN(gasPrice).mul(toBN(getters.withdrawGas)) const networkFee = toBN(gasPrice).mul(toBN(getters.withdrawGas))
@ -270,19 +263,15 @@ const actions = {
async updateSelectEvents({ dispatch, commit, state, rootGetters, getters }) { async updateSelectEvents({ dispatch, commit, state, rootGetters, getters }) {
const netId = rootGetters['metamask/netId'] const netId = rootGetters['metamask/netId']
const { currency, amount } = state.selectedStatistic const { currency, amount } = state.selectedStatistic
const { deployedBlock } = networkConfig[`netId${netId}`]
const eventService = getters.eventsInterface.getService({ netId, amount, currency }) const eventService = getters.eventsInterface.getService({ netId, amount, currency })
const savedEvents = await eventService.getEvents(eventsType.DEPOSIT) const graphEvents = await eventService.getEventsFromGraph({ methodName: 'getStatistic' })
const fromBlock = savedEvents?.lastBlock || deployedBlock
const graphEvents = await eventService.getEventsFromGraph({ fromBlock, methodName: 'getStatistic' })
let statistic = graphEvents?.events let statistic = graphEvents?.events
if (!statistic || !statistic.length) { if (!statistic || !statistic.length) {
const fresh = await eventService.getStatisticsRpc({ fromBlock, eventsCount: 10 }) const fresh = await eventService.getStatisticsRpc({ eventsCount: 10 })
statistic = fresh || [] statistic = fresh || []
} }
@ -554,7 +543,7 @@ const actions = {
storeName: `encrypted_events` storeName: `encrypted_events`
}) })
}, },
async sendDeposit({ state, rootState, getters, rootGetters, dispatch, commit }, { isEncrypted, gasPrice }) { async sendDeposit({ state, rootState, getters, rootGetters, dispatch, commit }, { isEncrypted }) {
try { try {
const { commitment, note, prefix } = state const { commitment, note, prefix } = state
// eslint-disable-next-line prefer-const // eslint-disable-next-line prefer-const
@ -593,7 +582,6 @@ const actions = {
const callParams = { const callParams = {
method: 'eth_sendTransaction', method: 'eth_sendTransaction',
params: { params: {
gasPrice,
to: contractInstance._address, to: contractInstance._address,
gas: numberToHex(gas + 50000), gas: numberToHex(gas + 50000),
value: numberToHex(value), value: numberToHex(value),
@ -770,7 +758,6 @@ const actions = {
return { args, proof } return { args, proof }
}, },
async prepareWithdraw({ dispatch, getters, commit }, { note, recipient }) { async prepareWithdraw({ dispatch, getters, commit }, { note, recipient }) {
commit('REMOVE_ERRORS')
commit('REMOVE_PROOF', { note }) commit('REMOVE_PROOF', { note })
try { try {
const parsedNote = parseNote(note) const parsedNote = parseNote(note)
@ -794,7 +781,7 @@ const actions = {
commit('SAVE_PROOF', { proof, args, note }) commit('SAVE_PROOF', { proof, args, note })
} catch (e) { } catch (e) {
console.error('prepareWithdraw', e) console.error('prepareWithdraw', e)
commit('SAVE_ERROR', e.message) throw new Error(e.message)
} }
}, },
async withdraw({ state, rootState, dispatch, getters }, { note }) { async withdraw({ state, rootState, dispatch, getters }, { note }) {
@ -956,12 +943,11 @@ const actions = {
} }
} catch (e) { } catch (e) {
console.error(`Method loadWithdrawalData has error: ${e}`) console.error(`Method loadWithdrawalData has error: ${e}`)
commit('SAVE_ERROR', e.message)
} }
}, },
calculateEthToReceive({ commit, state, rootGetters }, { currency }) { calculateEthToReceive({ commit, state, rootGetters }, { currency }) {
const gasLimit = rootGetters['metamask/networkConfig'].tokens[currency].gasLimit const gasLimit = rootGetters['metamask/networkConfig'].tokens[currency].gasLimit
const gasPrice = toBN(rootGetters['gasPrices/fastGasPrice']) const gasPrice = toBN(rootGetters['gasPrices/gasPrice'])
const ethToReceive = gasPrice const ethToReceive = gasPrice
.mul(toBN(gasLimit)) .mul(toBN(gasLimit))

View File

@ -1,8 +1,8 @@
/* eslint-disable no-console */ /* eslint-disable no-console */
import Web3 from 'web3' import Web3 from 'web3'
import { toHex, fromWei } from 'web3-utils'
import { GasPriceOracle } from 'gas-price-oracle' import { GasPriceOracle } from 'gas-price-oracle'
import { serialize } from '@ethersproject/transactions' import { serialize } from '@ethersproject/transactions'
import { toHex, toWei, toBN, fromWei } from 'web3-utils'
import networkConfig from '@/networkConfig' import networkConfig from '@/networkConfig'
import OvmGasPriceOracleABI from '@/abis/OvmGasPriceOracle.abi.json' import OvmGasPriceOracleABI from '@/abis/OvmGasPriceOracle.abi.json'
@ -10,39 +10,22 @@ import { DUMMY_NONCE, DUMMY_WITHDRAW_DATA } from '@/constants/variables'
export const state = () => { export const state = () => {
return { return {
oracle: { gasParams: { gasPrice: 50 },
instant: 80,
fast: 50,
standard: 25,
low: 8
},
eip: {
instant: {
baseFee: 80,
maxFeePerGas: 80,
maxPriorityFeePerGas: 3
},
fast: {
baseFee: 50,
maxFeePerGas: 50,
maxPriorityFeePerGas: 3
},
standard: {
baseFee: 25,
maxFeePerGas: 27,
maxPriorityFeePerGas: 2
},
low: {
baseFee: 8,
maxFeePerGas: 9,
maxPriorityFeePerGas: 1
}
},
l1Fee: '0' l1Fee: '0'
} }
} }
export const getters = { export const getters = {
oracle: (state, getters, rootState, rootGetters) => {
const netId = Number(rootGetters['metamask/netId'])
const { gasPrices } = rootGetters['metamask/networkConfig']
return new GasPriceOracle({
chainId: netId,
defaultRpc: rootGetters['settings/currentRpc'].url,
defaultFallbackGasPrices: gasPrices
})
},
ovmGasPriceOracleContract: (state, getters, rootState) => ({ netId }) => { ovmGasPriceOracleContract: (state, getters, rootState) => ({ netId }) => {
const config = networkConfig[`netId${netId}`] const config = networkConfig[`netId${netId}`]
const { url } = rootState.settings[`netId${netId}`].rpc const { url } = rootState.settings[`netId${netId}`].rpc
@ -57,78 +40,21 @@ export const getters = {
l1Fee: (state) => { l1Fee: (state) => {
return state.l1Fee return state.l1Fee
}, },
oracle: (state, getters, rootState, rootGetters) => { getGasParams: (state) => {
const netId = Number(rootGetters['metamask/netId']) return state.gasParams
const { gasPrices } = rootGetters['metamask/networkConfig']
return new GasPriceOracle({
chainId: netId,
defaultRpc: rootGetters['settings/currentRpc'].url,
defaultFallbackGasPrices: gasPrices
})
}, },
eipSupported: (state, getters, rootState, rootGetters) => { gasPrice: (state, getters) => {
const netId = rootGetters['metamask/netId'] const { gasPrice, maxFeePerGas } = getters.getGasParams
const networksWithEIP1559 = [1, 5] return toHex(maxFeePerGas || gasPrice)
return networksWithEIP1559.includes(netId)
}, },
getGasParams: (state, getters) => (speed = 'fast', isDisable = false) => { gasPriceInGwei: (state, getters) => {
const { maxFeePerGas, maxPriorityFeePerGas } = state.eip[speed] return fromWei(getters.gasPrice, 'gwei')
if (!isDisable && getters.eipSupported) {
return {
maxFeePerGas: toHex(maxFeePerGas),
maxPriorityFeePerGas: toHex(maxPriorityFeePerGas)
}
}
return {
gasPrice: getters.getGasPrice(speed)
}
},
getGasPrice: (state, getters) => (speed = 'fast') => {
const gasPrices = getters.gasPrices
return toHex(toWei(gasPrices[speed].toString(), 'gwei'))
},
fastGasPrice: (state, getters) => {
return getters.getGasPrice('fast')
},
gasPrices: (state, getters) => {
const parseGwei = (value) => String(Math.floor(Number(fromWei(String(value), 'gwei')) * 100) / 100)
const { eip, oracle } = state
if (getters.eipSupported) {
return {
instant: parseGwei(eip.instant.maxFeePerGas),
low: parseGwei(eip.low.maxFeePerGas),
standard: parseGwei(eip.standard.maxFeePerGas),
fast: parseGwei(eip.fast.maxFeePerGas)
}
}
return {
instant: String(oracle.instant),
low: String(oracle.low),
standard: String(oracle.standard),
fast: String(oracle.fast)
}
} }
} }
export const mutations = { export const mutations = {
SAVE_ORACLE_GAS_PRICES(state, { instant, fast, standard, low }) { SAVE_GAS_PARAMS(state, payload) {
this._vm.$set(state.oracle, 'instant', instant) state.gasParams = payload
this._vm.$set(state.oracle, 'fast', fast)
this._vm.$set(state.oracle, 'standard', standard)
this._vm.$set(state.oracle, 'low', low)
},
SAVE_EIP_GAS_PRICES(state, { instant, fast, standard, low }) {
this._vm.$set(state.eip, 'instant', instant)
this._vm.$set(state.eip, 'fast', fast)
this._vm.$set(state.eip, 'standard', standard)
this._vm.$set(state.eip, 'low', low)
}, },
SAVE_L1_FEE(state, l1Fee) { SAVE_L1_FEE(state, l1Fee) {
state.l1Fee = l1Fee state.l1Fee = l1Fee
@ -136,85 +62,27 @@ export const mutations = {
} }
export const actions = { export const actions = {
async fetchGasPrice({ getters, commit, dispatch, rootGetters, state }) { async fetchGasPrice({ getters, dispatch, commit, rootGetters }) {
const netId = rootGetters['metamask/netId']
const { pollInterval } = rootGetters['metamask/networkConfig'] const { pollInterval } = rootGetters['metamask/networkConfig']
const isLegacy = netId === 137
try { try {
if (getters.eipSupported) { const txGasParams = await getters.oracle.getTxGasParams({ isLegacy })
const result = await dispatch('estimateFees') commit('SAVE_GAS_PARAMS', txGasParams)
commit('SAVE_EIP_GAS_PRICES', result)
} else {
const gas = await dispatch('getGasPrice')
commit('SAVE_ORACLE_GAS_PRICES', gas)
}
await dispatch('fetchL1Fee') await dispatch('fetchL1Fee')
setTimeout(() => dispatch('fetchGasPrice'), 1000 * pollInterval)
} catch (e) { } catch (e) {
console.error('fetchGasPrice', e) console.error('fetchGasPrice', e)
} finally {
setTimeout(() => dispatch('fetchGasPrice'), 1000 * pollInterval) setTimeout(() => dispatch('fetchGasPrice'), 1000 * pollInterval)
} }
}, },
async estimateFees({ rootGetters }) {
try {
const { url } = rootGetters['settings/currentRpc']
const web3 = this.$provider.getWeb3(url)
const latestBlock = await web3.eth.getBlock('latest')
if (!latestBlock.baseFeePerGas) {
throw new Error('An error occurred while fetching current base fee, falling back')
}
const baseFee = toBN(latestBlock.baseFeePerGas)
const potentialMaxFee = baseFee.mul(toBN(1125)).div(toBN(1000))
const GWEI = (amount) => toBN(toWei(amount, 'gwei'))
const fastPriorityFee = GWEI('4')
const standardPriorityFee = GWEI('2.5')
const lowPriorityFee = GWEI('1')
return {
instant: {
baseFee,
maxFeePerGas: potentialMaxFee.add(fastPriorityFee),
maxPriorityFeePerGas: fastPriorityFee
},
fast: {
baseFee,
maxFeePerGas: potentialMaxFee.add(fastPriorityFee),
maxPriorityFeePerGas: fastPriorityFee
},
standard: {
baseFee,
maxFeePerGas: potentialMaxFee.add(standardPriorityFee),
maxPriorityFeePerGas: standardPriorityFee
},
low: {
baseFee,
maxFeePerGas: potentialMaxFee.add(lowPriorityFee),
maxPriorityFeePerGas: lowPriorityFee
}
}
} catch (err) {
throw new Error(err.message)
}
},
async getGasPrice({ state, getters }) {
try {
const gas = await getters.oracle.gasPrices(state.oracle)
return gas
} catch (err) {
throw new Error(err.message)
}
},
setDefault({ commit, rootGetters }) { setDefault({ commit, rootGetters }) {
const { gasPrices } = rootGetters['metamask/networkConfig'] const { gasPrices } = rootGetters['metamask/networkConfig']
commit('SAVE_ORACLE_GAS_PRICES', gasPrices) commit('SAVE_GAS_PARAMS', { gasPrice: gasPrices?.fast })
}, },
async fetchL1Fee({ commit, getters, dispatch, rootGetters }) { async fetchL1Fee({ commit, getters, rootGetters }) {
const netId = rootGetters['metamask/netId'] const netId = rootGetters['metamask/netId']
const isOptimismConnected = rootGetters['application/isOptimismConnected'] const isOptimismConnected = rootGetters['application/isOptimismConnected']
@ -225,15 +93,13 @@ export const actions = {
const gasLimit = rootGetters['application/withdrawGas'] const gasLimit = rootGetters['application/withdrawGas']
const tornadoProxyInstance = rootGetters['application/tornadoProxyContract']({ netId }) const tornadoProxyInstance = rootGetters['application/tornadoProxyContract']({ netId })
const gasPrice = getters.fastGasPrice
const tx = serialize({ const tx = serialize({
type: 0, type: 0,
gasLimit, gasLimit,
gasPrice,
chainId: netId, chainId: netId,
nonce: DUMMY_NONCE, nonce: DUMMY_NONCE,
data: DUMMY_WITHDRAW_DATA, data: DUMMY_WITHDRAW_DATA,
gasPrice: getters.gasPrice,
to: tornadoProxyInstance._address to: tornadoProxyInstance._address
}) })

View File

@ -155,11 +155,7 @@ const actions = {
) { ) {
try { try {
const { ethAccount, netId } = state const { ethAccount, netId } = state
const gasParams = rootGetters['gasPrices/getGasParams']('fast', eipDisable) const gasParams = rootGetters['gasPrices/getGasParams']
if (params.gasPrice && 'gasPrice' in gasParams) {
gasParams.gasPrice = params.gasPrice.value
}
const callParams = { const callParams = {
method, method,

View File

@ -236,8 +236,14 @@ export const actions = {
const hasEnabledLightProxy = rootGetters['application/hasEnabledLightProxy'] const hasEnabledLightProxy = rootGetters['application/hasEnabledLightProxy']
const getIsUpdated = () => { const getIsUpdated = () => {
const relayerVersion = response.data.version
if (relayerVersion === '5.0.0') {
return true
}
const requiredMajor = hasEnabledLightProxy ? '5' : '4' const requiredMajor = hasEnabledLightProxy ? '5' : '4'
const { major, patch, prerelease } = parseSemanticVersion(response.data.version) const { major, patch, prerelease } = parseSemanticVersion(relayerVersion)
const isUpdatedMajor = major === requiredMajor const isUpdatedMajor = major === requiredMajor

View File

@ -7893,10 +7893,10 @@ functional-red-black-tree@^1.0.1:
resolved "https://registry.yarnpkg.com/functional-red-black-tree/-/functional-red-black-tree-1.0.1.tgz#1b0ab3bd553b2a0d6399d29c0e3ea0b252078327" resolved "https://registry.yarnpkg.com/functional-red-black-tree/-/functional-red-black-tree-1.0.1.tgz#1b0ab3bd553b2a0d6399d29c0e3ea0b252078327"
integrity sha1-GwqzvVU7Kg1jmdKcDj6gslIHgyc= integrity sha1-GwqzvVU7Kg1jmdKcDj6gslIHgyc=
gas-price-oracle@^0.4.6: gas-price-oracle@^0.5.0:
version "0.4.6" version "0.5.0"
resolved "https://registry.yarnpkg.com/gas-price-oracle/-/gas-price-oracle-0.4.6.tgz#3e496092122896f1c80ea7eeeecea979d106b3aa" resolved "https://registry.yarnpkg.com/gas-price-oracle/-/gas-price-oracle-0.5.0.tgz#b29f83c97bb4b091a08da7c10e2d1e5888bbade4"
integrity sha512-/z0wtzKa6FDTWmgikPnELWN8KiPHhCy3Z+waeKVMgvs5FBxibgwOUL1VlMsC4mVkXBoDadnBtFNOpUMgbt5pvg== integrity sha512-um0cmd9qxGkDHirV1HcrjQ4vedVxK7u+uMeJIjo2yUMYe6T46ihbMnRncF5tfP9deU5hPHJ8FvVRZY1Y/CKkLQ==
dependencies: dependencies:
axios "^0.21.2" axios "^0.21.2"
bignumber.js "^9.0.0" bignumber.js "^9.0.0"