Skip to content

Commit

Permalink
test: smart contract tests improvements (#78)
Browse files Browse the repository at this point in the history
* test: use a simpler function to get the address of a contract
* test: introduce special functions to work with block timestamps
* test: import transaction-related classes from package "ethers"
  • Loading branch information
EvgeniiZaitsevCW authored May 27, 2024
1 parent 74a5498 commit 12a4d57
Show file tree
Hide file tree
Showing 5 changed files with 170 additions and 132 deletions.
47 changes: 43 additions & 4 deletions test-utils/eth.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,51 @@
import { BaseContract, Contract } from "ethers";
import { ethers, network } from "hardhat";
import { BaseContract, BlockTag, Contract, TransactionReceipt, TransactionResponse } from "ethers";
import { HardhatEthersSigner } from "@nomicfoundation/hardhat-ethers/signers";
import { TransactionReceipt, TransactionResponse } from "@ethersproject/abstract-provider";
import { time } from "@nomicfoundation/hardhat-network-helpers";

export async function proveTx(txResponsePromise: Promise<TransactionResponse>): Promise<TransactionReceipt> {
const txReceipt = await txResponsePromise;
return txReceipt.wait();
const txResponse = await txResponsePromise;
const txReceipt = await txResponse.wait();
if (!txReceipt) {
throw new Error("The transaction receipt is empty");
}
return txReceipt;
}

export function connect(contract: BaseContract, signer: HardhatEthersSigner): Contract {
return contract.connect(signer) as Contract;
}

export function getAddress(contract: Contract): string {
const address = contract.target;
if (typeof address !== "string" || address.length != 42 || !address.startsWith("0x")) {
throw new Error("The '.target' field of the contract is not an address string");
}
return address;
}

export async function getTxTimestamp(tx: Promise<TransactionResponse>): Promise<number> {
const receipt = await proveTx(tx);
const block = await ethers.provider.getBlock(receipt.blockNumber);
return Number(block?.timestamp ?? 0);
}

export async function getBlockTimestamp(blockTag: BlockTag): Promise<number> {
const block = await ethers.provider.getBlock(blockTag);
return block?.timestamp ?? 0;
}

export async function getLatestBlockTimestamp(): Promise<number> {
return getBlockTimestamp("latest");
}

export async function increaseBlockTimestampTo(target: number) {
if (network.name === "hardhat") {
await time.increaseTo(target);
} else if (network.name === "stratus") {
await ethers.provider.send("evm_setNextBlockTimestamp", [target]);
await ethers.provider.send("evm_mine", []);
} else {
throw new Error(`Setting block timestamp for the current blockchain is not supported: ${network.name}`);
}
}
Loading

0 comments on commit 12a4d57

Please sign in to comment.