Skip to content

Commit

Permalink
chai-matchers update iteration 1
Browse files Browse the repository at this point in the history
  • Loading branch information
nikola-bozin-txfusion committed Oct 30, 2023
1 parent 0f9efd6 commit 373ffb4
Show file tree
Hide file tree
Showing 19 changed files with 142 additions and 155 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { BigNumberish, ethers } from 'ethers';
import * as zk from 'zksync-web3';
import * as zk from 'zksync2-js';

import { buildAssert } from '@nomicfoundation/hardhat-chai-matchers/utils';
import { ensure } from '@nomicfoundation/hardhat-chai-matchers/internal/calledOnContract/utils';
Expand All @@ -13,22 +13,20 @@ export function supportChangeEtherBalance(Assertion: Chai.AssertionStatic) {
function (
this: any,
account: Account | string,
balanceChange: BigNumberish,
balanceChange: bigint,
options?: {
balanceChangeOptions?: BalanceChangeOptions;
overrides?: ethers.Overrides;
}
) {
const { BigNumber } = require('ethers');

const negated = this.__flags.negate;
const subject = this._obj;

const checkBalanceChange = ([actualChange, address]: [typeof BigNumber, string]) => {
const checkBalanceChange = ([actualChange, address]: [bigint, string]) => {
const assert = buildAssert(negated, checkBalanceChange);

assert(
actualChange.eq(BigNumber.from(balanceChange)),
actualChange===(balanceChange),
`Expected the ether balance of "${address}" to change by ${balanceChange.toString()} wei, but it changed by ${actualChange.toString()} wei`,
`Expected the ether balance of "${address}" NOT to change by ${balanceChange.toString()} wei, but it did`
);
Expand All @@ -55,8 +53,7 @@ export async function getBalanceChange(
options?: BalanceChangeOptions,
overrides?: ethers.Overrides
) {
const { BigNumber } = await import('ethers');
const provider = zk.Provider.getDefaultProvider();
const provider = zk.Provider.getDefaultProvider()!;

let txResponse: zk.types.TransactionResponse;

Expand All @@ -75,19 +72,19 @@ export async function getBalanceChange(

const address = await getAddressOf(account);

const balanceAfter = await provider.send('eth_getBalance', [address, `0x${txBlockNumber.toString(16)}`]);
const balanceAfter:bigint = await provider.send('eth_getBalance', [address, `0x${txBlockNumber.toString(16)}`]);

const balanceBefore = await provider.send('eth_getBalance', [address, `0x${(txBlockNumber - 1).toString(16)}`]);
const balanceBefore:bigint = await provider.send('eth_getBalance', [address, `0x${(txBlockNumber - 1).toString(16)}`]);

if (options?.includeFee !== true && address === txResponse.from) {
const gasPrice = overrides?.maxFeePerGas
? BigNumber.from(overrides?.maxFeePerGas)
? (overrides?.maxFeePerGas)
: txReceipt.effectiveGasPrice ?? txResponse.gasPrice;

Check failure on line 82 in packages/hardhat-zksync-chai-matchers/src/internal/changeEtherBalance.ts

View workflow job for this annotation

GitHub Actions / verify-vyper

Property 'effectiveGasPrice' does not exist on type 'TransactionReceipt'.

Check failure on line 82 in packages/hardhat-zksync-chai-matchers/src/internal/changeEtherBalance.ts

View workflow job for this annotation

GitHub Actions / upgradable

Property 'effectiveGasPrice' does not exist on type 'TransactionReceipt'.

Check failure on line 82 in packages/hardhat-zksync-chai-matchers/src/internal/changeEtherBalance.ts

View workflow job for this annotation

GitHub Actions / deploy

Property 'effectiveGasPrice' does not exist on type 'TransactionReceipt'.

Check failure on line 82 in packages/hardhat-zksync-chai-matchers/src/internal/changeEtherBalance.ts

View workflow job for this annotation

GitHub Actions / chai-matchers

Property 'effectiveGasPrice' does not exist on type 'TransactionReceipt'.
const gasUsed = txReceipt.gasUsed;
const txFee = gasPrice.mul(gasUsed);
const txFee:bigint = gasPrice*(gasUsed);

return BigNumber.from(balanceAfter).add(txFee).sub(balanceBefore);
return (balanceAfter)+(txFee)+(balanceBefore);
} else {
return BigNumber.from(balanceAfter).sub(balanceBefore);
return balanceAfter-(balanceBefore);
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { BigNumberish, ethers } from 'ethers';
import * as zk from 'zksync-web3';
import * as zk from 'zksync2-js';
import ordinal from 'ordinal';

import { buildAssert } from '@nomicfoundation/hardhat-chai-matchers/utils';
Expand All @@ -13,7 +13,7 @@ export function supportChangeEtherBalances(Assertion: Chai.AssertionStatic) {
function (
this: any,
accounts: Array<Account | string>,
balanceChanges: BigNumberish[],
balanceChanges: bigint[],
options?: {
balanceChangeOptions?: BalanceChangeOptions;
overrides?: ethers.Overrides;
Expand All @@ -28,15 +28,15 @@ export function supportChangeEtherBalances(Assertion: Chai.AssertionStatic) {
subject = subject();
}

const checkBalanceChanges = ([actualChanges, accountAddresses]: [Array<typeof BigNumber>, string[]]) => {
const checkBalanceChanges = ([actualChanges, accountAddresses]: [Array<bigint>, string[]]) => {
const assert = buildAssert(negated, checkBalanceChanges);

assert(
actualChanges.every((change, ind) => change.eq(BigNumber.from(balanceChanges[ind]))),
actualChanges.every((change, ind) => change===(balanceChanges[ind])),
() => {
const lines: string[] = [];
actualChanges.forEach((change, i) => {
if (!change.eq(BigNumber.from(balanceChanges[i]))) {
if (!(change===balanceChanges[i])) {
lines.push(
`Expected the ether balance of ${accountAddresses[i]} (the ${ordinal(
i + 1
Expand All @@ -51,7 +51,7 @@ export function supportChangeEtherBalances(Assertion: Chai.AssertionStatic) {
() => {
const lines: string[] = [];
actualChanges.forEach((change, i) => {
if (change.eq(BigNumber.from(balanceChanges[i]))) {
if (change===balanceChanges[i]) {
lines.push(
`Expected the ether balance of ${accountAddresses[i]} (the ${ordinal(
i + 1
Expand Down
Original file line number Diff line number Diff line change
@@ -1,20 +1,18 @@
import type { BigNumberish, BigNumber, ethers } from 'ethers';
import * as zk from 'zksync-web3';
import * as zk from 'zksync2-js';

import { buildAssert } from '@nomicfoundation/hardhat-chai-matchers/utils';
import { ensure } from '@nomicfoundation/hardhat-chai-matchers/internal/calledOnContract/utils';

import { Account, getAddressOf } from './misc/account';

interface Token extends zk.Contract {
balanceOf(address: string, overrides?: any): Promise<BigNumber>;
balanceOf(address: string, overrides?: any): Promise<bigint>;

Check failure on line 9 in packages/hardhat-zksync-chai-matchers/src/internal/changeTokenBalance.ts

View workflow job for this annotation

GitHub Actions / verify-vyper

Property 'balanceOf' of type '(address: string, overrides?: any) => Promise<bigint>' is not assignable to 'string' index type 'BaseContractMethod<any[], any, any>'.

Check failure on line 9 in packages/hardhat-zksync-chai-matchers/src/internal/changeTokenBalance.ts

View workflow job for this annotation

GitHub Actions / upgradable

Property 'balanceOf' of type '(address: string, overrides?: any) => Promise<bigint>' is not assignable to 'string' index type 'BaseContractMethod<any[], any, any>'.

Check failure on line 9 in packages/hardhat-zksync-chai-matchers/src/internal/changeTokenBalance.ts

View workflow job for this annotation

GitHub Actions / deploy

Property 'balanceOf' of type '(address: string, overrides?: any) => Promise<bigint>' is not assignable to 'string' index type 'BaseContractMethod<any[], any, any>'.

Check failure on line 9 in packages/hardhat-zksync-chai-matchers/src/internal/changeTokenBalance.ts

View workflow job for this annotation

GitHub Actions / chai-matchers

Property 'balanceOf' of type '(address: string, overrides?: any) => Promise<bigint>' is not assignable to 'string' index type 'BaseContractMethod<any[], any, any>'.
}

export function supportChangeTokenBalance(Assertion: Chai.AssertionStatic) {
Assertion.addMethod(
'changeTokenBalance',
function (this: any, token: Token, account: Account | string, balanceChange: BigNumberish) {
const { BigNumber } = require('ethers');
function (this: any, token: Token, account: Account | string, balanceChange: bigint) {

const negated = this.__flags.negate;

Expand All @@ -25,11 +23,11 @@ export function supportChangeTokenBalance(Assertion: Chai.AssertionStatic) {

checkToken(token, 'changeTokenBalance');

const checkBalanceChange = ([actualChange, address, tokenDescription]: [BigNumber, string, string]) => {
const checkBalanceChange = ([actualChange, address, tokenDescription]: [bigint, string, string]) => {
const assert = buildAssert(negated, checkBalanceChange);

assert(
actualChange.eq(BigNumber.from(balanceChange)),
actualChange===balanceChange,
`Expected the balance of ${tokenDescription} tokens for "${address}" to change by ${balanceChange.toString()}, but it changed by ${actualChange.toString()}`,
`Expected the balance of ${tokenDescription} tokens for "${address}" NOT to change by ${balanceChange.toString()}, but it did`
);
Expand All @@ -50,9 +48,7 @@ export function supportChangeTokenBalance(Assertion: Chai.AssertionStatic) {

Assertion.addMethod(
'changeTokenBalances',
function (this: any, token: Token, accounts: Array<Account | string>, balanceChanges: BigNumberish[]) {
const { BigNumber } = require('ethers');

function (this: any, token: Token, accounts: Array<Account | string>, balanceChanges: bigint[]) {
const negated = this.__flags.negate;

let subject = this._obj;
Expand All @@ -74,14 +70,14 @@ export function supportChangeTokenBalance(Assertion: Chai.AssertionStatic) {
const addressesPromise = Promise.all(accounts.map(getAddressOf));

const checkBalanceChanges = ([actualChanges, addresses, tokenDescription]: [
BigNumber[],
bigint[],
string[],
string
]) => {
const assert = buildAssert(negated, checkBalanceChanges);

assert(
actualChanges.every((change, ind) => change.eq(BigNumber.from(balanceChanges[ind]))),
actualChanges.every((change, ind) => change===balanceChanges[ind]),
`Expected the balances of ${tokenDescription} tokens for ${addresses as any} to change by ${
balanceChanges as any
}, respectively, but they changed by ${actualChanges as any}`,
Expand Down Expand Up @@ -119,7 +115,7 @@ export async function getBalanceChange(
account: Account | string
) {
const { BigNumber } = require('ethers');
const provider = zk.Provider.getDefaultProvider();
const provider = zk.Provider.getDefaultProvider()!;

const txResponse = await transaction;

Expand All @@ -131,11 +127,12 @@ export async function getBalanceChange(
ensure(block.transactions.length === 1, Error, 'Multiple transactions found in block');

const address = await getAddressOf(account);
const tokenAddress = await token.getAddress();

const balanceAfter = await provider.getBalance(address, txBlockNumber, token.address);
const balanceBefore = await provider.getBalance(address, txBlockNumber - 1, token.address);
const balanceAfter = await provider.getBalance(address as string, txBlockNumber, tokenAddress);
const balanceBefore = await provider.getBalance(address as string, txBlockNumber - 1, tokenAddress);

return BigNumber.from(balanceAfter).sub(balanceBefore);
return balanceAfter-balanceBefore;
}

let tokenDescriptionsCache: Record<string, string> = {};
Expand All @@ -145,8 +142,10 @@ let tokenDescriptionsCache: Record<string, string> = {};
* exist, the address of the token is used.
*/
async function getTokenDescription(token: Token): Promise<string> {
if (tokenDescriptionsCache[token.address] === undefined) {
let tokenDescription = `<token at ${token.address}>`;
const tokenAddress = await token.getAddress();

if (tokenDescriptionsCache[tokenAddress] === undefined) {
let tokenDescription = `<token at ${tokenAddress}>`;
try {
tokenDescription = await token.symbol();
} catch (e) {
Expand All @@ -155,10 +154,10 @@ async function getTokenDescription(token: Token): Promise<string> {
} catch (e2) {}
}

tokenDescriptionsCache[token.address] = tokenDescription;
tokenDescriptionsCache[tokenAddress] = tokenDescription;
}

return tokenDescriptionsCache[token.address];
return tokenDescriptionsCache[tokenAddress];
}

// only used by tests
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import assert from 'assert';
import type { Contract, Signer, Wallet } from 'zksync-web3';
import type { Contract, Signer, Wallet } from 'zksync2-js';

export type Account = Signer | Wallet | Contract;

export function isWalletOrContract(account: Account): account is Contract | Wallet {
const zk = require('zksync-web3');
const zk = require('zksync2-js');
return account instanceof zk.Contract || account instanceof zk.Wallet;
}

Expand All @@ -13,8 +13,8 @@ export async function getAddressOf(account: Account | string) {
assert(/^0x[0-9a-fA-F]{40}$/.test(account), `Invalid address ${account}`);
return account;
} else if (isWalletOrContract(account)) {
return account.address;
return account.address?account.address:await account.getAddress();
} else {
return account.getAddress();
return await account.getAddress();
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import * as zk from 'zksync-web3';
import * as zk from 'zksync2-js';

import { Account, getAddressOf } from './account';

Expand All @@ -11,14 +11,13 @@ export function getAddresses(accounts: Array<Account | string>) {
}

export async function getBalances(accounts: Array<Account | string>, blockNumber?: number) {
const { BigNumber } = await import('ethers');
const provider = zk.Provider.getDefaultProvider();
const provider = zk.Provider.getDefaultProvider()!;

return Promise.all(
accounts.map(async (account) => {
const address = await getAddressOf(account);
const result = await provider.send('eth_getBalance', [address, `0x${blockNumber?.toString(16) ?? 0}`]);
return BigNumber.from(result);
return result
})
);
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { buildAssert } from '@nomicfoundation/hardhat-chai-matchers/utils';
import * as zk from 'zksync-web3';
import * as zk from 'zksync2-js';

import { decodeReturnData, getReturnDataFromError } from './utils';

Expand Down Expand Up @@ -64,7 +64,7 @@ export function supportReverted(Assertion: Chai.AssertionStatic) {
assert(
true,
undefined,
`Expected transaction NOT to be reverted, but it reverted with panic code ${decodedReturnData.code.toHexString()} (${
`Expected transaction NOT to be reverted, but it reverted with panic code ${decodedReturnData.code.toString()} (${
decodedReturnData.description
})`
);
Expand All @@ -85,7 +85,7 @@ export function supportReverted(Assertion: Chai.AssertionStatic) {
}

async function getTransactionReceipt(hash: string) {
const provider = zk.Provider.getDefaultProvider();
const provider = zk.Provider.getDefaultProvider()!;

return provider.getTransactionReceipt(hash);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export function supportRevertedWith(Assertion: Chai.AssertionStatic) {
} else if (decodedReturnData.kind === 'Panic') {
assert(
false,
`Expected transaction to be reverted with reason '${expectedReason}', but it reverted with panic code ${decodedReturnData.code.toHexString()} (${
`Expected transaction to be reverted with reason '${expectedReason}', but it reverted with panic code ${decodedReturnData.code.toString()} (${
decodedReturnData.description
})`
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ export function supportRevertedWithCustomError(Assertion: Chai.AssertionStatic,
} else if (decodedReturnData.kind === 'Panic') {
assert(
false,
`Expected transaction to be reverted with custom error '${expectedCustomErrorName}', but it reverted with panic code ${decodedReturnData.code.toHexString()} (${
`Expected transaction to be reverted with custom error '${expectedCustomErrorName}', but it reverted with panic code ${decodedReturnData.code.toString()} (${
decodedReturnData.description
})`
);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import type { BigNumber } from 'ethers';

import { normalizeToBigInt } from 'hardhat/common';
import { panicErrorCodeToReason } from '@nomicfoundation/hardhat-chai-matchers/internal/reverted/panic';
import { buildAssert } from '@nomicfoundation/hardhat-chai-matchers/utils';
Expand All @@ -12,7 +10,7 @@ export function supportRevertedWithPanic(Assertion: Chai.AssertionStatic) {

const negated = this.__flags.negate;

let expectedCode: BigNumber | undefined;
let expectedCode: bigint | undefined;
try {
if (expectedCodeArg !== undefined) {
const normalizedCode = normalizeToBigInt(expectedCodeArg);
Expand All @@ -24,7 +22,7 @@ export function supportRevertedWithPanic(Assertion: Chai.AssertionStatic) {
);
}

const code: number | undefined = expectedCode as any;
const code: bigint | undefined = expectedCode as any;

let description: string | undefined;
let formattedPanicCode: string;
Expand Down Expand Up @@ -61,8 +59,8 @@ export function supportRevertedWithPanic(Assertion: Chai.AssertionStatic) {
} else if (decodedReturnData.kind === 'Panic') {
if (code !== undefined) {
assert(
decodedReturnData.code.eq(code),
`Expected transaction to be reverted with ${formattedPanicCode}, but it reverted with panic code ${decodedReturnData.code.toHexString()} (${
decodedReturnData.code===(code),
`Expected transaction to be reverted with ${formattedPanicCode}, but it reverted with panic code ${decodedReturnData.code.toString()} (${
decodedReturnData.description
})`,
`Expected transaction NOT to be reverted with ${formattedPanicCode}, but it was`
Expand All @@ -71,7 +69,7 @@ export function supportRevertedWithPanic(Assertion: Chai.AssertionStatic) {
assert(
true,
undefined,
`Expected transaction NOT to be reverted with ${formattedPanicCode}, but it reverted with panic code ${decodedReturnData.code.toHexString()} (${
`Expected transaction NOT to be reverted with ${formattedPanicCode}, but it reverted with panic code ${decodedReturnData.code.toString()} (${
decodedReturnData.description
})`
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export function supportRevertedWithoutReason(Assertion: Chai.AssertionStatic) {
} else if (decodedReturnData.kind === 'Panic') {
assert(
false,
`Expected transaction to be reverted without a reason, but it reverted with panic code ${decodedReturnData.code.toHexString()} (${
`Expected transaction to be reverted without a reason, but it reverted with panic code ${decodedReturnData.code.toString()} (${
decodedReturnData.description
})`
);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import type { BigNumber } from 'ethers';
import { AssertionError } from 'chai';

import { panicErrorCodeToReason } from '@nomicfoundation/hardhat-chai-matchers/internal/reverted/panic';
Expand Down Expand Up @@ -43,7 +42,7 @@ type DecodedReturnData =
}
| {
kind: 'Panic';
code: BigNumber;
code: bigint;
description: string;
}
| {
Expand Down Expand Up @@ -76,7 +75,7 @@ export function decodeReturnData(returnData: string): DecodedReturnData {
};
} else if (returnData.startsWith(PANIC_CODE_PREFIX)) {
const encodedReason = returnData.slice(PANIC_CODE_PREFIX.length);
let code: BigNumber;
let code: bigint;
try {
code = abi.decode(["uint256"], `0x${encodedReason}`)[0];
} catch (e: any) {
Expand Down
Loading

0 comments on commit 373ffb4

Please sign in to comment.