Skip to content

Commit

Permalink
refactor: Remove truffle dependencies and change testing suite to har…
Browse files Browse the repository at this point in the history
…dhat

Signed-off-by: Ilja von Hoessle <[email protected]>
  • Loading branch information
iljabvh committed Aug 7, 2024
1 parent eb96e7f commit 1c998b4
Show file tree
Hide file tree
Showing 16 changed files with 2,225 additions and 1,689 deletions.
14 changes: 14 additions & 0 deletions hardhat.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { HardhatUserConfig } from "hardhat/config";
import "@nomicfoundation/hardhat-toolbox";
import "@nomicfoundation/hardhat-chai-matchers";
import "@nomicfoundation/hardhat-ethers";
import "@typechain/hardhat";
import "@nomicfoundation/hardhat-ethers";
import "@nomicfoundation/hardhat-verify";
import "hardhat-gas-reporter";
import "solidity-coverage";
const config: HardhatUserConfig = {
solidity: "0.8.24",
};

export default config;
40 changes: 25 additions & 15 deletions src/lib/test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright 2019 - See NOTICE file for copyright holders.
// Copyright 2024 - See NOTICE file for copyright holders.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
Expand All @@ -12,10 +12,10 @@
// See the License for the specific language governing permissions and
// limitations under the License.

/// <reference types="truffle-typings" />
import Web3 from "web3";
declare const web3: Web3;
import { hash, asyncWeb3Send } from "./web3";

import { asyncWeb3Send } from "./web3";
import { ethers } from "hardhat";
import { AbiCoder, keccak256 } from "ethers";

export function sleep(milliseconds: any) {
return new Promise(resolve => setTimeout(resolve, milliseconds));
Expand All @@ -27,10 +27,15 @@ export async function advanceBlockTime(time: number): Promise<any> {
}

export function fundingID(channelID: string, participant: string): string {
return hash(web3.eth.abi.encodeParameters(
const paddedChannelID = ethers.zeroPadValue(channelID, 32);

const abiCoder = AbiCoder.defaultAbiCoder();
const encoded = abiCoder.encode(
['bytes32', 'address'],
[web3.utils.rightPad(channelID, 64, "0"),
participant]));
[paddedChannelID, participant]
);

return keccak256(encoded);
}

// describe test suite followed by blockchain revert
Expand All @@ -39,22 +44,27 @@ export function describeWithBlockRevert(name: string, tests: any) {
let snapshot_id: number;

before("take snapshot before first test", async () => {
snapshot_id = (await asyncWeb3Send('evm_snapshot', [])).result;
const result = (await asyncWeb3Send('evm_snapshot', []));
snapshot_id = result;
});

after("restore snapshot after last test", async () => {
return asyncWeb3Send('evm_revert', [snapshot_id]);
await asyncWeb3Send('evm_revert', [snapshot_id]);
});

tests();
});
}

// it test followed by blockchain revert
export function itWithBlockRevert(name: string, test: any) {
it(name, async () => {
let snapshot_id = (await asyncWeb3Send('evm_snapshot', [])).result;
await test();
await asyncWeb3Send('evm_revert', [snapshot_id]);
const result = (await asyncWeb3Send('evm_snapshot', []));
const snapshot_id = result;

try {
await test();
} finally {
await asyncWeb3Send('evm_revert', [snapshot_id]);
}
});
}
}
80 changes: 55 additions & 25 deletions src/lib/web3.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright 2020 - See NOTICE file for copyright holders.
// Copyright 2024 - See NOTICE file for copyright holders.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
Expand All @@ -12,46 +12,76 @@
// See the License for the specific language governing permissions and
// limitations under the License.

/// <reference types="truffle-typings" />
import { ethers } from "hardhat";

import {promisify} from "util";
import Web3 from "web3";
import { Signer, BigNumberish, parseEther, formatEther, keccak256, getBytes } from "ethers";

declare const web3: Web3;
export async function sign(data: string, account: string): Promise<string> {
const provider = ethers.provider;
const signer = await provider.getSigner(account);

export async function sign(data: string, account: string) {
let sig = await web3.eth.sign(web3.utils.soliditySha3(data) as string, account);
// Update v value (add 27), if not done by web3.
let v = parseInt(sig.slice(130, 132), 16);
// Hash the data using keccak256
const messageHash = keccak256(data);

// Convert hash to bytes
const messageHashBytes = getBytes(messageHash);
const signature = await signer.signMessage(messageHashBytes);

// Split the signature
const sig = ethers.Signature.from(signature);

// Combine r, s, and v
let combinedSig = sig.r + sig.s.slice(2) + (sig.v).toString(16).padStart(2, '0');

// Ensure v is 27 or 28
let v = parseInt(combinedSig.slice(130, 132), 16);
if (v < 27) {
v += 27;
}
return sig.slice(0, 130) + v.toString(16);

return combinedSig.slice(0, 130) + v.toString(16).padStart(2, '0');
}

export function ether(x: number): BN { return web3.utils.toWei(web3.utils.toBN(x), "ether"); }

export function wei2eth(x: BN): BN { return web3.utils.toBN(web3.utils.fromWei(x.toString(), "ether")); }
export function ether(x: number | string): BigNumberish {
return parseEther(x.toString());
}

export function wei2eth(x: BigNumberish): string {
return formatEther(x);
}

export function hash(...val: any[]): string {
return web3.utils.soliditySha3(...val) as string
export async function getAddresses(signers: Signer[]): Promise<string[]> {
return Promise.all(signers.map(signer => signer.getAddress()));
}

export async function asyncWeb3Send(method: string, params: any[], id?: number): Promise<any> {
let req: any = { jsonrpc: '2.0', method: method, params: params };
if (id != undefined) req.id = id;

return promisify((callback) => {
(web3.currentProvider as any).send(req, callback)
})();
export async function asyncWeb3Send(method: string, params: any[]): Promise<any> {
const provider = ethers.provider;

try {
const result = await provider.send(method, params);
return result;
} catch (error) {
console.error("Error sending request in asyncWeb3Send:", error);
throw error;
}
}


export async function currentTimestamp(): Promise<number> {
let blocknumber = await web3.eth.getBlockNumber();
let block = await web3.eth.getBlock(blocknumber);
return block.timestamp as number;
const blockNumber = await ethers.provider.getBlockNumber();
const block = await ethers.provider.getBlock(blockNumber);

if (!block) {
throw new Error("Failed to get the block");
}

return Number(block.timestamp);
}

export async function getChainID(): Promise<number> {
return await web3.eth.getChainId();
}
const network = await ethers.provider.getNetwork();

return Number(network.chainId);
}
Loading

0 comments on commit 1c998b4

Please sign in to comment.