Skip to content

Commit

Permalink
devop: switch to @ethereumjs/utils
Browse files Browse the repository at this point in the history
  • Loading branch information
kvhnuke committed Feb 29, 2024
1 parent 95bee65 commit 35b649b
Show file tree
Hide file tree
Showing 32 changed files with 91 additions and 80 deletions.
3 changes: 2 additions & 1 deletion packages/extension/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
"@enkryptcom/utils": "workspace:^",
"@ethereumjs/common": "^4.2.0",
"@ethereumjs/tx": "^5.2.1",
"@ethereumjs/util": "^9.0.2",
"@ledgerhq/hw-transport-webusb": "^6.28.4",
"@metamask/eth-sig-util": "^7.0.1",
"@rollup/plugin-replace": "^5.0.5",
Expand All @@ -47,8 +48,8 @@
"concurrently": "^8.2.2",
"core-js": "^3.36.0",
"echarts": "^5.5.0",
"ethereum-cryptography": "^2.1.3",
"ethereumjs-abi": "^0.6.8",
"ethereumjs-util": "^7.1.5",
"ethereumjs-wallet": "^1.0.2",
"eventemitter3": "^5.0.1",
"lodash": "^4.17.21",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,17 @@

import { BitcoinNetwork, PaymentType } from "../types/bitcoin-network";
import { address as BTCAddress, Transaction, Psbt } from "bitcoinjs-lib";
import { sha256 } from "ethereumjs-util";
import { sha256 } from "ethereum-cryptography/sha256";
import { PSBTSigner } from "../ui/libs/signer";
import { bufferToHex } from "@enkryptcom/utils";

const bip0322_hash = (message: string) => {
const tag = "BIP0322-signed-message";
const tagHash = sha256(Buffer.from(tag));
const result = sha256(
Buffer.concat([tagHash, tagHash, Buffer.from(message)])
);
return result.toString("hex");
return bufferToHex(result, true);
};

const MAX_SAFE_INTEGER = 9007199254740991;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { sha256 } from "ethereumjs-util";
import { sha256 } from "ethereum-cryptography/sha256";

const MAGIC_BYTES = Buffer.from("Bitcoin Signed Message:\n");

Expand Down Expand Up @@ -28,7 +28,7 @@ export const magicHash = (messageBuffer: Buffer) => {
const prefix1 = varintBufNum(MAGIC_BYTES.length);
const prefix2 = varintBufNum(messageBuffer.length);
const buf = Buffer.concat([prefix1, MAGIC_BYTES, prefix2, messageBuffer]);
return sha256(sha256(buf));
return Buffer.from(sha256(sha256(buf)));
};

export const toCompact = (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ import { getError } from "@/libs/error";
import { ErrorCodes } from "@/providers/ethereum/types";
import { WindowPromiseHandler } from "@/libs/window-promise";
import { DEFAULT_BTC_NETWORK, getNetworkByName } from "@/libs/utils/networks";
import { fromBase, hexToBuffer } from "@enkryptcom/utils";
import { fromBase, hexToBuffer, bufferToHex } from "@enkryptcom/utils";
import { ProviderRequestOptions } from "@/types/provider";
import { GasFeeType } from "./types";
import MarketData from "@/libs/market-data";
Expand All @@ -141,7 +141,6 @@ import { toBN } from "web3-utils";
import { Psbt } from "bitcoinjs-lib";
import BigNumber from "bignumber.js";
import { JsonTreeView } from "@/libs/json-tree-view";
import { bufferToHex } from "ethereumjs-util";
const isProcessing = ref(false);
const isPreLoading = ref(true);
Expand Down
3 changes: 1 addition & 2 deletions packages/extension/src/providers/bitcoin/ui/libs/signer.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { InternalMethods, InternalOnMessageResponse } from "@/types/messenger";
import { SignerTransactionOptions, SignerMessageOptions } from "../types";
import { bufferToHex } from "ethereumjs-util";
import sendUsingInternalMessengers from "@/libs/messenger/internal-messenger";
import { hexToBuffer } from "@enkryptcom/utils";
import { hexToBuffer, bufferToHex } from "@enkryptcom/utils";
import { Psbt } from "bitcoinjs-lib";
import { BitcoinNetwork, PaymentType } from "../../types/bitcoin-network";
import { EnkryptAccount } from "@enkryptcom/types";
Expand Down
4 changes: 4 additions & 0 deletions packages/extension/src/providers/common/types/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import type { toBN } from "web3-utils";

export interface GasFeeInfo {
nativeValue: string;
fiatValue: string;
Expand All @@ -16,3 +18,5 @@ export interface GasFeeType {
[GasPriceTypes.FAST]: GasFeeInfo;
[GasPriceTypes.FASTEST]: GasFeeInfo;
}

export type BNType = ReturnType<typeof toBN>;
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import BigNumber from "bignumber.js";
import { BN } from "ethereumjs-util";
import { toBN, toWei } from "web3-utils";
import { GasPriceTypes } from "@/providers/common/types";
import { BNType, GasPriceTypes } from "@/providers/common/types";
import { FeeHistoryResult } from "web3-eth";
import { FormattedFeeHistory } from "./types";

Expand All @@ -14,10 +13,10 @@ const FASTEST_MULTIPLIER = 1.21828571429;
const LIMITER = 25000000000;
const GAS_PERCENTILES = [25, 50, 75, 90];

const getEconomy = (gasPrice: string): BN => {
const getEconomy = (gasPrice: string): BNType => {
return toBN(gasPrice);
};
const getRegular = (gasPrice: string): BN => {
const getRegular = (gasPrice: string): BNType => {
const gpBN = toBN(gasPrice);
if (gpBN.gt(toBN(LIMITER))) {
let initialValue = new BigNumber(gasPrice).times(MED_MULTIPLIER);
Expand All @@ -26,7 +25,7 @@ const getRegular = (gasPrice: string): BN => {
}
return toBN(new BigNumber(gasPrice).times(1.25).toFixed(0));
};
const getFast = (gasPrice: string): BN => {
const getFast = (gasPrice: string): BNType => {
const gpBN = toBN(gasPrice);
if (gpBN.gt(toBN(LIMITER))) {
let initialValue = new BigNumber(gasPrice).times(FAST_MULTIPLIER);
Expand All @@ -35,7 +34,7 @@ const getFast = (gasPrice: string): BN => {
}
return toBN(new BigNumber(gasPrice).times(1.5).toFixed(0));
};
const getFastest = (gasPrice: string): BN => {
const getFastest = (gasPrice: string): BNType => {
const gpBN = toBN(gasPrice);
if (gpBN.gt(toBN(LIMITER))) {
let initialValue = new BigNumber(gasPrice).times(FASTEST_MULTIPLIER);
Expand All @@ -48,7 +47,7 @@ const getFastest = (gasPrice: string): BN => {
const getGasBasedOnType = (
gasPrice: string,
gasPriceType: GasPriceTypes
): BN => {
): BNType => {
switch (gasPriceType) {
case GasPriceTypes.ECONOMY:
return getEconomy(gasPrice);
Expand All @@ -62,10 +61,10 @@ const getGasBasedOnType = (
return getEconomy(gasPrice);
}
};
const getMinPriorityFee = (): BN => {
const getMinPriorityFee = (): BNType => {
return toBN(toWei("0.1", "gwei"));
};
const getPriorityFeeAvg = (arr: BN[]): BN => {
const getPriorityFeeAvg = (arr: BNType[]): BNType => {
const sum = arr.reduce((a, v) => a.add(v));
const fee = sum.divn(arr.length);
if (fee.eqn(0)) return getMinPriorityFee();
Expand All @@ -75,7 +74,7 @@ const getPriorityFeeAvg = (arr: BN[]): BN => {
const getPriorityFeeBasedOnType = (
gasFeeHistory: FormattedFeeHistory,
gasPriceType: GasPriceTypes
): BN => {
): BNType => {
if (gasFeeHistory.blocks.length === 0) return getMinPriorityFee();
switch (gasPriceType) {
case GasPriceTypes.ECONOMY:
Expand Down Expand Up @@ -141,7 +140,7 @@ const formatFeeHistory = (
const getBaseFeeBasedOnType = (
baseFee: string,
gasPriceType: GasPriceTypes
): BN => {
): BNType => {
const baseFeeBN = toBN(baseFee);
switch (gasPriceType) {
case GasPriceTypes.ECONOMY:
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { GasPriceTypes } from "@/providers/common/types";
import { BN } from "ethereumjs-util";
import { BNType as BN } from "@/providers/common/types";

export interface AccessList {
address: `0x${string}`;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { getCustomError } from "@/libs/error";
import { MiddlewareFunction } from "@enkryptcom/types";
import { hexToBuffer } from "@enkryptcom/utils";
import { bufferToHex, hexToBuffer } from "@enkryptcom/utils";
import {
ecrecover,
fromRpcSig,
hashPersonalMessage,
publicToAddress,
} from "ethereumjs-util";
} from "@ethereumjs/util";
import EthereumProvider from "..";
const method: MiddlewareFunction = function (
this: EthereumProvider,
Expand All @@ -23,7 +23,7 @@ const method: MiddlewareFunction = function (
const hashedMessage = hashPersonalMessage(hexToBuffer(payload.params[0]));
const { v, r, s } = fromRpcSig(payload.params[1]);
const recoveredPubKey = ecrecover(hashedMessage, v, r, s);
return res(null, "0x" + publicToAddress(recoveredPubKey).toString("hex"));
return res(null, bufferToHex(publicToAddress(recoveredPubKey)));
} catch (e) {
return res(getCustomError((e as Error).message));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import MarketData from "@/libs/market-data";
import { CustomErc20Token, TokenType } from "@/libs/tokens-state/types";
import { WindowPromise } from "@/libs/window-promise";
import { MiddlewareFunction } from "@enkryptcom/types";
import { isValidAddress } from "ethereumjs-util";
import { isValidAddress } from "@ethereumjs/util";
import EthereumProvider from "..";
import API from "../libs/api";
import { Erc20Token } from "../types/erc20-token";
Expand Down
2 changes: 1 addition & 1 deletion packages/extension/src/providers/ethereum/networks/rsk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
toChecksumAddress,
isValidChecksumAddress,
isValidAddress,
} from "ethereumjs-util";
} from "@ethereumjs/util";
import assetsInfoHandler from "@/providers/ethereum/libs/assets-handlers/assetinfo-mew";

const rootstockOptions: EvmNetworkOptions = {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import DataDecode from "../libs/transaction/data-decoder";
import { expect } from "chai";
import { BN } from "ethereumjs-util";
import { toBN } from "web3-utils";
import { numberToHex } from "web3-utils";
describe("Test Ethereum data decoding", () => {
it("should decode correct token transfer info", async () => {
Expand All @@ -15,7 +15,7 @@ describe("Test Ethereum data decoding", () => {
"0x92eefc435008af9dfc428e9f84c2a6c0fd385e8f"
);
expect(dataDecoder.decode().values[1]).to.eq(
numberToHex(new BN("390343345"))
numberToHex(toBN("390343345"))
);
});
it("should not decode unknown data", async () => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { BaseToken, BaseTokenOptions } from "@/types/base-token";
import { BN } from "ethereumjs-util";
import { numberToHex } from "web3-utils";
import erc20 from "../libs/abi/erc20";
import EvmAPI from "../libs/api";
import { NATIVE_TOKEN_ADDRESS } from "../libs/common";
import { BNType } from "@/providers/common/types";

export interface Erc20TokenOptions extends BaseTokenOptions {
contract: string;
Expand All @@ -27,7 +27,7 @@ export class Erc20Token extends BaseToken {
return contract.methods
.balanceOf(address)
.call()
.then((val: BN) => {
.then((val: BNType) => {
const balance = numberToHex(val);
this.balance = balance;
return balance;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,13 @@ import { NFTCollection } from "@/types/nft";
import { AssetsType, ProviderName } from "@/types/provider";
import { CoingeckoPlatform, NetworkNames, SignerType } from "@enkryptcom/types";
import BigNumber from "bignumber.js";
import { BNLike, toChecksumAddress } from "ethereumjs-util";
import { toChecksumAddress } from "@ethereumjs/util";
import { isAddress } from "web3-utils";
import API from "../libs/api";
import createIcon from "../libs/blockies";
import { NATIVE_TOKEN_ADDRESS } from "../libs/common";
import { Erc20Token, Erc20TokenOptions } from "./erc20-token";
import { BNType } from "@/providers/common/types";

export interface EvmNetworkOptions {
name: NetworkNames;
Expand Down Expand Up @@ -49,8 +50,8 @@ export interface EvmNetworkOptions {
address: string
) => Promise<Activity[]>;
customTokens?: boolean;
displayAddress?: (address: string, chainId?: BNLike) => string;
isAddress?: (address: string, chainId?: BNLike) => boolean;
displayAddress?: (address: string, chainId?: BNType) => string;
isAddress?: (address: string, chainId?: BNType) => boolean;
}

export class EvmNetwork extends BaseNetwork {
Expand All @@ -73,7 +74,7 @@ export class EvmNetwork extends BaseNetwork {

public assets: Erc20Token[] = [];

public isAddress: (address: string, chainId?: BNLike) => boolean;
public isAddress: (address: string, chainId?: BNType) => boolean;

constructor(options: EvmNetworkOptions) {
const api = async () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -150,9 +150,9 @@ import { defaultGasCostVals } from "@/providers/common/libs/default-vals";
import { EnkryptAccount } from "@enkryptcom/types";
import { TransactionSigner } from "./libs/signer";
import { Activity, ActivityStatus, ActivityType } from "@/types/activity";
import { generateAddress } from "ethereumjs-util";
import { generateAddress, bigIntToBytes } from "@ethereumjs/util";
import ActivityState from "@/libs/activity-state";
import { bigIntToBuffer, bigIntToHex, fromBase } from "@enkryptcom/utils";
import { bigIntToHex, fromBase, bufferToHex } from "@enkryptcom/utils";
import broadcastTx from "../libs/tx-broadcaster";
import TokenSigs from "../libs/transaction/lists/tokenSigs";
import AlertIcon from "@action/icons/send/alert-icon.vue";
Expand Down Expand Up @@ -303,10 +303,12 @@ const approve = async () => {
from: account.value.address,
to: tx.to
? tx.to.toString()
: `0x${generateAddress(
tx.getSenderAddress().toBuffer(),
bigIntToBuffer(tx.nonce)
).toString("hex")}`,
: bufferToHex(
generateAddress(
tx.getSenderAddress().toBytes(),
bigIntToBytes(tx.nonce)
)
),
isIncoming: tx.getSenderAddress().toString() === tx.to?.toString(),
network: network.value.name,
status: ActivityStatus.pending,
Expand Down Expand Up @@ -345,11 +347,11 @@ const approve = async () => {
});
});
};
broadcastTx("0x" + tx.serialize().toString("hex"), network.value.name)
broadcastTx(bufferToHex(tx.serialize()), network.value.name)
.then(onHash)
.catch(() => {
web3
.sendSignedTransaction("0x" + tx.serialize().toString("hex"))
.sendSignedTransaction(bufferToHex(tx.serialize()))
.on("transactionHash", onHash)
.on("error", (error) => {
txActivity.status = ActivityStatus.failed;
Expand Down
4 changes: 2 additions & 2 deletions packages/extension/src/providers/ethereum/ui/libs/signer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { FeeMarketEIP1559Transaction } from "@ethereumjs/tx";
import { SignerTransactionOptions, SignerMessageOptions } from "../types";
import HWwallet from "@enkryptcom/hw-wallets";
import { HWwalletType } from "@enkryptcom/types";
import { fromRpcSig, hashPersonalMessage } from "ethereumjs-util";
import { fromRpcSig, hashPersonalMessage } from "@ethereumjs/util";
import { getCustomError } from "@/libs/error";
import { bufferToHex } from "@enkryptcom/utils";
import sendUsingInternalMessengers from "@/libs/messenger/internal-messenger";
Expand Down Expand Up @@ -50,7 +50,7 @@ const TransactionSigner = (
} else {
const rpcSig = fromRpcSig(JSON.parse(res.result as string) || "0x");
const signedTx = (payload as FeeMarketEIP1559Transaction).addSignature(
BigInt(rpcSig.v),
rpcSig.v,
rpcSig.r,
rpcSig.s,
true
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
import { toBN } from "web3-utils";
import { KnownTokenDisplay } from "@/providers/polkadot/types";
import { SubstrateNativeToken } from "@/providers/polkadot/types/substrate-native-token";
import { BN } from "ethereumjs-util";
import { BNType } from "@/providers/common/types";

type AssetMetadata = {
name: `0x${string}`;
Expand Down Expand Up @@ -105,7 +105,7 @@ export default async (
const ormlOptions: AcalaOrmlAssetOptions = {
name: hexToString(asset!.name),
symbol: hexToString(asset!.symbol),
existentialDeposit: asset!.minimalBalance as BN,
existentialDeposit: asset!.minimalBalance as BNType,
assetType: asset!.assetLookupId,
lookupValue: asset!.assetLookupValue,
icon: network.icon,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { OrmlTokensAccountData } from "../../acala/types/acala-orml-asset";
import { toBN } from "web3-utils";
import { KnownTokenDisplay } from "@/providers/polkadot/types";
import { SubstrateNativeToken } from "@/providers/polkadot/types/substrate-native-token";
import { BN } from "ethereumjs-util";
import { BNType } from "@/providers/common/types";

type AssetMetadata = {
name: `0x${string}`;
Expand Down Expand Up @@ -105,7 +105,7 @@ export default async (
const ormlOptions: BifrostOrmlAssetOptions = {
name: hexToString(asset!.name),
symbol: hexToString(asset!.symbol),
existentialDeposit: asset!.minimalBalance as BN,
existentialDeposit: asset!.minimalBalance as BNType,
assetType: asset!.assetLookupId,
lookupValue: asset!.assetLookupValue,
icon: network.icon,
Expand Down
Loading

1 comment on commit 35b649b

@github-actions
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.