Skip to content

Commit

Permalink
lib: implement and use safe fromWei and toWei functions
Browse files Browse the repository at this point in the history
These always convert the number argument toBN, and include extra details
in the error message of failing cases.
  • Loading branch information
Fang- committed Jan 30, 2020
1 parent e88f47e commit c53aba4
Show file tree
Hide file tree
Showing 7 changed files with 46 additions and 15 deletions.
6 changes: 3 additions & 3 deletions src/components/NeedFundsNotice.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React from 'react';
import { fromWei, toBN } from 'web3-utils';
import { safeFromWei } from '../lib/lib';

import Highlighted from './Highlighted';
import CopiableAddress from './CopiableAddress';
Expand All @@ -16,8 +16,8 @@ export default function NeedFundsNotice({
<WarningBox {...rest}>
<Highlighted warning>
Your ownership address <CopiableAddress>{address}</CopiableAddress>{' '}
needs at least {fromWei(toBN(minBalance))} ETH and currently has{' '}
{fromWei(toBN(balance))} ETH. The transaction will automatically resume
needs at least {safeFromWei(minBalance)} ETH and currently has{' '}
{safeFromWei(balance)} ETH. The transaction will automatically resume
once enough ETH is available. Waiting... <Blinky />
</Highlighted>
</WarningBox>
Expand Down
6 changes: 3 additions & 3 deletions src/lib/error.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { fromWei, toBN } from 'web3-utils';
import { safeFromWei } from './lib';

const BRIDGE_ERROR = {
MISSING_WEB3: 'no web3 object found',
Expand All @@ -18,13 +18,13 @@ const BRIDGE_ERROR = {
const renderTxnError = (web3, msg) => {
const txnCost = (web3, msg) => {
const costWei = msg.match(/upfront cost is: ([0-9]+)/);
const costEth = fromWei(toBN(costWei[1]), 'ether');
const costEth = safeFromWei(costWei[1], 'ether');
return parseFloat(costEth).toFixed(4);
};

const acctBalance = (web3, msg) => {
const balWei = msg.match(/sender's account only has: ([0-9]+)/);
const balEth = fromWei(toBN(balWei[1]), 'ether');
const balEth = safeFromWei(balWei[1], 'ether');
return parseFloat(balEth).toFixed(4);
};

Expand Down
27 changes: 27 additions & 0 deletions src/lib/lib.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,30 @@
import ob from 'urbit-ob';
import patp2dec from './patp2dec';
import { fromWei, toWei, toBN } from 'web3-utils';

const safeFromWei = (num, target) => {
try {
return fromWei(toBN(num), target);
} catch (e) {
e.message =
`(safeFromWei got ${typeof num} (${num}), made ${typeof toBN(
num
)}. Please report this issue!) ` + e.message;
throw e;
}
};

const safeToWei = (num, source) => {
try {
return toWei(toBN(num), source);
} catch (e) {
e.message =
`(safeToWei got ${typeof num} (${num}), made ${typeof toBN(
num
)}. Please report this issue!) ` + e.message;
throw e;
}
};

const compose = (...fs) =>
fs.reduceRight((pF, nF) => (...args) => nF(pF(...args)), v => v);
Expand Down Expand Up @@ -43,6 +68,8 @@ const patpStringLength = byteLength =>
byteLength * 3 + Math.ceil(byteLength / 2);

export {
safeFromWei,
safeToWei,
compose,
allFalse,
isLast,
Expand Down
5 changes: 3 additions & 2 deletions src/lib/reticket.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ import { addHexPrefix } from './wallet';
import { sendAndAwaitAll } from './txn';
import getSuggestedGasPrice from './getSuggestedGasPrice';
import { GAS_LIMITS } from './constants';
import { toWei, toBN } from 'web3-utils';
import { toBN } from 'web3-utils';
import { safeToWei } from './lib';

// the initial network key revision is always 1
const INITIAL_NETWORK_KEY_REVISION = 1;
Expand Down Expand Up @@ -143,7 +144,7 @@ export async function reticketPointBetweenWallets({
progress(TRANSACTION_PROGRESS.SIGNING);

const suggestedGasPrice = await getSuggestedGasPrice(networkType);
const gasPrice = toWei(suggestedGasPrice.toFixed(), 'gwei');
const gasPrice = safeToWei(suggestedGasPrice.toFixed(), 'gwei');
const gasPriceBN = toBN(gasPrice);
let totalCost = toBN(0);
let inviteNonce = await web3.eth.getTransactionCount(fromWallet.address);
Expand Down
7 changes: 4 additions & 3 deletions src/lib/txn.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import Tx from 'ethereumjs-tx';
import { toWei, fromWei, toHex, toBN } from 'web3-utils';
import { toHex } from 'web3-utils';
import { safeFromWei, safeToWei } from './lib';
import retry from 'async-retry';

import { NETWORK_TYPES } from './network';
Expand Down Expand Up @@ -31,7 +32,7 @@ const signTransaction = async ({
// TODO: require these in txn object
nonce = toHex(nonce);
chainId = toHex(chainId);
gasPrice = toHex(toWei(gasPrice, 'gwei'));
gasPrice = toHex(safeToWei(gasPrice, 'gwei'));
gasLimit = toHex(gasLimit);

const txParams = { nonce, chainId, gasPrice, gasLimit };
Expand Down Expand Up @@ -193,7 +194,7 @@ const getTxnInfo = async (web3, addr) => {
return {
nonce: nonce,
chainId: chainId,
gasPrice: fromWei(toBN(gasPrice), 'gwei'),
gasPrice: safeFromWei(gasPrice, 'gwei'),
};
};

Expand Down
5 changes: 3 additions & 2 deletions src/lib/useEthereumTransaction.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useCallback, useEffect, useState } from 'react';
import { Just } from 'folktale/maybe';
import { toWei, toBN } from 'web3-utils';
import { toBN } from 'web3-utils';

import { useNetwork } from 'store/network';
import { useWallet } from 'store/wallet';
Expand All @@ -22,6 +22,7 @@ import { ensureFundsFor } from 'lib/tank';
import useDeepEqualReference from 'lib/useDeepEqualReference';
import useGasPrice from 'lib/useGasPrice';
import timeout from 'lib/timeout';
import { safeToWei } from 'lib/lib';

const STATE = {
NONE: 'NONE',
Expand Down Expand Up @@ -148,7 +149,7 @@ export default function useEthereumTransaction(
const costGwei = toBN(gasLimit)
.mul(toBN(gasPrice))
.mul(toBN(rawTxs.length));
const cost = toWei(costGwei.toString(), 'gwei');
const cost = safeToWei(costGwei, 'gwei');
let usedTank = false;
// if this ethereum transaction is being executed by a specific point
// see if we can use the tank
Expand Down
5 changes: 3 additions & 2 deletions src/lib/useInviter.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useState, useCallback, useEffect } from 'react';
import { toWei, toBN } from 'web3-utils';
import { toBN } from 'web3-utils';
import * as azimuth from 'azimuth-js';
import { FORM_ERROR } from 'final-form';

Expand All @@ -16,6 +16,7 @@ import {
} from 'lib/txn';
import useGasPrice from 'lib/useGasPrice';
import { MIN_PLANET } from 'lib/constants';
import { safeToWei } from 'lib/lib';

import { useNetwork } from 'store/network';
import { useWallet } from 'store/wallet';
Expand Down Expand Up @@ -148,7 +149,7 @@ const useInviter = () => {
_web3,
point,
_wallet.address,
toWei(totalCost.toString(), 'gwei'),
safeToWei(totalCost, 'gwei'),
Object.keys(invites).map(name => invites[name].rawTx),
(address, minBalance, balance) =>
setNeedFunds({ address, minBalance, balance }),
Expand Down

0 comments on commit c53aba4

Please sign in to comment.