commit
8c77e998e0
After Width: | Height: | Size: 786 B |
After Width: | Height: | Size: 11 KiB |
After Width: | Height: | Size: 6.1 KiB |
After Width: | Height: | Size: 6.8 KiB |
@ -0,0 +1,123 @@ |
||||
const Web3 = require('web3') |
||||
const contracts = require('eth-contract-metadata') |
||||
const { warn } = require('loglevel') |
||||
const { MAINNET } = require('./network/enums') |
||||
// By default, poll every 3 minutes
|
||||
const DEFAULT_INTERVAL = 180 * 1000 |
||||
const ERC20_ABI = [{'constant': true, 'inputs': [{'name': '_owner', 'type': 'address'}], 'name': 'balanceOf', 'outputs': [{'name': 'balance', 'type': 'uint256'}], 'payable': false, 'type': 'function'}] |
||||
|
||||
/** |
||||
* A controller that polls for token exchange |
||||
* rates based on a user's current token list |
||||
*/ |
||||
class DetectTokensController { |
||||
/** |
||||
* Creates a DetectTokensController |
||||
* |
||||
* @param {Object} [config] - Options to configure controller |
||||
*/ |
||||
constructor ({ interval = DEFAULT_INTERVAL, preferences, network, keyringMemStore } = {}) { |
||||
this.preferences = preferences |
||||
this.interval = interval |
||||
this.network = network |
||||
this.keyringMemStore = keyringMemStore |
||||
} |
||||
|
||||
/** |
||||
* For each token in eth-contract-metada, find check selectedAddress balance. |
||||
* |
||||
*/ |
||||
async detectNewTokens () { |
||||
if (!this.isActive) { return } |
||||
if (this._network.store.getState().provider.type !== MAINNET) { return } |
||||
this.web3.setProvider(this._network._provider) |
||||
for (const contractAddress in contracts) { |
||||
if (contracts[contractAddress].erc20 && !(this.tokenAddresses.includes(contractAddress.toLowerCase()))) { |
||||
this.detectTokenBalance(contractAddress) |
||||
} |
||||
} |
||||
} |
||||
|
||||
/** |
||||
* Find if selectedAddress has tokens with contract in contractAddress. |
||||
* |
||||
* @param {string} contractAddress Hex address of the token contract to explore. |
||||
* @returns {boolean} If balance is detected, token is added. |
||||
* |
||||
*/ |
||||
async detectTokenBalance (contractAddress) { |
||||
const ethContract = this.web3.eth.contract(ERC20_ABI).at(contractAddress) |
||||
ethContract.balanceOf(this.selectedAddress, (error, result) => { |
||||
if (!error) { |
||||
if (!result.isZero()) { |
||||
this._preferences.addToken(contractAddress, contracts[contractAddress].symbol, contracts[contractAddress].decimals) |
||||
} |
||||
} else { |
||||
warn(`MetaMask - DetectTokensController balance fetch failed for ${contractAddress}.`, error) |
||||
} |
||||
}) |
||||
} |
||||
|
||||
/** |
||||
* Restart token detection polling period and call detectNewTokens |
||||
* in case of address change or user session initialization. |
||||
* |
||||
*/ |
||||
restartTokenDetection () { |
||||
if (this.isActive && this.selectedAddress) { |
||||
this.detectNewTokens() |
||||
this.interval = DEFAULT_INTERVAL |
||||
} |
||||
} |
||||
|
||||
/** |
||||
* @type {Number} |
||||
*/ |
||||
set interval (interval) { |
||||
this._handle && clearInterval(this._handle) |
||||
if (!interval) { return } |
||||
this._handle = setInterval(() => { this.detectNewTokens() }, interval) |
||||
} |
||||
|
||||
/** |
||||
* In setter when selectedAddress is changed, detectNewTokens and restart polling |
||||
* @type {Object} |
||||
*/ |
||||
set preferences (preferences) { |
||||
if (!preferences) { return } |
||||
this._preferences = preferences |
||||
preferences.store.subscribe(({ tokens }) => { this.tokenAddresses = tokens.map((obj) => { return obj.address }) }) |
||||
preferences.store.subscribe(({ selectedAddress }) => { |
||||
if (this.selectedAddress !== selectedAddress) { |
||||
this.selectedAddress = selectedAddress |
||||
this.restartTokenDetection() |
||||
} |
||||
}) |
||||
} |
||||
|
||||
/** |
||||
* @type {Object} |
||||
*/ |
||||
set network (network) { |
||||
if (!network) { return } |
||||
this._network = network |
||||
this.web3 = new Web3(network._provider) |
||||
} |
||||
|
||||
/** |
||||
* In setter when isUnlocked is updated to true, detectNewTokens and restart polling |
||||
* @type {Object} |
||||
*/ |
||||
set keyringMemStore (keyringMemStore) { |
||||
if (!keyringMemStore) { return } |
||||
this._keyringMemStore = keyringMemStore |
||||
this._keyringMemStore.subscribe(({ isUnlocked }) => { |
||||
if (this.isUnlocked !== isUnlocked) { |
||||
if (isUnlocked) { this.restartTokenDetection() } |
||||
this.isUnlocked = isUnlocked |
||||
} |
||||
}) |
||||
} |
||||
} |
||||
|
||||
module.exports = DetectTokensController |
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@ -0,0 +1,25 @@ |
||||
# Using the TREZOR simulator |
||||
|
||||
You can install the TREZOR emulator and use it with Metamask. |
||||
Here is how: |
||||
|
||||
## 1 - Install the TREZOR Bridge |
||||
|
||||
Download the corresponding bridge for your platform from [this url](https://wallet.trezor.io/data/bridge/latest/index.html) |
||||
|
||||
## 2 - Download and build the simulator |
||||
|
||||
Follow this instructions: https://github.com/trezor/trezor-core/blob/master/docs/build.md |
||||
|
||||
## 3 - Restart the bridge with emulator support (Mac OSx instructions) |
||||
|
||||
` |
||||
# stop any existing instance of trezord |
||||
killall trezord |
||||
|
||||
# start the bridge for the simulator |
||||
/Applications/Utilities/TREZOR\ Bridge/trezord -e 21324 >> /dev/null 2>&1 & |
||||
|
||||
# launch the emulator |
||||
~/trezor-core/emu.sh |
||||
` |
File diff suppressed because one or more lines are too long
@ -0,0 +1,120 @@ |
||||
const assert = require('assert') |
||||
const sinon = require('sinon') |
||||
const ObservableStore = require('obs-store') |
||||
const DetectTokensController = require('../../../../app/scripts/controllers/detect-tokens') |
||||
const NetworkController = require('../../../../app/scripts/controllers/network/network') |
||||
const PreferencesController = require('../../../../app/scripts/controllers/preferences') |
||||
|
||||
describe('DetectTokensController', () => { |
||||
const sandbox = sinon.createSandbox() |
||||
let clock |
||||
let keyringMemStore |
||||
before(async () => { |
||||
keyringMemStore = new ObservableStore({ isUnlocked: false}) |
||||
}) |
||||
after(() => { |
||||
sandbox.restore() |
||||
}) |
||||
|
||||
it('should poll on correct interval', async () => { |
||||
const stub = sinon.stub(global, 'setInterval') |
||||
new DetectTokensController({ interval: 1337 }) // eslint-disable-line no-new
|
||||
assert.strictEqual(stub.getCall(0).args[1], 1337) |
||||
stub.restore() |
||||
}) |
||||
|
||||
it('should be called on every polling period', async () => { |
||||
clock = sandbox.useFakeTimers() |
||||
const network = new NetworkController() |
||||
network.setProviderType('mainnet') |
||||
const preferences = new PreferencesController() |
||||
const controller = new DetectTokensController({ preferences: preferences, network: network, keyringMemStore: keyringMemStore }) |
||||
controller.isActive = true |
||||
|
||||
var stub = sandbox.stub(controller, 'detectNewTokens') |
||||
|
||||
clock.tick(1) |
||||
sandbox.assert.notCalled(stub) |
||||
clock.tick(180000) |
||||
sandbox.assert.called(stub) |
||||
clock.tick(180000) |
||||
sandbox.assert.calledTwice(stub) |
||||
clock.tick(180000) |
||||
sandbox.assert.calledThrice(stub) |
||||
}) |
||||
|
||||
it('should not check tokens while in test network', async () => { |
||||
const network = new NetworkController() |
||||
network.setProviderType('rinkeby') |
||||
const preferences = new PreferencesController() |
||||
const controller = new DetectTokensController({ preferences: preferences, network: network, keyringMemStore: keyringMemStore }) |
||||
controller.isActive = true |
||||
|
||||
var stub = sandbox.stub(controller, 'detectTokenBalance') |
||||
.withArgs('0x0D262e5dC4A06a0F1c90cE79C7a60C09DfC884E4').returns(true) |
||||
.withArgs('0xBC86727E770de68B1060C91f6BB6945c73e10388').returns(true) |
||||
|
||||
await controller.detectNewTokens() |
||||
sandbox.assert.notCalled(stub) |
||||
}) |
||||
|
||||
it('should only check and add tokens while in main network', async () => { |
||||
const network = new NetworkController() |
||||
network.setProviderType('mainnet') |
||||
const preferences = new PreferencesController() |
||||
const controller = new DetectTokensController({ preferences: preferences, network: network, keyringMemStore: keyringMemStore }) |
||||
controller.isActive = true |
||||
|
||||
sandbox.stub(controller, 'detectTokenBalance') |
||||
.withArgs('0x0D262e5dC4A06a0F1c90cE79C7a60C09DfC884E4') |
||||
.returns(preferences.addToken('0x0d262e5dc4a06a0f1c90ce79c7a60c09dfc884e4', 'J8T', 8)) |
||||
.withArgs('0xBC86727E770de68B1060C91f6BB6945c73e10388') |
||||
.returns(preferences.addToken('0xbc86727e770de68b1060c91f6bb6945c73e10388', 'XNK', 18)) |
||||
|
||||
await controller.detectNewTokens() |
||||
assert.deepEqual(preferences.store.getState().tokens, [{address: '0x0d262e5dc4a06a0f1c90ce79c7a60c09dfc884e4', decimals: 8, symbol: 'J8T'}, |
||||
{address: '0xbc86727e770de68b1060c91f6bb6945c73e10388', decimals: 18, symbol: 'XNK'}]) |
||||
}) |
||||
|
||||
it('should not detect same token while in main network', async () => { |
||||
const network = new NetworkController() |
||||
network.setProviderType('mainnet') |
||||
const preferences = new PreferencesController() |
||||
preferences.addToken('0x0d262e5dc4a06a0f1c90ce79c7a60c09dfc884e4', 'J8T', 8) |
||||
const controller = new DetectTokensController({ preferences: preferences, network: network, keyringMemStore: keyringMemStore }) |
||||
controller.isActive = true |
||||
|
||||
sandbox.stub(controller, 'detectTokenBalance') |
||||
.withArgs('0x0D262e5dC4A06a0F1c90cE79C7a60C09DfC884E4') |
||||
.returns(preferences.addToken('0x0d262e5dc4a06a0f1c90ce79c7a60c09dfc884e4', 'J8T', 8)) |
||||
.withArgs('0xBC86727E770de68B1060C91f6BB6945c73e10388') |
||||
.returns(preferences.addToken('0xbc86727e770de68b1060c91f6bb6945c73e10388', 'XNK', 18)) |
||||
|
||||
await controller.detectNewTokens() |
||||
assert.deepEqual(preferences.store.getState().tokens, [{address: '0x0d262e5dc4a06a0f1c90ce79c7a60c09dfc884e4', decimals: 8, symbol: 'J8T'}, |
||||
{address: '0xbc86727e770de68b1060c91f6bb6945c73e10388', decimals: 18, symbol: 'XNK'}]) |
||||
}) |
||||
|
||||
it('should trigger detect new tokens when change address', async () => { |
||||
const network = new NetworkController() |
||||
network.setProviderType('mainnet') |
||||
const preferences = new PreferencesController() |
||||
const controller = new DetectTokensController({ preferences: preferences, network: network, keyringMemStore: keyringMemStore }) |
||||
controller.isActive = true |
||||
var stub = sandbox.stub(controller, 'detectNewTokens') |
||||
await preferences.setSelectedAddress('0xbc86727e770de68b1060c91f6bb6945c73e10388') |
||||
sandbox.assert.called(stub) |
||||
}) |
||||
|
||||
it('should trigger detect new tokens when submit password', async () => { |
||||
const network = new NetworkController() |
||||
network.setProviderType('mainnet') |
||||
const preferences = new PreferencesController() |
||||
const controller = new DetectTokensController({ preferences: preferences, network: network, keyringMemStore: keyringMemStore }) |
||||
controller.isActive = true |
||||
controller.selectedAddress = '0x0' |
||||
var stub = sandbox.stub(controller, 'detectNewTokens') |
||||
await controller._keyringMemStore.updateState({ isUnlocked: true }) |
||||
sandbox.assert.called(stub) |
||||
}) |
||||
}) |
@ -1,67 +0,0 @@ |
||||
const assert = require('assert') |
||||
const h = require('react-hyperscript') |
||||
const PendingTx = require('../../../ui/app/components/pending-tx') |
||||
const ethUtil = require('ethereumjs-util') |
||||
|
||||
const { createMockStore } = require('redux-test-utils') |
||||
const { shallowWithStore } = require('../../lib/shallow-with-store') |
||||
|
||||
const identities = { abc: {}, def: {} } |
||||
const mockState = { |
||||
metamask: { |
||||
accounts: { abc: {} }, |
||||
identities, |
||||
conversionRate: 10, |
||||
selectedAddress: 'abc', |
||||
}, |
||||
} |
||||
|
||||
describe('PendingTx', function () { |
||||
const gasPrice = '0x4A817C800' // 20 Gwei
|
||||
const txData = { |
||||
'id': 5021615666270214, |
||||
'time': 1494458763011, |
||||
'status': 'unapproved', |
||||
'metamaskNetworkId': '1494442339676', |
||||
'txParams': { |
||||
'from': '0xfdea65c8e26263f6d9a1b5de9555d2931a33b826', |
||||
'to': '0xc5b8dbac4c1d3f152cdeb400e2313f309c410acb', |
||||
'value': '0xde0b6b3a7640000', |
||||
gasPrice, |
||||
'gas': '0x7b0c', |
||||
}, |
||||
'gasLimitSpecified': false, |
||||
'estimatedGas': '0x5208', |
||||
} |
||||
const newGasPrice = '0x77359400' |
||||
|
||||
const computedBalances = {} |
||||
computedBalances[Object.keys(identities)[0]] = { |
||||
ethBalance: '0x00000000000000056bc75e2d63100000', |
||||
} |
||||
const props = { |
||||
txData, |
||||
computedBalances, |
||||
sendTransaction: (txMeta, event) => { |
||||
// Assert changes:
|
||||
const result = ethUtil.addHexPrefix(txMeta.txParams.gasPrice) |
||||
assert.notEqual(result, gasPrice, 'gas price should change') |
||||
assert.equal(result, newGasPrice, 'gas price assigned.') |
||||
}, |
||||
} |
||||
|
||||
let pendingTxComponent |
||||
let store |
||||
let component |
||||
beforeEach(function () { |
||||
store = createMockStore(mockState) |
||||
component = shallowWithStore(h(PendingTx, props), store) |
||||
pendingTxComponent = component |
||||
}) |
||||
|
||||
it('should render correctly', function (done) { |
||||
assert.equal(pendingTxComponent.props().identities, identities) |
||||
done() |
||||
}) |
||||
}) |
||||
|
@ -0,0 +1,22 @@ |
||||
const { Component } = require('react') |
||||
const PropTypes = require('prop-types') |
||||
const h = require('react-hyperscript') |
||||
|
||||
class Alert extends Component { |
||||
|
||||
render () { |
||||
const className = `.global-alert${this.props.visible ? '.visible' : '.hidden'}` |
||||
return ( |
||||
h(`div${className}`, {}, |
||||
h('a.msg', {}, this.props.msg) |
||||
) |
||||
) |
||||
} |
||||
} |
||||
|
||||
Alert.propTypes = { |
||||
visible: PropTypes.bool.isRequired, |
||||
msg: PropTypes.string, |
||||
} |
||||
module.exports = Alert |
||||
|
@ -0,0 +1,93 @@ |
||||
import React, { Component } from 'react' |
||||
import PropTypes from 'prop-types' |
||||
import Button from '../../button' |
||||
import { addressSummary } from '../../../util' |
||||
import Identicon from '../../identicon' |
||||
import genAccountLink from '../../../../lib/account-link' |
||||
|
||||
class ConfirmRemoveAccount extends Component { |
||||
static propTypes = { |
||||
hideModal: PropTypes.func.isRequired, |
||||
removeAccount: PropTypes.func.isRequired, |
||||
identity: PropTypes.object.isRequired, |
||||
network: PropTypes.string.isRequired, |
||||
} |
||||
|
||||
static contextTypes = { |
||||
t: PropTypes.func, |
||||
} |
||||
|
||||
handleRemove () { |
||||
this.props.removeAccount(this.props.identity.address) |
||||
.then(() => this.props.hideModal()) |
||||
} |
||||
|
||||
renderSelectedAccount () { |
||||
const { identity } = this.props |
||||
return ( |
||||
<div className="modal-container__account"> |
||||
<div className="modal-container__account__identicon"> |
||||
<Identicon |
||||
address={identity.address} |
||||
diameter={32} |
||||
/> |
||||
</div> |
||||
<div className="modal-container__account__name"> |
||||
<span className="modal-container__account__label">Name</span> |
||||
<span className="account_value">{identity.name}</span> |
||||
</div> |
||||
<div className="modal-container__account__address"> |
||||
<span className="modal-container__account__label">Public Address</span> |
||||
<span className="account_value">{ addressSummary(identity.address, 4, 4) }</span> |
||||
</div> |
||||
<div className="modal-container__account__link"> |
||||
<a |
||||
className="" |
||||
href={genAccountLink(identity.address, this.props.network)} |
||||
target={'_blank'} |
||||
title={this.context.t('etherscanView')} |
||||
> |
||||
<img src="images/popout.svg" /> |
||||
</a> |
||||
</div> |
||||
</div> |
||||
) |
||||
} |
||||
|
||||
render () { |
||||
const { t } = this.context |
||||
|
||||
return ( |
||||
<div className="modal-container"> |
||||
<div className="modal-container__content"> |
||||
<div className="modal-container__title"> |
||||
{ `${t('removeAccount')}` }? |
||||
</div> |
||||
{ this.renderSelectedAccount() } |
||||
<div className="modal-container__description"> |
||||
{ t('removeAccountDescription') } |
||||
<a className="modal-container__link" rel="noopener noreferrer" target="_blank" href="https://consensys.zendesk.com/hc/en-us/articles/360004180111-What-are-imported-accounts-New-UI-">{ t('learnMore') }</a> |
||||
</div> |
||||
</div> |
||||
<div className="modal-container__footer"> |
||||
<Button |
||||
type="default" |
||||
className="modal-container__footer-button" |
||||
onClick={() => this.props.hideModal()} |
||||
> |
||||
{ t('nevermind') } |
||||
</Button> |
||||
<Button |
||||
type="secondary" |
||||
className="modal-container__footer-button" |
||||
onClick={() => this.handleRemove()} |
||||
> |
||||
{ t('remove') } |
||||
</Button> |
||||
</div> |
||||
</div> |
||||
) |
||||
} |
||||
} |
||||
|
||||
export default ConfirmRemoveAccount |
@ -0,0 +1,20 @@ |
||||
import { connect } from 'react-redux' |
||||
import ConfirmRemoveAccount from './confirm-remove-account.component' |
||||
|
||||
const { hideModal, removeAccount } = require('../../../actions') |
||||
|
||||
const mapStateToProps = state => { |
||||
return { |
||||
identity: state.appState.modal.modalState.props.identity, |
||||
network: state.metamask.network, |
||||
} |
||||
} |
||||
|
||||
const mapDispatchToProps = dispatch => { |
||||
return { |
||||
hideModal: () => dispatch(hideModal()), |
||||
removeAccount: (address) => dispatch(removeAccount(address)), |
||||
} |
||||
} |
||||
|
||||
export default connect(mapStateToProps, mapDispatchToProps)(ConfirmRemoveAccount) |
@ -0,0 +1,2 @@ |
||||
import ConfirmRemoveAccount from './confirm-remove-account.container' |
||||
module.exports = ConfirmRemoveAccount |
@ -1,19 +0,0 @@ |
||||
.confirm-send-token { |
||||
&__title { |
||||
padding: 4px 0; |
||||
display: flex; |
||||
align-items: center; |
||||
} |
||||
|
||||
&__identicon { |
||||
flex: 0 0 auto; |
||||
} |
||||
|
||||
&__title-text { |
||||
font-size: 2.25rem; |
||||
white-space: nowrap; |
||||
overflow: hidden; |
||||
text-overflow: ellipsis; |
||||
padding-left: 8px; |
||||
} |
||||
} |
@ -0,0 +1,85 @@ |
||||
import React, { Component } from 'react' |
||||
import PropTypes from 'prop-types' |
||||
import ConfirmTransactionBase from '../confirm-transaction-base' |
||||
import { |
||||
formatCurrency, |
||||
convertTokenToFiat, |
||||
addFiat, |
||||
} from '../../../helpers/confirm-transaction/util' |
||||
|
||||
export default class ConfirmTokenTransactionBase extends Component { |
||||
static contextTypes = { |
||||
t: PropTypes.func, |
||||
} |
||||
|
||||
static propTypes = { |
||||
tokenAddress: PropTypes.string, |
||||
toAddress: PropTypes.string, |
||||
tokenAmount: PropTypes.number, |
||||
tokenSymbol: PropTypes.string, |
||||
fiatTransactionTotal: PropTypes.string, |
||||
ethTransactionTotal: PropTypes.string, |
||||
contractExchangeRate: PropTypes.number, |
||||
conversionRate: PropTypes.number, |
||||
currentCurrency: PropTypes.string, |
||||
} |
||||
|
||||
getFiatTransactionAmount () { |
||||
const { tokenAmount, currentCurrency, conversionRate, contractExchangeRate } = this.props |
||||
|
||||
return convertTokenToFiat({ |
||||
value: tokenAmount, |
||||
toCurrency: currentCurrency, |
||||
conversionRate, |
||||
contractExchangeRate, |
||||
}) |
||||
} |
||||
|
||||
getSubtitle () { |
||||
const { currentCurrency, contractExchangeRate } = this.props |
||||
|
||||
if (typeof contractExchangeRate === 'undefined') { |
||||
return this.context.t('noConversionRateAvailable') |
||||
} else { |
||||
const fiatTransactionAmount = this.getFiatTransactionAmount() |
||||
return formatCurrency(fiatTransactionAmount, currentCurrency) |
||||
} |
||||
} |
||||
|
||||
getFiatTotalTextOverride () { |
||||
const { fiatTransactionTotal, currentCurrency, contractExchangeRate } = this.props |
||||
|
||||
if (typeof contractExchangeRate === 'undefined') { |
||||
return formatCurrency(fiatTransactionTotal, currentCurrency) |
||||
} else { |
||||
const fiatTransactionAmount = this.getFiatTransactionAmount() |
||||
const fiatTotal = addFiat(fiatTransactionAmount, fiatTransactionTotal) |
||||
return formatCurrency(fiatTotal, currentCurrency) |
||||
} |
||||
} |
||||
|
||||
render () { |
||||
const { |
||||
toAddress, |
||||
tokenAddress, |
||||
tokenSymbol, |
||||
tokenAmount, |
||||
ethTransactionTotal, |
||||
...restProps |
||||
} = this.props |
||||
|
||||
const tokensText = `${tokenAmount} ${tokenSymbol}` |
||||
|
||||
return ( |
||||
<ConfirmTransactionBase |
||||
toAddress={toAddress} |
||||
identiconAddress={tokenAddress} |
||||
title={tokensText} |
||||
subtitle={this.getSubtitle()} |
||||
ethTotalTextOverride={`${tokensText} + \u2666 ${ethTransactionTotal}`} |
||||
fiatTotalTextOverride={this.getFiatTotalTextOverride()} |
||||
{...restProps} |
||||
/> |
||||
) |
||||
} |
||||
} |
@ -0,0 +1,34 @@ |
||||
import { connect } from 'react-redux' |
||||
import ConfirmTokenTransactionBase from './confirm-token-transaction-base.component' |
||||
import { |
||||
tokenAmountAndToAddressSelector, |
||||
contractExchangeRateSelector, |
||||
} from '../../../selectors/confirm-transaction' |
||||
|
||||
const mapStateToProps = (state, ownProps) => { |
||||
const { tokenAmount: ownTokenAmount } = ownProps |
||||
const { confirmTransaction, metamask: { currentCurrency, conversionRate } } = state |
||||
const { |
||||
txData: { txParams: { to: tokenAddress } = {} } = {}, |
||||
tokenProps: { tokenSymbol } = {}, |
||||
fiatTransactionTotal, |
||||
ethTransactionTotal, |
||||
} = confirmTransaction |
||||
|
||||
const { tokenAmount, toAddress } = tokenAmountAndToAddressSelector(state) |
||||
const contractExchangeRate = contractExchangeRateSelector(state) |
||||
|
||||
return { |
||||
toAddress, |
||||
tokenAddress, |
||||
tokenAmount: typeof ownTokenAmount !== 'undefined' ? ownTokenAmount : tokenAmount, |
||||
tokenSymbol, |
||||
currentCurrency, |
||||
conversionRate, |
||||
contractExchangeRate, |
||||
fiatTransactionTotal, |
||||
ethTransactionTotal, |
||||
} |
||||
} |
||||
|
||||
export default connect(mapStateToProps)(ConfirmTokenTransactionBase) |
@ -0,0 +1,2 @@ |
||||
export { default } from './confirm-token-transaction-base.container' |
||||
export { default as ConfirmTokenTransactionBase } from './confirm-token-transaction-base.component' |
@ -1,2 +1,3 @@ |
||||
export const TOKEN_METHOD_TRANSFER = 'transfer' |
||||
export const TOKEN_METHOD_APPROVE = 'approve' |
||||
export const TOKEN_METHOD_TRANSFER_FROM = 'transferfrom' |
||||
|
@ -0,0 +1,143 @@ |
||||
const { Component } = require('react') |
||||
const PropTypes = require('prop-types') |
||||
const h = require('react-hyperscript') |
||||
const genAccountLink = require('../../../../../lib/account-link.js') |
||||
|
||||
class AccountList extends Component { |
||||
constructor (props, context) { |
||||
super(props) |
||||
} |
||||
|
||||
renderHeader () { |
||||
return ( |
||||
h('div.hw-connect', [ |
||||
h('h3.hw-connect__title', {}, this.context.t('selectAnAccount')), |
||||
h('p.hw-connect__msg', {}, this.context.t('selectAnAccountHelp')), |
||||
]) |
||||
) |
||||
} |
||||
|
||||
renderAccounts () { |
||||
return h('div.hw-account-list', [ |
||||
this.props.accounts.map((a, i) => { |
||||
|
||||
return h('div.hw-account-list__item', { key: a.address }, [ |
||||
h('div.hw-account-list__item__radio', [ |
||||
h('input', { |
||||
type: 'radio', |
||||
name: 'selectedAccount', |
||||
id: `address-${i}`, |
||||
value: a.index, |
||||
onChange: (e) => this.props.onAccountChange(e.target.value), |
||||
checked: this.props.selectedAccount === a.index.toString(), |
||||
}), |
||||
h( |
||||
'label.hw-account-list__item__label', |
||||
{ |
||||
htmlFor: `address-${i}`, |
||||
}, |
||||
[ |
||||
h('span.hw-account-list__item__index', a.index + 1), |
||||
`${a.address.slice(0, 4)}...${a.address.slice(-4)}`, |
||||
h('span.hw-account-list__item__balance', `${a.balance}`), |
||||
]), |
||||
]), |
||||
h( |
||||
'a.hw-account-list__item__link', |
||||
{ |
||||
href: genAccountLink(a.address, this.props.network), |
||||
target: '_blank', |
||||
title: this.context.t('etherscanView'), |
||||
}, |
||||
h('img', { src: 'images/popout.svg' }) |
||||
), |
||||
]) |
||||
}), |
||||
]) |
||||
} |
||||
|
||||
renderPagination () { |
||||
return h('div.hw-list-pagination', [ |
||||
h( |
||||
'button.hw-list-pagination__button', |
||||
{ |
||||
onClick: () => this.props.getPage(-1), |
||||
}, |
||||
`< ${this.context.t('prev')}` |
||||
), |
||||
|
||||
h( |
||||
'button.hw-list-pagination__button', |
||||
{ |
||||
onClick: () => this.props.getPage(1), |
||||
}, |
||||
`${this.context.t('next')} >` |
||||
), |
||||
]) |
||||
} |
||||
|
||||
renderButtons () { |
||||
const disabled = this.props.selectedAccount === null |
||||
const buttonProps = {} |
||||
if (disabled) { |
||||
buttonProps.disabled = true |
||||
} |
||||
|
||||
return h('div.new-account-connect-form__buttons', {}, [ |
||||
h( |
||||
'button.btn-default.btn--large.new-account-connect-form__button', |
||||
{ |
||||
onClick: this.props.onCancel.bind(this), |
||||
}, |
||||
[this.context.t('cancel')] |
||||
), |
||||
|
||||
h( |
||||
`button.btn-primary.btn--large.new-account-connect-form__button.unlock ${disabled ? '.btn-primary--disabled' : ''}`, |
||||
{ |
||||
onClick: this.props.onUnlockAccount.bind(this), |
||||
...buttonProps, |
||||
}, |
||||
[this.context.t('unlock')] |
||||
), |
||||
]) |
||||
} |
||||
|
||||
renderForgetDevice () { |
||||
return h('div.hw-forget-device-container', {}, [ |
||||
h('a', { |
||||
onClick: this.props.onForgetDevice.bind(this), |
||||
}, this.context.t('forgetDevice')), |
||||
]) |
||||
} |
||||
|
||||
render () { |
||||
return h('div.new-account-connect-form.account-list', {}, [ |
||||
this.renderHeader(), |
||||
this.renderAccounts(), |
||||
this.renderPagination(), |
||||
this.renderButtons(), |
||||
this.renderForgetDevice(), |
||||
]) |
||||
} |
||||
|
||||
} |
||||
|
||||
|
||||
AccountList.propTypes = { |
||||
accounts: PropTypes.array.isRequired, |
||||
onAccountChange: PropTypes.func.isRequired, |
||||
onForgetDevice: PropTypes.func.isRequired, |
||||
getPage: PropTypes.func.isRequired, |
||||
network: PropTypes.string, |
||||
selectedAccount: PropTypes.string, |
||||
history: PropTypes.object, |
||||
onUnlockAccount: PropTypes.func, |
||||
onCancel: PropTypes.func, |
||||
} |
||||
|
||||
AccountList.contextTypes = { |
||||
t: PropTypes.func, |
||||
} |
||||
|
||||
module.exports = AccountList |
@ -0,0 +1,149 @@ |
||||
const { Component } = require('react') |
||||
const PropTypes = require('prop-types') |
||||
const h = require('react-hyperscript') |
||||
|
||||
class ConnectScreen extends Component { |
||||
constructor (props, context) { |
||||
super(props) |
||||
} |
||||
|
||||
renderUnsupportedBrowser () { |
||||
return ( |
||||
h('div.new-account-connect-form.unsupported-browser', {}, [ |
||||
h('div.hw-connect', [ |
||||
h('h3.hw-connect__title', {}, this.context.t('browserNotSupported')), |
||||
h('p.hw-connect__msg', {}, this.context.t('chromeRequiredForTrezor')), |
||||
]), |
||||
h( |
||||
'button.btn-primary.btn--large', |
||||
{ |
||||
onClick: () => global.platform.openWindow({ |
||||
url: 'https://google.com/chrome', |
||||
}), |
||||
}, |
||||
this.context.t('downloadGoogleChrome') |
||||
), |
||||
]) |
||||
) |
||||
} |
||||
|
||||
renderHeader () { |
||||
return ( |
||||
h('div.hw-connect__header', {}, [ |
||||
h('h3.hw-connect__header__title', {}, this.context.t(`hardwareSupport`)), |
||||
h('p.hw-connect__header__msg', {}, this.context.t(`hardwareSupportMsg`)), |
||||
]) |
||||
) |
||||
} |
||||
|
||||
renderTrezorAffiliateLink () { |
||||
return h('div.hw-connect__get-trezor', {}, [ |
||||
h('p.hw-connect__get-trezor__msg', {}, this.context.t(`dontHaveATrezorWallet`)), |
||||
h('a.hw-connect__get-trezor__link', { |
||||
href: 'https://shop.trezor.io/?a=metamask', |
||||
target: '_blank', |
||||
}, this.context.t('orderOneHere')), |
||||
]) |
||||
} |
||||
|
||||
renderConnectToTrezorButton () { |
||||
return h( |
||||
'button.btn-primary.btn--large', |
||||
{ onClick: this.props.connectToTrezor.bind(this) }, |
||||
this.props.btnText |
||||
) |
||||
} |
||||
|
||||
scrollToTutorial = (e) => { |
||||
if (this.referenceNode) this.referenceNode.scrollIntoView({behavior: 'smooth'}) |
||||
} |
||||
|
||||
renderLearnMore () { |
||||
return ( |
||||
h('p.hw-connect__learn-more', { |
||||
onClick: this.scrollToTutorial, |
||||
}, [ |
||||
this.context.t('learnMore'), |
||||
h('img.hw-connect__learn-more__arrow', { src: 'images/caret-right.svg'}), |
||||
]) |
||||
) |
||||
} |
||||
|
||||
renderTutorialSteps () { |
||||
const steps = [ |
||||
{ |
||||
asset: 'hardware-wallet-step-1', |
||||
dimensions: {width: '225px', height: '75px'}, |
||||
}, |
||||
{ |
||||
asset: 'hardware-wallet-step-2', |
||||
dimensions: {width: '300px', height: '100px'}, |
||||
}, |
||||
{ |
||||
asset: 'hardware-wallet-step-3', |
||||
dimensions: {width: '120px', height: '90px'}, |
||||
}, |
||||
] |
||||
|
||||
return h('.hw-tutorial', { |
||||
ref: node => { this.referenceNode = node }, |
||||
}, |
||||
steps.map((step, i) => ( |
||||
h('div.hw-connect', {}, [ |
||||
h('h3.hw-connect__title', {}, this.context.t(`step${i + 1}HardwareWallet`)), |
||||
h('p.hw-connect__msg', {}, this.context.t(`step${i + 1}HardwareWalletMsg`)), |
||||
h('img.hw-connect__step-asset', { src: `images/${step.asset}.svg`, ...step.dimensions }), |
||||
]) |
||||
)) |
||||
) |
||||
} |
||||
|
||||
renderFooter () { |
||||
return ( |
||||
h('div.hw-connect__footer', {}, [ |
||||
h('h3.hw-connect__footer__title', {}, this.context.t(`readyToConnect`)), |
||||
this.renderConnectToTrezorButton(), |
||||
h('p.hw-connect__footer__msg', {}, [ |
||||
this.context.t(`havingTroubleConnecting`), |
||||
h('a.hw-connect__footer__link', { |
||||
href: 'https://support.metamask.io/', |
||||
target: '_blank', |
||||
}, this.context.t('getHelp')), |
||||
]), |
||||
]) |
||||
) |
||||
} |
||||
|
||||
renderConnectScreen () { |
||||
return ( |
||||
h('div.new-account-connect-form', {}, [ |
||||
this.renderHeader(), |
||||
this.renderTrezorAffiliateLink(), |
||||
this.renderConnectToTrezorButton(), |
||||
this.renderLearnMore(), |
||||
this.renderTutorialSteps(), |
||||
this.renderFooter(), |
||||
]) |
||||
) |
||||
} |
||||
|
||||
render () { |
||||
if (this.props.browserSupported) { |
||||
return this.renderConnectScreen() |
||||
} |
||||
return this.renderUnsupportedBrowser() |
||||
} |
||||
} |
||||
|
||||
ConnectScreen.propTypes = { |
||||
connectToTrezor: PropTypes.func.isRequired, |
||||
btnText: PropTypes.string.isRequired, |
||||
browserSupported: PropTypes.bool.isRequired, |
||||
} |
||||
|
||||
ConnectScreen.contextTypes = { |
||||
t: PropTypes.func, |
||||
} |
||||
|
||||
module.exports = ConnectScreen |
||||
|
@ -0,0 +1,234 @@ |
||||
const { Component } = require('react') |
||||
const PropTypes = require('prop-types') |
||||
const h = require('react-hyperscript') |
||||
const connect = require('react-redux').connect |
||||
const actions = require('../../../../actions') |
||||
const ConnectScreen = require('./connect-screen') |
||||
const AccountList = require('./account-list') |
||||
const { DEFAULT_ROUTE } = require('../../../../routes') |
||||
const { formatBalance } = require('../../../../util') |
||||
|
||||
class ConnectHardwareForm extends Component { |
||||
constructor (props, context) { |
||||
super(props) |
||||
this.state = { |
||||
error: null, |
||||
btnText: context.t('connectToTrezor'), |
||||
selectedAccount: null, |
||||
accounts: [], |
||||
browserSupported: true, |
||||
} |
||||
} |
||||
|
||||
componentWillReceiveProps (nextProps) { |
||||
const { accounts } = nextProps |
||||
const newAccounts = this.state.accounts.map(a => { |
||||
const normalizedAddress = a.address.toLowerCase() |
||||
const balanceValue = accounts[normalizedAddress] && accounts[normalizedAddress].balance || null |
||||
a.balance = balanceValue ? formatBalance(balanceValue, 6) : '...' |
||||
return a |
||||
}) |
||||
this.setState({accounts: newAccounts}) |
||||
} |
||||
|
||||
|
||||
async componentDidMount () { |
||||
const unlocked = await this.props.checkHardwareStatus('trezor') |
||||
if (unlocked) { |
||||
this.getPage(0) |
||||
} |
||||
} |
||||
|
||||
connectToTrezor = () => { |
||||
if (this.state.accounts.length) { |
||||
return null |
||||
} |
||||
this.setState({ btnText: this.context.t('connecting')}) |
||||
this.getPage(0) |
||||
} |
||||
|
||||
onAccountChange = (account) => { |
||||
this.setState({selectedAccount: account.toString(), error: null}) |
||||
} |
||||
|
||||
showTemporaryAlert () { |
||||
this.props.showAlert(this.context.t('hardwareWalletConnected')) |
||||
// Autohide the alert after 5 seconds
|
||||
setTimeout(_ => { |
||||
this.props.hideAlert() |
||||
}, 5000) |
||||
} |
||||
|
||||
getPage = (page) => { |
||||
this.props |
||||
.connectHardware('trezor', page) |
||||
.then(accounts => { |
||||
if (accounts.length) { |
||||
|
||||
// If we just loaded the accounts for the first time
|
||||
// show the global alert
|
||||
if (this.state.accounts.length === 0) { |
||||
this.showTemporaryAlert() |
||||
} |
||||
|
||||
const newState = {} |
||||
// Default to the first account
|
||||
if (this.state.selectedAccount === null) { |
||||
accounts.forEach((a, i) => { |
||||
if (a.address.toLowerCase() === this.props.address) { |
||||
newState.selectedAccount = a.index.toString() |
||||
} |
||||
}) |
||||
// If the page doesn't contain the selected account, let's deselect it
|
||||
} else if (!accounts.filter(a => a.index.toString() === this.state.selectedAccount).length) { |
||||
newState.selectedAccount = null |
||||
} |
||||
|
||||
|
||||
// Map accounts with balances
|
||||
newState.accounts = accounts.map(account => { |
||||
const normalizedAddress = account.address.toLowerCase() |
||||
const balanceValue = this.props.accounts[normalizedAddress] && this.props.accounts[normalizedAddress].balance || null |
||||
account.balance = balanceValue ? formatBalance(balanceValue, 6) : '...' |
||||
return account |
||||
}) |
||||
|
||||
this.setState(newState) |
||||
} |
||||
}) |
||||
.catch(e => { |
||||
if (e === 'Window blocked') { |
||||
this.setState({ browserSupported: false }) |
||||
} |
||||
this.setState({ btnText: this.context.t('connectToTrezor') }) |
||||
}) |
||||
} |
||||
|
||||
onForgetDevice = () => { |
||||
this.props.forgetDevice('trezor') |
||||
.then(_ => { |
||||
this.setState({ |
||||
error: null, |
||||
btnText: this.context.t('connectToTrezor'), |
||||
selectedAccount: null, |
||||
accounts: [], |
||||
}) |
||||
}).catch(e => { |
||||
this.setState({ error: e.toString() }) |
||||
}) |
||||
} |
||||
|
||||
onUnlockAccount = () => { |
||||
|
||||
if (this.state.selectedAccount === null) { |
||||
this.setState({ error: this.context.t('accountSelectionRequired') }) |
||||
} |
||||
|
||||
this.props.unlockTrezorAccount(this.state.selectedAccount) |
||||
.then(_ => { |
||||
this.props.history.push(DEFAULT_ROUTE) |
||||
}).catch(e => { |
||||
this.setState({ error: e.toString() }) |
||||
}) |
||||
} |
||||
|
||||
onCancel = () => { |
||||
this.props.history.push(DEFAULT_ROUTE) |
||||
} |
||||
|
||||
renderError () { |
||||
return this.state.error |
||||
? h('span.error', { style: { marginBottom: 40 } }, this.state.error) |
||||
: null |
||||
} |
||||
|
||||
renderContent () { |
||||
if (!this.state.accounts.length) { |
||||
return h(ConnectScreen, { |
||||
connectToTrezor: this.connectToTrezor, |
||||
btnText: this.state.btnText, |
||||
browserSupported: this.state.browserSupported, |
||||
}) |
||||
} |
||||
|
||||
return h(AccountList, { |
||||
accounts: this.state.accounts, |
||||
selectedAccount: this.state.selectedAccount, |
||||
onAccountChange: this.onAccountChange, |
||||
network: this.props.network, |
||||
getPage: this.getPage, |
||||
history: this.props.history, |
||||
onUnlockAccount: this.onUnlockAccount, |
||||
onForgetDevice: this.onForgetDevice, |
||||
onCancel: this.onCancel, |
||||
}) |
||||
} |
||||
|
||||
render () { |
||||
return h('div', [ |
||||
this.renderError(), |
||||
this.renderContent(), |
||||
]) |
||||
} |
||||
} |
||||
|
||||
ConnectHardwareForm.propTypes = { |
||||
hideModal: PropTypes.func, |
||||
showImportPage: PropTypes.func, |
||||
showConnectPage: PropTypes.func, |
||||
connectHardware: PropTypes.func, |
||||
checkHardwareStatus: PropTypes.func, |
||||
forgetDevice: PropTypes.func, |
||||
showAlert: PropTypes.func, |
||||
hideAlert: PropTypes.func, |
||||
unlockTrezorAccount: PropTypes.func, |
||||
numberOfExistingAccounts: PropTypes.number, |
||||
history: PropTypes.object, |
||||
t: PropTypes.func, |
||||
network: PropTypes.string, |
||||
accounts: PropTypes.object, |
||||
address: PropTypes.string, |
||||
} |
||||
|
||||
const mapStateToProps = state => { |
||||
const { |
||||
metamask: { network, selectedAddress, identities = {}, accounts = [] }, |
||||
} = state |
||||
const numberOfExistingAccounts = Object.keys(identities).length |
||||
|
||||
return { |
||||
network, |
||||
accounts, |
||||
address: selectedAddress, |
||||
numberOfExistingAccounts, |
||||
} |
||||
} |
||||
|
||||
const mapDispatchToProps = dispatch => { |
||||
return { |
||||
connectHardware: (deviceName, page) => { |
||||
return dispatch(actions.connectHardware(deviceName, page)) |
||||
}, |
||||
checkHardwareStatus: (deviceName) => { |
||||
return dispatch(actions.checkHardwareStatus(deviceName)) |
||||
}, |
||||
forgetDevice: (deviceName) => { |
||||
return dispatch(actions.forgetDevice(deviceName)) |
||||
}, |
||||
unlockTrezorAccount: index => { |
||||
return dispatch(actions.unlockTrezorAccount(index)) |
||||
}, |
||||
showImportPage: () => dispatch(actions.showImportPage()), |
||||
showConnectPage: () => dispatch(actions.showConnectPage()), |
||||
showAlert: (msg) => dispatch(actions.showAlert(msg)), |
||||
hideAlert: () => dispatch(actions.hideAlert()), |
||||
} |
||||
} |
||||
|
||||
ConnectHardwareForm.contextTypes = { |
||||
t: PropTypes.func, |
||||
} |
||||
|
||||
module.exports = connect(mapStateToProps, mapDispatchToProps)( |
||||
ConnectHardwareForm |
||||
) |
@ -1,358 +0,0 @@ |
||||
const { Component } = require('react') |
||||
const connect = require('react-redux').connect |
||||
const h = require('react-hyperscript') |
||||
const PropTypes = require('prop-types') |
||||
const actions = require('../../actions') |
||||
const clone = require('clone') |
||||
const ethUtil = require('ethereumjs-util') |
||||
const BN = ethUtil.BN |
||||
const hexToBn = require('../../../../app/scripts/lib/hex-to-bn') |
||||
const { conversionUtil } = require('../../conversion-util') |
||||
const SenderToRecipient = require('../sender-to-recipient') |
||||
const NetworkDisplay = require('../network-display') |
||||
|
||||
const { MIN_GAS_PRICE_HEX } = require('../send_/send.constants') |
||||
|
||||
class ConfirmDeployContract extends Component { |
||||
constructor (props) { |
||||
super(props) |
||||
|
||||
this.state = { |
||||
valid: false, |
||||
submitting: false, |
||||
} |
||||
} |
||||
|
||||
onSubmit (event) { |
||||
event.preventDefault() |
||||
const txMeta = this.gatherTxMeta() |
||||
const valid = this.checkValidity() |
||||
this.setState({ valid, submitting: true }) |
||||
|
||||
if (valid && this.verifyGasParams()) { |
||||
this.props.sendTransaction(txMeta, event) |
||||
} else { |
||||
this.props.displayWarning(this.context.t('invalidGasParams')) |
||||
this.setState({ submitting: false }) |
||||
} |
||||
} |
||||
|
||||
cancel (event, txMeta) { |
||||
event.preventDefault() |
||||
this.props.cancelTransaction(txMeta) |
||||
} |
||||
|
||||
checkValidity () { |
||||
const form = this.getFormEl() |
||||
const valid = form.checkValidity() |
||||
return valid |
||||
} |
||||
|
||||
getFormEl () { |
||||
const form = document.querySelector('form#pending-tx-form') |
||||
// Stub out form for unit tests:
|
||||
if (!form) { |
||||
return { checkValidity () { return true } } |
||||
} |
||||
return form |
||||
} |
||||
|
||||
// After a customizable state value has been updated,
|
||||
gatherTxMeta () { |
||||
const props = this.props |
||||
const state = this.state |
||||
const txData = clone(state.txData) || clone(props.txData) |
||||
|
||||
// log.debug(`UI has defaulted to tx meta ${JSON.stringify(txData)}`)
|
||||
return txData |
||||
} |
||||
|
||||
verifyGasParams () { |
||||
// We call this in case the gas has not been modified at all
|
||||
if (!this.state) { return true } |
||||
return ( |
||||
this._notZeroOrEmptyString(this.state.gas) && |
||||
this._notZeroOrEmptyString(this.state.gasPrice) |
||||
) |
||||
} |
||||
|
||||
_notZeroOrEmptyString (obj) { |
||||
return obj !== '' && obj !== '0x0' |
||||
} |
||||
|
||||
bnMultiplyByFraction (targetBN, numerator, denominator) { |
||||
const numBN = new BN(numerator) |
||||
const denomBN = new BN(denominator) |
||||
return targetBN.mul(numBN).div(denomBN) |
||||
} |
||||
|
||||
getData () { |
||||
const { identities } = this.props |
||||
const txMeta = this.gatherTxMeta() |
||||
const txParams = txMeta.txParams || {} |
||||
|
||||
return { |
||||
from: { |
||||
address: txParams.from, |
||||
name: identities[txParams.from].name, |
||||
}, |
||||
memo: txParams.memo || '', |
||||
} |
||||
} |
||||
|
||||
getAmount () { |
||||
const { conversionRate, currentCurrency } = this.props |
||||
const txMeta = this.gatherTxMeta() |
||||
const txParams = txMeta.txParams || {} |
||||
|
||||
const FIAT = conversionUtil(txParams.value, { |
||||
fromNumericBase: 'hex', |
||||
toNumericBase: 'dec', |
||||
fromCurrency: 'ETH', |
||||
toCurrency: currentCurrency, |
||||
numberOfDecimals: 2, |
||||
fromDenomination: 'WEI', |
||||
conversionRate, |
||||
}) |
||||
const ETH = conversionUtil(txParams.value, { |
||||
fromNumericBase: 'hex', |
||||
toNumericBase: 'dec', |
||||
fromCurrency: 'ETH', |
||||
toCurrency: 'ETH', |
||||
fromDenomination: 'WEI', |
||||
conversionRate, |
||||
numberOfDecimals: 6, |
||||
}) |
||||
|
||||
return { |
||||
fiat: Number(FIAT), |
||||
token: Number(ETH), |
||||
} |
||||
|
||||
} |
||||
|
||||
getGasFee () { |
||||
const { conversionRate, currentCurrency } = this.props |
||||
const txMeta = this.gatherTxMeta() |
||||
const txParams = txMeta.txParams || {} |
||||
|
||||
// Gas
|
||||
const gas = txParams.gas |
||||
const gasBn = hexToBn(gas) |
||||
|
||||
// Gas Price
|
||||
const gasPrice = txParams.gasPrice || MIN_GAS_PRICE_HEX |
||||
const gasPriceBn = hexToBn(gasPrice) |
||||
|
||||
const txFeeBn = gasBn.mul(gasPriceBn) |
||||
|
||||
const FIAT = conversionUtil(txFeeBn, { |
||||
fromNumericBase: 'BN', |
||||
toNumericBase: 'dec', |
||||
fromDenomination: 'WEI', |
||||
fromCurrency: 'ETH', |
||||
toCurrency: currentCurrency, |
||||
numberOfDecimals: 2, |
||||
conversionRate, |
||||
}) |
||||
const ETH = conversionUtil(txFeeBn, { |
||||
fromNumericBase: 'BN', |
||||
toNumericBase: 'dec', |
||||
fromDenomination: 'WEI', |
||||
fromCurrency: 'ETH', |
||||
toCurrency: 'ETH', |
||||
numberOfDecimals: 6, |
||||
conversionRate, |
||||
}) |
||||
|
||||
return { |
||||
fiat: Number(FIAT), |
||||
eth: Number(ETH), |
||||
} |
||||
} |
||||
|
||||
renderGasFee () { |
||||
const { currentCurrency } = this.props |
||||
const { fiat: fiatGas, eth: ethGas } = this.getGasFee() |
||||
|
||||
return ( |
||||
h('section.flex-row.flex-center.confirm-screen-row', [ |
||||
h('span.confirm-screen-label.confirm-screen-section-column', [ this.context.t('gasFee') ]), |
||||
h('div.confirm-screen-section-column', [ |
||||
h('div.confirm-screen-row-info', `${fiatGas} ${currentCurrency.toUpperCase()}`), |
||||
|
||||
h( |
||||
'div.confirm-screen-row-detail', |
||||
`${ethGas} ETH` |
||||
), |
||||
]), |
||||
]) |
||||
) |
||||
} |
||||
|
||||
renderHeroAmount () { |
||||
const { currentCurrency } = this.props |
||||
const { fiat: fiatAmount } = this.getAmount() |
||||
const txMeta = this.gatherTxMeta() |
||||
const txParams = txMeta.txParams || {} |
||||
const { memo = '' } = txParams |
||||
|
||||
return ( |
||||
h('div.confirm-send-token__hero-amount-wrapper', [ |
||||
h('h3.flex-center.confirm-screen-send-amount', `${fiatAmount}`), |
||||
h('h3.flex-center.confirm-screen-send-amount-currency', currentCurrency.toUpperCase()), |
||||
h('div.flex-center.confirm-memo-wrapper', [ |
||||
h('h3.confirm-screen-send-memo', memo), |
||||
]), |
||||
]) |
||||
) |
||||
} |
||||
|
||||
renderTotalPlusGas () { |
||||
const { currentCurrency } = this.props |
||||
const { fiat: fiatAmount, token: tokenAmount } = this.getAmount() |
||||
const { fiat: fiatGas, eth: ethGas } = this.getGasFee() |
||||
|
||||
return ( |
||||
h('section.flex-row.flex-center.confirm-screen-row.confirm-screen-total-box ', [ |
||||
h('div.confirm-screen-section-column', [ |
||||
h('span.confirm-screen-label', [ this.context.t('total') + ' ' ]), |
||||
h('div.confirm-screen-total-box__subtitle', [ this.context.t('amountPlusGas') ]), |
||||
]), |
||||
|
||||
h('div.confirm-screen-section-column', [ |
||||
h('div.confirm-screen-row-info', `${fiatAmount + fiatGas} ${currentCurrency.toUpperCase()}`), |
||||
h('div.confirm-screen-row-detail', `${tokenAmount + ethGas} ETH`), |
||||
]), |
||||
]) |
||||
) |
||||
} |
||||
|
||||
render () { |
||||
const { backToAccountDetail, selectedAddress } = this.props |
||||
const txMeta = this.gatherTxMeta() |
||||
|
||||
const { |
||||
from: { |
||||
address: fromAddress, |
||||
name: fromName, |
||||
}, |
||||
} = this.getData() |
||||
|
||||
this.inputs = [] |
||||
|
||||
return ( |
||||
h('.page-container', [ |
||||
h('.page-container__header', [ |
||||
h('.page-container__header-row', [ |
||||
h('span.page-container__back-button', { |
||||
onClick: () => backToAccountDetail(selectedAddress), |
||||
}, this.context.t('back')), |
||||
window.METAMASK_UI_TYPE === 'notification' && h(NetworkDisplay), |
||||
]), |
||||
h('.page-container__title', this.context.t('confirmContract')), |
||||
h('.page-container__subtitle', this.context.t('pleaseReviewTransaction')), |
||||
]), |
||||
// Main Send token Card
|
||||
h('.page-container__content', [ |
||||
|
||||
h(SenderToRecipient, { |
||||
senderName: fromName, |
||||
senderAddress: fromAddress, |
||||
}), |
||||
|
||||
// h('h3.flex-center.confirm-screen-sending-to-message', {
|
||||
// style: {
|
||||
// textAlign: 'center',
|
||||
// fontSize: '16px',
|
||||
// },
|
||||
// }, [
|
||||
// `You're deploying a new contract.`,
|
||||
// ]),
|
||||
|
||||
this.renderHeroAmount(), |
||||
|
||||
h('div.confirm-screen-rows', [ |
||||
h('section.flex-row.flex-center.confirm-screen-row', [ |
||||
h('span.confirm-screen-label.confirm-screen-section-column', [ this.context.t('from') ]), |
||||
h('div.confirm-screen-section-column', [ |
||||
h('div.confirm-screen-row-info', fromName), |
||||
h('div.confirm-screen-row-detail', `...${fromAddress.slice(fromAddress.length - 4)}`), |
||||
]), |
||||
]), |
||||
|
||||
h('section.flex-row.flex-center.confirm-screen-row', [ |
||||
h('span.confirm-screen-label.confirm-screen-section-column', [ this.context.t('to') ]), |
||||
h('div.confirm-screen-section-column', [ |
||||
h('div.confirm-screen-row-info', this.context.t('newContract')), |
||||
]), |
||||
]), |
||||
|
||||
this.renderGasFee(), |
||||
|
||||
this.renderTotalPlusGas(), |
||||
|
||||
]), |
||||
]), |
||||
|
||||
h('form#pending-tx-form', { |
||||
onSubmit: event => this.onSubmit(event), |
||||
}, [ |
||||
h('.page-container__footer', [ |
||||
// Cancel Button
|
||||
h('button.btn-cancel.page-container__footer-button.allcaps', { |
||||
onClick: event => this.cancel(event, txMeta), |
||||
}, this.context.t('cancel')), |
||||
|
||||
// Accept Button
|
||||
h('button.btn-confirm.page-container__footer-button.allcaps', { |
||||
onClick: event => this.onSubmit(event), |
||||
}, this.context.t('confirm')), |
||||
]), |
||||
]), |
||||
]) |
||||
) |
||||
} |
||||
} |
||||
|
||||
ConfirmDeployContract.propTypes = { |
||||
sendTransaction: PropTypes.func, |
||||
cancelTransaction: PropTypes.func, |
||||
backToAccountDetail: PropTypes.func, |
||||
displayWarning: PropTypes.func, |
||||
identities: PropTypes.object, |
||||
conversionRate: PropTypes.number, |
||||
currentCurrency: PropTypes.string, |
||||
selectedAddress: PropTypes.string, |
||||
t: PropTypes.func, |
||||
} |
||||
|
||||
const mapStateToProps = state => { |
||||
const { |
||||
conversionRate, |
||||
identities, |
||||
currentCurrency, |
||||
} = state.metamask |
||||
const accounts = state.metamask.accounts |
||||
const selectedAddress = state.metamask.selectedAddress || Object.keys(accounts)[0] |
||||
return { |
||||
currentCurrency, |
||||
conversionRate, |
||||
identities, |
||||
selectedAddress, |
||||
} |
||||
} |
||||
|
||||
const mapDispatchToProps = dispatch => { |
||||
return { |
||||
backToAccountDetail: address => dispatch(actions.backToAccountDetail(address)), |
||||
cancelTransaction: ({ id }) => dispatch(actions.cancelTx({ id })), |
||||
displayWarning: warning => actions.displayWarning(warning), |
||||
} |
||||
} |
||||
|
||||
ConfirmDeployContract.contextTypes = { |
||||
t: PropTypes.func, |
||||
} |
||||
|
||||
module.exports = connect(mapStateToProps, mapDispatchToProps)(ConfirmDeployContract) |
@ -1,692 +0,0 @@ |
||||
const Component = require('react').Component |
||||
const { withRouter } = require('react-router-dom') |
||||
const { compose } = require('recompose') |
||||
const PropTypes = require('prop-types') |
||||
const connect = require('react-redux').connect |
||||
const h = require('react-hyperscript') |
||||
const inherits = require('util').inherits |
||||
const actions = require('../../actions') |
||||
const clone = require('clone') |
||||
const ethUtil = require('ethereumjs-util') |
||||
const BN = ethUtil.BN |
||||
const hexToBn = require('../../../../app/scripts/lib/hex-to-bn') |
||||
const classnames = require('classnames') |
||||
const { |
||||
conversionUtil, |
||||
addCurrencies, |
||||
multiplyCurrencies, |
||||
} = require('../../conversion-util') |
||||
const { |
||||
calcGasTotal, |
||||
isBalanceSufficient, |
||||
} = require('../send_/send.utils') |
||||
const GasFeeDisplay = require('../send_/send-content/send-gas-row/gas-fee-display/gas-fee-display.component').default |
||||
const SenderToRecipient = require('../sender-to-recipient') |
||||
const NetworkDisplay = require('../network-display') |
||||
const currencyFormatter = require('currency-formatter') |
||||
const currencies = require('currency-formatter/currencies') |
||||
|
||||
const { MIN_GAS_PRICE_HEX } = require('../send_/send.constants') |
||||
const { SEND_ROUTE, DEFAULT_ROUTE } = require('../../routes') |
||||
const { |
||||
ENVIRONMENT_TYPE_POPUP, |
||||
ENVIRONMENT_TYPE_NOTIFICATION, |
||||
} = require('../../../../app/scripts/lib/enums') |
||||
|
||||
import { |
||||
updateSendErrors, |
||||
} from '../../ducks/send.duck' |
||||
|
||||
ConfirmSendEther.contextTypes = { |
||||
t: PropTypes.func, |
||||
} |
||||
|
||||
module.exports = compose( |
||||
withRouter, |
||||
connect(mapStateToProps, mapDispatchToProps) |
||||
)(ConfirmSendEther) |
||||
|
||||
|
||||
function mapStateToProps (state) { |
||||
const { |
||||
conversionRate, |
||||
identities, |
||||
currentCurrency, |
||||
send, |
||||
} = state.metamask |
||||
const accounts = state.metamask.accounts |
||||
const selectedAddress = state.metamask.selectedAddress || Object.keys(accounts)[0] |
||||
const { balance } = accounts[selectedAddress] |
||||
return { |
||||
conversionRate, |
||||
identities, |
||||
selectedAddress, |
||||
currentCurrency, |
||||
send, |
||||
balance, |
||||
} |
||||
} |
||||
|
||||
function mapDispatchToProps (dispatch) { |
||||
return { |
||||
clearSend: () => dispatch(actions.clearSend()), |
||||
editTransaction: txMeta => { |
||||
const { id, txParams } = txMeta |
||||
const { |
||||
gas: gasLimit, |
||||
gasPrice, |
||||
to, |
||||
value: amount, |
||||
} = txParams |
||||
|
||||
dispatch(actions.updateSend({ |
||||
gasLimit, |
||||
gasPrice, |
||||
gasTotal: null, |
||||
to, |
||||
amount, |
||||
errors: { to: null, amount: null }, |
||||
editingTransactionId: id, |
||||
})) |
||||
}, |
||||
cancelTransaction: ({ id }) => dispatch(actions.cancelTx({ id })), |
||||
showCustomizeGasModal: (txMeta, sendGasLimit, sendGasPrice, sendGasTotal) => { |
||||
const { id, txParams, lastGasPrice } = txMeta |
||||
const { gas: txGasLimit, gasPrice: txGasPrice } = txParams |
||||
|
||||
let forceGasMin |
||||
if (lastGasPrice) { |
||||
forceGasMin = ethUtil.addHexPrefix(multiplyCurrencies(lastGasPrice, 1.1, { |
||||
multiplicandBase: 16, |
||||
multiplierBase: 10, |
||||
toNumericBase: 'hex', |
||||
fromDenomination: 'WEI', |
||||
})) |
||||
} |
||||
|
||||
dispatch(actions.updateSend({ |
||||
gasLimit: sendGasLimit || txGasLimit, |
||||
gasPrice: sendGasPrice || txGasPrice, |
||||
editingTransactionId: id, |
||||
gasTotal: sendGasTotal, |
||||
forceGasMin, |
||||
})) |
||||
dispatch(actions.showModal({ name: 'CUSTOMIZE_GAS' })) |
||||
}, |
||||
updateSendErrors: error => dispatch(updateSendErrors(error)), |
||||
} |
||||
} |
||||
|
||||
inherits(ConfirmSendEther, Component) |
||||
function ConfirmSendEther () { |
||||
Component.call(this) |
||||
this.state = {} |
||||
this.onSubmit = this.onSubmit.bind(this) |
||||
} |
||||
|
||||
ConfirmSendEther.prototype.updateComponentSendErrors = function (prevProps) { |
||||
const { |
||||
balance: oldBalance, |
||||
conversionRate: oldConversionRate, |
||||
} = prevProps |
||||
const { |
||||
updateSendErrors, |
||||
balance, |
||||
conversionRate, |
||||
send: { |
||||
errors: { |
||||
simulationFails, |
||||
}, |
||||
}, |
||||
} = this.props |
||||
const txMeta = this.gatherTxMeta() |
||||
|
||||
const shouldUpdateBalanceSendErrors = balance && [ |
||||
balance !== oldBalance, |
||||
conversionRate !== oldConversionRate, |
||||
].some(x => Boolean(x)) |
||||
|
||||
if (shouldUpdateBalanceSendErrors) { |
||||
const balanceIsSufficient = this.isBalanceSufficient(txMeta) |
||||
updateSendErrors({ |
||||
insufficientFunds: balanceIsSufficient ? false : 'insufficientFunds', |
||||
}) |
||||
} |
||||
|
||||
const shouldUpdateSimulationSendError = Boolean(txMeta.simulationFails) !== Boolean(simulationFails) |
||||
|
||||
if (shouldUpdateSimulationSendError) { |
||||
updateSendErrors({ |
||||
simulationFails: !txMeta.simulationFails ? false : 'transactionError', |
||||
}) |
||||
} |
||||
} |
||||
|
||||
ConfirmSendEther.prototype.componentWillMount = function () { |
||||
this.updateComponentSendErrors({}) |
||||
} |
||||
|
||||
ConfirmSendEther.prototype.componentDidUpdate = function (prevProps) { |
||||
this.updateComponentSendErrors(prevProps) |
||||
} |
||||
|
||||
ConfirmSendEther.prototype.getAmount = function () { |
||||
const { conversionRate, currentCurrency } = this.props |
||||
const txMeta = this.gatherTxMeta() |
||||
const txParams = txMeta.txParams || {} |
||||
|
||||
const FIAT = conversionUtil(txParams.value, { |
||||
fromNumericBase: 'hex', |
||||
toNumericBase: 'dec', |
||||
fromCurrency: 'ETH', |
||||
toCurrency: currentCurrency, |
||||
numberOfDecimals: 2, |
||||
fromDenomination: 'WEI', |
||||
conversionRate, |
||||
}) |
||||
const ETH = conversionUtil(txParams.value, { |
||||
fromNumericBase: 'hex', |
||||
toNumericBase: 'dec', |
||||
fromCurrency: 'ETH', |
||||
toCurrency: 'ETH', |
||||
fromDenomination: 'WEI', |
||||
conversionRate, |
||||
numberOfDecimals: 6, |
||||
}) |
||||
|
||||
return { |
||||
FIAT, |
||||
ETH, |
||||
} |
||||
|
||||
} |
||||
|
||||
ConfirmSendEther.prototype.getGasFee = function () { |
||||
const { conversionRate, currentCurrency } = this.props |
||||
const txMeta = this.gatherTxMeta() |
||||
const txParams = txMeta.txParams || {} |
||||
|
||||
// Gas
|
||||
const gas = txParams.gas |
||||
const gasBn = hexToBn(gas) |
||||
|
||||
// From latest master
|
||||
// const gasLimit = new BN(parseInt(blockGasLimit))
|
||||
// const safeGasLimitBN = this.bnMultiplyByFraction(gasLimit, 19, 20)
|
||||
// const saferGasLimitBN = this.bnMultiplyByFraction(gasLimit, 18, 20)
|
||||
// const safeGasLimit = safeGasLimitBN.toString(10)
|
||||
|
||||
// Gas Price
|
||||
const gasPrice = txParams.gasPrice || MIN_GAS_PRICE_HEX |
||||
const gasPriceBn = hexToBn(gasPrice) |
||||
|
||||
const txFeeBn = gasBn.mul(gasPriceBn) |
||||
|
||||
const FIAT = conversionUtil(txFeeBn, { |
||||
fromNumericBase: 'BN', |
||||
toNumericBase: 'dec', |
||||
fromDenomination: 'WEI', |
||||
fromCurrency: 'ETH', |
||||
toCurrency: currentCurrency, |
||||
numberOfDecimals: 2, |
||||
conversionRate, |
||||
}) |
||||
const ETH = conversionUtil(txFeeBn, { |
||||
fromNumericBase: 'BN', |
||||
toNumericBase: 'dec', |
||||
fromDenomination: 'WEI', |
||||
fromCurrency: 'ETH', |
||||
toCurrency: 'ETH', |
||||
numberOfDecimals: 6, |
||||
conversionRate, |
||||
}) |
||||
|
||||
return { |
||||
FIAT, |
||||
ETH, |
||||
gasFeeInHex: txFeeBn.toString(16), |
||||
} |
||||
} |
||||
|
||||
ConfirmSendEther.prototype.getData = function () { |
||||
const { identities } = this.props |
||||
const txMeta = this.gatherTxMeta() |
||||
const txParams = txMeta.txParams || {} |
||||
const account = identities ? identities[txParams.from] || {} : {} |
||||
const { FIAT: gasFeeInFIAT, ETH: gasFeeInETH, gasFeeInHex } = this.getGasFee() |
||||
const { FIAT: amountInFIAT, ETH: amountInETH } = this.getAmount() |
||||
|
||||
const totalInFIAT = addCurrencies(gasFeeInFIAT, amountInFIAT, { |
||||
toNumericBase: 'dec', |
||||
numberOfDecimals: 2, |
||||
}) |
||||
const totalInETH = addCurrencies(gasFeeInETH, amountInETH, { |
||||
toNumericBase: 'dec', |
||||
numberOfDecimals: 6, |
||||
}) |
||||
|
||||
return { |
||||
from: { |
||||
address: txParams.from, |
||||
name: account.name, |
||||
}, |
||||
to: { |
||||
address: txParams.to, |
||||
name: identities[txParams.to] ? identities[txParams.to].name : this.context.t('newRecipient'), |
||||
}, |
||||
memo: txParams.memo || '', |
||||
gasFeeInFIAT, |
||||
gasFeeInETH, |
||||
amountInFIAT, |
||||
amountInETH, |
||||
totalInFIAT, |
||||
totalInETH, |
||||
gasFeeInHex, |
||||
} |
||||
} |
||||
|
||||
ConfirmSendEther.prototype.convertToRenderableCurrency = function (value, currencyCode) { |
||||
const upperCaseCurrencyCode = currencyCode.toUpperCase() |
||||
|
||||
return currencies.find(currency => currency.code === upperCaseCurrencyCode) |
||||
? currencyFormatter.format(Number(value), { |
||||
code: upperCaseCurrencyCode, |
||||
}) |
||||
: value |
||||
} |
||||
|
||||
ConfirmSendEther.prototype.editTransaction = function () { |
||||
const { editTransaction, history } = this.props |
||||
const txMeta = this.gatherTxMeta() |
||||
editTransaction(txMeta) |
||||
history.push(SEND_ROUTE) |
||||
} |
||||
|
||||
ConfirmSendEther.prototype.renderHeaderRow = function (isTxReprice) { |
||||
const windowType = window.METAMASK_UI_TYPE |
||||
const isFullScreen = windowType !== ENVIRONMENT_TYPE_NOTIFICATION && |
||||
windowType !== ENVIRONMENT_TYPE_POPUP |
||||
|
||||
if (isTxReprice && isFullScreen) { |
||||
return null |
||||
} |
||||
|
||||
return ( |
||||
h('.page-container__header-row', [ |
||||
h('span.page-container__back-button', { |
||||
onClick: () => this.editTransaction(), |
||||
style: { |
||||
visibility: isTxReprice ? 'hidden' : 'initial', |
||||
}, |
||||
}, 'Edit'), |
||||
!isFullScreen && h(NetworkDisplay), |
||||
]) |
||||
) |
||||
} |
||||
|
||||
ConfirmSendEther.prototype.renderHeader = function (isTxReprice) { |
||||
const title = isTxReprice ? this.context.t('speedUpTitle') : this.context.t('confirm') |
||||
const subtitle = isTxReprice |
||||
? this.context.t('speedUpSubtitle') |
||||
: this.context.t('pleaseReviewTransaction') |
||||
|
||||
return ( |
||||
h('.page-container__header', [ |
||||
this.renderHeaderRow(isTxReprice), |
||||
h('.page-container__title', title), |
||||
h('.page-container__subtitle', subtitle), |
||||
]) |
||||
) |
||||
} |
||||
|
||||
ConfirmSendEther.prototype.render = function () { |
||||
const { |
||||
currentCurrency, |
||||
clearSend, |
||||
conversionRate, |
||||
currentCurrency: convertedCurrency, |
||||
showCustomizeGasModal, |
||||
send: { |
||||
gasTotal, |
||||
gasLimit: sendGasLimit, |
||||
gasPrice: sendGasPrice, |
||||
errors, |
||||
}, |
||||
} = this.props |
||||
const txMeta = this.gatherTxMeta() |
||||
const isTxReprice = Boolean(txMeta.lastGasPrice) |
||||
const txParams = txMeta.txParams || {} |
||||
|
||||
const { |
||||
from: { |
||||
address: fromAddress, |
||||
name: fromName, |
||||
}, |
||||
to: { |
||||
address: toAddress, |
||||
name: toName, |
||||
}, |
||||
memo, |
||||
gasFeeInHex, |
||||
amountInFIAT, |
||||
totalInFIAT, |
||||
totalInETH, |
||||
} = this.getData() |
||||
|
||||
const convertedAmountInFiat = this.convertToRenderableCurrency(amountInFIAT, currentCurrency) |
||||
const convertedTotalInFiat = this.convertToRenderableCurrency(totalInFIAT, currentCurrency) |
||||
|
||||
// This is from the latest master
|
||||
// It handles some of the errors that we are not currently handling
|
||||
// Leaving as comments fo reference
|
||||
|
||||
// const balanceBn = hexToBn(balance)
|
||||
// const insufficientBalance = balanceBn.lt(maxCost)
|
||||
// const buyDisabled = insufficientBalance || !this.state.valid || !isValidAddress || this.state.submitting
|
||||
// const showRejectAll = props.unconfTxListLength > 1
|
||||
// const dangerousGasLimit = gasBn.gte(saferGasLimitBN)
|
||||
// const gasLimitSpecified = txMeta.gasLimitSpecified
|
||||
|
||||
this.inputs = [] |
||||
|
||||
return ( |
||||
// Main Send token Card
|
||||
h('.page-container', [ |
||||
this.renderHeader(isTxReprice), |
||||
h('.page-container__content', [ |
||||
h(SenderToRecipient, { |
||||
senderName: fromName, |
||||
senderAddress: fromAddress, |
||||
recipientName: toName, |
||||
recipientAddress: txParams.to, |
||||
}), |
||||
|
||||
// h('h3.flex-center.confirm-screen-sending-to-message', {
|
||||
// style: {
|
||||
// textAlign: 'center',
|
||||
// fontSize: '16px',
|
||||
// },
|
||||
// }, [
|
||||
// `You're sending to Recipient ...${toAddress.slice(toAddress.length - 4)}`,
|
||||
// ]),
|
||||
|
||||
h('h3.flex-center.confirm-screen-send-amount', [`${convertedAmountInFiat}`]), |
||||
h('h3.flex-center.confirm-screen-send-amount-currency', [ currentCurrency.toUpperCase() ]), |
||||
h('div.flex-center.confirm-memo-wrapper', [ |
||||
h('h3.confirm-screen-send-memo', [ memo ? `"${memo}"` : '' ]), |
||||
]), |
||||
|
||||
h('div.confirm-screen-rows', [ |
||||
h('section.flex-row.flex-center.confirm-screen-row', [ |
||||
h('span.confirm-screen-label.confirm-screen-section-column', [ this.context.t('from') ]), |
||||
h('div.confirm-screen-section-column', [ |
||||
h('div.confirm-screen-row-info', fromName), |
||||
h('div.confirm-screen-row-detail', `...${fromAddress.slice(fromAddress.length - 4)}`), |
||||
]), |
||||
]), |
||||
|
||||
h('section.flex-row.flex-center.confirm-screen-row', [ |
||||
h('span.confirm-screen-label.confirm-screen-section-column', [ this.context.t('to') ]), |
||||
h('div.confirm-screen-section-column', [ |
||||
h('div.confirm-screen-row-info', toName), |
||||
h('div.confirm-screen-row-detail', `...${toAddress.slice(toAddress.length - 4)}`), |
||||
]), |
||||
]), |
||||
|
||||
h('section.flex-row.flex-center.confirm-screen-row', [ |
||||
h('span.confirm-screen-label.confirm-screen-section-column', [ this.context.t('gasFee') ]), |
||||
h('div.confirm-screen-section-column', [ |
||||
h(GasFeeDisplay, { |
||||
gasTotal: gasTotal || gasFeeInHex, |
||||
conversionRate, |
||||
convertedCurrency, |
||||
onClick: () => showCustomizeGasModal(txMeta, sendGasLimit, sendGasPrice, gasTotal), |
||||
}), |
||||
]), |
||||
]), |
||||
|
||||
h('section.flex-row.flex-center.confirm-screen-row.confirm-screen-total-box ', [ |
||||
h('div', { |
||||
className: classnames({ |
||||
'confirm-screen-section-column--with-error': errors['insufficientFunds'], |
||||
'confirm-screen-section-column': !errors['insufficientFunds'], |
||||
}), |
||||
}, [ |
||||
h('span.confirm-screen-label', [ this.context.t('total') + ' ' ]), |
||||
h('div.confirm-screen-total-box__subtitle', [ this.context.t('amountPlusGas') ]), |
||||
]), |
||||
|
||||
h('div.confirm-screen-section-column', [ |
||||
h('div.confirm-screen-row-info', `${convertedTotalInFiat} ${currentCurrency.toUpperCase()}`), |
||||
h('div.confirm-screen-row-detail', `${totalInETH} ETH`), |
||||
]), |
||||
|
||||
this.renderErrorMessage('insufficientFunds'), |
||||
]), |
||||
]), |
||||
|
||||
// These are latest errors handling from master
|
||||
// Leaving as comments as reference when we start implementing error handling
|
||||
// h('style', `
|
||||
// .conf-buttons button {
|
||||
// margin-left: 10px;
|
||||
// text-transform: uppercase;
|
||||
// }
|
||||
// `),
|
||||
|
||||
// txMeta.simulationFails ?
|
||||
// h('.error', {
|
||||
// style: {
|
||||
// marginLeft: 50,
|
||||
// fontSize: '0.9em',
|
||||
// },
|
||||
// }, 'Transaction Error. Exception thrown in contract code.')
|
||||
// : null,
|
||||
|
||||
// !isValidAddress ?
|
||||
// h('.error', {
|
||||
// style: {
|
||||
// marginLeft: 50,
|
||||
// fontSize: '0.9em',
|
||||
// },
|
||||
// }, 'Recipient address is invalid. Sending this transaction will result in a loss of ETH.')
|
||||
// : null,
|
||||
|
||||
// insufficientBalance ?
|
||||
// h('span.error', {
|
||||
// style: {
|
||||
// marginLeft: 50,
|
||||
// fontSize: '0.9em',
|
||||
// },
|
||||
// }, 'Insufficient balance for transaction')
|
||||
// : null,
|
||||
|
||||
// // send + cancel
|
||||
// h('.flex-row.flex-space-around.conf-buttons', {
|
||||
// style: {
|
||||
// display: 'flex',
|
||||
// justifyContent: 'flex-end',
|
||||
// margin: '14px 25px',
|
||||
// },
|
||||
// }, [
|
||||
// h('button', {
|
||||
// onClick: (event) => {
|
||||
// this.resetGasFields()
|
||||
// event.preventDefault()
|
||||
// },
|
||||
// }, 'Reset'),
|
||||
|
||||
// // Accept Button or Buy Button
|
||||
// insufficientBalance ? h('button.btn-green', { onClick: props.buyEth }, 'Buy Ether') :
|
||||
// h('input.confirm.btn-green', {
|
||||
// type: 'submit',
|
||||
// value: 'SUBMIT',
|
||||
// style: { marginLeft: '10px' },
|
||||
// disabled: buyDisabled,
|
||||
// }),
|
||||
|
||||
// h('button.cancel.btn-red', {
|
||||
// onClick: props.cancelTransaction,
|
||||
// }, 'Reject'),
|
||||
// ]),
|
||||
// showRejectAll ? h('.flex-row.flex-space-around.conf-buttons', {
|
||||
// style: {
|
||||
// display: 'flex',
|
||||
// justifyContent: 'flex-end',
|
||||
// margin: '14px 25px',
|
||||
// },
|
||||
// }, [
|
||||
// h('button.cancel.btn-red', {
|
||||
// onClick: props.cancelAllTransactions,
|
||||
// }, 'Reject All'),
|
||||
// ]) : null,
|
||||
// ]),
|
||||
// ])
|
||||
// )
|
||||
// }
|
||||
]), |
||||
|
||||
h('form#pending-tx-form', { |
||||
className: 'confirm-screen-form', |
||||
onSubmit: this.onSubmit, |
||||
}, [ |
||||
this.renderErrorMessage('simulationFails'), |
||||
h('.page-container__footer', [ |
||||
// Cancel Button
|
||||
h('button.btn-cancel.page-container__footer-button.allcaps', { |
||||
onClick: (event) => { |
||||
clearSend() |
||||
this.cancel(event, txMeta) |
||||
}, |
||||
}, this.context.t('cancel')), |
||||
|
||||
// Accept Button
|
||||
h('button.btn-confirm.page-container__footer-button.allcaps', { |
||||
onClick: event => this.onSubmit(event), |
||||
}, this.context.t('confirm')), |
||||
]), |
||||
]), |
||||
]) |
||||
) |
||||
} |
||||
|
||||
ConfirmSendEther.prototype.renderErrorMessage = function (message) { |
||||
const { send: { errors } } = this.props |
||||
|
||||
return errors[message] |
||||
? h('div.confirm-screen-error', [ errors[message] ]) |
||||
: null |
||||
} |
||||
|
||||
ConfirmSendEther.prototype.onSubmit = function (event) { |
||||
event.preventDefault() |
||||
const { updateSendErrors } = this.props |
||||
const txMeta = this.gatherTxMeta() |
||||
const valid = this.checkValidity() |
||||
const balanceIsSufficient = this.isBalanceSufficient(txMeta) |
||||
this.setState({ valid, submitting: true }) |
||||
|
||||
if (valid && this.verifyGasParams() && balanceIsSufficient) { |
||||
this.props.sendTransaction(txMeta, event) |
||||
} else if (!balanceIsSufficient) { |
||||
updateSendErrors({ insufficientFunds: 'insufficientFunds' }) |
||||
} else { |
||||
updateSendErrors({ invalidGasParams: 'invalidGasParams' }) |
||||
this.setState({ submitting: false }) |
||||
} |
||||
} |
||||
|
||||
ConfirmSendEther.prototype.cancel = function (event, txMeta) { |
||||
event.preventDefault() |
||||
const { cancelTransaction } = this.props |
||||
|
||||
cancelTransaction(txMeta) |
||||
.then(() => this.props.history.push(DEFAULT_ROUTE)) |
||||
} |
||||
|
||||
ConfirmSendEther.prototype.isBalanceSufficient = function (txMeta) { |
||||
const { |
||||
balance, |
||||
conversionRate, |
||||
} = this.props |
||||
const { |
||||
txParams: { |
||||
gas, |
||||
gasPrice, |
||||
value: amount, |
||||
}, |
||||
} = txMeta |
||||
const gasTotal = calcGasTotal(gas, gasPrice) |
||||
|
||||
return isBalanceSufficient({ |
||||
amount, |
||||
gasTotal, |
||||
balance, |
||||
conversionRate, |
||||
}) |
||||
} |
||||
|
||||
ConfirmSendEther.prototype.checkValidity = function () { |
||||
const form = this.getFormEl() |
||||
const valid = form.checkValidity() |
||||
return valid |
||||
} |
||||
|
||||
ConfirmSendEther.prototype.getFormEl = function () { |
||||
const form = document.querySelector('form#pending-tx-form') |
||||
// Stub out form for unit tests:
|
||||
if (!form) { |
||||
return { checkValidity () { return true } } |
||||
} |
||||
return form |
||||
} |
||||
|
||||
// After a customizable state value has been updated,
|
||||
ConfirmSendEther.prototype.gatherTxMeta = function () { |
||||
const props = this.props |
||||
const state = this.state |
||||
const txData = clone(state.txData) || clone(props.txData) |
||||
|
||||
const { gasPrice: sendGasPrice, gasLimit: sendGasLimit } = props.send |
||||
const { |
||||
lastGasPrice, |
||||
txParams: { |
||||
gasPrice: txGasPrice, |
||||
gas: txGasLimit, |
||||
}, |
||||
} = txData |
||||
|
||||
let forceGasMin |
||||
if (lastGasPrice) { |
||||
forceGasMin = ethUtil.addHexPrefix(multiplyCurrencies(lastGasPrice, 1.1, { |
||||
multiplicandBase: 16, |
||||
multiplierBase: 10, |
||||
toNumericBase: 'hex', |
||||
})) |
||||
} |
||||
|
||||
txData.txParams.gasPrice = sendGasPrice || forceGasMin || txGasPrice |
||||
txData.txParams.gas = sendGasLimit || txGasLimit |
||||
|
||||
// log.debug(`UI has defaulted to tx meta ${JSON.stringify(txData)}`)
|
||||
return txData |
||||
} |
||||
|
||||
ConfirmSendEther.prototype.verifyGasParams = function () { |
||||
// We call this in case the gas has not been modified at all
|
||||
if (!this.state) { return true } |
||||
return ( |
||||
this._notZeroOrEmptyString(this.state.gas) && |
||||
this._notZeroOrEmptyString(this.state.gasPrice) |
||||
) |
||||
} |
||||
|
||||
ConfirmSendEther.prototype._notZeroOrEmptyString = function (obj) { |
||||
return obj !== '' && obj !== '0x0' |
||||
} |
||||
|
||||
ConfirmSendEther.prototype.bnMultiplyByFraction = function (targetBN, numerator, denominator) { |
||||
const numBN = new BN(numerator) |
||||
const denomBN = new BN(denominator) |
||||
return targetBN.mul(numBN).div(denomBN) |
||||
} |
@ -1,696 +0,0 @@ |
||||
const Component = require('react').Component |
||||
const { withRouter } = require('react-router-dom') |
||||
const { compose } = require('recompose') |
||||
const PropTypes = require('prop-types') |
||||
const connect = require('react-redux').connect |
||||
const h = require('react-hyperscript') |
||||
const inherits = require('util').inherits |
||||
const tokenAbi = require('human-standard-token-abi') |
||||
const abiDecoder = require('abi-decoder') |
||||
abiDecoder.addABI(tokenAbi) |
||||
const actions = require('../../actions') |
||||
const clone = require('clone') |
||||
const Identicon = require('../identicon') |
||||
const GasFeeDisplay = require('../send_/send-content/send-gas-row/gas-fee-display/gas-fee-display.component.js').default |
||||
const NetworkDisplay = require('../network-display') |
||||
const ethUtil = require('ethereumjs-util') |
||||
const BN = ethUtil.BN |
||||
const { |
||||
conversionUtil, |
||||
multiplyCurrencies, |
||||
addCurrencies, |
||||
} = require('../../conversion-util') |
||||
const { |
||||
calcGasTotal, |
||||
isBalanceSufficient, |
||||
} = require('../send_/send.utils') |
||||
const { |
||||
calcTokenAmount, |
||||
} = require('../../token-util') |
||||
const classnames = require('classnames') |
||||
const currencyFormatter = require('currency-formatter') |
||||
const currencies = require('currency-formatter/currencies') |
||||
|
||||
const { MIN_GAS_PRICE_HEX } = require('../send_/send.constants') |
||||
|
||||
const { |
||||
getTokenExchangeRate, |
||||
getSelectedAddress, |
||||
getSelectedTokenContract, |
||||
} = require('../../selectors') |
||||
const { SEND_ROUTE, DEFAULT_ROUTE } = require('../../routes') |
||||
|
||||
import { |
||||
updateSendErrors, |
||||
} from '../../ducks/send.duck' |
||||
|
||||
const { |
||||
ENVIRONMENT_TYPE_POPUP, |
||||
ENVIRONMENT_TYPE_NOTIFICATION, |
||||
} = require('../../../../app/scripts/lib/enums') |
||||
|
||||
ConfirmSendToken.contextTypes = { |
||||
t: PropTypes.func, |
||||
} |
||||
|
||||
module.exports = compose( |
||||
withRouter, |
||||
connect(mapStateToProps, mapDispatchToProps) |
||||
)(ConfirmSendToken) |
||||
|
||||
|
||||
function mapStateToProps (state, ownProps) { |
||||
const { token: { address }, txData } = ownProps |
||||
const { txParams } = txData || {} |
||||
const tokenData = txParams.data && abiDecoder.decodeMethod(txParams.data) |
||||
|
||||
const { |
||||
conversionRate, |
||||
identities, |
||||
currentCurrency, |
||||
} = state.metamask |
||||
const accounts = state.metamask.accounts |
||||
const selectedAddress = getSelectedAddress(state) |
||||
const tokenExchangeRate = getTokenExchangeRate(state, address) |
||||
const { balance } = accounts[selectedAddress] |
||||
return { |
||||
conversionRate, |
||||
identities, |
||||
selectedAddress, |
||||
tokenExchangeRate, |
||||
tokenData: tokenData || {}, |
||||
currentCurrency: currentCurrency.toUpperCase(), |
||||
send: state.metamask.send, |
||||
tokenContract: getSelectedTokenContract(state), |
||||
balance, |
||||
} |
||||
} |
||||
|
||||
function mapDispatchToProps (dispatch, ownProps) { |
||||
return { |
||||
backToAccountDetail: address => dispatch(actions.backToAccountDetail(address)), |
||||
cancelTransaction: ({ id }) => dispatch(actions.cancelTx({ id })), |
||||
editTransaction: txMeta => { |
||||
const { token: { address } } = ownProps |
||||
const { txParams = {}, id } = txMeta |
||||
const tokenData = txParams.data && abiDecoder.decodeMethod(txParams.data) || {} |
||||
const { params = [] } = tokenData |
||||
const { value: to } = params[0] || {} |
||||
const { value: tokenAmountInDec } = params[1] || {} |
||||
const tokenAmountInHex = conversionUtil(tokenAmountInDec, { |
||||
fromNumericBase: 'dec', |
||||
toNumericBase: 'hex', |
||||
}) |
||||
const { |
||||
gas: gasLimit, |
||||
gasPrice, |
||||
} = txParams |
||||
dispatch(actions.setSelectedToken(address)) |
||||
dispatch(actions.updateSend({ |
||||
gasLimit, |
||||
gasPrice, |
||||
gasTotal: null, |
||||
to, |
||||
amount: tokenAmountInHex, |
||||
errors: { to: null, amount: null }, |
||||
editingTransactionId: id && id.toString(), |
||||
token: ownProps.token, |
||||
})) |
||||
dispatch(actions.showSendTokenPage()) |
||||
}, |
||||
showCustomizeGasModal: (txMeta, sendGasLimit, sendGasPrice, sendGasTotal) => { |
||||
const { id, txParams, lastGasPrice } = txMeta |
||||
const { gas: txGasLimit, gasPrice: txGasPrice } = txParams |
||||
const tokenData = txParams.data && abiDecoder.decodeMethod(txParams.data) |
||||
const { params = [] } = tokenData |
||||
const { value: to } = params[0] || {} |
||||
const { value: tokenAmountInDec } = params[1] || {} |
||||
const tokenAmountInHex = conversionUtil(tokenAmountInDec, { |
||||
fromNumericBase: 'dec', |
||||
toNumericBase: 'hex', |
||||
}) |
||||
|
||||
let forceGasMin |
||||
if (lastGasPrice) { |
||||
forceGasMin = ethUtil.addHexPrefix(multiplyCurrencies(lastGasPrice, 1.1, { |
||||
multiplicandBase: 16, |
||||
multiplierBase: 10, |
||||
toNumericBase: 'hex', |
||||
fromDenomination: 'WEI', |
||||
})) |
||||
} |
||||
|
||||
dispatch(actions.updateSend({ |
||||
gasLimit: sendGasLimit || txGasLimit, |
||||
gasPrice: sendGasPrice || txGasPrice, |
||||
editingTransactionId: id, |
||||
gasTotal: sendGasTotal, |
||||
to, |
||||
amount: tokenAmountInHex, |
||||
forceGasMin, |
||||
})) |
||||
dispatch(actions.showModal({ name: 'CUSTOMIZE_GAS' })) |
||||
}, |
||||
updateSendErrors: error => dispatch(updateSendErrors(error)), |
||||
} |
||||
} |
||||
|
||||
inherits(ConfirmSendToken, Component) |
||||
function ConfirmSendToken () { |
||||
Component.call(this) |
||||
this.state = {} |
||||
this.onSubmit = this.onSubmit.bind(this) |
||||
} |
||||
|
||||
ConfirmSendToken.prototype.editTransaction = function (txMeta) { |
||||
const { editTransaction, history } = this.props |
||||
editTransaction(txMeta) |
||||
history.push(SEND_ROUTE) |
||||
} |
||||
|
||||
ConfirmSendToken.prototype.updateComponentSendErrors = function (prevProps) { |
||||
const { |
||||
balance: oldBalance, |
||||
conversionRate: oldConversionRate, |
||||
} = prevProps |
||||
const { |
||||
updateSendErrors, |
||||
balance, |
||||
conversionRate, |
||||
send: { |
||||
errors: { |
||||
simulationFails, |
||||
}, |
||||
}, |
||||
} = this.props |
||||
const txMeta = this.gatherTxMeta() |
||||
|
||||
const shouldUpdateBalanceSendErrors = balance && [ |
||||
balance !== oldBalance, |
||||
conversionRate !== oldConversionRate, |
||||
].some(x => Boolean(x)) |
||||
|
||||
if (shouldUpdateBalanceSendErrors) { |
||||
const balanceIsSufficient = this.isBalanceSufficient(txMeta) |
||||
updateSendErrors({ |
||||
insufficientFunds: balanceIsSufficient ? false : this.context.t('insufficientFunds'), |
||||
}) |
||||
} |
||||
|
||||
const shouldUpdateSimulationSendError = Boolean(txMeta.simulationFails) !== Boolean(simulationFails) |
||||
|
||||
if (shouldUpdateSimulationSendError) { |
||||
updateSendErrors({ |
||||
simulationFails: !txMeta.simulationFails ? false : this.context.t('transactionError'), |
||||
}) |
||||
} |
||||
} |
||||
|
||||
ConfirmSendToken.prototype.componentWillMount = function () { |
||||
const { tokenContract, selectedAddress } = this.props |
||||
tokenContract && tokenContract |
||||
.balanceOf(selectedAddress) |
||||
.then(usersToken => { |
||||
}) |
||||
this.updateComponentSendErrors({}) |
||||
} |
||||
|
||||
ConfirmSendToken.prototype.componentDidUpdate = function (prevProps) { |
||||
this.updateComponentSendErrors(prevProps) |
||||
} |
||||
|
||||
ConfirmSendToken.prototype.getAmount = function () { |
||||
const { |
||||
conversionRate, |
||||
tokenExchangeRate, |
||||
token, |
||||
tokenData, |
||||
send: { amount, editingTransactionId }, |
||||
} = this.props |
||||
const { params = [] } = tokenData |
||||
let { value } = params[1] || {} |
||||
const { decimals } = token |
||||
|
||||
if (editingTransactionId) { |
||||
value = conversionUtil(amount, { |
||||
fromNumericBase: 'hex', |
||||
toNumericBase: 'dec', |
||||
}) |
||||
} |
||||
|
||||
const sendTokenAmount = calcTokenAmount(value, decimals) |
||||
|
||||
return { |
||||
fiat: tokenExchangeRate |
||||
? +(sendTokenAmount * tokenExchangeRate * conversionRate).toFixed(2) |
||||
: null, |
||||
token: typeof value === 'undefined' |
||||
? this.context.t('unknown') |
||||
: +sendTokenAmount.toFixed(decimals), |
||||
} |
||||
|
||||
} |
||||
|
||||
ConfirmSendToken.prototype.getGasFee = function () { |
||||
const { conversionRate, tokenExchangeRate, token, currentCurrency } = this.props |
||||
const txMeta = this.gatherTxMeta() |
||||
const txParams = txMeta.txParams || {} |
||||
const { decimals } = token |
||||
|
||||
const gas = txParams.gas |
||||
const gasPrice = txParams.gasPrice || MIN_GAS_PRICE_HEX |
||||
const gasTotal = multiplyCurrencies(gas, gasPrice, { |
||||
multiplicandBase: 16, |
||||
multiplierBase: 16, |
||||
}) |
||||
|
||||
const FIAT = conversionUtil(gasTotal, { |
||||
fromNumericBase: 'BN', |
||||
toNumericBase: 'dec', |
||||
fromDenomination: 'WEI', |
||||
fromCurrency: 'ETH', |
||||
toCurrency: currentCurrency, |
||||
numberOfDecimals: 2, |
||||
conversionRate, |
||||
}) |
||||
const ETH = conversionUtil(gasTotal, { |
||||
fromNumericBase: 'BN', |
||||
toNumericBase: 'dec', |
||||
fromDenomination: 'WEI', |
||||
fromCurrency: 'ETH', |
||||
toCurrency: 'ETH', |
||||
numberOfDecimals: 6, |
||||
conversionRate, |
||||
}) |
||||
const tokenGas = multiplyCurrencies(gas, gasPrice, { |
||||
toNumericBase: 'dec', |
||||
multiplicandBase: 16, |
||||
multiplierBase: 16, |
||||
toCurrency: 'BAT', |
||||
conversionRate: tokenExchangeRate, |
||||
invertConversionRate: true, |
||||
fromDenomination: 'WEI', |
||||
numberOfDecimals: decimals || 4, |
||||
}) |
||||
|
||||
return { |
||||
fiat: +Number(FIAT).toFixed(2), |
||||
eth: ETH, |
||||
token: tokenExchangeRate |
||||
? tokenGas |
||||
: null, |
||||
gasFeeInHex: gasTotal.toString(16), |
||||
} |
||||
} |
||||
|
||||
ConfirmSendToken.prototype.getData = function () { |
||||
const { identities, tokenData } = this.props |
||||
const { params = [] } = tokenData |
||||
const { value } = params[0] || {} |
||||
const txMeta = this.gatherTxMeta() |
||||
const txParams = txMeta.txParams || {} |
||||
|
||||
return { |
||||
from: { |
||||
address: txParams.from, |
||||
name: identities[txParams.from].name, |
||||
}, |
||||
to: { |
||||
address: value, |
||||
name: identities[value] ? identities[value].name : this.context.t('newRecipient'), |
||||
}, |
||||
memo: txParams.memo || '', |
||||
} |
||||
} |
||||
|
||||
ConfirmSendToken.prototype.renderHeroAmount = function () { |
||||
const { token: { symbol }, currentCurrency } = this.props |
||||
const { fiat: fiatAmount, token: tokenAmount } = this.getAmount() |
||||
const txMeta = this.gatherTxMeta() |
||||
const txParams = txMeta.txParams || {} |
||||
const { memo = '' } = txParams |
||||
|
||||
const convertedAmountInFiat = this.convertToRenderableCurrency(fiatAmount, currentCurrency) |
||||
|
||||
return fiatAmount |
||||
? ( |
||||
h('div.confirm-send-token__hero-amount-wrapper', [ |
||||
h('h3.flex-center.confirm-screen-send-amount', `${convertedAmountInFiat}`), |
||||
h('h3.flex-center.confirm-screen-send-amount-currency', currentCurrency), |
||||
h('div.flex-center.confirm-memo-wrapper', [ |
||||
h('h3.confirm-screen-send-memo', [ memo ? `"${memo}"` : '' ]), |
||||
]), |
||||
]) |
||||
) |
||||
: ( |
||||
h('div.confirm-send-token__hero-amount-wrapper', [ |
||||
h('h3.flex-center.confirm-screen-send-amount', tokenAmount), |
||||
h('h3.flex-center.confirm-screen-send-amount-currency', symbol), |
||||
h('div.flex-center.confirm-memo-wrapper', [ |
||||
h('h3.confirm-screen-send-memo', [ memo ? `"${memo}"` : '' ]), |
||||
]), |
||||
]) |
||||
) |
||||
} |
||||
|
||||
ConfirmSendToken.prototype.renderGasFee = function () { |
||||
const { |
||||
currentCurrency: convertedCurrency, |
||||
conversionRate, |
||||
send: { gasTotal, gasLimit: sendGasLimit, gasPrice: sendGasPrice }, |
||||
showCustomizeGasModal, |
||||
} = this.props |
||||
const txMeta = this.gatherTxMeta() |
||||
const { gasFeeInHex } = this.getGasFee() |
||||
|
||||
return ( |
||||
h('section.flex-row.flex-center.confirm-screen-row', [ |
||||
h('span.confirm-screen-label.confirm-screen-section-column', [ this.context.t('gasFee') ]), |
||||
h('div.confirm-screen-section-column', [ |
||||
h(GasFeeDisplay, { |
||||
gasTotal: gasTotal || gasFeeInHex, |
||||
conversionRate, |
||||
convertedCurrency, |
||||
onClick: () => showCustomizeGasModal(txMeta, sendGasLimit, sendGasPrice, gasTotal), |
||||
}), |
||||
]), |
||||
]) |
||||
) |
||||
} |
||||
|
||||
ConfirmSendToken.prototype.renderTotalPlusGas = function () { |
||||
const { token: { symbol }, currentCurrency, send: { errors } } = this.props |
||||
const { fiat: fiatAmount, token: tokenAmount } = this.getAmount() |
||||
const { fiat: fiatGas, token: tokenGas } = this.getGasFee() |
||||
|
||||
const totalInFIAT = fiatAmount && fiatGas && addCurrencies(fiatAmount, fiatGas) |
||||
const convertedTotalInFiat = this.convertToRenderableCurrency(totalInFIAT, currentCurrency) |
||||
|
||||
return fiatAmount && fiatGas |
||||
? ( |
||||
h('section.flex-row.flex-center.confirm-screen-row.confirm-screen-total-box ', [ |
||||
h('div.confirm-screen-section-column', [ |
||||
h('span.confirm-screen-label', [ this.context.t('total') + ' ' ]), |
||||
h('div.confirm-screen-total-box__subtitle', [ this.context.t('amountPlusGas') ]), |
||||
]), |
||||
|
||||
h('div.confirm-screen-section-column', [ |
||||
h('div.confirm-screen-row-info', `${convertedTotalInFiat} ${currentCurrency}`), |
||||
h('div.confirm-screen-row-detail', `${addCurrencies(tokenAmount, tokenGas || '0')} ${symbol}`), |
||||
]), |
||||
]) |
||||
) |
||||
: ( |
||||
h('section.flex-row.flex-center.confirm-screen-row.confirm-screen-total-box ', [ |
||||
h('div', { |
||||
className: classnames({ |
||||
'confirm-screen-section-column--with-error': errors['insufficientFunds'], |
||||
'confirm-screen-section-column': !errors['insufficientFunds'], |
||||
}), |
||||
}, [ |
||||
h('span.confirm-screen-label', [ this.context.t('total') + ' ' ]), |
||||
h('div.confirm-screen-total-box__subtitle', [ this.context.t('amountPlusGas') ]), |
||||
]), |
||||
|
||||
h('div.confirm-screen-section-column', [ |
||||
h('div.confirm-screen-row-info', `${tokenAmount} ${symbol}`), |
||||
h('div.confirm-screen-row-detail', `+ ${fiatGas} ${currentCurrency} ${this.context.t('gas')}`), |
||||
]), |
||||
|
||||
this.renderErrorMessage('insufficientFunds'), |
||||
]) |
||||
) |
||||
} |
||||
|
||||
ConfirmSendToken.prototype.renderErrorMessage = function (message) { |
||||
const { send: { errors } } = this.props |
||||
|
||||
return errors[message] |
||||
? h('div.confirm-screen-error', [ errors[message] ]) |
||||
: null |
||||
} |
||||
|
||||
ConfirmSendToken.prototype.convertToRenderableCurrency = function (value, currencyCode) { |
||||
const upperCaseCurrencyCode = currencyCode.toUpperCase() |
||||
|
||||
return currencies.find(currency => currency.code === upperCaseCurrencyCode) |
||||
? currencyFormatter.format(Number(value), { |
||||
code: upperCaseCurrencyCode, |
||||
}) |
||||
: value |
||||
} |
||||
|
||||
ConfirmSendToken.prototype.renderHeaderRow = function (isTxReprice) { |
||||
const windowType = window.METAMASK_UI_TYPE |
||||
const isFullScreen = windowType !== ENVIRONMENT_TYPE_NOTIFICATION && |
||||
windowType !== ENVIRONMENT_TYPE_POPUP |
||||
|
||||
if (isTxReprice && isFullScreen) { |
||||
return null |
||||
} |
||||
|
||||
return ( |
||||
h('.page-container__header-row', [ |
||||
h('span.page-container__back-button', { |
||||
onClick: () => this.editTransaction(), |
||||
style: { |
||||
visibility: isTxReprice ? 'hidden' : 'initial', |
||||
}, |
||||
}, 'Edit'), |
||||
!isFullScreen && h(NetworkDisplay), |
||||
]) |
||||
) |
||||
} |
||||
|
||||
ConfirmSendToken.prototype.renderHeader = function (isTxReprice) { |
||||
const title = isTxReprice ? this.context.t('speedUpTitle') : this.context.t('confirm') |
||||
const subtitle = isTxReprice |
||||
? this.context.t('speedUpSubtitle') |
||||
: this.context.t('pleaseReviewTransaction') |
||||
|
||||
return ( |
||||
h('.page-container__header', [ |
||||
this.renderHeaderRow(isTxReprice), |
||||
h('.page-container__title', title), |
||||
h('.page-container__subtitle', subtitle), |
||||
]) |
||||
) |
||||
} |
||||
|
||||
ConfirmSendToken.prototype.render = function () { |
||||
const txMeta = this.gatherTxMeta() |
||||
const { |
||||
from: { |
||||
address: fromAddress, |
||||
name: fromName, |
||||
}, |
||||
to: { |
||||
address: toAddress, |
||||
name: toName, |
||||
}, |
||||
} = this.getData() |
||||
|
||||
const isTxReprice = Boolean(txMeta.lastGasPrice) |
||||
|
||||
return ( |
||||
h('div.confirm-screen-container.confirm-send-token', [ |
||||
// Main Send token Card
|
||||
h('div.page-container', [ |
||||
this.renderHeader(isTxReprice), |
||||
h('.page-container__content', [ |
||||
h('div.flex-row.flex-center.confirm-screen-identicons', [ |
||||
h('div.confirm-screen-account-wrapper', [ |
||||
h( |
||||
Identicon, |
||||
{ |
||||
address: fromAddress, |
||||
diameter: 60, |
||||
}, |
||||
), |
||||
h('span.confirm-screen-account-name', fromName), |
||||
// h('span.confirm-screen-account-number', fromAddress.slice(fromAddress.length - 4)),
|
||||
]), |
||||
h('i.fa.fa-arrow-right.fa-lg'), |
||||
h('div.confirm-screen-account-wrapper', [ |
||||
h( |
||||
Identicon, |
||||
{ |
||||
address: toAddress, |
||||
diameter: 60, |
||||
}, |
||||
), |
||||
h('span.confirm-screen-account-name', toName), |
||||
// h('span.confirm-screen-account-number', toAddress.slice(toAddress.length - 4)),
|
||||
]), |
||||
]), |
||||
|
||||
// h('h3.flex-center.confirm-screen-sending-to-message', {
|
||||
// style: {
|
||||
// textAlign: 'center',
|
||||
// fontSize: '16px',
|
||||
// },
|
||||
// }, [
|
||||
// `You're sending to Recipient ...${toAddress.slice(toAddress.length - 4)}`,
|
||||
// ]),
|
||||
|
||||
this.renderHeroAmount(), |
||||
|
||||
h('div.confirm-screen-rows', [ |
||||
h('section.flex-row.flex-center.confirm-screen-row', [ |
||||
h('span.confirm-screen-label.confirm-screen-section-column', [ this.context.t('from') ]), |
||||
h('div.confirm-screen-section-column', [ |
||||
h('div.confirm-screen-row-info', fromName), |
||||
h('div.confirm-screen-row-detail', `...${fromAddress.slice(fromAddress.length - 4)}`), |
||||
]), |
||||
]), |
||||
|
||||
toAddress && h('section.flex-row.flex-center.confirm-screen-row', [ |
||||
h('span.confirm-screen-label.confirm-screen-section-column', [ this.context.t('to') ]), |
||||
h('div.confirm-screen-section-column', [ |
||||
h('div.confirm-screen-row-info', toName), |
||||
h('div.confirm-screen-row-detail', `...${toAddress.slice(toAddress.length - 4)}`), |
||||
]), |
||||
]), |
||||
|
||||
this.renderGasFee(), |
||||
|
||||
this.renderTotalPlusGas(), |
||||
|
||||
]), |
||||
|
||||
]), |
||||
|
||||
h('form#pending-tx-form', { |
||||
className: 'confirm-screen-form', |
||||
onSubmit: this.onSubmit, |
||||
}, [ |
||||
this.renderErrorMessage('simulationFails'), |
||||
h('.page-container__footer', [ |
||||
// Cancel Button
|
||||
h('button.btn-cancel.page-container__footer-button.allcaps', { |
||||
onClick: (event) => this.cancel(event, txMeta), |
||||
}, this.context.t('cancel')), |
||||
|
||||
// Accept Button
|
||||
h('button.btn-confirm.page-container__footer-button.allcaps', { |
||||
onClick: event => this.onSubmit(event), |
||||
}, [this.context.t('confirm')]), |
||||
]), |
||||
]), |
||||
]), |
||||
]) |
||||
) |
||||
} |
||||
|
||||
ConfirmSendToken.prototype.onSubmit = function (event) { |
||||
event.preventDefault() |
||||
const { updateSendErrors } = this.props |
||||
const txMeta = this.gatherTxMeta() |
||||
const valid = this.checkValidity() |
||||
const balanceIsSufficient = this.isBalanceSufficient(txMeta) |
||||
this.setState({ valid, submitting: true }) |
||||
|
||||
if (valid && this.verifyGasParams() && balanceIsSufficient) { |
||||
this.props.sendTransaction(txMeta, event) |
||||
} else if (!balanceIsSufficient) { |
||||
updateSendErrors({ insufficientFunds: 'insufficientFunds' }) |
||||
} else { |
||||
updateSendErrors({ invalidGasParams: 'invalidGasParams' }) |
||||
this.setState({ submitting: false }) |
||||
} |
||||
} |
||||
|
||||
ConfirmSendToken.prototype.isBalanceSufficient = function (txMeta) { |
||||
const { |
||||
balance, |
||||
conversionRate, |
||||
} = this.props |
||||
const { |
||||
txParams: { |
||||
gas, |
||||
gasPrice, |
||||
}, |
||||
} = txMeta |
||||
const gasTotal = calcGasTotal(gas, gasPrice) |
||||
|
||||
return isBalanceSufficient({ |
||||
amount: '0', |
||||
gasTotal, |
||||
balance, |
||||
conversionRate, |
||||
}) |
||||
} |
||||
|
||||
|
||||
ConfirmSendToken.prototype.cancel = function (event, txMeta) { |
||||
event.preventDefault() |
||||
const { cancelTransaction } = this.props |
||||
|
||||
cancelTransaction(txMeta) |
||||
.then(() => this.props.history.push(DEFAULT_ROUTE)) |
||||
} |
||||
|
||||
ConfirmSendToken.prototype.checkValidity = function () { |
||||
const form = this.getFormEl() |
||||
const valid = form.checkValidity() |
||||
return valid |
||||
} |
||||
|
||||
ConfirmSendToken.prototype.getFormEl = function () { |
||||
const form = document.querySelector('form#pending-tx-form') |
||||
// Stub out form for unit tests:
|
||||
if (!form) { |
||||
return { checkValidity () { return true } } |
||||
} |
||||
return form |
||||
} |
||||
|
||||
// After a customizable state value has been updated,
|
||||
ConfirmSendToken.prototype.gatherTxMeta = function () { |
||||
const props = this.props |
||||
const state = this.state |
||||
const txData = clone(state.txData) || clone(props.txData) |
||||
|
||||
const { gasPrice: sendGasPrice, gasLimit: sendGasLimit } = props.send |
||||
const { |
||||
lastGasPrice, |
||||
txParams: { |
||||
gasPrice: txGasPrice, |
||||
gas: txGasLimit, |
||||
}, |
||||
} = txData |
||||
|
||||
let forceGasMin |
||||
if (lastGasPrice) { |
||||
forceGasMin = ethUtil.addHexPrefix(multiplyCurrencies(lastGasPrice, 1.1, { |
||||
multiplicandBase: 16, |
||||
multiplierBase: 10, |
||||
toNumericBase: 'hex', |
||||
})) |
||||
} |
||||
|
||||
txData.txParams.gasPrice = sendGasPrice || forceGasMin || txGasPrice |
||||
txData.txParams.gas = sendGasLimit || txGasLimit |
||||
|
||||
// log.debug(`UI has defaulted to tx meta ${JSON.stringify(txData)}`)
|
||||
return txData |
||||
} |
||||
|
||||
ConfirmSendToken.prototype.verifyGasParams = function () { |
||||
// We call this in case the gas has not been modified at all
|
||||
if (!this.state) { return true } |
||||
return ( |
||||
this._notZeroOrEmptyString(this.state.gas) && |
||||
this._notZeroOrEmptyString(this.state.gasPrice) |
||||
) |
||||
} |
||||
|
||||
ConfirmSendToken.prototype._notZeroOrEmptyString = function (obj) { |
||||
return obj !== '' && obj !== '0x0' |
||||
} |
||||
|
||||
ConfirmSendToken.prototype.bnMultiplyByFraction = function (targetBN, numerator, denominator) { |
||||
const numBN = new BN(numerator) |
||||
const denomBN = new BN(denominator) |
||||
return targetBN.mul(numBN).div(denomBN) |
||||
} |
@ -1,165 +0,0 @@ |
||||
const Component = require('react').Component |
||||
const connect = require('react-redux').connect |
||||
const h = require('react-hyperscript') |
||||
const PropTypes = require('prop-types') |
||||
const clone = require('clone') |
||||
const abi = require('human-standard-token-abi') |
||||
const abiDecoder = require('abi-decoder') |
||||
abiDecoder.addABI(abi) |
||||
const inherits = require('util').inherits |
||||
const actions = require('../../actions') |
||||
const { getSymbolAndDecimals } = require('../../token-util') |
||||
const ConfirmSendEther = require('./confirm-send-ether') |
||||
const ConfirmSendToken = require('./confirm-send-token') |
||||
const ConfirmDeployContract = require('./confirm-deploy-contract') |
||||
const Loading = require('../loading-screen') |
||||
|
||||
const TX_TYPES = { |
||||
DEPLOY_CONTRACT: 'deploy_contract', |
||||
SEND_ETHER: 'send_ether', |
||||
SEND_TOKEN: 'send_token', |
||||
} |
||||
|
||||
module.exports = connect(mapStateToProps, mapDispatchToProps)(PendingTx) |
||||
|
||||
function mapStateToProps (state) { |
||||
const { |
||||
conversionRate, |
||||
identities, |
||||
tokens: existingTokens, |
||||
} = state.metamask |
||||
const accounts = state.metamask.accounts |
||||
const selectedAddress = state.metamask.selectedAddress || Object.keys(accounts)[0] |
||||
return { |
||||
conversionRate, |
||||
identities, |
||||
selectedAddress, |
||||
existingTokens, |
||||
} |
||||
} |
||||
|
||||
function mapDispatchToProps (dispatch) { |
||||
return { |
||||
backToAccountDetail: address => dispatch(actions.backToAccountDetail(address)), |
||||
cancelTransaction: ({ id }) => dispatch(actions.cancelTx({ id })), |
||||
} |
||||
} |
||||
|
||||
inherits(PendingTx, Component) |
||||
function PendingTx () { |
||||
Component.call(this) |
||||
this.state = { |
||||
isFetching: true, |
||||
transactionType: '', |
||||
tokenAddress: '', |
||||
tokenSymbol: '', |
||||
tokenDecimals: '', |
||||
} |
||||
} |
||||
|
||||
PendingTx.prototype.componentDidMount = function () { |
||||
this.setTokenData() |
||||
} |
||||
|
||||
PendingTx.prototype.componentDidUpdate = function (prevProps, prevState) { |
||||
if (prevState.isFetching) { |
||||
this.setTokenData() |
||||
} |
||||
} |
||||
|
||||
PendingTx.prototype.setTokenData = async function () { |
||||
const { existingTokens } = this.props |
||||
const txMeta = this.gatherTxMeta() |
||||
const txParams = txMeta.txParams || {} |
||||
|
||||
if (txMeta.loadingDefaults) { |
||||
return |
||||
} |
||||
|
||||
if (!txParams.to) { |
||||
return this.setState({ |
||||
transactionType: TX_TYPES.DEPLOY_CONTRACT, |
||||
isFetching: false, |
||||
}) |
||||
} |
||||
|
||||
// inspect tx data for supported special confirmation screens
|
||||
let isTokenTransaction = false |
||||
if (txParams.data) { |
||||
const tokenData = abiDecoder.decodeMethod(txParams.data) |
||||
const { name: tokenMethodName } = tokenData || {} |
||||
isTokenTransaction = (tokenMethodName === 'transfer') |
||||
} |
||||
|
||||
if (isTokenTransaction) { |
||||
const { symbol, decimals } = await getSymbolAndDecimals(txParams.to, existingTokens) |
||||
|
||||
this.setState({ |
||||
transactionType: TX_TYPES.SEND_TOKEN, |
||||
tokenAddress: txParams.to, |
||||
tokenSymbol: symbol, |
||||
tokenDecimals: decimals, |
||||
isFetching: false, |
||||
}) |
||||
} else { |
||||
this.setState({ |
||||
transactionType: TX_TYPES.SEND_ETHER, |
||||
isFetching: false, |
||||
}) |
||||
} |
||||
} |
||||
|
||||
PendingTx.prototype.gatherTxMeta = function () { |
||||
const props = this.props |
||||
const state = this.state |
||||
const txData = clone(state.txData) || clone(props.txData) |
||||
|
||||
return txData |
||||
} |
||||
|
||||
PendingTx.prototype.render = function () { |
||||
const { |
||||
isFetching, |
||||
transactionType, |
||||
tokenAddress, |
||||
tokenSymbol, |
||||
tokenDecimals, |
||||
} = this.state |
||||
|
||||
const { sendTransaction } = this.props |
||||
|
||||
if (isFetching) { |
||||
return h(Loading, { |
||||
loadingMessage: this.context.t('generatingTransaction'), |
||||
}) |
||||
} |
||||
|
||||
switch (transactionType) { |
||||
case TX_TYPES.SEND_ETHER: |
||||
return h(ConfirmSendEther, { |
||||
txData: this.gatherTxMeta(), |
||||
sendTransaction, |
||||
}) |
||||
case TX_TYPES.SEND_TOKEN: |
||||
return h(ConfirmSendToken, { |
||||
txData: this.gatherTxMeta(), |
||||
sendTransaction, |
||||
token: { |
||||
address: tokenAddress, |
||||
symbol: tokenSymbol, |
||||
decimals: tokenDecimals, |
||||
}, |
||||
}) |
||||
case TX_TYPES.DEPLOY_CONTRACT: |
||||
return h(ConfirmDeployContract, { |
||||
txData: this.gatherTxMeta(), |
||||
sendTransaction, |
||||
}) |
||||
default: |
||||
return h(Loading) |
||||
} |
||||
} |
||||
|
||||
PendingTx.contextTypes = { |
||||
t: PropTypes.func, |
||||
} |
@ -0,0 +1 @@ |
||||
export { default } from './currency-display.js' |
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in new issue