Skip to content

Commit

Permalink
refactor: Centralise BigNumber import (#1820)
Browse files Browse the repository at this point in the history
Stop depending directly on ethers for this, such that it should be
easier to eventually shift away from ethers v5.
  • Loading branch information
pxrl authored Sep 19, 2024
1 parent 0452644 commit 04d4c51
Show file tree
Hide file tree
Showing 33 changed files with 91 additions and 67 deletions.
7 changes: 7 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,13 @@ module.exports = {
"no-duplicate-imports": "error",
"@typescript-eslint/no-floating-promises": ["error"],
"@typescript-eslint/no-misused-promises": ["error", { checksVoidReturn: false }],
"no-restricted-imports": [
"error",
{
patterns: [{ group: ["@ethersproject/bignumber"], message: "Use 'src/utils/BNUtils' instead" }],
paths: [{ name: "ethers", importNames: ["BigNumber"], message: "Use 'src/utils/BNUtils' instead" }],
},
],
},
settings: {
node: {
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
"@ethersproject/abi": "^5.7.0",
"@ethersproject/abstract-provider": "^5.7.0",
"@ethersproject/abstract-signer": "^5.7.0",
"@ethersproject/bignumber": "^5.7.0",
"@google-cloud/kms": "^3.6.0",
"@google-cloud/storage": "^6.10.1",
"@maticnetwork/maticjs": "^3.6.0",
Expand Down
8 changes: 3 additions & 5 deletions scripts/hubpool.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
import minimist from "minimist";
import { WETH9__factory as WETH9 } from "@across-protocol/contracts";
import { constants as sdkConsts } from "@across-protocol/sdk";
import { BigNumber, ethers, Signer } from "ethers";
import { ethers, Signer } from "ethers";
import { config } from "dotenv";
import { getNetworkName, getSigner } from "../src/utils";
import { BigNumber, bnOne, bnUint256Max, formatEther, formatUnits, getNetworkName, getSigner } from "../src/utils";
import * as utils from "./utils";

const { PROTOCOL_DEFAULT_CHAIN_ID_INDICES } = sdkConsts;
const { MaxUint256, One: bnOne } = ethers.constants;
const { formatEther, formatUnits } = ethers.utils;

const { NODE_SUCCESS, NODE_INPUT_ERR, NODE_APP_ERR } = utils;

Expand Down Expand Up @@ -99,7 +97,7 @@ async function dispute(args: Record<string, number | string>, signer: Signer): P

if (allowance.lt(bondAmount)) {
console.log(`Approving ${network} HubPool @ ${hubPool.address} to transfer ${symbol}.`);
const approval = await bondToken.connect(signer).approve(hubPool.address, MaxUint256);
const approval = await bondToken.connect(signer).approve(hubPool.address, bnUint256Max);
console.log(`Approval: ${approval.hash}...`);
await approval.wait();
}
Expand Down
4 changes: 2 additions & 2 deletions src/adapter/bridges/UsdcCCTPBridge.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { BigNumber, Contract, Signer } from "ethers";
import { Contract, Signer } from "ethers";
import { CONTRACT_ADDRESSES, chainIdsToCctpDomains } from "../../common";
import { BridgeTransactionDetails, BaseBridgeAdapter, BridgeEvents } from "./BaseBridgeAdapter";
import { EventSearchConfig, Provider, TOKEN_SYMBOLS_MAP, compareAddressesSimple, assert } from "../../utils";
import { BigNumber, EventSearchConfig, Provider, TOKEN_SYMBOLS_MAP, compareAddressesSimple, assert } from "../../utils";
import { processEvent } from "../utils";
import { cctpAddressToBytes32, retrieveOutstandingCCTPBridgeUSDCTransfers } from "../../utils/CCTPUtils";

Expand Down
4 changes: 2 additions & 2 deletions src/adapter/bridges/UsdcTokenSplitterBridge.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { BigNumber, Signer } from "ethers";
import { Signer } from "ethers";
import { CONTRACT_ADDRESSES, CANONICAL_BRIDGE } from "../../common";
import { UsdcCCTPBridge } from "./UsdcCCTPBridge";
import { BridgeTransactionDetails, BaseBridgeAdapter, BridgeEvents } from "./BaseBridgeAdapter";
import { EventSearchConfig, Provider, TOKEN_SYMBOLS_MAP, compareAddressesSimple, assert } from "../../utils";
import { BigNumber, EventSearchConfig, Provider, TOKEN_SYMBOLS_MAP, compareAddressesSimple, assert } from "../../utils";

export class UsdcTokenSplitterBridge extends BaseBridgeAdapter {
protected cctpBridge: BaseBridgeAdapter;
Expand Down
2 changes: 1 addition & 1 deletion src/adapter/bridges/ZKSyncBridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ export class ZKSyncBridge extends BaseBridgeAdapter {
return l2Gas;
}

protected getMailboxContract() {
protected getMailboxContract(): Contract {
return this.zkSyncMailbox;
}
}
3 changes: 2 additions & 1 deletion src/adapter/utils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { BigNumber, Event } from "ethers";
import { Event } from "ethers";
import { TOKEN_APPROVALS_TO_FIRST_ZERO } from "../common";
import {
BigNumber,
spreadEventWithBlockNumber,
toBN,
MAX_SAFE_ALLOWANCE,
Expand Down
8 changes: 4 additions & 4 deletions src/clients/InventoryClient.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { utils as ethersUtils } from "ethers";
import { constants, utils as sdkUtils } from "@across-protocol/sdk";
import WETH_ABI from "../common/abi/Weth.json";
import {
Expand All @@ -10,6 +9,7 @@ import {
createFormatFunction,
blockExplorerLink,
Contract,
formatUnits,
runTransaction,
isDefined,
DefaultLogLevels,
Expand Down Expand Up @@ -577,9 +577,9 @@ export class InventoryClient {
cumulativeVirtualBalance,
cumulativeVirtualBalanceWithShortfall,
cumulativeVirtualBalanceWithShortfallPostRefunds,
targetPct: ethersUtils.formatUnits(tokenConfig.targetPct, 18),
targetOverage: ethersUtils.formatUnits(targetOverageBuffer, 18),
effectiveTargetPct: ethersUtils.formatUnits(effectiveTargetPct, 18),
targetPct: formatUnits(tokenConfig.targetPct, 18),
targetOverage: formatUnits(targetOverageBuffer, 18),
effectiveTargetPct: formatUnits(effectiveTargetPct, 18),
expectedPostRelayAllocation,
chainsToEvaluate,
}
Expand Down
2 changes: 1 addition & 1 deletion src/clients/MultiCallerClient.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { utils as sdkUtils } from "@across-protocol/sdk";
import { BigNumber } from "ethers";
import { DEFAULT_MULTICALL_CHUNK_SIZE, Multicall2Call } from "../common";
import {
BigNumber,
winston,
bnZero,
getNetworkName,
Expand Down
4 changes: 2 additions & 2 deletions src/clients/bridges/op-stack/OpStackAdapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ import {
Contract,
BigNumber,
BigNumberish,
bnZero,
TransactionResponse,
Event,
checkAddressChecksum,
ethers,
spreadEventWithBlockNumber,
assign,
winston,
Expand Down Expand Up @@ -146,7 +146,7 @@ export class OpStackAdapter extends BaseAdapter {
method,
args,
gasLimitMultiplier,
ethers.constants.Zero,
bnZero,
simMode
);
}
Expand Down
4 changes: 2 additions & 2 deletions src/clients/bridges/op-stack/UsdcCCTPBridge.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { BigNumber, Contract, Signer } from "ethers";
import { Contract, Signer } from "ethers";
import { CONTRACT_ADDRESSES, chainIdsToCctpDomains } from "../../../common";
import { BridgeTransactionDetails, OpStackBridge, OpStackEvents } from "./OpStackBridgeInterface";
import { EventSearchConfig, Provider, TOKEN_SYMBOLS_MAP } from "../../../utils";
import { BigNumber, EventSearchConfig, Provider, TOKEN_SYMBOLS_MAP } from "../../../utils";
import { cctpAddressToBytes32, retrieveOutstandingCCTPBridgeUSDCTransfers } from "../../../utils/CCTPUtils";

export class UsdcCCTPBridge extends OpStackBridge {
Expand Down
11 changes: 9 additions & 2 deletions src/clients/bridges/op-stack/UsdcTokenSplitterBridge.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
import { BigNumber, Signer } from "ethers";
import { Signer } from "ethers";
import { DefaultERC20Bridge } from "./DefaultErc20Bridge";
import { UsdcCCTPBridge } from "./UsdcCCTPBridge";
import { EventSearchConfig, Provider, TOKEN_SYMBOLS_MAP, assert, compareAddressesSimple } from "../../../utils";
import {
BigNumber,
EventSearchConfig,
Provider,
TOKEN_SYMBOLS_MAP,
assert,
compareAddressesSimple,
} from "../../../utils";
import { BridgeTransactionDetails, OpStackBridge, OpStackEvents } from "./OpStackBridgeInterface";
import { CONTRACT_ADDRESSES } from "../../../common";

Expand Down
3 changes: 2 additions & 1 deletion src/clients/bridges/utils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { BigNumber, Contract, Event } from "ethers";
import { Contract, Event } from "ethers";
import { TOKEN_APPROVALS_TO_FIRST_ZERO } from "../../common";
import {
BigNumber,
MAX_SAFE_ALLOWANCE,
blockExplorerLink,
bnZero,
Expand Down
6 changes: 4 additions & 2 deletions src/finalizer/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { utils as sdkUtils } from "@across-protocol/sdk";
import assert from "assert";
import { BigNumber, Contract, constants } from "ethers";
import { Contract } from "ethers";
import { getAddress } from "ethers/lib/utils";
import { groupBy, uniq } from "lodash";
import { AugmentedTransaction, HubPoolClient, MultiCallerClient, TransactionClient } from "../clients";
Expand All @@ -17,6 +17,8 @@ import {
import { DataworkerConfig } from "../dataworker/DataworkerConfig";
import { SpokePoolClientsByChain } from "../interfaces";
import {
BigNumber,
bnZero,
Signer,
blockExplorerLink,
config,
Expand Down Expand Up @@ -253,7 +255,7 @@ export async function finalize(

const txnClient = new TransactionClient(logger);

let gasEstimation = constants.Zero;
let gasEstimation = bnZero;
const batchGasLimit = BigNumber.from(10_000_000);
// @dev To avoid running into block gas limit in case the # of finalizations gets too high, keep a running
// counter of the approximate gas estimation and cut off the list of finalizations if it gets too high.
Expand Down
4 changes: 2 additions & 2 deletions src/interfaces/InventoryManagement.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { BigNumber, utils as ethersUtils } from "ethers";
import { TOKEN_SYMBOLS_MAP } from "../utils";
import { utils as ethersUtils } from "ethers";
import { BigNumber, TOKEN_SYMBOLS_MAP } from "../utils";

export type TokenBalanceConfig = {
targetOverageBuffer: BigNumber; // Max multiplier for targetPct, to give flexibility in repayment chain selection.
Expand Down
2 changes: 1 addition & 1 deletion src/interfaces/Report.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { BigNumber } from "ethers";
import { BigNumber } from "../utils";

export enum BundleAction {
PROPOSED = "proposed",
Expand Down
2 changes: 1 addition & 1 deletion src/interfaces/Token.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { BigNumber } from "ethers";
import { BigNumber } from "../utils";
import { SortableEvent } from ".";

export interface TokenTransfer extends SortableEvent {
Expand Down
2 changes: 1 addition & 1 deletion src/interfaces/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { BigNumber } from "ethers";
import { interfaces } from "@across-protocol/sdk";
import { BigNumber } from "../utils";

export * from "./InventoryManagement";
export * from "./SpokePool";
Expand Down
27 changes: 13 additions & 14 deletions src/monitor/Monitor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,17 @@ import {
convertFromWei,
createFormatFunction,
ERC20,
ethers,
fillStatusArray,
blockExplorerLink,
blockExplorerLinks,
formatUnits,
getNativeTokenAddressForChain,
getGasPrice,
getNativeTokenSymbol,
getNetworkName,
getUnfilledDeposits,
mapAsync,
parseUnits,
providers,
toBN,
toBNWei,
Expand All @@ -42,11 +43,9 @@ import { MonitorClients, updateMonitorClients } from "./MonitorClientHelper";
import { MonitorConfig } from "./MonitorConfig";
import { CombinedRefunds } from "../dataworker/DataworkerUtils";

export const REBALANCE_FINALIZE_GRACE_PERIOD = process.env.REBALANCE_FINALIZE_GRACE_PERIOD
? Number(process.env.REBALANCE_FINALIZE_GRACE_PERIOD)
: 60 * 60;
// 60 minutes, which is the length of the challenge window, so if a rebalance takes longer than this to finalize,
// then its finalizing after the subsequent challenge period has started, which is sub-optimal.
export const REBALANCE_FINALIZE_GRACE_PERIOD = Number(process.env.REBALANCE_FINALIZE_GRACE_PERIOD ?? 60 * 60);

// bundle frequency.
export const ALL_CHAINS_NAME = "All chains";
Expand Down Expand Up @@ -381,8 +380,8 @@ export class Monitor {
token,
account,
currentBalance: balances[i].toString(),
warnThreshold: ethers.utils.parseUnits(warnThreshold.toString(), decimalValues[i]),
errorThreshold: ethers.utils.parseUnits(errorThreshold.toString(), decimalValues[i]),
warnThreshold: parseUnits(warnThreshold.toString(), decimalValues[i]),
errorThreshold: parseUnits(errorThreshold.toString(), decimalValues[i]),
};
}),
});
Expand All @@ -397,10 +396,10 @@ export class Monitor {
const decimals = decimalValues[i];
let trippedThreshold: { level: "warn" | "error"; threshold: number } | null = null;

if (warnThreshold !== null && balance.lt(ethers.utils.parseUnits(warnThreshold.toString(), decimals))) {
if (warnThreshold !== null && balance.lt(parseUnits(warnThreshold.toString(), decimals))) {
trippedThreshold = { level: "warn", threshold: warnThreshold };
}
if (errorThreshold !== null && balance.lt(ethers.utils.parseUnits(errorThreshold.toString(), decimals))) {
if (errorThreshold !== null && balance.lt(parseUnits(errorThreshold.toString(), decimals))) {
trippedThreshold = { level: "error", threshold: errorThreshold };
}
if (trippedThreshold !== null) {
Expand All @@ -418,7 +417,7 @@ export class Monitor {
text: ` ${getNetworkName(chainId)} ${symbol} balance for ${blockExplorerLink(
account,
chainId
)} is ${ethers.utils.formatUnits(balance, decimals)}. Threshold: ${trippedThreshold.threshold}`,
)} is ${formatUnits(balance, decimals)}. Threshold: ${trippedThreshold.threshold}`,
};
}
}
Expand Down Expand Up @@ -456,7 +455,7 @@ export class Monitor {
token,
account,
currentBalance: currentBalances[i].toString(),
target: ethers.utils.parseUnits(target.toString(), decimalValues[i]),
target: parseUnits(target.toString(), decimalValues[i]),
};
}),
});
Expand All @@ -467,11 +466,11 @@ export class Monitor {
refillEnabledBalances.map(async ({ chainId, isHubPool, token, account, target, trigger }, i) => {
const currentBalance = currentBalances[i];
const decimals = decimalValues[i];
const balanceTrigger = ethers.utils.parseUnits(trigger.toString(), decimals);
const balanceTrigger = parseUnits(trigger.toString(), decimals);
const isBelowTrigger = currentBalance.lte(balanceTrigger);
if (isBelowTrigger) {
// Fill balance back to target, not trigger.
const balanceTarget = ethers.utils.parseUnits(target.toString(), decimals);
const balanceTarget = parseUnits(target.toString(), decimals);
const deficit = balanceTarget.sub(currentBalance);
let canRefill = await this.balanceAllocator.requestBalanceAllocation(
chainId,
Expand Down Expand Up @@ -541,7 +540,7 @@ export class Monitor {
method: "loadEthForL2Calls",
args: [],
message: "Reloaded ETH in HubPool 🫡!",
mrkdwn: `Loaded ${ethers.utils.formatUnits(deficit, decimals)} ETH from ${signerAddress}.`,
mrkdwn: `Loaded ${formatUnits(deficit, decimals)} ETH from ${signerAddress}.`,
value: deficit,
});
} else {
Expand All @@ -554,7 +553,7 @@ export class Monitor {
const receipt = await tx.wait();
this.logger.info({
at: "Monitor#refillBalances",
message: `Reloaded ${ethers.utils.formatUnits(
message: `Reloaded ${formatUnits(
deficit,
decimals
)} ${nativeSymbolForChain} for ${account} from ${signerAddress} 🫡!`,
Expand Down
6 changes: 5 additions & 1 deletion src/utils/BNUtils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { BigNumber } from "ethers";
// eslint-disable-next-line no-restricted-imports
import { BigNumber } from "@ethersproject/bignumber";

// eslint-disable-next-line no-restricted-imports
export * from "@ethersproject/bignumber";

export function bnComparatorDescending(a: BigNumber, b: BigNumber): -1 | 0 | 1 {
if (b.gt(a)) {
Expand Down
3 changes: 2 additions & 1 deletion src/utils/CCTPUtils.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { utils } from "@across-protocol/sdk";
import { TransactionReceipt } from "@ethersproject/abstract-provider";
import axios from "axios";
import { BigNumber, ethers } from "ethers";
import { ethers } from "ethers";
import { CONTRACT_ADDRESSES, chainIdsToCctpDomains } from "../common";
import { EventSearchConfig, paginatedEventQuery } from "./EventUtils";
import { BigNumber } from "./BNUtils";
import { bnZero, compareAddressesSimple } from "./SDKUtils";
import { isDefined } from "./TypeGuards";
import { getProvider } from "./ProviderUtils";
Expand Down
3 changes: 3 additions & 0 deletions src/utils/SDKUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,10 @@ export const {
fillStatusArray,
fixedPointAdjustment,
forEachAsync,
formatEther,
formatUnits,
mapAsync,
parseUnits,
filterAsync,
toBN,
bnToHex,
Expand Down
8 changes: 5 additions & 3 deletions src/utils/TokenUtils.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { TOKEN_SYMBOLS_MAP } from "@across-protocol/constants";
import { constants, utils } from "@across-protocol/sdk";
import { CONTRACT_ADDRESSES } from "../common";
import { BigNumberish, utils as ethersUtils } from "ethers";
import { TOKEN_SYMBOLS_MAP } from "@across-protocol/constants";
import { BigNumberish } from "./BNUtils";
import { formatUnits } from "./SDKUtils";

const { ZERO_ADDRESS } = constants;

export const { fetchTokenInfo, getL2TokenAddresses } = utils;
Expand All @@ -18,5 +20,5 @@ export function getNativeTokenAddressForChain(chainId: number): string {
*/
export function formatUnitsForToken(symbol: string, amount: BigNumberish): string {
const decimals = (TOKEN_SYMBOLS_MAP[symbol]?.decimals as number) ?? 18;
return ethersUtils.formatUnits(amount, decimals);
return formatUnits(amount, decimals);
}
2 changes: 1 addition & 1 deletion src/utils/TransactionUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,6 @@ export function getTarget(targetAddress: string):
}
}

function scaleByNumber(amount: ethers.BigNumber, scaling: number) {
function scaleByNumber(amount: BigNumber, scaling: number) {
return amount.mul(toBNWei(scaling)).div(fixedPoint);
}
Loading

0 comments on commit 04d4c51

Please sign in to comment.