diff --git a/.all-contributorsrc b/.all-contributorsrc deleted file mode 100644 index 809c3abe0ed..00000000000 --- a/.all-contributorsrc +++ /dev/null @@ -1,142 +0,0 @@ -{ - "files": [ - "README.md" - ], - "imageSize": 100, - "commit": false, - "commitConvention": "angular", - "contributors": [ - { - "login": "d1onys1us", - "name": "d1onys1us", - "avatar_url": "https://avatars.githubusercontent.com/u/13951458?v=4", - "profile": "https://github.com/d1onys1us", - "contributions": [ - "doc" - ] - }, - { - "login": "davidtaikocha", - "name": "David", - "avatar_url": "https://avatars.githubusercontent.com/u/104078303?v=4", - "profile": "https://github.com/davidtaikocha", - "contributions": [ - "doc", - "code" - ] - }, - { - "login": "dantaik", - "name": "dantaik", - "avatar_url": "https://avatars.githubusercontent.com/u/99078276?v=4", - "profile": "http://taiko.xyz", - "contributions": [ - "doc", - "code" - ] - }, - { - "login": "cyberhorsey", - "name": "cyberhorsey", - "avatar_url": "https://avatars.githubusercontent.com/u/113397187?v=4", - "profile": "https://github.com/cyberhorsey", - "contributions": [ - "doc", - "code" - ] - }, - { - "login": "RogerLamTd", - "name": "RogerLamTd", - "avatar_url": "https://avatars.githubusercontent.com/u/50648015?v=4", - "profile": "https://github.com/RogerLamTd", - "contributions": [ - "doc", - "code" - ] - }, - { - "login": "alexshliu", - "name": "alexshliu", - "avatar_url": "https://avatars.githubusercontent.com/u/104080237?v=4", - "profile": "https://github.com/alexshliu", - "contributions": [ - "doc", - "code" - ] - }, - { - "login": "kirataik", - "name": "kirataik", - "avatar_url": "https://avatars.githubusercontent.com/u/104244966?v=4", - "profile": "https://github.com/kirataik", - "contributions": [ - "doc", - "code" - ] - }, - { - "login": "mfinestone", - "name": "mfinestone", - "avatar_url": "https://avatars.githubusercontent.com/u/36642873?v=4", - "profile": "https://github.com/mfinestone", - "contributions": [ - "business", - "content" - ] - }, - { - "login": "shadab-taiko", - "name": "shadab-taiko", - "avatar_url": "https://avatars.githubusercontent.com/u/108871478?v=4", - "profile": "https://github.com/shadab-taiko", - "contributions": [ - "doc", - "code" - ] - }, - { - "login": "1xDeFi", - "name": "1xDeFi", - "avatar_url": "https://avatars.githubusercontent.com/u/90858998?v=4", - "profile": "https://github.com/1xDeFi", - "contributions": [ - "doc" - ] - }, - { - "login": "odesium", - "name": "Ben", - "avatar_url": "https://avatars.githubusercontent.com/u/56487762?v=4", - "profile": "https://github.com/odesium", - "contributions": [ - "doc" - ] - }, - { - "login": "omahs", - "name": "omahs", - "avatar_url": "https://avatars.githubusercontent.com/u/73983677?v=4", - "profile": "https://github.com/omahs", - "contributions": [ - "doc" - ] - }, - { - "login": "wolfderechter", - "name": "wolfderechter", - "avatar_url": "https://avatars.githubusercontent.com/u/60930264?v=4", - "profile": "https://github.com/wolfderechter", - "contributions": [ - "code", - "doc" - ] - } - ], - "contributorsPerLine": 7, - "skipCi": true, - "repoType": "github", - "repoHost": "https://github.com", - "projectName": "taiko-mono", - "projectOwner": "taikoxyz" -} diff --git a/packages/bridge-ui/package.json b/packages/bridge-ui/package.json index d084f58c3f3..4e565227eaf 100644 --- a/packages/bridge-ui/package.json +++ b/packages/bridge-ui/package.json @@ -1,6 +1,7 @@ { - "name": "@taiko/ui", + "name": "@taiko/bridge-ui", "version": "0.0.0", + "private": true, "type": "module", "scripts": { "start": "pnpm run dev", diff --git a/packages/protocol/.eslintrc.js b/packages/protocol/.eslintrc.js index 6294d5381f5..6d4c06dc472 100644 --- a/packages/protocol/.eslintrc.js +++ b/packages/protocol/.eslintrc.js @@ -26,4 +26,4 @@ module.exports = { "node/no-missing-require": "off", "no-unused-expressions": "off", }, -} +}; diff --git a/packages/protocol/.prettierrc.json b/packages/protocol/.prettierrc.json index 600a14ea67f..e75916e8274 100644 --- a/packages/protocol/.prettierrc.json +++ b/packages/protocol/.prettierrc.json @@ -1,5 +1,4 @@ { - "semi": false, "overrides": [ { "files": ["*.sol", "*.ts"], diff --git a/packages/protocol/.solcover.js b/packages/protocol/.solcover.js index 497f7160667..8064404e0ca 100644 --- a/packages/protocol/.solcover.js +++ b/packages/protocol/.solcover.js @@ -6,7 +6,7 @@ module.exports = { "test/libs/TestLibReceiptDecoder.sol", //integration tests "test/thirdparty/TestLibBlockHeaderDecoder.sol", // assembly too long ], - mocha:{ - grep: '^[^integration]' - } + mocha: { + grep: "^[^integration]", + }, }; diff --git a/packages/protocol/hardhat.config.ts b/packages/protocol/hardhat.config.ts index 09f309c9919..94cc257500f 100644 --- a/packages/protocol/hardhat.config.ts +++ b/packages/protocol/hardhat.config.ts @@ -1,17 +1,17 @@ -import "@nomiclabs/hardhat-etherscan" -import "@nomiclabs/hardhat-waffle" -import "@openzeppelin/hardhat-upgrades" -import "@typechain/hardhat" -import "hardhat-abi-exporter" -import "hardhat-gas-reporter" -import "hardhat-preprocessor" -import { HardhatUserConfig } from "hardhat/config" -import "solidity-coverage" -import "solidity-docgen" -import "./tasks/deploy_L1" +import "@nomiclabs/hardhat-etherscan"; +import "@nomiclabs/hardhat-waffle"; +import "@openzeppelin/hardhat-upgrades"; +import "@typechain/hardhat"; +import "hardhat-abi-exporter"; +import "hardhat-gas-reporter"; +import "hardhat-preprocessor"; +import { HardhatUserConfig } from "hardhat/config"; +import "solidity-coverage"; +import "solidity-docgen"; +import "./tasks/deploy_L1"; const hardhatMnemonic = - "test test test test test test test test test test test taik" + "test test test test test test test test test test test taik"; const config: HardhatUserConfig = { docgen: { exclude: [ @@ -114,15 +114,15 @@ const config: HardhatUserConfig = { ) { return `${line.slice(0, line.indexOf(" ="))} = ${ process.env[constantName] - };` + };`; } } - return line + return line; }, files: "libs/LibConstants.sol", }), }, -} +}; -export default config +export default config; diff --git a/packages/protocol/package.json b/packages/protocol/package.json index eb44fdcf17d..fbebf637597 100644 --- a/packages/protocol/package.json +++ b/packages/protocol/package.json @@ -1,7 +1,7 @@ { - "name": "@taiko/proto", - "version": "1.0.0", - "description": "Taiko L2 Protocol", + "name": "@taiko/protocol", + "version": "0.0.0", + "private": true, "scripts": { "compile": "pnpm hardhat preprocess && pnpm hardhat compile", "export:abi": "pnpm hardhat clear-abi && pnpm hardhat export-abi", diff --git a/packages/protocol/tasks/config.ts b/packages/protocol/tasks/config.ts index de7f7afc3b2..cc9ebfd4334 100644 --- a/packages/protocol/tasks/config.ts +++ b/packages/protocol/tasks/config.ts @@ -1,3 +1,3 @@ // https://github.com/ethereum-lists/chains/pull/1611 -export const K_CHAIN_ID = 167 -export const K_DEPLOY_CONFIRMATIONS = 12 +export const K_CHAIN_ID = 167; +export const K_DEPLOY_CONFIRMATIONS = 12; diff --git a/packages/protocol/tasks/deploy_L1.ts b/packages/protocol/tasks/deploy_L1.ts index 0cd99308fb8..ca45b2b8736 100644 --- a/packages/protocol/tasks/deploy_L1.ts +++ b/packages/protocol/tasks/deploy_L1.ts @@ -1,9 +1,9 @@ -import * as ethers from "ethers" -import { task } from "hardhat/config" -import * as types from "hardhat/internal/core/params/argumentTypes" -import * as config from "./config" -import * as log from "./log" -import * as utils from "./utils" +import * as ethers from "ethers"; +import { task } from "hardhat/config"; +import * as types from "hardhat/internal/core/params/argumentTypes"; +import * as config from "./config"; +import * as log from "./log"; +import * as utils from "./utils"; task("deploy_L1") .addParam("daoVault", "The DAO vault address") @@ -42,110 +42,110 @@ task("deploy_L1") hre.network.name === "localhost" || hre.network.name === "hardhat" ) { - args.confirmations = 1 + args.confirmations = 1; } else if ( hre.network.name === "ropsten" || hre.network.name === "goerli" ) { - args.confirmations = 6 + args.confirmations = 6; } - hre.args = args - await deployContracts(hre) - }) + hre.args = args; + await deployContracts(hre); + }); export async function deployContracts(hre: any) { - const network = hre.network.name - const { chainId } = await hre.ethers.provider.getNetwork() - const deployer = await utils.getDeployer(hre) - const daoVault = hre.args.daoVault - const teamVault = hre.args.teamVault - const l2GenesisBlockHash = hre.args.l2GenesisBlockHash - const taikoL2Address = hre.args.taikoL2 - const l2ChainId = hre.args.l2ChainId - const bridgeFunderPrivateKey = hre.args.bridgeFunderPrivateKey - const bridgeFund = hre.args.bridgeFund - - log.debug(`network: ${network}`) - log.debug(`chainId: ${chainId}`) - log.debug(`deployer: ${deployer}`) - log.debug(`daoVault: ${daoVault}`) - log.debug(`l2GenesisBlockHash: ${l2GenesisBlockHash}`) - log.debug(`taikoL2Address: ${taikoL2Address}`) - log.debug(`l2ChainId: ${l2ChainId}`) - log.debug(`bridgeFunderPrivateKey: ${bridgeFunderPrivateKey}`) - log.debug(`bridgeFund: ${bridgeFund}`) - log.debug(`confirmations: ${hre.args.confirmations}`) - log.debug() + const network = hre.network.name; + const { chainId } = await hre.ethers.provider.getNetwork(); + const deployer = await utils.getDeployer(hre); + const daoVault = hre.args.daoVault; + const teamVault = hre.args.teamVault; + const l2GenesisBlockHash = hre.args.l2GenesisBlockHash; + const taikoL2Address = hre.args.taikoL2; + const l2ChainId = hre.args.l2ChainId; + const bridgeFunderPrivateKey = hre.args.bridgeFunderPrivateKey; + const bridgeFund = hre.args.bridgeFund; + + log.debug(`network: ${network}`); + log.debug(`chainId: ${chainId}`); + log.debug(`deployer: ${deployer}`); + log.debug(`daoVault: ${daoVault}`); + log.debug(`l2GenesisBlockHash: ${l2GenesisBlockHash}`); + log.debug(`taikoL2Address: ${taikoL2Address}`); + log.debug(`l2ChainId: ${l2ChainId}`); + log.debug(`bridgeFunderPrivateKey: ${bridgeFunderPrivateKey}`); + log.debug(`bridgeFund: ${bridgeFund}`); + log.debug(`confirmations: ${hre.args.confirmations}`); + log.debug(); // AddressManager - const AddressManager = await utils.deployContract(hre, "AddressManager") - await utils.waitTx(hre, await AddressManager.init()) + const AddressManager = await utils.deployContract(hre, "AddressManager"); + await utils.waitTx(hre, await AddressManager.init()); await utils.waitTx( hre, await AddressManager.setAddress(`${chainId}.dao_vault`, daoVault) - ) + ); await utils.waitTx( hre, await AddressManager.setAddress(`${chainId}.team_vault`, teamVault) - ) + ); // Used by V1Proving await utils.waitTx( hre, await AddressManager.setAddress(`${l2ChainId}.taiko`, taikoL2Address) - ) + ); // TkoToken - const TkoToken = await utils.deployContract(hre, "TkoToken") - await utils.waitTx(hre, await TkoToken.init(AddressManager.address)) + const TkoToken = await utils.deployContract(hre, "TkoToken"); + await utils.waitTx(hre, await TkoToken.init(AddressManager.address)); await utils.waitTx( hre, await AddressManager.setAddress( `${chainId}.tko_token`, TkoToken.address ) - ) + ); // Config manager - const ConfigManager = await utils.deployContract(hre, "ConfigManager") - await utils.waitTx(hre, await ConfigManager.init()) + const ConfigManager = await utils.deployContract(hre, "ConfigManager"); + await utils.waitTx(hre, await ConfigManager.init()); await utils.waitTx( hre, await AddressManager.setAddress( `${chainId}.config_manager`, ConfigManager.address ) - ) + ); // TaikoL1 const TaikoL1 = await utils.deployContract( hre, "TaikoL1", await deployBaseLibs(hre) - ) + ); await utils.waitTx( hre, await TaikoL1.init(AddressManager.address, l2GenesisBlockHash) - ) + ); // Used by LibBridgeRead await utils.waitTx( hre, await AddressManager.setAddress(`${chainId}.taiko`, TaikoL1.address) - ) + ); // Bridge - const Bridge = await deployBridge(hre, AddressManager.address) + const Bridge = await deployBridge(hre, AddressManager.address); // TokenVault - const TokenVault = await deployTokenVault(hre, AddressManager.address) + const TokenVault = await deployTokenVault(hre, AddressManager.address); // Used by TokenVault await utils.waitTx( hre, await AddressManager.setAddress(`${chainId}.bridge`, Bridge.address) - ) + ); // Fund L1 bridge, which is necessary when there is a L2 faucet if ( @@ -155,7 +155,7 @@ export async function deployContracts(hre: any) { const funder = new hre.ethers.Wallet( bridgeFunderPrivateKey, hre.ethers.provider - ) + ); await utils.waitTx( hre, @@ -163,13 +163,13 @@ export async function deployContracts(hre: any) { to: Bridge.address, value: hre.ethers.BigNumber.from(bridgeFund), }) - ) + ); log.debug( `L1 bridge balance: ${hre.ethers.utils.hexlify( await hre.ethers.provider.getBalance(Bridge.address) )}` - ) + ); } // save deployments @@ -185,66 +185,66 @@ export async function deployContracts(hre: any) { { Bridge: Bridge.address }, { TokenVault: TokenVault.address } ), - } + }; - utils.saveDeployments(`${network}_L1`, deployments) + utils.saveDeployments(`${network}_L1`, deployments); - return deployments + return deployments; } async function deployBaseLibs(hre: any) { - const libZKP = await utils.deployContract(hre, "LibZKP") + const libZKP = await utils.deployContract(hre, "LibZKP"); const libReceiptDecoder = await utils.deployContract( hre, "LibReceiptDecoder" - ) - const libTxDecoder = await utils.deployContract(hre, "LibTxDecoder") + ); + const libTxDecoder = await utils.deployContract(hre, "LibTxDecoder"); - const v1Verifying = await utils.deployContract(hre, "V1Verifying", {}) - const v1Proposing = await utils.deployContract(hre, "V1Proposing", {}) + const v1Verifying = await utils.deployContract(hre, "V1Verifying", {}); + const v1Proposing = await utils.deployContract(hre, "V1Proposing", {}); const v1Proving = await utils.deployContract(hre, "V1Proving", { LibZKP: libZKP.address, LibReceiptDecoder: libReceiptDecoder.address, LibTxDecoder: libTxDecoder.address, - }) + }); return { V1Verifying: v1Verifying.address, V1Proposing: v1Proposing.address, V1Proving: v1Proving.address, - } + }; } async function deployBridge(hre: any, addressManager: string): Promise { - const libTrieProof = await utils.deployContract(hre, "LibTrieProof") - const libBridgeRetry = await utils.deployContract(hre, "LibBridgeRetry") + const libTrieProof = await utils.deployContract(hre, "LibTrieProof"); + const libBridgeRetry = await utils.deployContract(hre, "LibBridgeRetry"); const libBridgeProcess = await utils.deployContract( hre, "LibBridgeProcess", { LibTrieProof: libTrieProof.address, } - ) + ); const Bridge = await utils.deployContract(hre, "Bridge", { LibTrieProof: libTrieProof.address, LibBridgeRetry: libBridgeRetry.address, LibBridgeProcess: libBridgeProcess.address, - }) + }); - await utils.waitTx(hre, await Bridge.init(addressManager)) + await utils.waitTx(hre, await Bridge.init(addressManager)); - return Bridge + return Bridge; } async function deployTokenVault( hre: any, addressManager: string ): Promise { - const TokenVault = await utils.deployContract(hre, "TokenVault") + const TokenVault = await utils.deployContract(hre, "TokenVault"); - await utils.waitTx(hre, await TokenVault.init(addressManager)) + await utils.waitTx(hre, await TokenVault.init(addressManager)); - return TokenVault + return TokenVault; } diff --git a/packages/protocol/tasks/log.ts b/packages/protocol/tasks/log.ts index e6f535ca7ac..45733800e77 100644 --- a/packages/protocol/tasks/log.ts +++ b/packages/protocol/tasks/log.ts @@ -1,4 +1,4 @@ -import * as chalk from "chalk" +import * as chalk from "chalk"; // default LOG_LEVEL: INFO function isInfoEnabled() { @@ -7,31 +7,31 @@ function isInfoEnabled() { (process.env.LOG_LEVEL && process.env.LOG_LEVEL.toUpperCase() === "INFO") || isDebugEnabled() - ) + ); } function isDebugEnabled() { return ( process.env.LOG_LEVEL && process.env.LOG_LEVEL.toUpperCase() === "DEBUG" - ) + ); } export function info(...args: any[]) { if (isInfoEnabled()) { - console.log(chalk.blue.bold(["[INFO]", ...args].join(" "))) + console.log(chalk.blue.bold(["[INFO]", ...args].join(" "))); } } export function debug(...args: any[]) { if (isDebugEnabled()) { - console.log(...args) + console.log(...args); } } export function warn(...args: any[]) { - console.log(chalk.magenta.bold(["[WARN]", ...args].join(" "))) + console.log(chalk.magenta.bold(["[WARN]", ...args].join(" "))); } export function error(...args: any[]) { - console.log(chalk.red.bold.underline(["[ERROR]", ...args].join(" "))) + console.log(chalk.red.bold.underline(["[ERROR]", ...args].join(" "))); } diff --git a/packages/protocol/tasks/utils.ts b/packages/protocol/tasks/utils.ts index 3820c49a297..add662ae8a2 100644 --- a/packages/protocol/tasks/utils.ts +++ b/packages/protocol/tasks/utils.ts @@ -1,7 +1,7 @@ -import * as fs from "fs" -import * as log from "./log" -import { Block, BlockHeader, EthGetProofResponse } from "../test/utils/rpc" -import RLP from "rlp" +import * as fs from "fs"; +import * as log from "./log"; +import { Block, BlockHeader, EthGetProofResponse } from "../test/utils/rpc"; +import RLP from "rlp"; async function deployContract( hre: any, @@ -10,73 +10,73 @@ async function deployContract( args: any[] = [], overrides = {} ) { - const contractArgs = args || [] + const contractArgs = args || []; const contractArtifacts = await hre.ethers.getContractFactory( contractName, { libraries: libraries, } - ) + ); - const deployed = await contractArtifacts.deploy(...contractArgs, overrides) + const deployed = await contractArtifacts.deploy(...contractArgs, overrides); log.debug( `${contractName} deploying, tx ${deployed.deployTransaction.hash}, waiting for confirmations` - ) + ); - await deployed.deployed() + await deployed.deployed(); - log.debug(`${contractName} deployed at ${deployed.address}`) - return deployed + log.debug(`${contractName} deployed at ${deployed.address}`); + return deployed; } async function getDeployer(hre: any) { - const accounts = await hre.ethers.provider.listAccounts() + const accounts = await hre.ethers.provider.listAccounts(); if (accounts[0] !== undefined) { - return accounts[0] + return accounts[0]; } throw new Error( `Could not get account, check hardhat.config.ts: networks.${hre.network.name}.accounts` - ) + ); } async function waitTx(hre: any, tx: any) { - return tx.wait(hre.args.confirmations) + return tx.wait(hre.args.confirmations); } async function getContract(hre: any, abi: string[], contractAddress: string) { - const signers = await hre.ethers.getSigners() + const signers = await hre.ethers.getSigners(); if (!signers || signers.length === 0) { throw new Error( `Could not get account, check hardhat.config.ts. network: ${hre.network.name}` - ) + ); } - return new hre.ethers.Contract(contractAddress, abi, signers[0]) + return new hre.ethers.Contract(contractAddress, abi, signers[0]); } function saveDeployments(_fileName: string, deployments: any) { - const fileName = `deployments/${_fileName}.json` - fs.writeFileSync(fileName, JSON.stringify(deployments, undefined, 2)) - log.debug(`deployments saved to ${fileName}`) + const fileName = `deployments/${_fileName}.json`; + fs.writeFileSync(fileName, JSON.stringify(deployments, undefined, 2)); + log.debug(`deployments saved to ${fileName}`); } function getDeployments(_fileName: string) { - const fileName = `deployments/${_fileName}.json` - const json = fs.readFileSync(fileName) - return JSON.parse(`${json}`) + const fileName = `deployments/${_fileName}.json`; + const json = fs.readFileSync(fileName); + return JSON.parse(`${json}`); } async function getSlot(hre: any, signal: any, mappingSlot: any) { return hre.ethers.utils.solidityKeccak256( ["bytes", "uint256"], [signal, mappingSlot] - ) + ); } async function decode(hre: any, type: any, data: any) { - return hre.ethers.utils.defaultAbiCoder.decode([type], data).toString() + return hre.ethers.utils.defaultAbiCoder.decode([type], data).toString(); } const MessageStatus = { @@ -84,15 +84,15 @@ const MessageStatus = { RETRIABLE: 1, DONE: 2, FAILED: 3, -} +}; async function getLatestBlockHeader(hre: any) { const block: Block = await hre.ethers.provider.send( "eth_getBlockByNumber", ["latest", false] - ) + ); - const logsBloom = block.logsBloom.toString().substring(2) + const logsBloom = block.logsBloom.toString().substring(2); const blockHeader: BlockHeader = { parentHash: block.parentHash, @@ -111,9 +111,9 @@ async function getLatestBlockHeader(hre: any) { mixHash: block.mixHash, nonce: block.nonce, baseFeePerGas: block.baseFeePerGas ? parseInt(block.baseFeePerGas) : 0, - } + }; - return { block, blockHeader } + return { block, blockHeader }; } async function getSignalProof( @@ -126,7 +126,7 @@ async function getSignalProof( const proof: EthGetProofResponse = await hre.ethers.provider.send( "eth_getProof", [contractAddress, [key], blockNumber] - ) + ); // RLP encode the proof together for LibTrieProof to decode const encodedProof = hre.ethers.utils.defaultAbiCoder.encode( @@ -135,16 +135,16 @@ async function getSignalProof( RLP.encode(proof.accountProof), RLP.encode(proof.storageProof[0].proof), ] - ) + ); // encode the SignalProof struct from LibBridgeSignal const signalProof = hre.ethers.utils.defaultAbiCoder.encode( [ "tuple(tuple(bytes32 parentHash, bytes32 ommersHash, address beneficiary, bytes32 stateRoot, bytes32 transactionsRoot, bytes32 receiptsRoot, bytes32[8] logsBloom, uint256 difficulty, uint128 height, uint64 gasLimit, uint64 gasUsed, uint64 timestamp, bytes extraData, bytes32 mixHash, uint64 nonce, uint256 baseFeePerGas) header, bytes proof)", ], [{ header: blockHeader, proof: encodedProof }] - ) + ); - return signalProof + return signalProof; } export { @@ -159,4 +159,4 @@ export { MessageStatus, getLatestBlockHeader, getSignalProof, -} +}; diff --git a/packages/protocol/test/ConfigManager.test.ts b/packages/protocol/test/ConfigManager.test.ts index 64ad39de07e..b967cdbe964 100644 --- a/packages/protocol/test/ConfigManager.test.ts +++ b/packages/protocol/test/ConfigManager.test.ts @@ -1,41 +1,41 @@ -import { expect } from "chai" -import { ConfigManager } from "../typechain" -const hre = require("hardhat") -const ethers = hre.ethers +import { expect } from "chai"; +import { ConfigManager } from "../typechain"; +const hre = require("hardhat"); +const ethers = hre.ethers; describe("ConfigManager", function () { - let configManager: ConfigManager - let testKey: string - let testName: string + let configManager: ConfigManager; + let testKey: string; + let testName: string; before(async function () { configManager = await ( await ethers.getContractFactory("ConfigManager") - ).deploy() - await configManager.init() - testKey = ethers.utils.hexlify(ethers.utils.randomBytes(32)) - testName = "test" - }) + ).deploy(); + await configManager.init(); + testKey = ethers.utils.hexlify(ethers.utils.randomBytes(32)); + testName = "test"; + }); it("should set new value to replace an old value and emit an Updated event.", async function () { await expect(configManager.setValue(testName, testKey)).to.emit( configManager, "Updated" - ) - }) + ); + }); it("should not emit any event if the new value is the same as the old value.", async function () { await expect(configManager.setValue(testName, testKey)).to.not.emit( configManager, "Updated" - ) - }) + ); + }); it("should return an empty byte array for non-set name", async function () { - const returnValue = await configManager.getValue("unsetName") - expect(returnValue).to.equal("0x") - }) + const returnValue = await configManager.getValue("unsetName"); + expect(returnValue).to.equal("0x"); + }); it("should return the correct key given the previous set name.", async function () { - expect(await configManager.getValue(testName)).to.equal(testKey) - }) -}) + expect(await configManager.getValue(testName)).to.equal(testKey); + }); +}); diff --git a/packages/protocol/test/L1/TaikoL1.test.ts b/packages/protocol/test/L1/TaikoL1.test.ts index 4a723279f04..c235ea58885 100644 --- a/packages/protocol/test/L1/TaikoL1.test.ts +++ b/packages/protocol/test/L1/TaikoL1.test.ts @@ -1,32 +1,32 @@ -import { expect } from "chai" -import { ethers } from "hardhat" -import { TaikoL1 } from "../../typechain" +import { expect } from "chai"; +import { ethers } from "hardhat"; +import { TaikoL1 } from "../../typechain"; describe("TaikoL1", function () { - let taikoL1: TaikoL1 - let genesisHash: string + let taikoL1: TaikoL1; + let genesisHash: string; beforeEach(async function () { const addressManager = await ( await ethers.getContractFactory("AddressManager") - ).deploy() - await addressManager.init() + ).deploy(); + await addressManager.init(); const libReceiptDecoder = await ( await ethers.getContractFactory("LibReceiptDecoder") - ).deploy() + ).deploy(); const libTxDecoder = await ( await ethers.getContractFactory("LibTxDecoder") - ).deploy() + ).deploy(); const libZKP = await ( await ethers.getContractFactory("LibZKP") - ).deploy() + ).deploy(); const v1Proposing = await ( await ethers.getContractFactory("V1Proposing") - ).deploy() + ).deploy(); const v1Proving = await ( await ethers.getContractFactory("V1Proving", { @@ -36,13 +36,13 @@ describe("TaikoL1", function () { LibZKP: libZKP.address, }, }) - ).deploy() + ).deploy(); const v1Verifying = await ( await ethers.getContractFactory("V1Verifying") - ).deploy() + ).deploy(); - genesisHash = randomBytes32() + genesisHash = randomBytes32(); taikoL1 = await ( await ethers.getContractFactory("TaikoL1", { libraries: { @@ -51,40 +51,42 @@ describe("TaikoL1", function () { V1Proving: v1Proving.address, }, }) - ).deploy() - await taikoL1.init(addressManager.address, genesisHash) - }) + ).deploy(); + await taikoL1.init(addressManager.address, genesisHash); + }); describe("getLatestSyncedHeader()", async function () { it("should be genesisHash because no headers have been synced", async function () { - const hash = await taikoL1.getLatestSyncedHeader() - expect(hash).to.be.eq(genesisHash) - }) - }) + const hash = await taikoL1.getLatestSyncedHeader(); + expect(hash).to.be.eq(genesisHash); + }); + }); describe("getSyncedHeader()", async function () { it("should revert because header number has not been synced", async function () { - await expect(taikoL1.getSyncedHeader(1)).to.be.revertedWith("L1:id") - }) + await expect(taikoL1.getSyncedHeader(1)).to.be.revertedWith( + "L1:id" + ); + }); it("should return appropraite hash for header", async function () { - const hash = await taikoL1.getSyncedHeader(0) - expect(hash).to.be.eq(genesisHash) - }) - }) + const hash = await taikoL1.getSyncedHeader(0); + expect(hash).to.be.eq(genesisHash); + }); + }); describe("getBlockProvers()", async function () { it("should return empty list when there is no proof for that block", async function () { const provers = await taikoL1.getBlockProvers( Math.ceil(Math.random() * 1024), randomBytes32() - ) + ); - expect(provers).to.be.empty - }) - }) -}) + expect(provers).to.be.empty; + }); + }); +}); function randomBytes32() { - return ethers.utils.hexlify(ethers.utils.randomBytes(32)) + return ethers.utils.hexlify(ethers.utils.randomBytes(32)); } diff --git a/packages/protocol/test/L1/TkoToken.test.ts b/packages/protocol/test/L1/TkoToken.test.ts index f7dfe55c133..34afa79845e 100644 --- a/packages/protocol/test/L1/TkoToken.test.ts +++ b/packages/protocol/test/L1/TkoToken.test.ts @@ -1,132 +1,132 @@ -import { expect } from "chai" -import { AddressManager, TkoToken } from "../../typechain" -import { ethers } from "hardhat" +import { expect } from "chai"; +import { AddressManager, TkoToken } from "../../typechain"; +import { ethers } from "hardhat"; import { ADDRESS_RESOLVER_DENIED, ERC20_BURN_AMOUNT_EXCEEDED, ERC20_TRANSFER_AMOUNT_EXCEEDED, -} from "../constants/errors" -import { BigNumber } from "ethers" +} from "../constants/errors"; +import { BigNumber } from "ethers"; describe("TokenVault", function () { - let owner: any - let nonOwner: any - let protoBroker: any - let token: TkoToken - let amountMinted: BigNumber + let owner: any; + let nonOwner: any; + let protoBroker: any; + let token: TkoToken; + let amountMinted: BigNumber; before(async function () { - ;[owner, nonOwner, protoBroker] = await ethers.getSigners() - }) + [owner, nonOwner, protoBroker] = await ethers.getSigners(); + }); beforeEach(async function () { const addressManager: AddressManager = await ( await ethers.getContractFactory("AddressManager") - ).deploy() - await addressManager.init() + ).deploy(); + await addressManager.init(); token = await (await ethers.getContractFactory("TkoToken")) .connect(owner) - .deploy() - await token.init(addressManager.address) + .deploy(); + await token.init(addressManager.address); - const { chainId } = await ethers.provider.getNetwork() + const { chainId } = await ethers.provider.getNetwork(); await addressManager.setAddress( `${chainId}.proto_broker`, protoBroker.address - ) + ); - amountMinted = ethers.utils.parseEther("100") - await token.connect(protoBroker).mint(owner.address, amountMinted) + amountMinted = ethers.utils.parseEther("100"); + await token.connect(protoBroker).mint(owner.address, amountMinted); - const ownerBalance = await token.balanceOf(owner.address) - expect(ownerBalance).to.be.eq(amountMinted) - }) + const ownerBalance = await token.balanceOf(owner.address); + expect(ownerBalance).to.be.eq(amountMinted); + }); describe("mint()", async () => { it("throws when to is equal to the zero address", async () => { await expect( token.connect(protoBroker).mint(ethers.constants.AddressZero, 1) - ).to.be.revertedWith("TKO: invalid address") - }) + ).to.be.revertedWith("TKO: invalid address"); + }); it("throws when minter is not the protoBroker", async () => { await expect( token.connect(owner).mint(nonOwner.address, amountMinted.add(1)) - ).to.be.revertedWith(ADDRESS_RESOLVER_DENIED) - }) + ).to.be.revertedWith(ADDRESS_RESOLVER_DENIED); + }); it("succeeds", async () => { - const originalBalance = await token.balanceOf(nonOwner.address) + const originalBalance = await token.balanceOf(nonOwner.address); await token .connect(protoBroker) - .mint(nonOwner.address, amountMinted) + .mint(nonOwner.address, amountMinted); - const postTransferBalance = await token.balanceOf(nonOwner.address) + const postTransferBalance = await token.balanceOf(nonOwner.address); expect(postTransferBalance).to.be.eq( originalBalance.add(amountMinted) - ) - }) - }) + ); + }); + }); describe("burn()", async () => { it("throws when to is equal to the zero address", async () => { await expect( token.connect(protoBroker).burn(ethers.constants.AddressZero, 1) - ).to.be.revertedWith("TKO: invalid address") - }) + ).to.be.revertedWith("TKO: invalid address"); + }); it("throws when burner is not the protoBroker", async () => { await expect( token.connect(owner).burn(nonOwner.address, amountMinted.add(1)) - ).to.be.revertedWith(ADDRESS_RESOLVER_DENIED) - }) + ).to.be.revertedWith(ADDRESS_RESOLVER_DENIED); + }); it("throws when account balance is < amount requested to burn", async () => { await expect( token .connect(protoBroker) .burn(owner.address, amountMinted.add(1)) - ).to.be.revertedWith(ERC20_BURN_AMOUNT_EXCEEDED) - }) + ).to.be.revertedWith(ERC20_BURN_AMOUNT_EXCEEDED); + }); it("succeeds", async () => { - const originalBalance = await token.balanceOf(owner.address) + const originalBalance = await token.balanceOf(owner.address); - await token.connect(protoBroker).burn(owner.address, amountMinted) + await token.connect(protoBroker).burn(owner.address, amountMinted); - const postTransferBalance = await token.balanceOf(owner.address) + const postTransferBalance = await token.balanceOf(owner.address); expect(postTransferBalance).to.be.eq( originalBalance.sub(amountMinted) - ) - }) - }) + ); + }); + }); describe("transfer()", async () => { it("throws when to is equal to the contract address", async () => { await expect( token.connect(owner).transfer(token.address, 1) - ).to.be.revertedWith("TKO: invalid to") - }) + ).to.be.revertedWith("TKO: invalid to"); + }); it("throws when transfer is > user's amount", async () => { await expect( token .connect(owner) .transfer(nonOwner.address, amountMinted.add(1)) - ).to.be.revertedWith(ERC20_TRANSFER_AMOUNT_EXCEEDED) - }) + ).to.be.revertedWith(ERC20_TRANSFER_AMOUNT_EXCEEDED); + }); it("succeeds", async () => { - const originalBalance = await token.balanceOf(nonOwner.address) + const originalBalance = await token.balanceOf(nonOwner.address); - await token.connect(owner).transfer(nonOwner.address, amountMinted) - const postTransferBalance = await token.balanceOf(nonOwner.address) + await token.connect(owner).transfer(nonOwner.address, amountMinted); + const postTransferBalance = await token.balanceOf(nonOwner.address); expect(postTransferBalance).to.be.eq( originalBalance.add(amountMinted) - ) - }) - }) -}) + ); + }); + }); +}); diff --git a/packages/protocol/test/L2/TaikoL2.test.ts b/packages/protocol/test/L2/TaikoL2.test.ts index f6186697db3..ff9f5502882 100644 --- a/packages/protocol/test/L2/TaikoL2.test.ts +++ b/packages/protocol/test/L2/TaikoL2.test.ts @@ -1,20 +1,20 @@ -import { expect } from "chai" -import { ethers } from "hardhat" -import { TaikoL2 } from "../../typechain" +import { expect } from "chai"; +import { ethers } from "hardhat"; +import { TaikoL2 } from "../../typechain"; describe("TaikoL2", function () { - let taikoL2: TaikoL2 + let taikoL2: TaikoL2; beforeEach(async function () { const addressManager = await ( await ethers.getContractFactory("AddressManager") - ).deploy() - await addressManager.init() + ).deploy(); + await addressManager.init(); // Deploying TaikoL2 Contract linked with LibTxDecoder (throws error otherwise) const libTxDecoder = await ( await ethers.getContractFactory("LibTxDecoder") - ).deploy() + ).deploy(); taikoL2 = await ( await ethers.getContractFactory("TaikoL2", { @@ -22,32 +22,32 @@ describe("TaikoL2", function () { LibTxDecoder: libTxDecoder.address, }, }) - ).deploy(addressManager.address) - }) + ).deploy(addressManager.address); + }); describe("anchor()", async function () { it("should revert since ancestor hashes not written", async function () { await expect( taikoL2.anchor(Math.ceil(Math.random() * 1024), randomBytes32()) - ).to.be.revertedWith("L2:publicInputHash") - }) - }) + ).to.be.revertedWith("L2:publicInputHash"); + }); + }); describe("getLatestSyncedHeader()", async function () { it("should be 0 because no headers have been synced", async function () { - const hash = await taikoL2.getLatestSyncedHeader() - expect(hash).to.be.eq(ethers.constants.HashZero) - }) - }) + const hash = await taikoL2.getLatestSyncedHeader(); + expect(hash).to.be.eq(ethers.constants.HashZero); + }); + }); describe("getSyncedHeader()", async function () { it("should be 0 because header number has not been synced", async function () { - const hash = await taikoL2.getSyncedHeader(1) - expect(hash).to.be.eq(ethers.constants.HashZero) - }) - }) -}) + const hash = await taikoL2.getSyncedHeader(1); + expect(hash).to.be.eq(ethers.constants.HashZero); + }); + }); +}); function randomBytes32() { - return ethers.utils.hexlify(ethers.utils.randomBytes(32)) + return ethers.utils.hexlify(ethers.utils.randomBytes(32)); } diff --git a/packages/protocol/test/bridge/Bridge.test.ts b/packages/protocol/test/bridge/Bridge.test.ts index a2958054610..22eb25b676f 100644 --- a/packages/protocol/test/bridge/Bridge.test.ts +++ b/packages/protocol/test/bridge/Bridge.test.ts @@ -1,7 +1,7 @@ -import { expect } from "chai" -import hre, { ethers } from "hardhat" -import { BigNumber, Signer } from "ethers" -import { Message } from "../utils/message" +import { expect } from "chai"; +import hre, { ethers } from "hardhat"; +import { BigNumber, Signer } from "ethers"; +import { Message } from "../utils/message"; import { AddressManager, Bridge, @@ -10,8 +10,8 @@ import { TestBadReceiver, TestHeaderSync, TestLibBridgeData, -} from "../../typechain" -import { getLatestBlockHeader, getSignalProof } from "../../tasks/utils" +} from "../../typechain"; +import { getLatestBlockHeader, getSignalProof } from "../../tasks/utils"; async function deployBridge( signer: Signer, @@ -23,7 +23,7 @@ async function deployBridge( await ethers.getContractFactory("LibTrieProof") ) .connect(signer) - .deploy() + .deploy(); const libBridgeProcess = await ( await ethers.getContractFactory("LibBridgeProcess", { @@ -33,13 +33,13 @@ async function deployBridge( }) ) .connect(signer) - .deploy() + .deploy(); const libBridgeRetry = await ( await ethers.getContractFactory("LibBridgeRetry") ) .connect(signer) - .deploy() + .deploy(); const BridgeFactory = await ethers.getContractFactory("Bridge", { libraries: { @@ -47,53 +47,53 @@ async function deployBridge( LibBridgeRetry: libBridgeRetry.address, LibTrieProof: libTrieProof.address, }, - }) + }); - const bridge: Bridge = await BridgeFactory.connect(signer).deploy() + const bridge: Bridge = await BridgeFactory.connect(signer).deploy(); - await bridge.connect(signer).init(addressManager.address) + await bridge.connect(signer).init(addressManager.address); - await bridge.connect(signer).enableDestChain(destChain, true) + await bridge.connect(signer).enableDestChain(destChain, true); const etherVault: EtherVault = await ( await ethers.getContractFactory("EtherVault") ) .connect(signer) - .deploy() + .deploy(); - await etherVault.connect(signer).init(addressManager.address) + await etherVault.connect(signer).init(addressManager.address); - await etherVault.connect(signer).authorize(bridge.address, true) + await etherVault.connect(signer).authorize(bridge.address, true); - await etherVault.connect(signer).authorize(await signer.getAddress(), true) + await etherVault.connect(signer).authorize(await signer.getAddress(), true); await addressManager.setAddress( `${srcChain}.ether_vault`, etherVault.address - ) + ); await signer.sendTransaction({ to: etherVault.address, value: BigNumber.from(100000000), gasLimit: 1000000, - }) + }); - return { bridge, etherVault } + return { bridge, etherVault }; } describe("Bridge", function () { async function deployBridgeFixture() { - const [owner, nonOwner] = await ethers.getSigners() + const [owner, nonOwner] = await ethers.getSigners(); - const { chainId } = await ethers.provider.getNetwork() + const { chainId } = await ethers.provider.getNetwork(); - const srcChainId = chainId + const srcChainId = chainId; - const enabledDestChainId = srcChainId + 1 + const enabledDestChainId = srcChainId + 1; const addressManager: AddressManager = await ( await ethers.getContractFactory("AddressManager") - ).deploy() - await addressManager.init() + ).deploy(); + await addressManager.init(); const { bridge: l1Bridge, etherVault: l1EtherVault } = await deployBridge( @@ -101,7 +101,7 @@ describe("Bridge", function () { addressManager, enabledDestChainId, srcChainId - ) + ); // deploy protocol contract return { @@ -112,12 +112,12 @@ describe("Bridge", function () { enabledDestChainId, l1EtherVault, srcChainId, - } + }; } describe("sendMessage()", function () { it("throws when owner is the zero address", async () => { - const { owner, nonOwner, l1Bridge } = await deployBridgeFixture() + const { owner, nonOwner, l1Bridge } = await deployBridgeFixture(); const message: Message = { id: 1, @@ -133,17 +133,17 @@ describe("Bridge", function () { gasLimit: 100, data: ethers.constants.HashZero, memo: "", - } + }; await expect(l1Bridge.sendMessage(message)).to.be.revertedWith( "B:owner" - ) - }) + ); + }); it("throws when dest chain id is same as block.chainid", async () => { - const { owner, nonOwner, l1Bridge } = await deployBridgeFixture() + const { owner, nonOwner, l1Bridge } = await deployBridgeFixture(); - const network = await ethers.provider.getNetwork() + const network = await ethers.provider.getNetwork(); const message: Message = { id: 1, sender: owner.address, @@ -158,15 +158,15 @@ describe("Bridge", function () { gasLimit: 100, data: ethers.constants.HashZero, memo: "", - } + }; await expect(l1Bridge.sendMessage(message)).to.be.revertedWith( "B:destChainId" - ) - }) + ); + }); it("throws when dest chain id is not enabled", async () => { - const { owner, nonOwner, l1Bridge } = await deployBridgeFixture() + const { owner, nonOwner, l1Bridge } = await deployBridgeFixture(); const message: Message = { id: 1, @@ -182,16 +182,16 @@ describe("Bridge", function () { gasLimit: 100, data: ethers.constants.HashZero, memo: "", - } + }; await expect(l1Bridge.sendMessage(message)).to.be.revertedWith( "B:destChainId" - ) - }) + ); + }); it("throws when msg.value is not the same as expected amount", async () => { const { owner, nonOwner, l1Bridge, enabledDestChainId } = - await deployBridgeFixture() + await deployBridgeFixture(); const message: Message = { id: 1, @@ -207,12 +207,12 @@ describe("Bridge", function () { gasLimit: 100, data: ethers.constants.HashZero, memo: "", - } + }; await expect(l1Bridge.sendMessage(message)).to.be.revertedWith( "B:value" - ) - }) + ); + }); it("emits event and is successful when message is valid, ether_vault receives the expectedAmount", async () => { const { @@ -221,11 +221,11 @@ describe("Bridge", function () { l1EtherVault, l1Bridge, enabledDestChainId, - } = await deployBridgeFixture() + } = await deployBridgeFixture(); const etherVaultOriginalBalance = await ethers.provider.getBalance( l1EtherVault.address - ) + ); const message: Message = { id: 1, @@ -241,95 +241,98 @@ describe("Bridge", function () { gasLimit: 100, data: ethers.constants.HashZero, memo: "", - } + }; const expectedAmount = - message.depositValue + message.callValue + message.processingFee + message.depositValue + + message.callValue + + message.processingFee; await expect( l1Bridge.sendMessage(message, { value: expectedAmount, }) - ).to.emit(l1Bridge, "MessageSent") + ).to.emit(l1Bridge, "MessageSent"); const etherVaultUpdatedBalance = await ethers.provider.getBalance( l1EtherVault.address - ) + ); expect(etherVaultUpdatedBalance).to.be.eq( etherVaultOriginalBalance.add(expectedAmount) - ) - }) - }) + ); + }); + }); describe("sendSignal()", async function () { it("throws when signal is empty", async function () { - const { owner, l1Bridge } = await deployBridgeFixture() + const { owner, l1Bridge } = await deployBridgeFixture(); await expect( l1Bridge.connect(owner).sendSignal(ethers.constants.HashZero) - ).to.be.revertedWith("B:signal") - }) + ).to.be.revertedWith("B:signal"); + }); it("sends signal, confirms it was sent", async function () { - const { owner, l1Bridge } = await deployBridgeFixture() + const { owner, l1Bridge } = await deployBridgeFixture(); const hash = - "0xf2e08f6b93d8cf4f37a3b38f91a8c37198095dde8697463ca3789e25218a8e9d" + "0xf2e08f6b93d8cf4f37a3b38f91a8c37198095dde8697463ca3789e25218a8e9d"; await expect(l1Bridge.connect(owner).sendSignal(hash)) .to.emit(l1Bridge, "SignalSent") - .withArgs(owner.address, hash) + .withArgs(owner.address, hash); const isSignalSent = await l1Bridge.isSignalSent( owner.address, hash - ) - expect(isSignalSent).to.be.eq(true) - }) - }) + ); + expect(isSignalSent).to.be.eq(true); + }); + }); describe("isDestChainEnabled()", function () { it("is disabled for unabled chainIds", async () => { - const { l1Bridge } = await deployBridgeFixture() + const { l1Bridge } = await deployBridgeFixture(); - const enabled = await l1Bridge.isDestChainEnabled(68) - expect(enabled).to.be.eq(false) - }) + const enabled = await l1Bridge.isDestChainEnabled(68); + expect(enabled).to.be.eq(false); + }); it("is enabled for enabled chainId", async () => { - const { l1Bridge, enabledDestChainId } = await deployBridgeFixture() + const { l1Bridge, enabledDestChainId } = + await deployBridgeFixture(); const enabled = await l1Bridge.isDestChainEnabled( enabledDestChainId - ) - expect(enabled).to.be.eq(true) - }) - }) + ); + expect(enabled).to.be.eq(true); + }); + }); describe("context()", function () { it("returns unitialized context", async () => { - const { l1Bridge } = await deployBridgeFixture() + const { l1Bridge } = await deployBridgeFixture(); - const ctx = await l1Bridge.context() - expect(ctx[0]).to.be.eq(ethers.constants.HashZero) - expect(ctx[1]).to.be.eq(ethers.constants.AddressZero) - expect(ctx[2]).to.be.eq(BigNumber.from(0)) - }) - }) + const ctx = await l1Bridge.context(); + expect(ctx[0]).to.be.eq(ethers.constants.HashZero); + expect(ctx[1]).to.be.eq(ethers.constants.AddressZero); + expect(ctx[2]).to.be.eq(BigNumber.from(0)); + }); + }); describe("getMessageStatus()", function () { it("returns new for uninitialized signal", async () => { - const { l1Bridge } = await deployBridgeFixture() + const { l1Bridge } = await deployBridgeFixture(); const messageStatus = await l1Bridge.getMessageStatus( ethers.constants.HashZero - ) + ); - expect(messageStatus).to.be.eq(0) - }) + expect(messageStatus).to.be.eq(0); + }); it("returns for initiaized signal", async () => { const { owner, nonOwner, enabledDestChainId, l1Bridge } = - await deployBridgeFixture() + await deployBridgeFixture(); const message: Message = { id: 1, @@ -345,33 +348,35 @@ describe("Bridge", function () { gasLimit: 100, data: ethers.constants.HashZero, memo: "", - } + }; const expectedAmount = - message.depositValue + message.callValue + message.processingFee + message.depositValue + + message.callValue + + message.processingFee; const tx = await l1Bridge.sendMessage(message, { value: expectedAmount, - }) + }); - const receipt = await tx.wait() + const receipt = await tx.wait(); - const [messageSentEvent] = receipt.events as any as Event[] + const [messageSentEvent] = receipt.events as any as Event[]; - const { signal } = (messageSentEvent as any).args + const { signal } = (messageSentEvent as any).args; - expect(signal).not.to.be.eq(ethers.constants.HashZero) + expect(signal).not.to.be.eq(ethers.constants.HashZero); - const messageStatus = await l1Bridge.getMessageStatus(signal) + const messageStatus = await l1Bridge.getMessageStatus(signal); - expect(messageStatus).to.be.eq(0) - }) - }) + expect(messageStatus).to.be.eq(0); + }); + }); describe("processMessage()", async function () { it("throws when message.gasLimit is 0 and msg.sender is not the message.owner", async () => { const { owner, nonOwner, l1Bridge, enabledDestChainId } = - await deployBridgeFixture() + await deployBridgeFixture(); const message: Message = { id: 1, @@ -387,17 +392,17 @@ describe("Bridge", function () { gasLimit: 0, data: ethers.constants.HashZero, memo: "", - } + }; - const proof = ethers.constants.HashZero + const proof = ethers.constants.HashZero; await expect( l1Bridge.processMessage(message, proof) - ).to.be.revertedWith("B:forbidden") - }) + ).to.be.revertedWith("B:forbidden"); + }); it("throws message.destChainId is not block.chainId", async () => { - const { owner, nonOwner, l1Bridge } = await deployBridgeFixture() + const { owner, nonOwner, l1Bridge } = await deployBridgeFixture(); const message: Message = { id: 1, @@ -413,50 +418,50 @@ describe("Bridge", function () { gasLimit: 0, data: ethers.constants.HashZero, memo: "", - } + }; - const proof = ethers.constants.HashZero + const proof = ethers.constants.HashZero; await expect( l1Bridge.processMessage(message, proof) - ).to.be.revertedWith("B:destChainId") - }) - }) -}) + ).to.be.revertedWith("B:destChainId"); + }); + }); +}); describe("integration:Bridge", function () { async function deployBridgeFixture() { - const [owner, nonOwner] = await ethers.getSigners() + const [owner, nonOwner] = await ethers.getSigners(); - const { chainId } = await ethers.provider.getNetwork() + const { chainId } = await ethers.provider.getNetwork(); - const srcChainId = chainId + const srcChainId = chainId; // seondary node to deploy L2 on const l2Provider = new ethers.providers.JsonRpcProvider( "http://localhost:28545" - ) + ); const l2Signer = await l2Provider.getSigner( "0x4D9E82AC620246f6782EAaBaC3E3c86895f3f0F8" - ) + ); - const l2NonOwner = await l2Provider.getSigner() + const l2NonOwner = await l2Provider.getSigner(); - const l2Network = await l2Provider.getNetwork() - const enabledDestChainId = l2Network.chainId + const l2Network = await l2Provider.getNetwork(); + const enabledDestChainId = l2Network.chainId; const addressManager: AddressManager = await ( await ethers.getContractFactory("AddressManager") - ).deploy() - await addressManager.init() + ).deploy(); + await addressManager.init(); const l2AddressManager: AddressManager = await ( await ethers.getContractFactory("AddressManager") ) .connect(l2Signer) - .deploy() - await l2AddressManager.init() + .deploy(); + await l2AddressManager.init(); const { bridge: l1Bridge, etherVault: l1EtherVault } = await deployBridge( @@ -464,7 +469,7 @@ describe("integration:Bridge", function () { addressManager, enabledDestChainId, srcChainId - ) + ); const { bridge: l2Bridge, etherVault: l2EtherVault } = await deployBridge( @@ -472,26 +477,26 @@ describe("integration:Bridge", function () { l2AddressManager, srcChainId, enabledDestChainId - ) + ); await addressManager.setAddress( `${enabledDestChainId}.bridge`, l2Bridge.address - ) + ); await l2AddressManager .connect(l2Signer) - .setAddress(`${srcChainId}.bridge`, l1Bridge.address) + .setAddress(`${srcChainId}.bridge`, l1Bridge.address); const headerSync: TestHeaderSync = await ( await ethers.getContractFactory("TestHeaderSync") ) .connect(l2Signer) - .deploy() + .deploy(); await l2AddressManager .connect(l2Signer) - .setAddress(`${enabledDestChainId}.taiko`, headerSync.address) + .setAddress(`${enabledDestChainId}.taiko`, headerSync.address); const m: Message = { id: 1, @@ -507,7 +512,7 @@ describe("integration:Bridge", function () { gasLimit: 10000, data: ethers.constants.HashZero, memo: "", - } + }; return { owner, @@ -523,7 +528,7 @@ describe("integration:Bridge", function () { srcChainId, headerSync, m, - } + }; } describe("processMessage()", function () { @@ -534,7 +539,7 @@ describe("integration:Bridge", function () { srcChainId, enabledDestChainId, l2Bridge, - } = await deployBridgeFixture() + } = await deployBridgeFixture(); const m: Message = { id: 1, @@ -550,16 +555,16 @@ describe("integration:Bridge", function () { gasLimit: 0, data: ethers.constants.HashZero, memo: "", - } + }; await expect( l2Bridge.processMessage(m, ethers.constants.HashZero) - ).to.be.revertedWith("B:forbidden") - }) + ).to.be.revertedWith("B:forbidden"); + }); it("should throw if message.destChainId is not equal to current block.chainId", async function () { const { owner, srcChainId, enabledDestChainId, l2Bridge } = - await deployBridgeFixture() + await deployBridgeFixture(); const m: Message = { id: 1, @@ -575,41 +580,41 @@ describe("integration:Bridge", function () { gasLimit: 10000, data: ethers.constants.HashZero, memo: "", - } + }; await expect( l2Bridge.processMessage(m, ethers.constants.HashZero) - ).to.be.revertedWith("B:destChainId") - }) + ).to.be.revertedWith("B:destChainId"); + }); it("should throw if messageStatus of message is != NEW", async function () { const { l1Bridge, l2Bridge, headerSync, m } = - await deployBridgeFixture() + await deployBridgeFixture(); const expectedAmount = - m.depositValue + m.callValue + m.processingFee + m.depositValue + m.callValue + m.processingFee; const tx = await l1Bridge.sendMessage(m, { value: expectedAmount, - }) + }); - const receipt = await tx.wait() + const receipt = await tx.wait(); - const [messageSentEvent] = receipt.events as any as Event[] + const [messageSentEvent] = receipt.events as any as Event[]; - const { signal, message } = (messageSentEvent as any).args + const { signal, message } = (messageSentEvent as any).args; - const sender = l1Bridge.address + const sender = l1Bridge.address; const key = ethers.utils.keccak256( ethers.utils.solidityPack( ["address", "bytes32"], [sender, signal] ) - ) + ); - const { block, blockHeader } = await getLatestBlockHeader(hre) + const { block, blockHeader } = await getLatestBlockHeader(hre); - await headerSync.setSyncedHeader(block.hash) + await headerSync.setSyncedHeader(block.hash); const signalProof = await getSignalProof( hre, @@ -617,38 +622,38 @@ describe("integration:Bridge", function () { key, block.number, blockHeader - ) + ); // upon successful processing, this immediately gets marked as DONE - await l2Bridge.processMessage(message, signalProof) + await l2Bridge.processMessage(message, signalProof); // recalling this process should be prevented as it's status is no longer NEW await expect( l2Bridge.processMessage(message, signalProof) - ).to.be.revertedWith("B:status") - }) + ).to.be.revertedWith("B:status"); + }); it("should throw if message signalproof is not valid", async function () { const { l1Bridge, l2Bridge, headerSync, m } = - await deployBridgeFixture() + await deployBridgeFixture(); const libData: TestLibBridgeData = await ( await ethers.getContractFactory("TestLibBridgeData") - ).deploy() + ).deploy(); - const signal = await libData.hashMessage(m) + const signal = await libData.hashMessage(m); - const sender = l1Bridge.address + const sender = l1Bridge.address; const key = ethers.utils.keccak256( ethers.utils.solidityPack( ["address", "bytes32"], [sender, signal] ) - ) - const { block, blockHeader } = await getLatestBlockHeader(hre) + ); + const { block, blockHeader } = await getLatestBlockHeader(hre); - await headerSync.setSyncedHeader(ethers.constants.HashZero) + await headerSync.setSyncedHeader(ethers.constants.HashZero); const signalProof = await getSignalProof( hre, @@ -656,58 +661,58 @@ describe("integration:Bridge", function () { key, block.number, blockHeader - ) + ); await expect( l2Bridge.processMessage(m, signalProof) - ).to.be.revertedWith("LTP:invalid storage proof") - }) + ).to.be.revertedWith("LTP:invalid storage proof"); + }); it("should throw if message has not been received", async function () { const { l1Bridge, l2Bridge, headerSync, m } = - await deployBridgeFixture() + await deployBridgeFixture(); const expectedAmount = - m.depositValue + m.callValue + m.processingFee + m.depositValue + m.callValue + m.processingFee; const tx = await l1Bridge.sendMessage(m, { value: expectedAmount, - }) + }); - const receipt = await tx.wait() + const receipt = await tx.wait(); - const [messageSentEvent] = receipt.events as any as Event[] + const [messageSentEvent] = receipt.events as any as Event[]; - const { signal, message } = (messageSentEvent as any).args + const { signal, message } = (messageSentEvent as any).args; - expect(signal).not.to.be.eq(ethers.constants.HashZero) + expect(signal).not.to.be.eq(ethers.constants.HashZero); - const messageStatus = await l1Bridge.getMessageStatus(signal) + const messageStatus = await l1Bridge.getMessageStatus(signal); - expect(messageStatus).to.be.eq(0) + expect(messageStatus).to.be.eq(0); - const sender = l1Bridge.address + const sender = l1Bridge.address; const key = ethers.utils.keccak256( ethers.utils.solidityPack( ["address", "bytes32"], [sender, signal] ) - ) + ); - const { block, blockHeader } = await getLatestBlockHeader(hre) + const { block, blockHeader } = await getLatestBlockHeader(hre); - await headerSync.setSyncedHeader(ethers.constants.HashZero) + await headerSync.setSyncedHeader(ethers.constants.HashZero); // get storageValue for the key const storageValue = await ethers.provider.getStorageAt( l1Bridge.address, key, block.number - ) + ); // make sure it equals 1 so our proof will pass expect(storageValue).to.be.eq( "0x0000000000000000000000000000000000000000000000000000000000000001" - ) + ); const signalProof = await getSignalProof( hre, @@ -715,58 +720,58 @@ describe("integration:Bridge", function () { key, block.number, blockHeader - ) + ); await expect( l2Bridge.processMessage(message, signalProof) - ).to.be.revertedWith("B:notReceived") - }) + ).to.be.revertedWith("B:notReceived"); + }); it("processes a message when the signal has been verified from the sending chain", async () => { const { l1Bridge, l2Bridge, headerSync, m } = - await deployBridgeFixture() + await deployBridgeFixture(); const expectedAmount = - m.depositValue + m.callValue + m.processingFee + m.depositValue + m.callValue + m.processingFee; const tx = await l1Bridge.sendMessage(m, { value: expectedAmount, - }) + }); - const receipt = await tx.wait() + const receipt = await tx.wait(); - const [messageSentEvent] = receipt.events as any as Event[] + const [messageSentEvent] = receipt.events as any as Event[]; - const { signal, message } = (messageSentEvent as any).args + const { signal, message } = (messageSentEvent as any).args; - expect(signal).not.to.be.eq(ethers.constants.HashZero) + expect(signal).not.to.be.eq(ethers.constants.HashZero); - const messageStatus = await l1Bridge.getMessageStatus(signal) + const messageStatus = await l1Bridge.getMessageStatus(signal); - expect(messageStatus).to.be.eq(0) + expect(messageStatus).to.be.eq(0); - const sender = l1Bridge.address + const sender = l1Bridge.address; const key = ethers.utils.keccak256( ethers.utils.solidityPack( ["address", "bytes32"], [sender, signal] ) - ) + ); - const { block, blockHeader } = await getLatestBlockHeader(hre) + const { block, blockHeader } = await getLatestBlockHeader(hre); - await headerSync.setSyncedHeader(block.hash) + await headerSync.setSyncedHeader(block.hash); // get storageValue for the key const storageValue = await ethers.provider.getStorageAt( l1Bridge.address, key, block.number - ) + ); // make sure it equals 1 so our proof will pass expect(storageValue).to.be.eq( "0x0000000000000000000000000000000000000000000000000000000000000001" - ) + ); const signalProof = await getSignalProof( hre, @@ -774,48 +779,48 @@ describe("integration:Bridge", function () { key, block.number, blockHeader - ) + ); expect( await l2Bridge.processMessage(message, signalProof, { gasLimit: BigNumber.from(2000000), }) - ).to.emit(l2Bridge, "MessageStatusChanged") - }) - }) + ).to.emit(l2Bridge, "MessageStatusChanged"); + }); + }); describe("isMessageSent()", function () { it("should return false, since no message was sent", async function () { - const { l1Bridge, m } = await deployBridgeFixture() + const { l1Bridge, m } = await deployBridgeFixture(); const libData = await ( await ethers.getContractFactory("TestLibBridgeData") - ).deploy() - const signal = await libData.hashMessage(m) + ).deploy(); + const signal = await libData.hashMessage(m); - expect(await l1Bridge.isMessageSent(signal)).to.be.eq(false) - }) + expect(await l1Bridge.isMessageSent(signal)).to.be.eq(false); + }); it("should return true if message was sent properly", async function () { - const { l1Bridge, m } = await deployBridgeFixture() + const { l1Bridge, m } = await deployBridgeFixture(); const expectedAmount = - m.depositValue + m.callValue + m.processingFee + m.depositValue + m.callValue + m.processingFee; const tx = await l1Bridge.sendMessage(m, { value: expectedAmount, - }) + }); - const receipt = await tx.wait() + const receipt = await tx.wait(); - const [messageSentEvent] = receipt.events as any as Event[] + const [messageSentEvent] = receipt.events as any as Event[]; - const { signal } = (messageSentEvent as any).args + const { signal } = (messageSentEvent as any).args; - expect(signal).not.to.be.eq(ethers.constants.HashZero) + expect(signal).not.to.be.eq(ethers.constants.HashZero); - expect(await l1Bridge.isMessageSent(signal)).to.be.eq(true) - }) - }) + expect(await l1Bridge.isMessageSent(signal)).to.be.eq(true); + }); + }); describe("retryMessage()", function () { async function retriableMessageSetup() { @@ -832,15 +837,15 @@ describe("integration:Bridge", function () { l2EtherVault, srcChainId, headerSync, - } = await deployBridgeFixture() + } = await deployBridgeFixture(); const testBadReceiver: TestBadReceiver = await ( await ethers.getContractFactory("TestBadReceiver") ) .connect(l2Signer) - .deploy() + .deploy(); - await testBadReceiver.deployed() + await testBadReceiver.deployed(); const m: Message = { id: 1, @@ -856,38 +861,38 @@ describe("integration:Bridge", function () { gasLimit: 1, data: ethers.constants.HashZero, memo: "", - } + }; const expectedAmount = - m.depositValue + m.callValue + m.processingFee + m.depositValue + m.callValue + m.processingFee; const tx = await l1Bridge.connect(owner).sendMessage(m, { value: expectedAmount, - }) + }); - const receipt = await tx.wait() + const receipt = await tx.wait(); - const [messageSentEvent] = receipt.events as any as Event[] + const [messageSentEvent] = receipt.events as any as Event[]; - const { signal, message } = (messageSentEvent as any).args + const { signal, message } = (messageSentEvent as any).args; - expect(signal).not.to.be.eq(ethers.constants.HashZero) + expect(signal).not.to.be.eq(ethers.constants.HashZero); - const messageStatus = await l1Bridge.getMessageStatus(signal) + const messageStatus = await l1Bridge.getMessageStatus(signal); - expect(messageStatus).to.be.eq(0) + expect(messageStatus).to.be.eq(0); - const sender = l1Bridge.address + const sender = l1Bridge.address; const key = ethers.utils.keccak256( ethers.utils.solidityPack( ["address", "bytes32"], [sender, signal] ) - ) + ); - const { block, blockHeader } = await getLatestBlockHeader(hre) + const { block, blockHeader } = await getLatestBlockHeader(hre); - await headerSync.setSyncedHeader(block.hash) + await headerSync.setSyncedHeader(block.hash); const signalProof = await getSignalProof( hre, @@ -895,16 +900,16 @@ describe("integration:Bridge", function () { key, block.number, blockHeader - ) + ); await l2Bridge .connect(l2NonOwner) .processMessage(message, signalProof, { gasLimit: BigNumber.from(2000000), - }) + }); - const status = await l2Bridge.getMessageStatus(signal) - expect(status).to.be.eq(1) // message is retriable now + const status = await l2Bridge.getMessageStatus(signal); + expect(status).to.be.eq(1); // message is retriable now // because the LibBridgeInvoke call failed, because // message.to is a bad receiver and throws upon receipt @@ -923,49 +928,49 @@ describe("integration:Bridge", function () { l1EtherVault, l2EtherVault, signal, - } + }; } it("setup message to fail first processMessage", async function () { - const { l2Bridge, signal } = await retriableMessageSetup() - l2Bridge - signal - }) - }) + const { l2Bridge, signal } = await retriableMessageSetup(); + l2Bridge; + signal; + }); + }); describe("isMessageReceived()", function () { it("should throw if signal is not a bridge message; proof is invalid since sender != bridge.", async function () { const { owner, l1Bridge, l2Bridge, headerSync, srcChainId } = - await deployBridgeFixture() + await deployBridgeFixture(); - const signal = ethers.utils.hexlify(ethers.utils.randomBytes(32)) + const signal = ethers.utils.hexlify(ethers.utils.randomBytes(32)); - const tx = await l1Bridge.connect(owner).sendSignal(signal) + const tx = await l1Bridge.connect(owner).sendSignal(signal); - await tx.wait() + await tx.wait(); - const sender = owner.address + const sender = owner.address; const key = ethers.utils.keccak256( ethers.utils.solidityPack( ["address", "bytes32"], [sender, signal] ) - ) + ); - const { block, blockHeader } = await getLatestBlockHeader(hre) + const { block, blockHeader } = await getLatestBlockHeader(hre); - await headerSync.setSyncedHeader(block.hash) + await headerSync.setSyncedHeader(block.hash); // get storageValue for the key const storageValue = await ethers.provider.getStorageAt( l1Bridge.address, key, block.number - ) + ); // // make sure it equals 1 so we know sendSignal worked expect(storageValue).to.be.eq( "0x0000000000000000000000000000000000000000000000000000000000000001" - ) + ); const signalProof = await getSignalProof( hre, @@ -973,55 +978,55 @@ describe("integration:Bridge", function () { key, block.number, blockHeader - ) + ); - console.log("signal:", signal) - console.log("signalProof:", signalProof) + console.log("signal:", signal); + console.log("signalProof:", signalProof); await expect( l2Bridge.isMessageReceived(signal, srcChainId, signalProof) - ).to.be.revertedWith("Invalid large internal hash") - }) + ).to.be.revertedWith("Invalid large internal hash"); + }); it("should return true", async function () { const { l1Bridge, srcChainId, l2Bridge, headerSync, m } = - await deployBridgeFixture() + await deployBridgeFixture(); const expectedAmount = - m.depositValue + m.callValue + m.processingFee + m.depositValue + m.callValue + m.processingFee; const tx = await l1Bridge.sendMessage(m, { value: expectedAmount, - }) + }); - const receipt = await tx.wait() + const receipt = await tx.wait(); - const [messageSentEvent] = receipt.events as any as Event[] + const [messageSentEvent] = receipt.events as any as Event[]; - const { signal } = (messageSentEvent as any).args + const { signal } = (messageSentEvent as any).args; - const sender = l1Bridge.address + const sender = l1Bridge.address; const key = ethers.utils.keccak256( ethers.utils.solidityPack( ["address", "bytes32"], [sender, signal] ) - ) + ); - const { block, blockHeader } = await getLatestBlockHeader(hre) + const { block, blockHeader } = await getLatestBlockHeader(hre); - await headerSync.setSyncedHeader(block.hash) + await headerSync.setSyncedHeader(block.hash); // get storageValue for the key const storageValue = await ethers.provider.getStorageAt( l1Bridge.address, key, block.number - ) + ); // // make sure it equals 1 so we know sendMessage worked expect(storageValue).to.be.eq( "0x0000000000000000000000000000000000000000000000000000000000000001" - ) + ); const signalProof = await getSignalProof( hre, @@ -1029,7 +1034,7 @@ describe("integration:Bridge", function () { key, block.number, blockHeader - ) + ); expect( await l2Bridge.isMessageReceived( @@ -1037,17 +1042,17 @@ describe("integration:Bridge", function () { srcChainId, signalProof ) - ).to.be.eq(true) - }) - }) + ).to.be.eq(true); + }); + }); describe("isSignalReceived()", function () { it("should throw if sender == address(0)", async function () { - const { l2Bridge, srcChainId } = await deployBridgeFixture() + const { l2Bridge, srcChainId } = await deployBridgeFixture(); - const signal = ethers.utils.randomBytes(32) - const sender = ethers.constants.AddressZero - const signalProof = ethers.constants.HashZero + const signal = ethers.utils.randomBytes(32); + const sender = ethers.constants.AddressZero; + const signalProof = ethers.constants.HashZero; await expect( l2Bridge.isSignalReceived( @@ -1056,15 +1061,15 @@ describe("integration:Bridge", function () { sender, signalProof ) - ).to.be.revertedWith("B:sender") - }) + ).to.be.revertedWith("B:sender"); + }); it("should throw if signal == HashZero", async function () { - const { owner, l2Bridge, srcChainId } = await deployBridgeFixture() + const { owner, l2Bridge, srcChainId } = await deployBridgeFixture(); - const signal = ethers.constants.HashZero - const sender = owner.address - const signalProof = ethers.constants.HashZero + const signal = ethers.constants.HashZero; + const sender = owner.address; + const signalProof = ethers.constants.HashZero; await expect( l2Bridge.isSignalReceived( @@ -1073,41 +1078,41 @@ describe("integration:Bridge", function () { sender, signalProof ) - ).to.be.revertedWith("B:signal") - }) + ).to.be.revertedWith("B:signal"); + }); it("should throw if calling from same layer", async function () { const { owner, l1Bridge, headerSync, srcChainId } = - await deployBridgeFixture() - const signal = ethers.utils.hexlify(ethers.utils.randomBytes(32)) + await deployBridgeFixture(); + const signal = ethers.utils.hexlify(ethers.utils.randomBytes(32)); - const tx = await l1Bridge.connect(owner).sendSignal(signal) + const tx = await l1Bridge.connect(owner).sendSignal(signal); - await tx.wait() + await tx.wait(); - const sender = owner.address + const sender = owner.address; const key = ethers.utils.keccak256( ethers.utils.solidityPack( ["address", "bytes32"], [sender, signal] ) - ) + ); - const { block, blockHeader } = await getLatestBlockHeader(hre) + const { block, blockHeader } = await getLatestBlockHeader(hre); - await headerSync.setSyncedHeader(block.hash) + await headerSync.setSyncedHeader(block.hash); // get storageValue for the key const storageValue = await ethers.provider.getStorageAt( l1Bridge.address, key, block.number - ) + ); // make sure it equals 1 so our proof is valid expect(storageValue).to.be.eq( "0x0000000000000000000000000000000000000000000000000000000000000001" - ) + ); const signalProof = await getSignalProof( hre, @@ -1115,7 +1120,7 @@ describe("integration:Bridge", function () { key, block.number, blockHeader - ) + ); await expect( l1Bridge.isSignalReceived( @@ -1124,42 +1129,42 @@ describe("integration:Bridge", function () { sender, signalProof ) - ).to.be.revertedWith("B:srcBridge") - }) + ).to.be.revertedWith("B:srcBridge"); + }); it("should return true and pass", async function () { const { owner, l1Bridge, l2Bridge, headerSync, srcChainId } = - await deployBridgeFixture() + await deployBridgeFixture(); - const signal = ethers.utils.hexlify(ethers.utils.randomBytes(32)) + const signal = ethers.utils.hexlify(ethers.utils.randomBytes(32)); - const tx = await l1Bridge.connect(owner).sendSignal(signal) + const tx = await l1Bridge.connect(owner).sendSignal(signal); - await tx.wait() + await tx.wait(); - const sender = owner.address + const sender = owner.address; const key = ethers.utils.keccak256( ethers.utils.solidityPack( ["address", "bytes32"], [sender, signal] ) - ) + ); - const { block, blockHeader } = await getLatestBlockHeader(hre) + const { block, blockHeader } = await getLatestBlockHeader(hre); - await headerSync.setSyncedHeader(block.hash) + await headerSync.setSyncedHeader(block.hash); // get storageValue for the key const storageValue = await ethers.provider.getStorageAt( l1Bridge.address, key, block.number - ) + ); // make sure it equals 1 so our proof will pass expect(storageValue).to.be.eq( "0x0000000000000000000000000000000000000000000000000000000000000001" - ) + ); const signalProof = await getSignalProof( hre, @@ -1167,7 +1172,7 @@ describe("integration:Bridge", function () { key, block.number, blockHeader - ) + ); // proving functionality; l2Bridge can check if l1Bridge receives a signal // allowing for dapp cross layer communication expect( @@ -1177,7 +1182,7 @@ describe("integration:Bridge", function () { sender, signalProof ) - ).to.be.eq(true) - }) - }) -}) + ).to.be.eq(true); + }); + }); +}); diff --git a/packages/protocol/test/bridge/BridgedERC20.test.ts b/packages/protocol/test/bridge/BridgedERC20.test.ts index f809f45cd5f..3d24213e060 100644 --- a/packages/protocol/test/bridge/BridgedERC20.test.ts +++ b/packages/protocol/test/bridge/BridgedERC20.test.ts @@ -1,57 +1,57 @@ -import { expect } from "chai" -import { AddressManager, BridgedERC20 } from "../../typechain" -import { ethers } from "hardhat" -import { BigNumber } from "ethers" +import { expect } from "chai"; +import { AddressManager, BridgedERC20 } from "../../typechain"; +import { ethers } from "hardhat"; +import { BigNumber } from "ethers"; import { ADDRESS_RESOLVER_DENIED, ERC20_BURN_AMOUNT_EXCEEDED, ERC20_TRANSFER_AMOUNT_EXCEEDED, -} from "../constants/errors" +} from "../constants/errors"; -const WETH_GOERLI = "0xB4FBF271143F4FBf7B91A5ded31805e42b2208d6" -const CHAIN_ID_GOERLI = 5 +const WETH_GOERLI = "0xB4FBF271143F4FBf7B91A5ded31805e42b2208d6"; +const CHAIN_ID_GOERLI = 5; describe("BridgedERC20", function () { - let owner: any - let tokenVault: any - let accountWithTokens: any + let owner: any; + let tokenVault: any; + let accountWithTokens: any; // uninitialized BridgedERC20 for testing - let unInitAddressManager: AddressManager - let unInitERC20: BridgedERC20 + let unInitAddressManager: AddressManager; + let unInitERC20: BridgedERC20; // properly initialized BridgedERC20 for testing - let addressManager: AddressManager - let erc20: BridgedERC20 + let addressManager: AddressManager; + let erc20: BridgedERC20; before(async function () { - ;[owner, tokenVault, accountWithTokens] = await ethers.getSigners() - }) + [owner, tokenVault, accountWithTokens] = await ethers.getSigners(); + }); beforeEach(async function () { unInitAddressManager = await ( await ethers.getContractFactory("AddressManager") - ).deploy() - await unInitAddressManager.init() + ).deploy(); + await unInitAddressManager.init(); unInitERC20 = await (await ethers.getContractFactory("BridgedERC20")) .connect(owner) - .deploy() + .deploy(); addressManager = await ( await ethers.getContractFactory("AddressManager") - ).deploy() - await addressManager.init() + ).deploy(); + await addressManager.init(); - const network = await ethers.provider.getNetwork() + const network = await ethers.provider.getNetwork(); await addressManager.setAddress( `${network.chainId}.token_vault`, tokenVault.address - ) + ); erc20 = await (await ethers.getContractFactory("BridgedERC20")) .connect(owner) - .deploy() + .deploy(); await erc20 .connect(owner) @@ -62,15 +62,15 @@ describe("BridgedERC20", function () { 18, "SYMB", "Name" - ) + ); await erc20 .connect(tokenVault) .bridgeMintTo( accountWithTokens.address, ethers.utils.parseEther("1.0") - ) - }) + ); + }); describe("init()", function () { it("inits when srctoken is not 0, srcChainId is not 0, srcChainId is not the current blocks chain id, symbol is not 0 length, name is not 0 length", async () => { @@ -85,8 +85,8 @@ describe("BridgedERC20", function () { "SYMB", "Name" ) - ).not.to.be.revertedWith("BE:params") - }) + ).not.to.be.revertedWith("BE:params"); + }); it("throws when _srcToken is address 0 ", async () => { await expect( @@ -100,8 +100,8 @@ describe("BridgedERC20", function () { "SYMB", "Name" ) - ).to.be.revertedWith("BE:params") - }) + ).to.be.revertedWith("BE:params"); + }); it("throws when _srcChainId is 0", async () => { await expect( @@ -115,8 +115,8 @@ describe("BridgedERC20", function () { "SYMB", "Name" ) - ).to.be.revertedWith("BE:params") - }) + ).to.be.revertedWith("BE:params"); + }); it("throws when _symbol is 0 length", async () => { await expect( @@ -130,8 +130,8 @@ describe("BridgedERC20", function () { "", "Name" ) - ).to.be.revertedWith("BE:params") - }) + ).to.be.revertedWith("BE:params"); + }); it("throws when _name is 0 length", async () => { await expect( @@ -145,11 +145,11 @@ describe("BridgedERC20", function () { "SYMB", "" ) - ).to.be.revertedWith("BE:params") - }) + ).to.be.revertedWith("BE:params"); + }); it("throws when _srcChainId is equal to block.chainid", async () => { - const network = await ethers.provider.getNetwork() + const network = await ethers.provider.getNetwork(); await expect( unInitERC20 .connect(owner) @@ -161,32 +161,32 @@ describe("BridgedERC20", function () { "SYMB", "name" ) - ).to.be.revertedWith("BE:params") - }) - }) + ).to.be.revertedWith("BE:params"); + }); + }); describe("source()", function () { it("returns srcToken and srcChainId", async () => { - const [srcToken, srcChainId] = await erc20.source() + const [srcToken, srcChainId] = await erc20.source(); - expect(srcToken).to.be.eq(WETH_GOERLI) - expect(srcChainId).to.be.eq(CHAIN_ID_GOERLI) - }) - }) + expect(srcToken).to.be.eq(WETH_GOERLI); + expect(srcChainId).to.be.eq(CHAIN_ID_GOERLI); + }); + }); describe("bridgeMintTo()", function () { it("throws when not called by token_vault", async () => { - const amount = BigNumber.from(1) + const amount = BigNumber.from(1); await expect( erc20.bridgeMintTo(owner.address, amount) - ).to.be.revertedWith(ADDRESS_RESOLVER_DENIED) - }) + ).to.be.revertedWith(ADDRESS_RESOLVER_DENIED); + }); it("successfully mintes and emits BridgeMint when called by token_vault, balance inceases for account specified, burns and emits BridgeBurn", async () => { - const amount = BigNumber.from(150) + const amount = BigNumber.from(150); - const initialBalance = await erc20.balanceOf(owner.address) - expect(initialBalance).to.be.eq(BigNumber.from(0)) + const initialBalance = await erc20.balanceOf(owner.address); + expect(initialBalance).to.be.eq(BigNumber.from(0)); expect( await erc20 @@ -194,9 +194,9 @@ describe("BridgedERC20", function () { .bridgeMintTo(owner.address, amount) ) .to.emit(erc20, "BridgeMint") - .withArgs(owner.address, amount) - const newBalance = await erc20.balanceOf(owner.address) - expect(newBalance).to.be.eq(initialBalance.add(amount)) + .withArgs(owner.address, amount); + const newBalance = await erc20.balanceOf(owner.address); + expect(newBalance).to.be.eq(initialBalance.add(amount)); expect( await erc20 @@ -204,25 +204,25 @@ describe("BridgedERC20", function () { .bridgeBurnFrom(owner.address, amount) ) .to.emit(erc20, "BridgeBurn") - .withArgs(owner.address, amount) + .withArgs(owner.address, amount); - const afterBurnBalance = await erc20.balanceOf(owner.address) - expect(afterBurnBalance).to.be.eq(newBalance.sub(amount)) - }) - }) + const afterBurnBalance = await erc20.balanceOf(owner.address); + expect(afterBurnBalance).to.be.eq(newBalance.sub(amount)); + }); + }); describe("bridgeBurnFrom()", function () { it("throws when not called by token_vault", async () => { - const amount = BigNumber.from(1) + const amount = BigNumber.from(1); await expect( erc20.bridgeBurnFrom(owner.address, amount) - ).to.be.revertedWith(ADDRESS_RESOLVER_DENIED) - }) + ).to.be.revertedWith(ADDRESS_RESOLVER_DENIED); + }); it("can not burn an amount greater than was minted", async () => { const initialBalance = await erc20.balanceOf( accountWithTokens.address - ) + ); await expect( erc20 @@ -231,9 +231,9 @@ describe("BridgedERC20", function () { accountWithTokens.address, initialBalance.add(1) ) - ).to.be.revertedWith(ERC20_BURN_AMOUNT_EXCEEDED) - }) - }) + ).to.be.revertedWith(ERC20_BURN_AMOUNT_EXCEEDED); + }); + }); describe("transferFrom()", function () { it("throws when trying to transfer to itself", async () => { @@ -241,35 +241,37 @@ describe("BridgedERC20", function () { erc20 .connect(accountWithTokens) .transferFrom(accountWithTokens.address, erc20.address, 1) - ).to.be.revertedWith("BE:to") - }) - }) + ).to.be.revertedWith("BE:to"); + }); + }); describe("transfer()", function () { it("throws when trying to transfer to itself", async () => { await expect( erc20.connect(accountWithTokens).transfer(erc20.address, 1) - ).to.be.revertedWith("BE:to") - }) + ).to.be.revertedWith("BE:to"); + }); it("throws when trying to transfer amount greater than holder owns", async () => { const initialBalance = await erc20.balanceOf( accountWithTokens.address - ) + ); await expect( erc20 .connect(accountWithTokens) .transfer(owner.address, initialBalance.add(1)) - ).to.be.revertedWith(ERC20_TRANSFER_AMOUNT_EXCEEDED) - }) + ).to.be.revertedWith(ERC20_TRANSFER_AMOUNT_EXCEEDED); + }); it("transfers, emits Transfer event, balances are correct after transfer", async () => { - const initialRecipientBalance = await erc20.balanceOf(owner.address) + const initialRecipientBalance = await erc20.balanceOf( + owner.address + ); const initialAccountWithTokensBalance = await erc20.balanceOf( accountWithTokens.address - ) - const amount = BigNumber.from(100) + ); + const amount = BigNumber.from(100); expect( await erc20 @@ -277,19 +279,19 @@ describe("BridgedERC20", function () { .transfer(owner.address, amount) ) .to.emit(erc20, "Transfer") - .withArgs(accountWithTokens.address, owner.address, amount) + .withArgs(accountWithTokens.address, owner.address, amount); - const newRecipientBalance = await erc20.balanceOf(owner.address) + const newRecipientBalance = await erc20.balanceOf(owner.address); const newAccountWithTokensBalance = await erc20.balanceOf( accountWithTokens.address - ) + ); expect(newRecipientBalance).to.be.eq( initialRecipientBalance.add(amount) - ) + ); expect(newAccountWithTokensBalance).to.be.eq( initialAccountWithTokensBalance.sub(amount) - ) - }) - }) -}) + ); + }); + }); +}); diff --git a/packages/protocol/test/bridge/EtherVault.test.ts b/packages/protocol/test/bridge/EtherVault.test.ts index 91bad88ddc8..0d4b403d21a 100644 --- a/packages/protocol/test/bridge/EtherVault.test.ts +++ b/packages/protocol/test/bridge/EtherVault.test.ts @@ -1,112 +1,118 @@ -import { expect } from "chai" -import { AddressManager, EtherVault } from "../../typechain" -import { ethers } from "hardhat" -import { BigNumber } from "ethers" +import { expect } from "chai"; +import { AddressManager, EtherVault } from "../../typechain"; +import { ethers } from "hardhat"; +import { BigNumber } from "ethers"; describe("EtherVault", function () { - let owner: any - let nonOwner: any - let authorized: any - let notAuthorized: any - let etherVault: EtherVault + let owner: any; + let nonOwner: any; + let authorized: any; + let notAuthorized: any; + let etherVault: EtherVault; before(async function () { - ;[owner, nonOwner, authorized, notAuthorized] = - await ethers.getSigners() - }) + [owner, nonOwner, authorized, notAuthorized] = + await ethers.getSigners(); + }); beforeEach(async function () { const addressManager: AddressManager = await ( await ethers.getContractFactory("AddressManager") - ).deploy() - await addressManager.init() + ).deploy(); + await addressManager.init(); etherVault = await (await ethers.getContractFactory("EtherVault")) .connect(owner) - .deploy() - await etherVault.init(addressManager.address) + .deploy(); + await etherVault.init(addressManager.address); - await etherVault.connect(owner).authorize(authorized.address, true) + await etherVault.connect(owner).authorize(authorized.address, true); - const isAuthorized = await etherVault.isAuthorized(authorized.address) - expect(isAuthorized).to.be.eq(true) + const isAuthorized = await etherVault.isAuthorized(authorized.address); + expect(isAuthorized).to.be.eq(true); await authorized.sendTransaction({ to: etherVault.address, value: ethers.utils.parseEther("1.0"), - }) + }); expect(await ethers.provider.getBalance(etherVault.address)).to.be.eq( ethers.utils.parseEther("1.0") - ) - }) + ); + }); describe("receive()", async function () { it("throws if not authorized and balance > 0", async () => { - const balance = await ethers.provider.getBalance(etherVault.address) - expect(balance).to.not.be.eq(BigNumber.from(0)) + const balance = await ethers.provider.getBalance( + etherVault.address + ); + expect(balance).to.not.be.eq(BigNumber.from(0)); await expect( notAuthorized.sendTransaction({ to: etherVault.address, value: ethers.utils.parseEther("1.0"), }) - ).to.be.revertedWith("EV:denied") - }) + ).to.be.revertedWith("EV:denied"); + }); it("receives if authorized and balance > 0", async () => { - const amount = BigNumber.from(1) + const amount = BigNumber.from(1); const originalBalance = await ethers.provider.getBalance( etherVault.address - ) - expect(originalBalance).to.not.be.eq(BigNumber.from(0)) + ); + expect(originalBalance).to.not.be.eq(BigNumber.from(0)); await authorized.sendTransaction({ to: etherVault.address, value: amount, - }) + }); const newBalance = await ethers.provider.getBalance( etherVault.address - ) - expect(newBalance).to.be.eq(amount.add(originalBalance)) - }) - }) + ); + expect(newBalance).to.be.eq(amount.add(originalBalance)); + }); + }); describe("receiveEther()", async function () { it("throws if not enough ether to send", async () => { - const balance = await ethers.provider.getBalance(etherVault.address) - const additionalAmount = 1 + const balance = await ethers.provider.getBalance( + etherVault.address + ); + const additionalAmount = 1; await expect( etherVault .connect(authorized) .receiveEther(balance.add(additionalAmount)) - ).to.be.revertedWith("ETH transfer failed") - }) + ).to.be.revertedWith("ETH transfer failed"); + }); it("throws if not authorized", async () => { await expect( etherVault.connect(notAuthorized).receiveEther(1) - ).to.be.revertedWith("EV:denied") - }) + ).to.be.revertedWith("EV:denied"); + }); it("sends ether to caller", async () => { - const amount = 100000 + const amount = 100000; const originalBalance = await ethers.provider.getBalance( authorized.address - ) + ); - const tx = await etherVault.connect(authorized).receiveEther(amount) - const receipt = await tx.wait() + const tx = await etherVault + .connect(authorized) + .receiveEther(amount); + const receipt = await tx.wait(); const gasUsed = receipt.cumulativeGasUsed.mul( receipt.effectiveGasPrice - ) + ); const newBalance = await ethers.provider.getBalance( authorized.address - ) + ); expect(newBalance).to.be.eq( originalBalance.add(amount).sub(gasUsed) - ) - }) - }) + ); + }); + }); describe("authorize()", async function () { it("throws when not called by owner", async () => { @@ -114,47 +120,47 @@ describe("EtherVault", function () { etherVault .connect(nonOwner) .authorize(notAuthorized.address, true) - ).to.be.revertedWith("Ownable: caller is not the owner") - }) + ).to.be.revertedWith("Ownable: caller is not the owner"); + }); it("throws when address is 0", async () => { await expect( etherVault .connect(owner) .authorize(ethers.constants.AddressZero, true) - ).to.be.revertedWith("EV:param") - }) + ).to.be.revertedWith("EV:param"); + }); it("throws when authorized state is the same as input", async () => { await expect( etherVault.connect(owner).authorize(authorized.address, true) - ).to.be.revertedWith("EV:param") - }) + ).to.be.revertedWith("EV:param"); + }); it("emits Authorized event upon success", async () => { await expect( etherVault.connect(owner).authorize(notAuthorized.address, true) ) .to.emit(etherVault, "Authorized") - .withArgs(notAuthorized.address, true) - }) + .withArgs(notAuthorized.address, true); + }); it("address is authorized in mapping, can de-authorize", async () => { await etherVault .connect(owner) - .authorize(notAuthorized.address, true) + .authorize(notAuthorized.address, true); let isAuthorized = await etherVault.isAuthorized( notAuthorized.address - ) - expect(isAuthorized).to.be.eq(true) + ); + expect(isAuthorized).to.be.eq(true); await etherVault .connect(owner) - .authorize(notAuthorized.address, false) + .authorize(notAuthorized.address, false); - isAuthorized = await etherVault.isAuthorized(notAuthorized.address) - expect(isAuthorized).to.be.eq(false) - }) - }) -}) + isAuthorized = await etherVault.isAuthorized(notAuthorized.address); + expect(isAuthorized).to.be.eq(false); + }); + }); +}); diff --git a/packages/protocol/test/bridge/TokenVault.test.ts b/packages/protocol/test/bridge/TokenVault.test.ts index f256c653831..7843a2b14b7 100644 --- a/packages/protocol/test/bridge/TokenVault.test.ts +++ b/packages/protocol/test/bridge/TokenVault.test.ts @@ -1,16 +1,16 @@ -import { expect } from "chai" -import { AddressManager, TokenVault } from "../../typechain" -import { ethers } from "hardhat" -import { BigNumber, BigNumberish } from "ethers" -import { ADDRESS_RESOLVER_DENIED } from "../constants/errors" +import { expect } from "chai"; +import { AddressManager, TokenVault } from "../../typechain"; +import { ethers } from "hardhat"; +import { BigNumber, BigNumberish } from "ethers"; +import { ADDRESS_RESOLVER_DENIED } from "../constants/errors"; type CanonicalERC20 = { - chainId: BigNumberish - addr: string - decimals: BigNumberish - symbol: string - name: string -} + chainId: BigNumberish; + addr: string; + decimals: BigNumberish; + symbol: string; + name: string; +}; const weth: CanonicalERC20 = { chainId: 5, @@ -18,48 +18,48 @@ const weth: CanonicalERC20 = { decimals: 18, symbol: "WETH", name: "Wrapped Ether", -} +}; describe("TokenVault", function () { - let owner: any - let nonOwner: any - let tokenVault: TokenVault - const defaultProcessingFee = 10 - const destChainId = 167001 + let owner: any; + let nonOwner: any; + let tokenVault: TokenVault; + const defaultProcessingFee = 10; + const destChainId = 167001; before(async function () { - ;[owner, nonOwner] = await ethers.getSigners() - }) + [owner, nonOwner] = await ethers.getSigners(); + }); beforeEach(async function () { const tokenVaultAddressManager: AddressManager = await ( await ethers.getContractFactory("AddressManager") - ).deploy() - await tokenVaultAddressManager.init() + ).deploy(); + await tokenVaultAddressManager.init(); tokenVault = await (await ethers.getContractFactory("TokenVault")) .connect(owner) - .deploy() + .deploy(); - await tokenVault.init(tokenVaultAddressManager.address) + await tokenVault.init(tokenVaultAddressManager.address); - const network = await ethers.provider.getNetwork() + const network = await ethers.provider.getNetwork(); const TestMessageSenderFactory = await ethers.getContractFactory( "TestMessageSender" - ) + ); - const testMessageSender = await TestMessageSenderFactory.deploy() + const testMessageSender = await TestMessageSenderFactory.deploy(); await tokenVaultAddressManager.setAddress( `${network.chainId}.bridge`, testMessageSender.address - ) - }) + ); + }); describe("receiveERC20()", async () => { it("throws when named 'bridge' is not the caller", async () => { - const amount = BigNumber.from(1) + const amount = BigNumber.from(1); await expect( tokenVault.receiveERC20( @@ -68,9 +68,9 @@ describe("TokenVault", function () { nonOwner.address, amount ) - ).to.be.revertedWith(ADDRESS_RESOLVER_DENIED) - }) - }) + ).to.be.revertedWith(ADDRESS_RESOLVER_DENIED); + }); + }); describe("sendEther()", async () => { it("throws when msg.value is 0", async () => { @@ -83,8 +83,8 @@ describe("TokenVault", function () { owner.address, "" ) - ).to.be.revertedWith("V:msgValue") - }) + ).to.be.revertedWith("V:msgValue"); + }); it("throws when msg.value - processing fee is 0", async () => { await expect( @@ -99,8 +99,8 @@ describe("TokenVault", function () { value: defaultProcessingFee, } ) - ).to.be.revertedWith("V:msgValue") - }) + ).to.be.revertedWith("V:msgValue"); + }); it("throws when msg.value is < processingFee", async () => { await expect( @@ -115,8 +115,8 @@ describe("TokenVault", function () { value: defaultProcessingFee - 1, } ) - ).to.be.revertedWith("V:msgValue") - }) + ).to.be.revertedWith("V:msgValue"); + }); it("throws when to is 0", async () => { await expect( @@ -131,14 +131,14 @@ describe("TokenVault", function () { value: defaultProcessingFee - 1, } ) - ).to.be.revertedWith("V:to") - }) + ).to.be.revertedWith("V:to"); + }); it("succeeds with processingFee", async () => { - const depositValue = 1000 + const depositValue = 1000; const testSignal = - "0x3fd54831f488a22b28398de0c567a3b064b937f54f81739ae9bd545967f3abab" + "0x3fd54831f488a22b28398de0c567a3b064b937f54f81739ae9bd545967f3abab"; await expect( tokenVault.sendEther( @@ -159,14 +159,14 @@ describe("TokenVault", function () { destChainId, depositValue - defaultProcessingFee, testSignal - ) - }) + ); + }); it("succeeds with 0 processingFee", async () => { - const depositValue = 1000 + const depositValue = 1000; const testSignal = - "0x3fd54831f488a22b28398de0c567a3b064b937f54f81739ae9bd545967f3abab" + "0x3fd54831f488a22b28398de0c567a3b064b937f54f81739ae9bd545967f3abab"; await expect( tokenVault.sendEther( @@ -187,7 +187,7 @@ describe("TokenVault", function () { destChainId, depositValue - defaultProcessingFee, testSignal - ) - }) - }) -}) + ); + }); + }); +}); diff --git a/packages/protocol/test/bridge/libs/LibBridgeData.test.ts b/packages/protocol/test/bridge/libs/LibBridgeData.test.ts index 38bdf75dc59..2d04c6e4d4b 100644 --- a/packages/protocol/test/bridge/libs/LibBridgeData.test.ts +++ b/packages/protocol/test/bridge/libs/LibBridgeData.test.ts @@ -1,20 +1,20 @@ -import { expect } from "chai" -import { ethers } from "hardhat" -import { TestLibBridgeData } from "../../../typechain" -import { K_BRIDGE_MESSAGE } from "../../constants/messages" -import { MessageStatus } from "../../../tasks/utils" -import { Message } from "../../utils/message" +import { expect } from "chai"; +import { ethers } from "hardhat"; +import { TestLibBridgeData } from "../../../typechain"; +import { K_BRIDGE_MESSAGE } from "../../constants/messages"; +import { MessageStatus } from "../../../tasks/utils"; +import { Message } from "../../utils/message"; describe("LibBridgeData", function () { - let owner: any - let nonOwner: any - let testMessage: Message - let testTypes: any - let testVar: any - let libData: TestLibBridgeData + let owner: any; + let nonOwner: any; + let testMessage: Message; + let testTypes: any; + let testVar: any; + let libData: TestLibBridgeData; before(async function () { - ;[owner, nonOwner] = await ethers.getSigners() + [owner, nonOwner] = await ethers.getSigners(); testMessage = { id: 1, @@ -30,33 +30,33 @@ describe("LibBridgeData", function () { gasLimit: 0, data: ethers.constants.HashZero, memo: "", - } + }; testTypes = [ "string", "tuple(uint256 id, address sender, uint256 srcChainId, uint256 destChainId, address owner, address to, address refundAddress, uint256 depositValue, uint256 callValue, uint256 processingFee, uint256 gasLimit, bytes data, string memo)", - ] + ]; - testVar = [K_BRIDGE_MESSAGE, testMessage] - }) + testVar = [K_BRIDGE_MESSAGE, testMessage]; + }); beforeEach(async function () { libData = await ( await ethers.getContractFactory("TestLibBridgeData") - ).deploy() - }) + ).deploy(); + }); describe("hashMessage()", async function () { it("should return properly hashed message", async function () { - const hashed = await libData.hashMessage(testMessage) + const hashed = await libData.hashMessage(testMessage); const expectedEncoded = ethers.utils.defaultAbiCoder.encode( testTypes, testVar - ) + ); - const expectedHash = await ethers.utils.keccak256(expectedEncoded) + const expectedHash = await ethers.utils.keccak256(expectedEncoded); - expect(expectedHash).to.be.eq(hashed) - }) + expect(expectedHash).to.be.eq(hashed); + }); it("should return properly hashed message from actual bridge message", async function () { const testMessage: Message = { @@ -73,41 +73,41 @@ describe("LibBridgeData", function () { gasLimit: 1000000, data: "0x0c6fab8200000000000000000000000000000000000000000000000000000000000000800000000000000000000000004ec242468812b6ffc8be8ff423af7bd23108d9910000000000000000000000004ec242468812b6ffc8be8ff423af7bd23108d99100000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000007a68000000000000000000000000e48a03e23449975df36603c93f59a15e2de75c74000000000000000000000000000000000000000000000000000000000000001200000000000000000000000000000000000000000000000000000000000000a000000000000000000000000000000000000000000000000000000000000000e00000000000000000000000000000000000000000000000000000000000000004544553540000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000095465737445524332300000000000000000000000000000000000000000000000", memo: "CronJob SendTokens", - } + }; - const hashed = await libData.hashMessage(testMessage) + const hashed = await libData.hashMessage(testMessage); expect( "0xea159ca9f8fa8d139853755222c652413568310fab38095f5700286155a5179b" - ).to.be.eq(hashed) - }) - }) + ).to.be.eq(hashed); + }); + }); describe("updateMessageStatus()", async function () { it("should emit upon successful change, and value should be changed correctly", async function () { - const signal = await libData.hashMessage(testMessage) + const signal = await libData.hashMessage(testMessage); expect( await libData.updateMessageStatus(signal, MessageStatus.NEW) - ).to.emit(libData, "MessageStatusChanged") + ).to.emit(libData, "MessageStatusChanged"); - const messageStatus = await libData.getMessageStatus(signal) + const messageStatus = await libData.getMessageStatus(signal); - expect(messageStatus).to.eq(MessageStatus.NEW) - }) + expect(messageStatus).to.eq(MessageStatus.NEW); + }); it("unchanged MessageStatus should not emit event", async function () { - const signal = await libData.hashMessage(testMessage) + const signal = await libData.hashMessage(testMessage); - await libData.updateMessageStatus(signal, MessageStatus.NEW) + await libData.updateMessageStatus(signal, MessageStatus.NEW); expect( await libData.updateMessageStatus(signal, MessageStatus.NEW) - ).to.not.emit(libData, "MessageStatusChanged") + ).to.not.emit(libData, "MessageStatusChanged"); expect(await libData.getMessageStatus(signal)).to.eq( MessageStatus.NEW - ) - }) - }) -}) + ); + }); + }); +}); diff --git a/packages/protocol/test/bridge/libs/LibBridgeInvoke.test.ts b/packages/protocol/test/bridge/libs/LibBridgeInvoke.test.ts index 1ca465d1199..7d116095fea 100644 --- a/packages/protocol/test/bridge/libs/LibBridgeInvoke.test.ts +++ b/packages/protocol/test/bridge/libs/LibBridgeInvoke.test.ts @@ -1,31 +1,31 @@ -import { expect } from "chai" -import { ethers } from "hardhat" -import { Message } from "../../utils/message" +import { expect } from "chai"; +import { ethers } from "hardhat"; +import { Message } from "../../utils/message"; import { TestLibBridgeData, TestLibBridgeInvoke, TestReceiver, -} from "../../../typechain" +} from "../../../typechain"; describe("LibBridgeInvoke", function () { - let owner: any - let nonOwner: any - let libInvoke: TestLibBridgeInvoke - let libData: TestLibBridgeData + let owner: any; + let nonOwner: any; + let libInvoke: TestLibBridgeInvoke; + let libData: TestLibBridgeData; before(async function () { - ;[owner, nonOwner] = await ethers.getSigners() - }) + [owner, nonOwner] = await ethers.getSigners(); + }); beforeEach(async function () { libInvoke = await ( await ethers.getContractFactory("TestLibBridgeInvoke") - ).deploy() + ).deploy(); libData = await ( await ethers.getContractFactory("TestLibBridgeData") - ).deploy() - }) + ).deploy(); + }); describe("invokeMessageCall()", async function () { it("should throw when gasLimit <= 0", async function () { @@ -43,14 +43,14 @@ describe("LibBridgeInvoke", function () { gasLimit: 0, data: ethers.constants.HashZero, memo: "", - } + }; - const signal = await libData.hashMessage(message) + const signal = await libData.hashMessage(message); await expect( libInvoke.invokeMessageCall(message, signal, message.gasLimit) - ).to.be.revertedWith("B:gasLimit") - }) + ).to.be.revertedWith("B:gasLimit"); + }); it("should emit event with success false if message does not actually invoke", async function () { const message: Message = { @@ -67,27 +67,27 @@ describe("LibBridgeInvoke", function () { gasLimit: 100, data: ethers.constants.HashZero, memo: "", - } + }; - const signal = await libData.hashMessage(message) + const signal = await libData.hashMessage(message); await expect( libInvoke.invokeMessageCall(message, signal, message.gasLimit) ) .to.emit(libInvoke, "MessageInvoked") - .withArgs(signal, false) - }) + .withArgs(signal, false); + }); it("should emit event with success true if message invokes successfully", async function () { const testReceiver: TestReceiver = await ( await ethers.getContractFactory("TestReceiver") - ).deploy() + ).deploy(); - await testReceiver.deployed() + await testReceiver.deployed(); - const ABI = ["function receiveTokens(uint256) payable"] - const iface = new ethers.utils.Interface(ABI) - const data = iface.encodeFunctionData("receiveTokens", [1]) + const ABI = ["function receiveTokens(uint256) payable"]; + const iface = new ethers.utils.Interface(ABI); + const data = iface.encodeFunctionData("receiveTokens", [1]); const message: Message = { id: 1, @@ -103,9 +103,9 @@ describe("LibBridgeInvoke", function () { gasLimit: 300000, data: data, memo: "", - } + }; - const signal = await libData.hashMessage(message) + const signal = await libData.hashMessage(message); await expect( libInvoke.invokeMessageCall(message, signal, message.gasLimit, { @@ -113,7 +113,7 @@ describe("LibBridgeInvoke", function () { }) ) .to.emit(libInvoke, "MessageInvoked") - .withArgs(signal, true) - }) - }) -}) + .withArgs(signal, true); + }); + }); +}); diff --git a/packages/protocol/test/bridge/libs/LibBridgeProcess.test.ts b/packages/protocol/test/bridge/libs/LibBridgeProcess.test.ts index 1e984c4481f..7b197db18a0 100644 --- a/packages/protocol/test/bridge/libs/LibBridgeProcess.test.ts +++ b/packages/protocol/test/bridge/libs/LibBridgeProcess.test.ts @@ -1,89 +1,91 @@ -import * as helpers from "@nomicfoundation/hardhat-network-helpers" -import { expect } from "chai" -import hre, { ethers } from "hardhat" -import * as fs from "fs" -import * as path from "path" -import { getSlot, MessageStatus } from "../../../tasks/utils" -import { Message } from "../../utils/message" +import * as helpers from "@nomicfoundation/hardhat-network-helpers"; +import { expect } from "chai"; +import hre, { ethers } from "hardhat"; +import * as fs from "fs"; +import * as path from "path"; +import { getSlot, MessageStatus } from "../../../tasks/utils"; +import { Message } from "../../utils/message"; import { AddressManager, EtherVault, TestLibBridgeData, TestLibBridgeProcess, -} from "../../../typechain" +} from "../../../typechain"; describe("LibBridgeProcess", async function () { function getStateSlot() { const buildInfoDir = path.join( __dirname, "../../../artifacts/build-info" - ) + ); const contractPath = - "contracts/test/bridge/libs/TestLibBridgeProcess.sol" - const contractName = "TestLibBridgeProcess" + "contracts/test/bridge/libs/TestLibBridgeProcess.sol"; + const contractName = "TestLibBridgeProcess"; for (const buildInfoJson of fs.readdirSync(buildInfoDir)) { - const { output } = require(path.join(buildInfoDir, buildInfoJson)) + const { output } = require(path.join(buildInfoDir, buildInfoJson)); - if (!output.contracts[contractPath]) continue + if (!output.contracts[contractPath]) continue; const slotInfo = output.contracts[contractPath][ contractName - ].storageLayout.storage.find(({ label }: any) => label === "state") + ].storageLayout.storage.find(({ label }: any) => label === "state"); - if (slotInfo) return Number(slotInfo.slot) + if (slotInfo) return Number(slotInfo.slot); } - throw new Error("TestLibBridgeProcess.state slot number not found") + throw new Error("TestLibBridgeProcess.state slot number not found"); } - let owner: any - let nonOwner: any - let etherVaultOwner: any - let addressManager: AddressManager - let etherVault: EtherVault - let libTrieLink - let libProcessLink - let libProcess: TestLibBridgeProcess - let testLibData: TestLibBridgeData - const stateSlot = getStateSlot() - const srcChainId = 1 - const blockChainId = hre.network.config.chainId ?? 0 + let owner: any; + let nonOwner: any; + let etherVaultOwner: any; + let addressManager: AddressManager; + let etherVault: EtherVault; + let libTrieLink; + let libProcessLink; + let libProcess: TestLibBridgeProcess; + let testLibData: TestLibBridgeData; + const stateSlot = getStateSlot(); + const srcChainId = 1; + const blockChainId = hre.network.config.chainId ?? 0; before(async function () { - ;[owner, nonOwner, etherVaultOwner] = await ethers.getSigners() - }) + [owner, nonOwner, etherVaultOwner] = await ethers.getSigners(); + }); beforeEach(async function () { addressManager = await ( await ethers.getContractFactory("AddressManager") - ).deploy() - await addressManager.init() + ).deploy(); + await addressManager.init(); etherVault = await (await ethers.getContractFactory("EtherVault")) .connect(etherVaultOwner) - .deploy() + .deploy(); - await etherVault.deployed() + await etherVault.deployed(); - await etherVault.init(addressManager.address) + await etherVault.init(addressManager.address); - await etherVault.connect(etherVaultOwner).authorize(owner.address, true) - const blockChainId = hre.network.config.chainId ?? 0 + await etherVault + .connect(etherVaultOwner) + .authorize(owner.address, true); + const blockChainId = hre.network.config.chainId ?? 0; await addressManager.setAddress( `${blockChainId}.ether_vault`, etherVault.address - ) + ); // Sends initial value of 10 ether to EtherVault for receiveEther calls await owner.sendTransaction({ to: etherVault.address, value: ethers.utils.parseEther("10.0"), - }) + }); libTrieLink = await (await ethers.getContractFactory("LibTrieProof")) .connect(owner) - .deploy() - await libTrieLink.deployed() + .deploy(); + await libTrieLink.deployed(); libProcessLink = await ( await ethers.getContractFactory("LibBridgeProcess", { @@ -93,8 +95,8 @@ describe("LibBridgeProcess", async function () { }) ) .connect(owner) - .deploy() - await libProcessLink.deployed() + .deploy(); + await libProcessLink.deployed(); libProcess = await ( await ethers.getContractFactory("TestLibBridgeProcess", { @@ -104,18 +106,18 @@ describe("LibBridgeProcess", async function () { }) ) .connect(owner) - .deploy() + .deploy(); - await libProcess.init(addressManager.address) + await libProcess.init(addressManager.address); testLibData = await ( await ethers.getContractFactory("TestLibBridgeData") - ).deploy() + ).deploy(); await etherVault .connect(etherVaultOwner) - .authorize(libProcess.address, true) - }) + .authorize(libProcess.address, true); + }); describe("processMessage()", async function () { it("should throw if gaslimit == 0 & msg.sender != message.owner", async function () { @@ -133,14 +135,14 @@ describe("LibBridgeProcess", async function () { gasLimit: 0, data: ethers.constants.HashZero, memo: "", - } + }; await expect( libProcess.processMessage(message, ethers.constants.HashZero) - ).to.be.revertedWith("B:forbidden") - }) + ).to.be.revertedWith("B:forbidden"); + }); it("should throw if message.destChain != block.chainId", async function () { - const badBlockChainId = blockChainId + 1 + const badBlockChainId = blockChainId + 1; const message: Message = { id: 1, sender: nonOwner.address, @@ -155,11 +157,11 @@ describe("LibBridgeProcess", async function () { gasLimit: 100000000, data: ethers.constants.HashZero, memo: "", - } + }; await expect( libProcess.processMessage(message, ethers.constants.HashZero) - ).to.be.revertedWith("B:destChainId") - }) + ).to.be.revertedWith("B:destChainId"); + }); it("should throw if message's status is not NEW", async function () { const message: Message = { @@ -176,20 +178,20 @@ describe("LibBridgeProcess", async function () { gasLimit: 100000000, data: ethers.constants.HashZero, memo: "", - } + }; - const signal = await testLibData.hashMessage(message) + const signal = await testLibData.hashMessage(message); await helpers.setStorageAt( libProcess.address, await getSlot(hre, signal, stateSlot + 1), MessageStatus.RETRIABLE - ) + ); await expect( libProcess.processMessage(message, ethers.constants.HashZero) - ).to.be.revertedWith("B:status") - }) + ).to.be.revertedWith("B:status"); + }); // Remaining test cases require integration, will be covered in Bridge.test.ts - }) -}) + }); +}); diff --git a/packages/protocol/test/bridge/libs/LibBridgeRetry.test.ts b/packages/protocol/test/bridge/libs/LibBridgeRetry.test.ts index f336e097b5d..59bc5e3a26e 100644 --- a/packages/protocol/test/bridge/libs/LibBridgeRetry.test.ts +++ b/packages/protocol/test/bridge/libs/LibBridgeRetry.test.ts @@ -1,8 +1,8 @@ -import * as helpers from "@nomicfoundation/hardhat-network-helpers" -import { expect } from "chai" -import hre, { ethers } from "hardhat" -import { Message } from "../../utils/message" -import { getSlot, decode, MessageStatus } from "../../../tasks/utils" +import * as helpers from "@nomicfoundation/hardhat-network-helpers"; +import { expect } from "chai"; +import hre, { ethers } from "hardhat"; +import { Message } from "../../utils/message"; +import { getSlot, decode, MessageStatus } from "../../../tasks/utils"; import { AddressManager, EtherVault, @@ -10,63 +10,65 @@ import { TestLibBridgeData, TestLibBridgeRetry, TestReceiver, -} from "../../../typechain" +} from "../../../typechain"; describe("LibBridgeRetry", function () { - let owner: any - let nonOwner: any - let refundAddress: any - let etherVaultOwner: any - let etherVault: EtherVault - let libRetry: TestLibBridgeRetry - let badLibRetry: TestLibBridgeRetry - let testLibData: TestLibBridgeData + let owner: any; + let nonOwner: any; + let refundAddress: any; + let etherVaultOwner: any; + let etherVault: EtherVault; + let libRetry: TestLibBridgeRetry; + let badLibRetry: TestLibBridgeRetry; + let testLibData: TestLibBridgeData; before(async function () { - ;[owner, nonOwner, refundAddress, etherVaultOwner] = - await ethers.getSigners() - }) + [owner, nonOwner, refundAddress, etherVaultOwner] = + await ethers.getSigners(); + }); beforeEach(async function () { const addressManager: AddressManager = await ( await ethers.getContractFactory("AddressManager") - ).deploy() - await addressManager.init() + ).deploy(); + await addressManager.init(); const badAddressManager: AddressManager = await ( await ethers.getContractFactory("AddressManager") - ).deploy() - await badAddressManager.init() + ).deploy(); + await badAddressManager.init(); etherVault = await (await ethers.getContractFactory("EtherVault")) .connect(etherVaultOwner) - .deploy() + .deploy(); - await etherVault.deployed() + await etherVault.deployed(); - await etherVault.init(addressManager.address) + await etherVault.init(addressManager.address); - await etherVault.connect(etherVaultOwner).authorize(owner.address, true) - const blockChainId = hre.network.config.chainId ?? 0 + await etherVault + .connect(etherVaultOwner) + .authorize(owner.address, true); + const blockChainId = hre.network.config.chainId ?? 0; await addressManager.setAddress( `${blockChainId}.ether_vault`, etherVault.address - ) + ); await badAddressManager.setAddress( `${blockChainId}.ether_vault`, ethers.constants.AddressZero - ) + ); await owner.sendTransaction({ to: etherVault.address, value: ethers.utils.parseEther("10.0"), - }) + }); const libRetryLink = await ( await ethers.getContractFactory("LibBridgeRetry") - ).deploy() - await libRetryLink.deployed() + ).deploy(); + await libRetryLink.deployed(); const libRetryFactory = await ( await ethers.getContractFactory("TestLibBridgeRetry", { @@ -74,24 +76,24 @@ describe("LibBridgeRetry", function () { LibBridgeRetry: libRetryLink.address, }, }) - ).connect(owner) + ).connect(owner); - libRetry = await libRetryFactory.deploy() - await libRetry.init(addressManager.address) - await libRetry.deployed() + libRetry = await libRetryFactory.deploy(); + await libRetry.init(addressManager.address); + await libRetry.deployed(); - badLibRetry = await libRetryFactory.deploy() - await badLibRetry.init(badAddressManager.address) - await badLibRetry.deployed() + badLibRetry = await libRetryFactory.deploy(); + await badLibRetry.init(badAddressManager.address); + await badLibRetry.deployed(); await etherVault .connect(etherVaultOwner) - .authorize(libRetry.address, true) + .authorize(libRetry.address, true); testLibData = await ( await ethers.getContractFactory("TestLibBridgeData") - ).deploy() - }) + ).deploy(); + }); describe("retryMessage()", async function () { it("should throw if message.gaslimit == 0 && msg.sender != message.owner", async function () { @@ -109,12 +111,12 @@ describe("LibBridgeRetry", function () { gasLimit: 0, data: ethers.constants.HashZero, memo: "", - } + }; await expect( libRetry.retryMessage(message, false) - ).to.be.revertedWith("B:denied") - }) + ).to.be.revertedWith("B:denied"); + }); it("should throw if lastAttempt == true && msg.sender != message.owner", async function () { const message: Message = { @@ -131,12 +133,12 @@ describe("LibBridgeRetry", function () { gasLimit: 1000000, data: ethers.constants.HashZero, memo: "", - } + }; await expect( libRetry.retryMessage(message, true) - ).to.be.revertedWith("B:denied") - }) + ).to.be.revertedWith("B:denied"); + }); it("should throw if message status is not RETRIABLE", async function () { const message: Message = { @@ -153,21 +155,21 @@ describe("LibBridgeRetry", function () { gasLimit: 300000, data: ethers.constants.HashZero, memo: "", - } + }; await expect( libRetry.retryMessage(message, false) - ).to.be.revertedWith("B:notFound") - }) + ).to.be.revertedWith("B:notFound"); + }); it("if etherVault resolves to address(0), retry should fail and messageStatus should not change if not lastAttempt since no ether received", async function () { const testReceiver: TestReceiver = await ( await ethers.getContractFactory("TestReceiver") - ).deploy() + ).deploy(); - await testReceiver.deployed() + await testReceiver.deployed(); - const destChainId = 5 + const destChainId = 5; const message: Message = { id: 1, sender: owner.address, @@ -182,19 +184,19 @@ describe("LibBridgeRetry", function () { gasLimit: 1, data: ethers.constants.HashZero, memo: "", - } + }; - const signal = await testLibData.hashMessage(message) + const signal = await testLibData.hashMessage(message); await helpers.setStorageAt( badLibRetry.address, await getSlot(hre, signal, 202), MessageStatus.RETRIABLE - ) + ); - const originalToBalance = await testReceiver.getBalance() - await badLibRetry.retryMessage(message, false) - const newToBalance = await testReceiver.getBalance() + const originalToBalance = await testReceiver.getBalance(); + await badLibRetry.retryMessage(message, false); + const newToBalance = await testReceiver.getBalance(); expect( await decode( hre, @@ -204,19 +206,19 @@ describe("LibBridgeRetry", function () { getSlot(hre, signal, 202) ) ) - ).to.equal(MessageStatus.RETRIABLE.toString()) + ).to.equal(MessageStatus.RETRIABLE.toString()); - expect(newToBalance).to.be.equal(originalToBalance) - }) + expect(newToBalance).to.be.equal(originalToBalance); + }); it("should fail, but since lastAttempt == true messageStatus should be set to DONE", async function () { const testBadReceiver: TestBadReceiver = await ( await ethers.getContractFactory("TestBadReceiver") - ).deploy() + ).deploy(); - await testBadReceiver.deployed() + await testBadReceiver.deployed(); - const destChainId = 5 + const destChainId = 5; const message: Message = { id: 1, sender: owner.address, @@ -231,19 +233,19 @@ describe("LibBridgeRetry", function () { gasLimit: 300000, data: ethers.constants.HashZero, memo: "", - } + }; - const signal = await testLibData.hashMessage(message) + const signal = await testLibData.hashMessage(message); await helpers.setStorageAt( libRetry.address, await getSlot(hre, signal, 202), MessageStatus.RETRIABLE - ) + ); - const originalBalance = await refundAddress.getBalance() - await libRetry.retryMessage(message, true) - const balancePlusRefund = await refundAddress.getBalance() + const originalBalance = await refundAddress.getBalance(); + await libRetry.retryMessage(message, true); + const balancePlusRefund = await refundAddress.getBalance(); expect( await decode( @@ -254,21 +256,21 @@ describe("LibBridgeRetry", function () { getSlot(hre, signal, 202) ) ) - ).to.equal(MessageStatus.FAILED.toString()) + ).to.equal(MessageStatus.FAILED.toString()); expect(balancePlusRefund).to.be.equal( originalBalance.add(message.callValue) - ) - }) + ); + }); it("should fail, messageStatus is still RETRIABLE and balance is returned to etherVault", async function () { const testBadReceiver: TestBadReceiver = await ( await ethers.getContractFactory("TestBadReceiver") - ).deploy() + ).deploy(); - await testBadReceiver.deployed() + await testBadReceiver.deployed(); - const destChainId = 5 + const destChainId = 5; const message: Message = { id: 1, sender: owner.address, @@ -283,23 +285,23 @@ describe("LibBridgeRetry", function () { gasLimit: 300000, data: ethers.constants.HashZero, memo: "", - } + }; - const signal = await testLibData.hashMessage(message) + const signal = await testLibData.hashMessage(message); await helpers.setStorageAt( libRetry.address, await getSlot(hre, signal, 202), MessageStatus.RETRIABLE - ) + ); const originalBalance = await ethers.provider.getBalance( etherVault.address - ) - await libRetry.retryMessage(message, false) + ); + await libRetry.retryMessage(message, false); const balancePlusRefund = await ethers.provider.getBalance( etherVault.address - ) + ); expect( await decode( @@ -310,19 +312,19 @@ describe("LibBridgeRetry", function () { getSlot(hre, signal, 202) ) ) - ).to.equal(MessageStatus.RETRIABLE.toString()) + ).to.equal(MessageStatus.RETRIABLE.toString()); - expect(balancePlusRefund).to.be.equal(originalBalance) - }) + expect(balancePlusRefund).to.be.equal(originalBalance); + }); it("should succeed, set message status to done, invoke message succesfsully", async function () { const testReceiver: TestReceiver = await ( await ethers.getContractFactory("TestReceiver") - ).deploy() + ).deploy(); - await testReceiver.deployed() + await testReceiver.deployed(); - const destChainId = 5 + const destChainId = 5; const message: Message = { id: 1, sender: owner.address, @@ -337,19 +339,19 @@ describe("LibBridgeRetry", function () { gasLimit: 1, data: ethers.constants.HashZero, memo: "", - } + }; - const signal = await testLibData.hashMessage(message) + const signal = await testLibData.hashMessage(message); await helpers.setStorageAt( libRetry.address, await getSlot(hre, signal, 202), MessageStatus.RETRIABLE - ) + ); - const originalToBalance = await testReceiver.getBalance() - await libRetry.retryMessage(message, true) - const newToBalance = await testReceiver.getBalance() + const originalToBalance = await testReceiver.getBalance(); + await libRetry.retryMessage(message, true); + const newToBalance = await testReceiver.getBalance(); expect( await decode( @@ -360,11 +362,11 @@ describe("LibBridgeRetry", function () { getSlot(hre, signal, 202) ) ) - ).to.equal(MessageStatus.DONE.toString()) + ).to.equal(MessageStatus.DONE.toString()); expect(newToBalance).to.be.equal( originalToBalance.add(message.callValue) - ) - }) - }) -}) + ); + }); + }); +}); diff --git a/packages/protocol/test/bridge/libs/LibBridgeSend.test.ts b/packages/protocol/test/bridge/libs/LibBridgeSend.test.ts index 8a80bf22b18..ffc897beb57 100644 --- a/packages/protocol/test/bridge/libs/LibBridgeSend.test.ts +++ b/packages/protocol/test/bridge/libs/LibBridgeSend.test.ts @@ -1,79 +1,79 @@ -import { expect } from "chai" -import hre, { ethers } from "hardhat" +import { expect } from "chai"; +import hre, { ethers } from "hardhat"; import { AddressManager, TestLibBridgeSend, EtherVault, -} from "../../../typechain" -import { Message } from "../../utils/message" +} from "../../../typechain"; +import { Message } from "../../utils/message"; describe("LibBridgeSend", function () { - let owner: any - let nonOwner: any - let etherVaultOwner: any - let libSend: TestLibBridgeSend - let blockChainId: number - const enabledDestChainId = 100 - const srcChainId = 1 + let owner: any; + let nonOwner: any; + let etherVaultOwner: any; + let libSend: TestLibBridgeSend; + let blockChainId: number; + const enabledDestChainId = 100; + const srcChainId = 1; before(async function () { - ;[owner, nonOwner, etherVaultOwner] = await ethers.getSigners() - blockChainId = hre.network.config.chainId ?? 0 - }) + [owner, nonOwner, etherVaultOwner] = await ethers.getSigners(); + blockChainId = hre.network.config.chainId ?? 0; + }); beforeEach(async function () { const addressManager: AddressManager = await ( await ethers.getContractFactory("AddressManager") - ).deploy() - await addressManager.init() + ).deploy(); + await addressManager.init(); const etherVault: EtherVault = await ( await ethers.getContractFactory("EtherVault") ) .connect(etherVaultOwner) - .deploy() + .deploy(); - await etherVault.deployed() - await etherVault.init(addressManager.address) + await etherVault.deployed(); + await etherVault.init(addressManager.address); await addressManager.setAddress( `${blockChainId}.ether_vault`, etherVault.address - ) + ); libSend = await (await ethers.getContractFactory("TestLibBridgeSend")) .connect(owner) - .deploy() + .deploy(); - await libSend.init(addressManager.address) + await libSend.init(addressManager.address); await etherVault .connect(etherVaultOwner) - .authorize(libSend.address, true) - }) + .authorize(libSend.address, true); + }); describe("enableDestChain()", async function () { it("should throw when chainId <= 0", async function () { await expect(libSend.enableDestChain(0, true)).to.be.revertedWith( "B:chainId" - ) - }) + ); + }); it("should throw when chainId == block.chainId", async function () { await expect( libSend.enableDestChain(blockChainId, true) - ).to.be.revertedWith("B:chainId") - }) + ).to.be.revertedWith("B:chainId"); + }); it("should emit DestChainEnabled() event", async function () { expect( await libSend.enableDestChain(enabledDestChainId, true) - ).to.emit(libSend, "DestChainEnabled") - }) - }) + ).to.emit(libSend, "DestChainEnabled"); + }); + }); describe("sendMessage()", async function () { it("should throw when message.owner == address(0)", async function () { - const nonEnabledDestChain = 2 + const nonEnabledDestChain = 2; const message: Message = { id: 1, @@ -89,12 +89,12 @@ describe("LibBridgeSend", function () { gasLimit: 100, data: ethers.constants.HashZero, memo: "", - } + }; await expect(libSend.sendMessage(message)).to.be.revertedWith( "B:owner" - ) - }) + ); + }); it("should throw when destchainId == block.chainId", async function () { const message: Message = { @@ -111,15 +111,15 @@ describe("LibBridgeSend", function () { gasLimit: 100, data: ethers.constants.HashZero, memo: "", - } + }; await expect(libSend.sendMessage(message)).to.be.revertedWith( "B:destChainId" - ) - }) + ); + }); it("should throw when destChainId has not yet been enabled", async function () { - const nonEnabledDestChain = 2 + const nonEnabledDestChain = 2; const message: Message = { id: 1, @@ -135,15 +135,15 @@ describe("LibBridgeSend", function () { gasLimit: 100, data: ethers.constants.HashZero, memo: "", - } + }; await expect(libSend.sendMessage(message)).to.be.revertedWith( "B:destChainId" - ) - }) + ); + }); it("should throw when expectedAmount != msg.value", async function () { - await libSend.enableDestChain(enabledDestChainId, true) + await libSend.enableDestChain(enabledDestChainId, true); const message: Message = { id: 1, @@ -159,15 +159,15 @@ describe("LibBridgeSend", function () { gasLimit: 100, data: ethers.constants.HashZero, memo: "", - } + }; await expect(libSend.sendMessage(message)).to.be.revertedWith( "B:value" - ) - }) + ); + }); it("should emit MessageSent() event and signal should be hashed correctly", async function () { - await libSend.enableDestChain(enabledDestChainId, true) + await libSend.enableDestChain(enabledDestChainId, true); const message: Message = { id: 1, @@ -183,16 +183,18 @@ describe("LibBridgeSend", function () { gasLimit: 100, data: ethers.constants.HashZero, memo: "", - } + }; const expectedAmount = - message.depositValue + message.callValue + message.processingFee + message.depositValue + + message.callValue + + message.processingFee; expect( await libSend.sendMessage(message, { value: expectedAmount, }) - ).to.emit(libSend, "MessageSent") - }) - }) -}) + ).to.emit(libSend, "MessageSent"); + }); + }); +}); diff --git a/packages/protocol/test/bridge/libs/LibBridgeSignal.test.ts b/packages/protocol/test/bridge/libs/LibBridgeSignal.test.ts index 7afefb24c6b..3282a0cffd7 100644 --- a/packages/protocol/test/bridge/libs/LibBridgeSignal.test.ts +++ b/packages/protocol/test/bridge/libs/LibBridgeSignal.test.ts @@ -1,17 +1,17 @@ -import { expect } from "chai" -import { ethers } from "hardhat" -import { TestLibBridgeData, TestLibBridgeSignal } from "../../../typechain" -import { Message } from "../../utils/message" +import { expect } from "chai"; +import { ethers } from "hardhat"; +import { TestLibBridgeData, TestLibBridgeSignal } from "../../../typechain"; +import { Message } from "../../utils/message"; describe("LibBridgeSignal", function () { - let owner: any - let nonOwner: any - let testMessage: Message - let libData: TestLibBridgeData - let libSignal: TestLibBridgeSignal + let owner: any; + let nonOwner: any; + let testMessage: Message; + let libData: TestLibBridgeData; + let libSignal: TestLibBridgeSignal; before(async function () { - ;[owner, nonOwner] = await ethers.getSigners() + [owner, nonOwner] = await ethers.getSigners(); testMessage = { id: 1, @@ -27,44 +27,44 @@ describe("LibBridgeSignal", function () { gasLimit: 0, data: ethers.constants.HashZero, memo: "", - } - }) + }; + }); beforeEach(async function () { libData = await ( await ethers.getContractFactory("TestLibBridgeData") - ).deploy() + ).deploy(); libSignal = await ( await ethers.getContractFactory("TestLibBridgeSignal") - ).deploy() - }) + ).deploy(); + }); describe("sendSignal()", async function () { it("throws when sender is zero address", async function () { - const signal = await libData.hashMessage(testMessage) + const signal = await libData.hashMessage(testMessage); await expect( libSignal.sendSignal(ethers.constants.AddressZero, signal) - ).to.revertedWith("B:sender") - }) + ).to.revertedWith("B:sender"); + }); it("throws when signal is zero", async function () { await expect( libSignal.sendSignal(owner.address, ethers.constants.HashZero) - ).to.be.revertedWith("B:signal") - }) - }) + ).to.be.revertedWith("B:signal"); + }); + }); describe("isSignalSent()", async function () { it("properly sent signal should change storage value", async function () { - const signal = await libData.hashMessage(testMessage) + const signal = await libData.hashMessage(testMessage); - await libSignal.sendSignal(owner.address, signal) + await libSignal.sendSignal(owner.address, signal); expect(await libSignal.isSignalSent(owner.address, signal)).to.eq( true - ) - }) - }) -}) + ); + }); + }); +}); diff --git a/packages/protocol/test/constants/errors.ts b/packages/protocol/test/constants/errors.ts index ce6034582e5..d419bc93a0d 100644 --- a/packages/protocol/test/constants/errors.ts +++ b/packages/protocol/test/constants/errors.ts @@ -1,8 +1,8 @@ -const ADDRESS_RESOLVER_DENIED = "AR:denied" -const ERC20_BURN_AMOUNT_EXCEEDED = "ERC20: burn amount exceeds balance" -const ERC20_TRANSFER_AMOUNT_EXCEEDED = "ERC20: transfer amount exceeds balance" +const ADDRESS_RESOLVER_DENIED = "AR:denied"; +const ERC20_BURN_AMOUNT_EXCEEDED = "ERC20: burn amount exceeds balance"; +const ERC20_TRANSFER_AMOUNT_EXCEEDED = "ERC20: transfer amount exceeds balance"; export { ADDRESS_RESOLVER_DENIED, ERC20_BURN_AMOUNT_EXCEEDED, ERC20_TRANSFER_AMOUNT_EXCEEDED, -} +}; diff --git a/packages/protocol/test/constants/messages.ts b/packages/protocol/test/constants/messages.ts index c6880c6fd00..c519885a5e4 100644 --- a/packages/protocol/test/constants/messages.ts +++ b/packages/protocol/test/constants/messages.ts @@ -1,3 +1,3 @@ -const K_BRIDGE_MESSAGE = "TAIKO_BRIDGE_MESSAGE" +const K_BRIDGE_MESSAGE = "TAIKO_BRIDGE_MESSAGE"; -export { K_BRIDGE_MESSAGE } +export { K_BRIDGE_MESSAGE }; diff --git a/packages/protocol/test/genesis/generate_genesis.test.ts b/packages/protocol/test/genesis/generate_genesis.test.ts index ca94efa9d7a..d7721e37cc5 100644 --- a/packages/protocol/test/genesis/generate_genesis.test.ts +++ b/packages/protocol/test/genesis/generate_genesis.test.ts @@ -1,184 +1,184 @@ -import { expect } from "chai" -import * as hre from "hardhat" +import { expect } from "chai"; +import * as hre from "hardhat"; -const ethers = hre.ethers -const action = process.env.TEST_L2_GENESIS ? describe : describe.skip +const ethers = hre.ethers; +const action = process.env.TEST_L2_GENESIS ? describe : describe.skip; action("Generate Genesis", function () { - let alloc: any = null + let alloc: any = null; if (process.env.TEST_L2_GENESIS) { - alloc = require("../../deployments/genesis_alloc.json") + alloc = require("../../deployments/genesis_alloc.json"); } const provider = new hre.ethers.providers.JsonRpcProvider( "http://localhost:18545" - ) + ); const signer = new hre.ethers.Wallet( "2bdd21761a483f71054e14f5b827213567971c676928d9a1808cbfa4b7501200", provider - ) + ); - const testConfig = require("./test_config") + const testConfig = require("./test_config"); - const seedAccounts = testConfig.seedAccounts + const seedAccounts = testConfig.seedAccounts; before(async () => { - let retry = 0 + let retry = 0; while (true) { try { - const network = await provider.getNetwork() - if (network.chainId) break + const network = await provider.getNetwork(); + if (network.chainId) break; } catch (_) {} if (++retry > 10) { - throw new Error("geth initializing timeout") + throw new Error("geth initializing timeout"); } - await sleep(1000) + await sleep(1000); } - console.log("geth initialized") - }) + console.log("geth initialized"); + }); it("contracts should be deployed", async function () { for (const address of Object.keys(alloc)) { if ( seedAccounts .map((seedAccount: any) => { - const accountAddress = Object.keys(seedAccount)[0] - return accountAddress + const accountAddress = Object.keys(seedAccount)[0]; + return accountAddress; }) .includes(address) ) { - continue + continue; } - const code: string = await provider.getCode(address) - const expectCode: string = alloc[address].code + const code: string = await provider.getCode(address); + const expectCode: string = alloc[address].code; - expect(code.toLowerCase()).to.be.equal(expectCode.toLowerCase()) + expect(code.toLowerCase()).to.be.equal(expectCode.toLowerCase()); if (testConfig.contractAddresses[alloc[address].contractName]) { expect(address).to.be.equal( testConfig.contractAddresses[alloc[address].contractName] - ) + ); } } - }) + }); it("premint ETH should be allocated", async function () { - let etherVaultBalance = hre.ethers.BigNumber.from("2").pow(128).sub(1) // MaxUint128 + let etherVaultBalance = hre.ethers.BigNumber.from("2").pow(128).sub(1); // MaxUint128 for (const seedAccount of seedAccounts) { - const accountAddress = Object.keys(seedAccount)[0] + const accountAddress = Object.keys(seedAccount)[0]; const balance = hre.ethers.utils.parseEther( `${Object.values(seedAccount)[0]}` - ) + ); expect(await provider.getBalance(accountAddress)).to.be.equal( balance.toHexString() - ) + ); - etherVaultBalance = etherVaultBalance.sub(balance) + etherVaultBalance = etherVaultBalance.sub(balance); } - const etherVaultAddress = getContractAlloc("EtherVault").address + const etherVaultAddress = getContractAlloc("EtherVault").address; expect(await provider.getBalance(etherVaultAddress)).to.be.equal( etherVaultBalance.toHexString() - ) - }) + ); + }); describe("contracts can be called normally", function () { it("AddressManager", async function () { - const addressManagerAlloc = getContractAlloc("AddressManager") + const addressManagerAlloc = getContractAlloc("AddressManager"); const addressManager = new hre.ethers.Contract( addressManagerAlloc.address, require("../../artifacts/contracts/thirdparty/AddressManager.sol/AddressManager.json").abi, provider - ) + ); - const owner = await addressManager.owner() + const owner = await addressManager.owner(); - expect(owner).to.be.equal(testConfig.contractOwner) + expect(owner).to.be.equal(testConfig.contractOwner); const bridge = await addressManager.getAddress( `${testConfig.chainId}.bridge` - ) + ); - expect(bridge).to.be.equal(getContractAlloc("Bridge").address) + expect(bridge).to.be.equal(getContractAlloc("Bridge").address); const tokenValut = await addressManager.getAddress( `${testConfig.chainId}.token_vault` - ) + ); expect(tokenValut).to.be.equal( getContractAlloc("TokenVault").address - ) + ); const etherVault = await addressManager.getAddress( `${testConfig.chainId}.ether_vault` - ) + ); expect(etherVault).to.be.equal( getContractAlloc("EtherVault").address - ) + ); const taikoL2 = await addressManager.getAddress( `${testConfig.chainId}.taiko` - ) + ); - expect(taikoL2).to.be.equal(getContractAlloc("TaikoL2").address) - }) + expect(taikoL2).to.be.equal(getContractAlloc("TaikoL2").address); + }); it("LibTxDecoder", async function () { - const LibTxDecoderAlloc = getContractAlloc("LibTxDecoder") + const LibTxDecoderAlloc = getContractAlloc("LibTxDecoder"); const LibTxDecoder = new hre.ethers.Contract( LibTxDecoderAlloc.address, require("../../artifacts/contracts/libs/LibTxDecoder.sol/LibTxDecoder.json").abi, signer - ) + ); const decoded = await LibTxDecoder.callStatic.decodeTxList( ethers.utils.RLP.encode([]) - ) + ); - expect(decoded.items.length).to.be.eql(0) - }) + expect(decoded.items.length).to.be.eql(0); + }); it("TaikoL2", async function () { - const TaikoL2Alloc = getContractAlloc("TaikoL2") + const TaikoL2Alloc = getContractAlloc("TaikoL2"); const TaikoL2 = new hre.ethers.Contract( TaikoL2Alloc.address, require("../../artifacts/contracts/L2/TaikoL2.sol/TaikoL2.json").abi, signer - ) + ); - let latestL1Height = 1 + let latestL1Height = 1; for (let i = 0; i < 300; i++) { const tx = await TaikoL2.anchor( latestL1Height++, ethers.utils.hexlify(ethers.utils.randomBytes(32)), { gasLimit: 1000000 } - ) + ); - const receipt = await tx.wait() + const receipt = await tx.wait(); - expect(receipt.status).to.be.equal(1) + expect(receipt.status).to.be.equal(1); if (i === 299) { console.log({ message: "TaikoL2.anchor gas cost after 256 L2 blocks", gasUsed: receipt.gasUsed, - }) + }); } } - const [bytes, txNums] = await generateMaxSizeInvalidTxList(TaikoL2) + const [bytes, txNums] = await generateMaxSizeInvalidTxList(TaikoL2); await expect( TaikoL2.invalidateBlock( @@ -202,11 +202,11 @@ action("Generate Genesis", function () { 5, // hint: TX_INVALID_SIG 0, { gasPrice: 0 } - ) + ); - const receipt = await tx.wait() + const receipt = await tx.wait(); - expect(receipt.status).to.be.equal(1) + expect(receipt.status).to.be.equal(1); console.log({ message: "TaikoL2.invalidateBlock gas cost after 256 L2 blocks", @@ -214,22 +214,22 @@ action("Generate Genesis", function () { txNums, reason: "TX_INVALID_SIG", gasUsed: receipt.gasUsed, - }) - }) + }); + }); it("Bridge", async function () { - const BridgeAlloc = getContractAlloc("Bridge") + const BridgeAlloc = getContractAlloc("Bridge"); const Bridge = new hre.ethers.Contract( BridgeAlloc.address, require("../../artifacts/contracts/bridge/Bridge.sol/Bridge.json").abi, signer - ) + ); - const owner = await Bridge.owner() + const owner = await Bridge.owner(); - expect(owner).to.be.equal(testConfig.contractOwner) + expect(owner).to.be.equal(testConfig.contractOwner); - await expect(Bridge.enableDestChain(1, true)).not.to.reverted + await expect(Bridge.enableDestChain(1, true)).not.to.reverted; await expect( Bridge.processMessage( @@ -250,20 +250,20 @@ action("Generate Genesis", function () { }, ethers.utils.randomBytes(1024) ) - ).to.be.revertedWith("B:forbidden") - }) + ).to.be.revertedWith("B:forbidden"); + }); it("TokenVault", async function () { - const TokenVaultAlloc = getContractAlloc("TokenVault") + const TokenVaultAlloc = getContractAlloc("TokenVault"); const TokenVault = new hre.ethers.Contract( TokenVaultAlloc.address, require("../../artifacts/contracts/bridge/TokenVault.sol/TokenVault.json").abi, signer - ) + ); - const owner = await TokenVault.owner() + const owner = await TokenVault.owner(); - expect(owner).to.be.equal(testConfig.contractOwner) + expect(owner).to.be.equal(testConfig.contractOwner); await expect( TokenVault.sendEther( @@ -278,84 +278,84 @@ action("Generate Genesis", function () { value: hre.ethers.utils.parseEther("100"), } ) - ).to.emit(TokenVault, "EtherSent") - }) + ).to.emit(TokenVault, "EtherSent"); + }); it("EtherVault", async function () { const EtherVault = new hre.ethers.Contract( getContractAlloc("EtherVault").address, require("../../artifacts/contracts/bridge/EtherVault.sol/EtherVault.json").abi, signer - ) + ); - const owner = await EtherVault.owner() + const owner = await EtherVault.owner(); - expect(owner).to.be.equal(testConfig.contractOwner) + expect(owner).to.be.equal(testConfig.contractOwner); expect( await EtherVault.isAuthorized( getContractAlloc("Bridge").address ) - ).to.be.true + ).to.be.true; expect( await EtherVault.isAuthorized( ethers.Wallet.createRandom().address ) - ).to.be.false - }) + ).to.be.false; + }); it("ERC20", async function () { const ERC20 = new hre.ethers.Contract( getContractAlloc("TestERC20").address, require("../../artifacts/contracts/test/thirdparty/TestERC20.sol/TestERC20.json").abi, signer - ) + ); const { TOKEN_NAME, TOKEN_SYMBOL, PREMINT_SEED_ACCOUNT_BALANCE, - } = require("../../utils/generate_genesis/erc20") + } = require("../../utils/generate_genesis/erc20"); - expect(await ERC20.name()).to.be.equal(TOKEN_NAME) - expect(await ERC20.symbol()).to.be.equal(TOKEN_SYMBOL) + expect(await ERC20.name()).to.be.equal(TOKEN_NAME); + expect(await ERC20.symbol()).to.be.equal(TOKEN_SYMBOL); for (const seedAccount of seedAccounts) { - const accountAddress = Object.keys(seedAccount)[0] + const accountAddress = Object.keys(seedAccount)[0]; expect(await ERC20.balanceOf(accountAddress)).to.be.equal( PREMINT_SEED_ACCOUNT_BALANCE - ) + ); } expect(await ERC20.totalSupply()).to.be.equal( seedAccounts.length * PREMINT_SEED_ACCOUNT_BALANCE - ) + ); await expect( ERC20.transfer(ethers.Wallet.createRandom().address, 1) - ).to.emit(ERC20, "Transfer") - }) - }) + ).to.emit(ERC20, "Transfer"); + }); + }); function getContractAlloc(name: string): any { for (const address of Object.keys(alloc)) { if (alloc[address].contractName === name) { - return Object.assign(alloc[address], { address }) + return Object.assign(alloc[address], { address }); } } - throw new Error(`contract alloc: ${name} not found`) + throw new Error(`contract alloc: ${name} not found`); } -}) +}); async function generateMaxSizeInvalidTxList(TaikoL2: any) { - const constants = await TaikoL2.getConstants() + const constants = await TaikoL2.getConstants(); - const chainId = constants[0].toNumber() - const blockMaxTxNums = constants[7].toNumber() - const txListMaxBytes = constants[9].toNumber() + const chainId = constants[0].toNumber(); + const blockMaxTxNums = constants[7].toNumber(); + const txListMaxBytes = constants[9].toNumber(); const tx = { type: 2, @@ -370,33 +370,33 @@ async function generateMaxSizeInvalidTxList(TaikoL2: any) { data: ethers.utils.randomBytes( Math.floor(txListMaxBytes / blockMaxTxNums) ), - } + }; const invalidSig = { v: 75, r: "0xb14e3f5eab11cd2c459b04a91a9db8bd6f5acccfbd830c9693c84f8d21187eef", s: "0x5cf4b3b2b3957e7016366d180493c2c226ea8ad12aed7faddbc0ce3a6789256d", - } + }; - const txs = new Array(blockMaxTxNums).fill(tx) + const txs = new Array(blockMaxTxNums).fill(tx); let txListBytes = ethers.utils.RLP.encode( txs.map((tx) => ethers.utils.serializeTransaction(tx, invalidSig)) - ) + ); while (ethers.utils.arrayify(txListBytes).length > txListMaxBytes) { - txs[0] = Object.assign(txs[0], { data: txs[0].data.slice(10) }) + txs[0] = Object.assign(txs[0], { data: txs[0].data.slice(10) }); txListBytes = ethers.utils.RLP.encode( txs.map((tx) => ethers.utils.serializeTransaction(tx, invalidSig)) - ) + ); } - return [txListBytes, txs.length] + return [txListBytes, txs.length]; } function sleep(ms: number) { return new Promise((resolve) => { - setTimeout(resolve, ms) - }) + setTimeout(resolve, ms); + }); } diff --git a/packages/protocol/test/libs/Lib1559Math.test.ts b/packages/protocol/test/libs/Lib1559Math.test.ts index ca424208707..29c949fee93 100644 --- a/packages/protocol/test/libs/Lib1559Math.test.ts +++ b/packages/protocol/test/libs/Lib1559Math.test.ts @@ -1,16 +1,16 @@ -import { expect } from "chai" +import { expect } from "chai"; // import * as log from "../tasks/log" -const hre = require("hardhat") -const ethers = hre.ethers +const hre = require("hardhat"); +const ethers = hre.ethers; describe("Lib1559Math", function () { - let Lib1559Math: any + let Lib1559Math: any; before(async function () { Lib1559Math = await ( await ethers.getContractFactory("TestLib1559Math") - ).deploy() - }) + ).deploy(); + }); describe("Testing adjustTarget", function () { it("testing adjustTarget works as docs intend", async function () { @@ -18,51 +18,51 @@ describe("Lib1559Math", function () { // divide by: // (10 * 15000000) == 1.5E8 // == 1.45E7 - const initTarget = 15000000 - const prevMeasurement = 10000000 - const baseTarget = 15000000 - const adjustFactor = 10 + const initTarget = 15000000; + const prevMeasurement = 10000000; + const baseTarget = 15000000; + const adjustFactor = 10; const result = await Lib1559Math.adjustTarget( initTarget, prevMeasurement, baseTarget, adjustFactor - ) - expect(result).to.equal(14500000) - }) + ); + expect(result).to.equal(14500000); + }); it("testing adjustTarget iterative is increasing", async function () { // (since prevMeasured > T, nextTarget > prevTarget) as described in Lib1559Math.sol - const initTarget = 10000000 - const prevMeasured = 20000000 - const baseTarget = 15000000 - const adjustFactor = 10 + const initTarget = 10000000; + const prevMeasured = 20000000; + const baseTarget = 15000000; + const adjustFactor = 10; let target = await Lib1559Math.adjustTarget( initTarget, prevMeasured, baseTarget, adjustFactor - ) - const arr: any[] = [] + ); + const arr: any[] = []; for (let index = 0; index < 10; index++) { target = await Lib1559Math.adjustTarget( target, prevMeasured, baseTarget, adjustFactor - ) - arr.push(target) + ); + arr.push(target); // log.info(target) } // eslint-disable-next-line eqeqeq const isAscending = arr.every((x, i) => { - return i === 0 || x >= arr[i - 1] - }) - expect(isAscending).to.equal(true) - }) - }) + return i === 0 || x >= arr[i - 1]; + }); + expect(isAscending).to.equal(true); + }); + }); describe("Testing adjustTargetReverse", function () { it("testing adjustTargetReverse works as docs intend", async function () { @@ -71,49 +71,49 @@ describe("Lib1559Math", function () { // ((9) * 15000000 + 10000000) == 1.45E8 // == 15,517,241.379310345 // == 15517241 - const initTarget = 15000000 - const prevMeasurement = 10000000 - const baseTarget = 15000000 - const adjustFactor = 10 + const initTarget = 15000000; + const prevMeasurement = 10000000; + const baseTarget = 15000000; + const adjustFactor = 10; const result = await Lib1559Math.adjustTargetReverse( initTarget, prevMeasurement, baseTarget, adjustFactor - ) - expect(result).to.equal(15517241) - }) + ); + expect(result).to.equal(15517241); + }); it("testing adjustTargetReverse iterative is decreasing", async function () { // (since prevTarget >= T, nextTarget < prevTarget) as described in Lib1559Math.sol - const initTarget = 15000000 - const prevMeasurement = 20000000 - const baseTarget = 15000000 - const adjustFactor = 10 + const initTarget = 15000000; + const prevMeasurement = 20000000; + const baseTarget = 15000000; + const adjustFactor = 10; let target = await Lib1559Math.adjustTargetReverse( initTarget, prevMeasurement, baseTarget, adjustFactor - ) - const arr: any[] = [] + ); + const arr: any[] = []; for (let index = 0; index < 10; index++) { target = await Lib1559Math.adjustTargetReverse( target, prevMeasurement, baseTarget, adjustFactor - ) - arr.push(target) + ); + arr.push(target); // log.info(target) } // eslint-disable-next-line eqeqeq const isDescending = arr.every((x, i) => { - return i === 0 || x <= arr[i - 1] - }) - expect(isDescending).to.equal(true) - }) - }) -}) + return i === 0 || x <= arr[i - 1]; + }); + expect(isDescending).to.equal(true); + }); + }); +}); diff --git a/packages/protocol/test/libs/LibAnchorSignature.test.ts b/packages/protocol/test/libs/LibAnchorSignature.test.ts index ddb083210de..ae779a46ad3 100644 --- a/packages/protocol/test/libs/LibAnchorSignature.test.ts +++ b/packages/protocol/test/libs/LibAnchorSignature.test.ts @@ -1,6 +1,6 @@ -import { expect } from "chai" -import { UnsignedTransaction } from "ethers" -import { ethers } from "hardhat" +import { expect } from "chai"; +import { UnsignedTransaction } from "ethers"; +import { ethers } from "hardhat"; describe("LibAnchorSignature", function () { const unsignedLegacyTx: UnsignedTransaction = { @@ -12,23 +12,23 @@ describe("LibAnchorSignature", function () { to: ethers.Wallet.createRandom().address, value: randomBigInt(), data: ethers.utils.randomBytes(32), - } + }; it("should calculate correct signature values", async function () { const libAnchorSignature: any = await ( await ethers.getContractFactory("TestLibAnchorSignature") - ).deploy() + ).deploy(); - const validKs = [1, 2] + const validKs = [1, 2]; for (const k of validKs) { const hash = ethers.utils.keccak256( ethers.utils.serializeTransaction(unsignedLegacyTx) - ) + ); - const [v, r, s] = await libAnchorSignature.signTransaction(hash, k) + const [v, r, s] = await libAnchorSignature.signTransaction(hash, k); - const [addr] = await libAnchorSignature.goldenTouchAddress() + const [addr] = await libAnchorSignature.goldenTouchAddress(); expect( await libAnchorSignature.recover( hash, @@ -36,11 +36,11 @@ describe("LibAnchorSignature", function () { ethers.utils.hexZeroPad(r, 32), ethers.utils.hexZeroPad(s, 32) ) - ).to.be.equal(addr) + ).to.be.equal(addr); } - }) + }); function randomBigInt() { - return ethers.BigNumber.from(ethers.utils.randomBytes(32)) + return ethers.BigNumber.from(ethers.utils.randomBytes(32)); } -}) +}); diff --git a/packages/protocol/test/libs/LibBlockHeader.test.ts b/packages/protocol/test/libs/LibBlockHeader.test.ts index 53c74f729ff..7959d0752d3 100644 --- a/packages/protocol/test/libs/LibBlockHeader.test.ts +++ b/packages/protocol/test/libs/LibBlockHeader.test.ts @@ -1,25 +1,25 @@ -import { expect } from "chai" -import * as log from "../../tasks/log" -const hre = require("hardhat") -const ethers = hre.ethers -const EBN = ethers.BigNumber +import { expect } from "chai"; +import * as log from "../../tasks/log"; +const hre = require("hardhat"); +const ethers = hre.ethers; +const EBN = ethers.BigNumber; describe("LibBlockHeader tests", function () { - let libBlockHeader: any + let libBlockHeader: any; before(async function () { libBlockHeader = await ( await ethers.getContractFactory("TestLibBlockHeader") - ).deploy() - }) + ).deploy(); + }); it("can calculate block header hash correctly", async function () { const blockHash = - "0xc0528bca43a7316776dddb92380cc3a5d9e717bc948ce71f6f1605d7281a4fe8" + "0xc0528bca43a7316776dddb92380cc3a5d9e717bc948ce71f6f1605d7281a4fe8"; // block 0xc0528bca43a7316776dddb92380cc3a5d9e717bc948ce71f6f1605d7281a4fe8 on Ethereum mainnet const parentHash = - "0xa7881266ca0a344c43cb24175d9dbd243b58d45d6ae6ad71310a273a3d1d3afb" + "0xa7881266ca0a344c43cb24175d9dbd243b58d45d6ae6ad71310a273a3d1d3afb"; const l2BlockHeader: any = { parentHash: parentHash, @@ -46,19 +46,19 @@ describe("LibBlockHeader tests", function () { "0xf5ba25df1e92e89a09e0b32063b81795f631100801158f5fa733f2ba26843bd0", nonce: EBN.from("0x738b7e38476abe98"), baseFeePerGas: 0, - } + }; const headerComputed = await libBlockHeader.hashBlockHeader( l2BlockHeader - ) - log.debug("headerComputed:", headerComputed) + ); + log.debug("headerComputed:", headerComputed); - expect(headerComputed).to.equal(blockHash) - }) + expect(headerComputed).to.equal(blockHash); + }); it("can hash block header which contains hash with leading zeros correctly", async function () { const blockHash = - "0x6341fd3daf94b748c72ced5a5b26028f2474f5f00d824504e4fa37a75767e177" + "0x6341fd3daf94b748c72ced5a5b26028f2474f5f00d824504e4fa37a75767e177"; // block 0x6341fd3daf94b748c72ced5a5b26028f2474f5f00d824504e4fa37a75767e177 on Rinkeby testnet // https://rinkeby.etherscan.io/block/0 @@ -87,20 +87,22 @@ describe("LibBlockHeader tests", function () { mixHash: ethers.constants.HashZero, nonce: EBN.from("0x0"), baseFeePerGas: 0, - } + }; - const headerComputed = await libBlockHeader.hashBlockHeader(blockHeader) + const headerComputed = await libBlockHeader.hashBlockHeader( + blockHeader + ); - expect(headerComputed).to.equal(blockHash) - }) + expect(headerComputed).to.equal(blockHash); + }); it("can calculate EIP1159", async function () { const blockHash = - "0xb39b05b327d23ca29286fa7e2331d8269cd257cf10a8310b40ebaddf411f191e" + "0xb39b05b327d23ca29286fa7e2331d8269cd257cf10a8310b40ebaddf411f191e"; // block 0xb39b05b327d23ca29286fa7e2331d8269cd257cf10a8310b40ebaddf411f191e on our L1 testnet const parentHash = - "0xaafe1871246cecd3ff9b0025f731f227bad9f63525f46e83a6f140b5bd6bca00" + "0xaafe1871246cecd3ff9b0025f731f227bad9f63525f46e83a6f140b5bd6bca00"; const l2BlockHeader: any = { parentHash: parentHash, @@ -128,13 +130,13 @@ describe("LibBlockHeader tests", function () { "0x0000000000000000000000000000000000000000000000000000000000000000", nonce: "0x0", baseFeePerGas: EBN.from("0x37"), - } + }; const headerComputed = await libBlockHeader.hashBlockHeader( l2BlockHeader - ) - log.debug("headerComputed:", headerComputed) + ); + log.debug("headerComputed:", headerComputed); - expect(headerComputed).to.equal(blockHash) - }) -}) + expect(headerComputed).to.equal(blockHash); + }); +}); diff --git a/packages/protocol/test/libs/LibReceiptDecoder.test.ts b/packages/protocol/test/libs/LibReceiptDecoder.test.ts index a8203a351d7..137df93683f 100644 --- a/packages/protocol/test/libs/LibReceiptDecoder.test.ts +++ b/packages/protocol/test/libs/LibReceiptDecoder.test.ts @@ -1,20 +1,20 @@ -import { expect } from "chai" +import { expect } from "chai"; // eslint-disable-next-line import/no-named-default -import { default as hre, ethers } from "hardhat" +import { default as hre, ethers } from "hardhat"; describe("integration:LibReceiptDecoder", function () { - let libReceiptDecoder: any + let libReceiptDecoder: any; before(async function () { if (hre.network.name === "hardhat") { throw new Error( `hardhat: debug_getRawReceipts - Method not supported` - ) + ); } const baseLibReceiptDecoder = await ( await ethers.getContractFactory("LibReceiptDecoder") - ).deploy() + ).deploy(); libReceiptDecoder = await ( await ethers.getContractFactory("TestLibReceiptDecoder", { @@ -22,60 +22,62 @@ describe("integration:LibReceiptDecoder", function () { LibReceiptDecoder: baseLibReceiptDecoder.address, }, }) - ).deploy() - }) + ).deploy(); + }); it("should decode RLP encoded transaction receipts", async function () { for (const txType of [0, 1, 2]) { const { maxFeePerGas, gasPrice } = - await hre.ethers.provider.getFeeData() + await hre.ethers.provider.getFeeData(); - let txOptions = {} + let txOptions = {}; - if (txType === 0) txOptions = { gasPrice } - else if (txType === 1) txOptions = { gasPrice, accessList: [] } - else txOptions = { maxFeePerGas } + if (txType === 0) txOptions = { gasPrice }; + else if (txType === 1) txOptions = { gasPrice, accessList: [] }; + else txOptions = { maxFeePerGas }; const tx = await libReceiptDecoder.emitTestEvent( ethers.BigNumber.from(ethers.utils.randomBytes(32)), ethers.utils.randomBytes(32), txOptions - ) + ); - expect(tx.type).to.be.equal(txType) + expect(tx.type).to.be.equal(txType); - const expectedReceipt = await tx.wait() + const expectedReceipt = await tx.wait(); // Retrieves the RLP-encoded raw receipts from node const [encodedReceipt] = await hre.ethers.provider.send( "debug_getRawReceipts", [tx.blockHash] - ) + ); const receipt = await libReceiptDecoder.decodeReceipt( encodedReceipt - ) + ); // Status - expect(receipt.status).to.be.equal(expectedReceipt.status) + expect(receipt.status).to.be.equal(expectedReceipt.status); // CumulativeGasUsed expect(receipt.cumulativeGasUsed).to.be.equal( expectedReceipt.cumulativeGasUsed - ) + ); // LogsBloom expect( `0x${receipt.logsBloom.map((s: any) => s.slice(2)).join("")}` - ).to.be.equal(expectedReceipt.logsBloom) + ).to.be.equal(expectedReceipt.logsBloom); // Logs - expect(receipt.logs.length).to.be.equal(expectedReceipt.logs.length) + expect(receipt.logs.length).to.be.equal( + expectedReceipt.logs.length + ); for (let i = 0; i < receipt.logs.length; i++) { - const log = receipt.logs[i] - const expectedLog = expectedReceipt.logs[i] + const log = receipt.logs[i]; + const expectedLog = expectedReceipt.logs[i]; - expect(log.contractAddress).to.be.equal(expectedLog.address) - expect(log.topics).to.be.eql(expectedLog.topics) - expect(log.data).to.be.equal(expectedLog.data) + expect(log.contractAddress).to.be.equal(expectedLog.address); + expect(log.topics).to.be.eql(expectedLog.topics); + expect(log.data).to.be.equal(expectedLog.data); } } - }) -}) + }); +}); diff --git a/packages/protocol/test/libs/LibTrieProof.test.ts b/packages/protocol/test/libs/LibTrieProof.test.ts index aebfe0909b9..7535911a488 100644 --- a/packages/protocol/test/libs/LibTrieProof.test.ts +++ b/packages/protocol/test/libs/LibTrieProof.test.ts @@ -1,14 +1,14 @@ -import { expect } from "chai" -import { ethers } from "hardhat" -import RLP from "rlp" -import { Message } from "../utils/message" -import { EthGetProofResponse } from "../utils/rpc" +import { expect } from "chai"; +import { ethers } from "hardhat"; +import RLP from "rlp"; +import { Message } from "../utils/message"; +import { EthGetProofResponse } from "../utils/rpc"; describe("integration:LibTrieProof", function () { async function deployLibTrieProofFixture() { const libTrieProof = await ( await ethers.getContractFactory("LibTrieProof") - ).deploy() + ).deploy(); const testLibTreProof = await ( await ethers.getContractFactory("TestLibTrieProof", { @@ -16,23 +16,23 @@ describe("integration:LibTrieProof", function () { LibTrieProof: libTrieProof.address, }, }) - ).deploy() + ).deploy(); const addressManager = await ( await ethers.getContractFactory("AddressManager") - ).deploy() - await addressManager.init() + ).deploy(); + await addressManager.init(); - const { chainId } = await ethers.provider.getNetwork() + const { chainId } = await ethers.provider.getNetwork(); await addressManager.setAddress( `${chainId}.ether_vault`, "0xEA3dD11036f668F08940E13e3bcB097C93b09E07" - ) + ); const libBridgeRetry = await ( await ethers.getContractFactory("LibBridgeRetry") - ).deploy() + ).deploy(); const libBridgeProcess = await ( await ethers.getContractFactory("LibBridgeProcess", { @@ -40,7 +40,7 @@ describe("integration:LibTrieProof", function () { LibTrieProof: libTrieProof.address, }, }) - ).deploy() + ).deploy(); const BridgeFactory = await ethers.getContractFactory("Bridge", { libraries: { @@ -48,25 +48,25 @@ describe("integration:LibTrieProof", function () { LibBridgeRetry: libBridgeRetry.address, LibTrieProof: libTrieProof.address, }, - }) + }); - const bridge = await BridgeFactory.deploy() + const bridge = await BridgeFactory.deploy(); - await bridge.init(addressManager.address) + await bridge.init(addressManager.address); - const [owner] = await ethers.getSigners() + const [owner] = await ethers.getSigners(); - return { owner, testLibTreProof, bridge } + return { owner, testLibTreProof, bridge }; } describe("verify()", function () { it("verifies", async function () { const { owner, testLibTreProof, bridge } = - await deployLibTrieProofFixture() + await deployLibTrieProofFixture(); - const { chainId } = await ethers.provider.getNetwork() - const srcChainId = chainId - const destChainId = srcChainId + 1 - await (await bridge.enableDestChain(destChainId, true)).wait() + const { chainId } = await ethers.provider.getNetwork(); + const srcChainId = chainId; + const destChainId = srcChainId + 1; + await (await bridge.enableDestChain(destChainId, true)).wait(); const message: Message = { id: 1, @@ -82,34 +82,36 @@ describe("integration:LibTrieProof", function () { gasLimit: 10000, data: ethers.constants.HashZero, memo: "", - } + }; const expectedAmount = - message.depositValue + message.callValue + message.processingFee + message.depositValue + + message.callValue + + message.processingFee; const tx = await bridge.sendMessage(message, { value: expectedAmount, - }) + }); - const receipt = await tx.wait() + const receipt = await tx.wait(); - const [messageSentEvent] = receipt.events as any as Event[] + const [messageSentEvent] = receipt.events as any as Event[]; - const { signal } = (messageSentEvent as any).args + const { signal } = (messageSentEvent as any).args; - expect(signal).not.to.be.eq(ethers.constants.HashZero) + expect(signal).not.to.be.eq(ethers.constants.HashZero); - const messageStatus = await bridge.getMessageStatus(signal) + const messageStatus = await bridge.getMessageStatus(signal); - expect(messageStatus).to.be.eq(0) + expect(messageStatus).to.be.eq(0); - const sender = bridge.address + const sender = bridge.address; const key = ethers.utils.keccak256( ethers.utils.solidityPack( ["address", "bytes32"], [sender, signal] ) - ) + ); // use this instead of ethers.provider.getBlock() beccause it doesnt have stateRoot // in the response @@ -117,25 +119,25 @@ describe("integration:LibTrieProof", function () { await ethers.provider.send("eth_getBlockByNumber", [ "latest", false, - ]) + ]); // get storageValue for the key const storageValue = await ethers.provider.getStorageAt( bridge.address, key, block.number - ) + ); // make sure it equals 1 so our proof will pass expect(storageValue).to.be.eq( "0x0000000000000000000000000000000000000000000000000000000000000001" - ) + ); // rpc call to get the merkle proof what value is at key on the bridge contract const proof: EthGetProofResponse = await ethers.provider.send( "eth_getProof", [bridge.address, [key], block.hash] - ) + ); - const stateRoot = block.stateRoot + const stateRoot = block.stateRoot; // RLP encode the proof together for LibTrieProof to decode const encodedProof = ethers.utils.defaultAbiCoder.encode( @@ -144,7 +146,7 @@ describe("integration:LibTrieProof", function () { RLP.encode(proof.accountProof), RLP.encode(proof.storageProof[0].proof), ] - ) + ); // proof verifies the storageValue at key is 1 await testLibTreProof.verify( stateRoot, @@ -152,7 +154,7 @@ describe("integration:LibTrieProof", function () { key, "0x0000000000000000000000000000000000000000000000000000000000000001", encodedProof - ) - }) - }) -}) + ); + }); + }); +}); diff --git a/packages/protocol/test/libs/LibTxDecoder.test.ts b/packages/protocol/test/libs/LibTxDecoder.test.ts index 6e46b66bd4a..672c2831e6e 100644 --- a/packages/protocol/test/libs/LibTxDecoder.test.ts +++ b/packages/protocol/test/libs/LibTxDecoder.test.ts @@ -1,58 +1,58 @@ -import { expect } from "chai" -import { UnsignedTransaction } from "ethers" -import { ethers } from "hardhat" -import * as log from "../../tasks/log" +import { expect } from "chai"; +import { UnsignedTransaction } from "ethers"; +import { ethers } from "hardhat"; +import * as log from "../../tasks/log"; describe("LibTxDecoder", function () { - let rlpWriter: any - let libTxDecoder: any - let signer0: any + let rlpWriter: any; + let libTxDecoder: any; + let signer0: any; before(async function () { rlpWriter = await ( await ethers.getContractFactory("TestLibRLPWriter") - ).deploy() + ).deploy(); libTxDecoder = await ( await ethers.getContractFactory("LibTxDecoder") - ).deploy() + ).deploy(); - signer0 = (await ethers.getSigners())[0] - }) + signer0 = (await ethers.getSigners())[0]; + }); async function rlpEncodeTxList(txList: string[]) { - const rlpEncodedBytes = [] + const rlpEncodedBytes = []; for (const tx of txList) { - const txRlp = await rlpWriter.writeBytes(tx) - rlpEncodedBytes.push(txRlp) + const txRlp = await rlpWriter.writeBytes(tx); + rlpEncodedBytes.push(txRlp); } - const txListBytes = await rlpWriter.writeList(rlpEncodedBytes) - return txListBytes + const txListBytes = await rlpWriter.writeList(rlpEncodedBytes); + return txListBytes; } describe("decodeTxList", function () { it("should not revert if tx list is empty", async function () { - const txList: string[] = [] - const txListBytes = await rlpEncodeTxList(txList) + const txList: string[] = []; + const txListBytes = await rlpEncodeTxList(txList); let decoded = await libTxDecoder.callStatic.decodeTxList( txListBytes - ) + ); - expect(decoded.items.length).to.be.eql(0) + expect(decoded.items.length).to.be.eql(0); - decoded = await libTxDecoder.callStatic.decodeTxList([]) + decoded = await libTxDecoder.callStatic.decodeTxList([]); - expect(decoded.items.length).to.be.eql(0) - }) + expect(decoded.items.length).to.be.eql(0); + }); it("should revert with random bytes", async function () { const randomBytes = ethers.utils.hexlify( ethers.utils.randomBytes(73) - ) + ); await expect(libTxDecoder.callStatic.decodeTxList(randomBytes)).to - .be.reverted - }) + .be.reverted; + }); it("can decode txList with legacy transaction", async function () { const txLegacy: UnsignedTransaction = { @@ -63,27 +63,27 @@ describe("LibTxDecoder", function () { to: ethers.Wallet.createRandom().address, value: ethers.utils.parseEther("1.23"), data: ethers.utils.randomBytes(10), - } + }; - const signature = await signer0.signMessage("abc123") + const signature = await signer0.signMessage("abc123"); // log.debug('signature: ', signature) const txLegacyBytes = ethers.utils.serializeTransaction( txLegacy, signature - ) - log.debug("txLegacyBytes: ", txLegacyBytes) - const txListBytes = await rlpEncodeTxList([txLegacyBytes]) - log.debug("txListBytes: ", txListBytes) + ); + log.debug("txLegacyBytes: ", txLegacyBytes); + const txListBytes = await rlpEncodeTxList([txLegacyBytes]); + log.debug("txListBytes: ", txListBytes); const decodedTxList = await libTxDecoder.callStatic.decodeTxList( txListBytes - ) + ); // log.debug('decodedT: ', decodedTxList) - expect(decodedTxList.items.length).to.equal(1) - const decodedTx1 = decodedTxList.items[0] - expect(decodedTx1.gasLimit.toNumber()).to.equal(txLegacy.gasLimit) - }) + expect(decodedTxList.items.length).to.equal(1); + const decodedTx1 = decodedTxList.items[0]; + expect(decodedTx1.gasLimit.toNumber()).to.equal(txLegacy.gasLimit); + }); it("can decode txList with 2930 transaction", async function () { const tx2930: UnsignedTransaction = { @@ -96,23 +96,28 @@ describe("LibTxDecoder", function () { value: ethers.utils.parseEther("10.23"), accessList: [], data: ethers.utils.randomBytes(20), - } + }; - const signature = await signer0.signMessage(tx2930.data?.toString()) - log.debug("signature: ", signature) + const signature = await signer0.signMessage( + tx2930.data?.toString() + ); + log.debug("signature: ", signature); - const txBytes = ethers.utils.serializeTransaction(tx2930, signature) - log.debug("txBytes: ", txBytes) - const txListBytes = await rlpEncodeTxList([txBytes]) - log.debug("txListBytes: ", txListBytes) + const txBytes = ethers.utils.serializeTransaction( + tx2930, + signature + ); + log.debug("txBytes: ", txBytes); + const txListBytes = await rlpEncodeTxList([txBytes]); + log.debug("txListBytes: ", txListBytes); const decodedTxList = await libTxDecoder.callStatic.decodeTxList( txListBytes - ) - expect(decodedTxList.items.length).to.equal(1) - const decodedTx1 = decodedTxList.items[0] - expect(decodedTx1.gasLimit.toNumber()).to.equal(tx2930.gasLimit) - }) + ); + expect(decodedTxList.items.length).to.equal(1); + const decodedTx1 = decodedTxList.items[0]; + expect(decodedTx1.gasLimit.toNumber()).to.equal(tx2930.gasLimit); + }); it("can decode txList with 1559 transaction", async function () { const tx1559: UnsignedTransaction = { @@ -126,27 +131,32 @@ describe("LibTxDecoder", function () { value: ethers.utils.parseEther("10.123"), accessList: [], data: ethers.utils.randomBytes(20), - } + }; - const signature = await signer0.signMessage(tx1559.data?.toString()) - log.debug("signature: ", signature) + const signature = await signer0.signMessage( + tx1559.data?.toString() + ); + log.debug("signature: ", signature); - const txBytes = ethers.utils.serializeTransaction(tx1559, signature) - log.debug("txBytes: ", txBytes) - const txListBytes = await rlpEncodeTxList([txBytes]) - log.debug("txListBytes: ", txListBytes) + const txBytes = ethers.utils.serializeTransaction( + tx1559, + signature + ); + log.debug("txBytes: ", txBytes); + const txListBytes = await rlpEncodeTxList([txBytes]); + log.debug("txListBytes: ", txListBytes); const decodedTxList = await libTxDecoder.callStatic.decodeTxList( txListBytes - ) - expect(decodedTxList.items.length).to.equal(1) - const decodedTx1 = decodedTxList.items[0] - expect(decodedTx1.gasLimit.toNumber()).to.equal(tx1559.gasLimit) - }) - }) + ); + expect(decodedTxList.items.length).to.equal(1); + const decodedTx1 = decodedTxList.items[0]; + expect(decodedTx1.gasLimit.toNumber()).to.equal(tx1559.gasLimit); + }); + }); it("can decode txList with multiple types", async function () { - const signature = await signer0.signMessage("123456abcdef") + const signature = await signer0.signMessage("123456abcdef"); const txLegacy: UnsignedTransaction = { nonce: 1, chainId: 167, @@ -155,7 +165,7 @@ describe("LibTxDecoder", function () { to: ethers.Wallet.createRandom().address, value: ethers.utils.parseEther("1.23"), data: ethers.utils.randomBytes(10), - } + }; const tx2930: UnsignedTransaction = { type: 1, @@ -167,7 +177,7 @@ describe("LibTxDecoder", function () { value: ethers.utils.parseEther("10.23"), accessList: [], data: ethers.utils.randomBytes(20), - } + }; const tx1559: UnsignedTransaction = { type: 2, @@ -180,25 +190,25 @@ describe("LibTxDecoder", function () { value: ethers.utils.parseEther("10.123"), accessList: [], data: ethers.utils.randomBytes(20), - } + }; - const txObjArr = [txLegacy, tx2930, tx1559] - const txRawBytesArr = [] + const txObjArr = [txLegacy, tx2930, tx1559]; + const txRawBytesArr = []; for (const txObj of txObjArr) { - const txBytes = ethers.utils.serializeTransaction(txObj, signature) - txRawBytesArr.push(txBytes) + const txBytes = ethers.utils.serializeTransaction(txObj, signature); + txRawBytesArr.push(txBytes); } - const txListBytes = await rlpEncodeTxList(txRawBytesArr) + const txListBytes = await rlpEncodeTxList(txRawBytesArr); const decodedTxList = await libTxDecoder.callStatic.decodeTxList( txListBytes - ) + ); // log.debug('decodedT: ', decodedTxList) - expect(decodedTxList.items.length).to.equal(txObjArr.length) + expect(decodedTxList.items.length).to.equal(txObjArr.length); for (let i = 0; i < txObjArr.length; i++) { - const txObj = txObjArr[i] - const decodedTx = decodedTxList.items[i] - expect(decodedTx.gasLimit.toNumber()).to.equal(txObj.gasLimit) + const txObj = txObjArr[i]; + const decodedTx = decodedTxList.items[i]; + expect(decodedTx.gasLimit.toNumber()).to.equal(txObj.gasLimit); } - }) -}) + }); +}); diff --git a/packages/protocol/test/libs/LibTxUtils.test.ts b/packages/protocol/test/libs/LibTxUtils.test.ts index ae92f04db92..68f2e352b8c 100644 --- a/packages/protocol/test/libs/LibTxUtils.test.ts +++ b/packages/protocol/test/libs/LibTxUtils.test.ts @@ -1,36 +1,38 @@ -import { expect } from "chai" -import { UnsignedTransaction } from "ethers" -import { ethers } from "hardhat" +import { expect } from "chai"; +import { UnsignedTransaction } from "ethers"; +import { ethers } from "hardhat"; describe("LibTxUtils", function () { - let libTxUtils: any - let libRLPWriter: any - let libRLPReader: any - let libConstants: any - let testUnsignedTxs: Array - let chainId: any - - const signingKey = new ethers.utils.SigningKey(ethers.utils.randomBytes(32)) - const signerAddress = new ethers.Wallet(signingKey.privateKey).address + let libTxUtils: any; + let libRLPWriter: any; + let libRLPReader: any; + let libConstants: any; + let testUnsignedTxs: Array; + let chainId: any; + + const signingKey = new ethers.utils.SigningKey( + ethers.utils.randomBytes(32) + ); + const signerAddress = new ethers.Wallet(signingKey.privateKey).address; before(async function () { libConstants = await ( await ethers.getContractFactory("LibConstants") - ).deploy() + ).deploy(); libTxUtils = await ( await ethers.getContractFactory("TestLibTxUtils") - ).deploy() + ).deploy(); libRLPReader = await ( await ethers.getContractFactory("TestLibRLPReader") - ).deploy() + ).deploy(); libRLPWriter = await ( await ethers.getContractFactory("TestLibRLPWriter") - ).deploy() + ).deploy(); - chainId = (await libConstants.K_CHAIN_ID()).toNumber() + chainId = (await libConstants.K_CHAIN_ID()).toNumber(); const unsignedLegacyTx: UnsignedTransaction = { type: 0, @@ -43,7 +45,7 @@ describe("LibTxUtils", function () { to: ethers.Wallet.createRandom().address, value: randomBigInt(), data: ethers.utils.randomBytes(32), - } + }; const unsigned2930Tx: UnsignedTransaction = { type: 1, @@ -60,7 +62,7 @@ describe("LibTxUtils", function () { ], ], data: ethers.utils.randomBytes(32), - } + }; const unsigned1559Tx: UnsignedTransaction = { type: 2, @@ -78,18 +80,18 @@ describe("LibTxUtils", function () { ], ], data: ethers.utils.randomBytes(32), - } + }; - testUnsignedTxs = [unsignedLegacyTx, unsigned2930Tx, unsigned1559Tx] - }) + testUnsignedTxs = [unsignedLegacyTx, unsigned2930Tx, unsigned1559Tx]; + }); it("should hash the unsigned tx payloads correctly", async function () { for (const unsignedTx of testUnsignedTxs) { const expectedHash = ethers.utils.keccak256( ethers.utils.serializeTransaction(unsignedTx) - ) + ); - const signature = signingKey.signDigest(expectedHash) + const signature = signingKey.signDigest(expectedHash); const hash = await libTxUtils.hashUnsignedTx({ txType: unsignedTx.type, @@ -103,18 +105,18 @@ describe("LibTxUtils", function () { unsignedTx, signature ), - }) + }); - expect(hash).to.be.equal(expectedHash) + expect(hash).to.be.equal(expectedHash); } - }) + }); it("should verify valid transaction signatures", async function () { for (const unsignedTx of testUnsignedTxs) { const expectedHash = ethers.utils.keccak256( ethers.utils.serializeTransaction(unsignedTx) - ) - const signature = signingKey.signDigest(expectedHash) + ); + const signature = signingKey.signDigest(expectedHash); expect( await libTxUtils.recoverSender({ @@ -130,22 +132,22 @@ describe("LibTxUtils", function () { signature ), }) - ).to.be.equal(signerAddress) + ).to.be.equal(signerAddress); } - }) + }); it("should verify invalid transaction signatures", async function () { for (const unsignedTx of testUnsignedTxs) { const expectedHash = ethers.utils.keccak256( ethers.utils.serializeTransaction(unsignedTx) - ) - const signature = signingKey.signDigest(expectedHash) + ); + const signature = signingKey.signDigest(expectedHash); const invalidSignature = { v: 75, r: "0xb14e3f5eab11cd2c459b04a91a9db8bd6f5acccfbd830c9693c84f8d21187eef", s: "0x5cf4b3b2b3957e7016366d180493c2c226ea8ad12aed7faddbc0ce3a6789256d", - } + }; const txData = await changeSignature( unsignedTx.type, @@ -153,7 +155,7 @@ describe("LibTxUtils", function () { ethers.utils.serializeTransaction(unsignedTx, signature) ), invalidSignature - ) + ); expect( await libTxUtils.recoverSender({ @@ -166,18 +168,21 @@ describe("LibTxUtils", function () { s: invalidSignature.s, txData, }) - ).to.be.equal(ethers.constants.AddressZero) + ).to.be.equal(ethers.constants.AddressZero); } - }) + }); async function changeSignature( type: any, encoded: Uint8Array, signature: any ) { - if (type !== 0) encoded = encoded.slice(1) + if (type !== 0) encoded = encoded.slice(1); - const rlpItemsList = (await libRLPReader.readList(encoded)).slice(0, -3) + const rlpItemsList = (await libRLPReader.readList(encoded)).slice( + 0, + -3 + ); let result = await libRLPWriter.writeList( rlpItemsList.concat([ @@ -185,14 +190,14 @@ describe("LibTxUtils", function () { await libRLPWriter.writeBytes(signature.r), await libRLPWriter.writeBytes(signature.s), ]) - ) + ); - if (type !== 0) result = ethers.utils.concat([[type], result]) + if (type !== 0) result = ethers.utils.concat([[type], result]); - return ethers.utils.hexlify(result) + return ethers.utils.hexlify(result); } function randomBigInt() { - return ethers.BigNumber.from(ethers.utils.randomBytes(32)) + return ethers.BigNumber.from(ethers.utils.randomBytes(32)); } -}) +}); diff --git a/packages/protocol/test/thirdparty/AddressManager.test.ts b/packages/protocol/test/thirdparty/AddressManager.test.ts index 33d6430ab49..c4cf33276c8 100644 --- a/packages/protocol/test/thirdparty/AddressManager.test.ts +++ b/packages/protocol/test/thirdparty/AddressManager.test.ts @@ -1,50 +1,50 @@ -import { expect } from "chai" -import { AddressManager } from "../../typechain" -import { ethers } from "hardhat" +import { expect } from "chai"; +import { AddressManager } from "../../typechain"; +import { ethers } from "hardhat"; describe("AddressManager", function () { - let owner: any - let nonOwner: any - let addressManager: AddressManager + let owner: any; + let nonOwner: any; + let addressManager: AddressManager; before(async function () { - ;[owner, nonOwner] = await ethers.getSigners() - }) + [owner, nonOwner] = await ethers.getSigners(); + }); beforeEach(async function () { addressManager = await ( await ethers.getContractFactory("AddressManager") - ).deploy() - await addressManager.init() - }) + ).deploy(); + await addressManager.init(); + }); describe("setAddress()", async () => { it("throws when non-owner calls", async () => { - const name = "fakename" + const name = "fakename"; await expect( addressManager .connect(nonOwner) .setAddress(name, nonOwner.address) - ).to.be.revertedWith("") - }) + ).to.be.revertedWith(""); + }); it("emits setAddress event", async () => { - const name = "fakename" + const name = "fakename"; await expect( addressManager.connect(owner).setAddress(name, nonOwner.address) ) .to.emit(addressManager, "AddressSet") - .withArgs(name, nonOwner.address, ethers.constants.AddressZero) + .withArgs(name, nonOwner.address, ethers.constants.AddressZero); await expect( addressManager.connect(owner).setAddress(name, owner.address) ) .to.emit(addressManager, "AddressSet") - .withArgs(name, owner.address, nonOwner.address) + .withArgs(name, owner.address, nonOwner.address); expect(await addressManager.getAddress(name)).to.be.eq( owner.address - ) - }) - }) -}) + ); + }); + }); +}); diff --git a/packages/protocol/test/thirdparty/LibBlockHeaderDecoder.test.ts b/packages/protocol/test/thirdparty/LibBlockHeaderDecoder.test.ts index 761333a640d..e3e21156016 100644 --- a/packages/protocol/test/thirdparty/LibBlockHeaderDecoder.test.ts +++ b/packages/protocol/test/thirdparty/LibBlockHeaderDecoder.test.ts @@ -1,20 +1,20 @@ // eslint-disable-next-line no-unused-vars -import { expect } from "chai" -import { keccak256 } from "ethers/lib/utils" -const hre = require("hardhat") -const ethers = hre.ethers -const EBN = ethers.BigNumber +import { expect } from "chai"; +import { keccak256 } from "ethers/lib/utils"; +const hre = require("hardhat"); +const ethers = hre.ethers; +const EBN = ethers.BigNumber; describe("LibBlockHeaderDecoder", async function () { // eslint-disable-next-line no-unused-vars - let blockHeaderDecoder: any - let hashBlockHeader: any + let blockHeaderDecoder: any; + let hashBlockHeader: any; before(async function () { // Deploying Lib to Link const blkHdrDcdrLib = await ( await ethers.getContractFactory("LibBlockHeaderDecoder") - ).deploy() + ).deploy(); // Deploying Library blockHeaderDecoder = await ( @@ -23,16 +23,16 @@ describe("LibBlockHeaderDecoder", async function () { LibBlockHeaderDecoder: blkHdrDcdrLib.address, }, }) - ).deploy() + ).deploy(); hashBlockHeader = await ( await ethers.getContractFactory("TestLibBlockHeader") - ).deploy() - }) + ).deploy(); + }); it("Decode should return stateRoot and timeStamp", async function () { const parentHash = - "0xa7881266ca0a344c43cb24175d9dbd243b58d45d6ae6ad71310a273a3d1d3afb" + "0xa7881266ca0a344c43cb24175d9dbd243b58d45d6ae6ad71310a273a3d1d3afb"; const blockHeader: any = { parentHash: parentHash, ommersHash: @@ -58,31 +58,31 @@ describe("LibBlockHeaderDecoder", async function () { "0xf5ba25df1e92e89a09e0b32063b81795f631100801158f5fa733f2ba26843bd0", nonce: EBN.from("0x738b7e38476abe98"), baseFeePerGas: 0, - } + }; const encodedBlockHeader = await hashBlockHeader.rlpBlockHeader( blockHeader - ) + ); const [_stateRoot, _timeStamp, _transactionsRoot, _receiptsRoot] = await blockHeaderDecoder.decodeBlockHeader( encodedBlockHeader, keccak256(encodedBlockHeader), false - ) + ); - expect(_stateRoot).to.equal(blockHeader.stateRoot) - expect(_timeStamp).to.equal(blockHeader.timestamp) - expect(_transactionsRoot).to.equal(blockHeader.transactionsRoot) - expect(_receiptsRoot).to.equal(blockHeader.receiptsRoot) - }) + expect(_stateRoot).to.equal(blockHeader.stateRoot); + expect(_timeStamp).to.equal(blockHeader.timestamp); + expect(_transactionsRoot).to.equal(blockHeader.transactionsRoot); + expect(_receiptsRoot).to.equal(blockHeader.receiptsRoot); + }); it("Same as above, using latest blockHeader", async function () { const block = await hre.ethers.provider.send("eth_getBlockByNumber", [ "latest", false, - ]) - const logsBloom = block.logsBloom.toString().substring(2) + ]); + const logsBloom = block.logsBloom.toString().substring(2); const blockHeader = { parentHash: block.parentHash, ommersHash: block.sha3Uncles, @@ -102,30 +102,30 @@ describe("LibBlockHeaderDecoder", async function () { mixHash: block.mixHash, nonce: block.nonce, baseFeePerGas: 0, - } + }; const encodedBlockHeader = await hashBlockHeader.rlpBlockHeader( blockHeader - ) + ); const [_stateRoot, _timeStamp, _transactionsRoot, _receiptsRoot] = await blockHeaderDecoder.decodeBlockHeader( encodedBlockHeader, keccak256(encodedBlockHeader), false - ) + ); - expect(_stateRoot).to.equal(blockHeader.stateRoot) - expect(_timeStamp).to.equal(blockHeader.timestamp) - expect(_transactionsRoot).to.equal(blockHeader.transactionsRoot) - expect(_receiptsRoot).to.equal(blockHeader.receiptsRoot) - }) + expect(_stateRoot).to.equal(blockHeader.stateRoot); + expect(_timeStamp).to.equal(blockHeader.timestamp); + expect(_transactionsRoot).to.equal(blockHeader.transactionsRoot); + expect(_receiptsRoot).to.equal(blockHeader.receiptsRoot); + }); it("Same as above, using earliest blockHeader", async function () { const block = await hre.ethers.provider.send("eth_getBlockByNumber", [ "earliest", false, - ]) - const logsBloom = block.logsBloom.toString().substring(2) + ]); + const logsBloom = block.logsBloom.toString().substring(2); const blockHeader = { parentHash: block.parentHash, ommersHash: block.sha3Uncles, @@ -145,21 +145,21 @@ describe("LibBlockHeaderDecoder", async function () { mixHash: block.mixHash, nonce: block.nonce, baseFeePerGas: 0, - } + }; const encodedBlockHeader = await hashBlockHeader.rlpBlockHeader( blockHeader - ) + ); const [_stateRoot, _timeStamp, _transactionsRoot, _receiptsRoot] = await blockHeaderDecoder.decodeBlockHeader( encodedBlockHeader, keccak256(encodedBlockHeader), false - ) + ); - expect(_stateRoot).to.equal(blockHeader.stateRoot) - expect(_timeStamp).to.equal(blockHeader.timestamp) - expect(_transactionsRoot).to.equal(blockHeader.transactionsRoot) - expect(_receiptsRoot).to.equal(blockHeader.receiptsRoot) - }) -}) + expect(_stateRoot).to.equal(blockHeader.stateRoot); + expect(_timeStamp).to.equal(blockHeader.timestamp); + expect(_transactionsRoot).to.equal(blockHeader.transactionsRoot); + expect(_receiptsRoot).to.equal(blockHeader.receiptsRoot); + }); +}); diff --git a/packages/protocol/test/thirdparty/LibMerkleTrie.test.ts b/packages/protocol/test/thirdparty/LibMerkleTrie.test.ts index f55391180dc..15318b41cf0 100644 --- a/packages/protocol/test/thirdparty/LibMerkleTrie.test.ts +++ b/packages/protocol/test/thirdparty/LibMerkleTrie.test.ts @@ -1,74 +1,74 @@ -import { expect } from "chai" -import { ethers } from "hardhat" -import { BaseTrie } from "merkle-patricia-tree" -import { TestLibMerkleTrie } from "../../typechain" -import { MerkleTrie } from "../utils/trie" -import { randomBytes } from "crypto" +import { expect } from "chai"; +import { ethers } from "hardhat"; +import { BaseTrie } from "merkle-patricia-tree"; +import { TestLibMerkleTrie } from "../../typechain"; +import { MerkleTrie } from "../utils/trie"; +import { randomBytes } from "crypto"; describe("LibMerkleTrie", function () { - let libMerkleTrie: TestLibMerkleTrie - let defaultMerkleTrie: MerkleTrie - const defaultAmountOfNodes = 32 - const defaultNodeLength = 32 + let libMerkleTrie: TestLibMerkleTrie; + let defaultMerkleTrie: MerkleTrie; + const defaultAmountOfNodes = 32; + const defaultNodeLength = 32; beforeEach(async function () { libMerkleTrie = await ( await ethers.getContractFactory("TestLibMerkleTrie") - ).deploy() + ).deploy(); defaultMerkleTrie = new MerkleTrie( defaultAmountOfNodes, defaultNodeLength, () => new BaseTrie() - ) - await defaultMerkleTrie.init() - }) + ); + await defaultMerkleTrie.init(); + }); describe("verifyInclusionProof()", () => { it(`is included, ${defaultAmountOfNodes} bytes, ${defaultNodeLength} node length`, async () => { for (const n of defaultMerkleTrie.nodes) { - const key = n.key - const t = await defaultMerkleTrie.makeTest(key) + const key = n.key; + const t = await defaultMerkleTrie.makeTest(key); const isIncluded = await libMerkleTrie.verifyInclusionProof( key, t.node.value, t.proof.proof, t.root.root - ) - expect(isIncluded).to.be.eq(true) + ); + expect(isIncluded).to.be.eq(true); } - }) - }) + }); + }); describe("get()", () => { it(`is included`, async () => { - const key = defaultMerkleTrie.nodes[0].key - const t = await defaultMerkleTrie.makeTest(key) + const key = defaultMerkleTrie.nodes[0].key; + const t = await defaultMerkleTrie.makeTest(key); const isIncluded = await libMerkleTrie.get( key, t.proof.proof, t.root.root - ) + ); - expect(isIncluded[0]).to.be.eq(true) + expect(isIncluded[0]).to.be.eq(true); expect(isIncluded[1]).to.be.eq( ethers.utils.hexlify(defaultMerkleTrie.nodes[0].value) - ) - }) + ); + }); it(`is not included`, async () => { const t = await defaultMerkleTrie.makeTest( defaultMerkleTrie.nodes[0].key - ) + ); - const key = randomBytes(defaultNodeLength) + const key = randomBytes(defaultNodeLength); const isIncluded = await libMerkleTrie.get( key, t.proof.proof, t.root.root - ) + ); - expect(isIncluded[0]).to.be.eq(false) - expect(isIncluded[1]).to.be.eq("0x") - }) - }) -}) + expect(isIncluded[0]).to.be.eq(false); + expect(isIncluded[1]).to.be.eq("0x"); + }); + }); +}); diff --git a/packages/protocol/test/thirdparty/LibSecureMerkleTrie.test.ts b/packages/protocol/test/thirdparty/LibSecureMerkleTrie.test.ts index 41e5979e6c6..b9042868c91 100644 --- a/packages/protocol/test/thirdparty/LibSecureMerkleTrie.test.ts +++ b/packages/protocol/test/thirdparty/LibSecureMerkleTrie.test.ts @@ -1,74 +1,74 @@ -import { expect } from "chai" -import { randomBytes } from "crypto" -import { ethers } from "hardhat" -import { SecureTrie } from "merkle-patricia-tree" -import { TestLibSecureMerkleTrie } from "../../typechain" -import { MerkleTrie } from "../utils/trie" +import { expect } from "chai"; +import { randomBytes } from "crypto"; +import { ethers } from "hardhat"; +import { SecureTrie } from "merkle-patricia-tree"; +import { TestLibSecureMerkleTrie } from "../../typechain"; +import { MerkleTrie } from "../utils/trie"; describe("LibSecureMerkleTrie", function () { - let libSecureMerkleTrie: TestLibSecureMerkleTrie - let defaultSecureMerkleTrie: MerkleTrie - const defaultAmountOfNodes = 32 - const defaultNodeLength = 32 + let libSecureMerkleTrie: TestLibSecureMerkleTrie; + let defaultSecureMerkleTrie: MerkleTrie; + const defaultAmountOfNodes = 32; + const defaultNodeLength = 32; beforeEach(async function () { libSecureMerkleTrie = await ( await ethers.getContractFactory("TestLibSecureMerkleTrie") - ).deploy() + ).deploy(); defaultSecureMerkleTrie = new MerkleTrie( defaultAmountOfNodes, defaultNodeLength, () => new SecureTrie() - ) - await defaultSecureMerkleTrie.init() - }) + ); + await defaultSecureMerkleTrie.init(); + }); describe("verifyInclusionProof()", () => { it(`is included, ${defaultAmountOfNodes} bytes, ${defaultNodeLength} node length`, async () => { - const n = defaultSecureMerkleTrie.nodes[0] - const key = n.key - const t = await defaultSecureMerkleTrie.makeTest(key) + const n = defaultSecureMerkleTrie.nodes[0]; + const key = n.key; + const t = await defaultSecureMerkleTrie.makeTest(key); const isIncluded = await libSecureMerkleTrie.verifyInclusionProof( key, t.node.value, t.proof.proof, t.root.root - ) - expect(isIncluded).to.be.eq(true) - }) - }) + ); + expect(isIncluded).to.be.eq(true); + }); + }); describe("get()", () => { it(`is included`, async () => { - const key = defaultSecureMerkleTrie.nodes[0].key - const t = await defaultSecureMerkleTrie.makeTest(key) + const key = defaultSecureMerkleTrie.nodes[0].key; + const t = await defaultSecureMerkleTrie.makeTest(key); const isIncluded = await libSecureMerkleTrie.get( key, t.proof.proof, t.root.root - ) + ); - expect(isIncluded[0]).to.be.eq(true) + expect(isIncluded[0]).to.be.eq(true); expect(isIncluded[1]).to.be.eq( ethers.utils.hexlify(defaultSecureMerkleTrie.nodes[0].value) - ) - }) + ); + }); it(`is not included`, async () => { const t = await defaultSecureMerkleTrie.makeTest( defaultSecureMerkleTrie.nodes[0].key - ) + ); - const key = randomBytes(defaultNodeLength) + const key = randomBytes(defaultNodeLength); const isIncluded = await libSecureMerkleTrie.get( key, t.proof.proof, t.root.root - ) + ); - expect(isIncluded[0]).to.be.eq(false) - expect(isIncluded[1]).to.be.eq("0x") - }) - }) -}) + expect(isIncluded[0]).to.be.eq(false); + expect(isIncluded[1]).to.be.eq("0x"); + }); + }); +}); diff --git a/packages/protocol/test/utils/message.ts b/packages/protocol/test/utils/message.ts index c7e5a6b1d12..717641d1b22 100644 --- a/packages/protocol/test/utils/message.ts +++ b/packages/protocol/test/utils/message.ts @@ -1,17 +1,17 @@ type Message = { - id: number - sender: string - srcChainId: number - destChainId: number - owner: string - to: string - refundAddress: string - depositValue: number - callValue: number - processingFee: number - gasLimit: number - data: string - memo: string -} + id: number; + sender: string; + srcChainId: number; + destChainId: number; + owner: string; + to: string; + refundAddress: string; + depositValue: number; + callValue: number; + processingFee: number; + gasLimit: number; + data: string; + memo: string; +}; -export { Message } +export { Message }; diff --git a/packages/protocol/test/utils/rpc.ts b/packages/protocol/test/utils/rpc.ts index 74d8947f17b..250d4ea87a9 100644 --- a/packages/protocol/test/utils/rpc.ts +++ b/packages/protocol/test/utils/rpc.ts @@ -1,59 +1,59 @@ type StorageEntry = { - key: string - value: string - proof: string[] // Array of rlp-serialized MerkleTree-Nodes, starting with the storageHash-Node, -} + key: string; + value: string; + proof: string[]; // Array of rlp-serialized MerkleTree-Nodes, starting with the storageHash-Node, +}; type EthGetProofResponse = { - balance: string - codeHash: string - nonce: string - storageHash: string - accountProof: string[] // array of rlp-serialized merkle nodes beginning with stateRoot-node - storageProof: StorageEntry[] -} + balance: string; + codeHash: string; + nonce: string; + storageHash: string; + accountProof: string[]; // array of rlp-serialized merkle nodes beginning with stateRoot-node + storageProof: StorageEntry[]; +}; type Block = { - number: number - hash: string - parentHash: string - nonce: number - sha3Uncles: string - logsBloom: string[] - transactionsRoot: string - stateRoot: string - receiptsRoot: string - miner: string - difficulty: number - totalDifficulty: number - extraData: string - size: number - gasLimit: number - gasUsed: number - timestamp: number - transactions: string[] - uncles: string[] - baseFeePerGas?: string - mixHash: string -} + number: number; + hash: string; + parentHash: string; + nonce: number; + sha3Uncles: string; + logsBloom: string[]; + transactionsRoot: string; + stateRoot: string; + receiptsRoot: string; + miner: string; + difficulty: number; + totalDifficulty: number; + extraData: string; + size: number; + gasLimit: number; + gasUsed: number; + timestamp: number; + transactions: string[]; + uncles: string[]; + baseFeePerGas?: string; + mixHash: string; +}; type BlockHeader = { - parentHash: string - ommersHash: string - beneficiary: string - stateRoot: string - transactionsRoot: string - receiptsRoot: string - logsBloom: string[] - difficulty: number - height: number - gasLimit: number - gasUsed: number - timestamp: number - extraData: string - mixHash: string - nonce: number - baseFeePerGas: number -} + parentHash: string; + ommersHash: string; + beneficiary: string; + stateRoot: string; + transactionsRoot: string; + receiptsRoot: string; + logsBloom: string[]; + difficulty: number; + height: number; + gasLimit: number; + gasUsed: number; + timestamp: number; + extraData: string; + mixHash: string; + nonce: number; + baseFeePerGas: number; +}; -export { Block, BlockHeader, StorageEntry, EthGetProofResponse } +export { Block, BlockHeader, StorageEntry, EthGetProofResponse }; diff --git a/packages/protocol/test/utils/trie.ts b/packages/protocol/test/utils/trie.ts index 2c3bd231414..7afec4cc43c 100644 --- a/packages/protocol/test/utils/trie.ts +++ b/packages/protocol/test/utils/trie.ts @@ -1,62 +1,62 @@ -import { BaseTrie, SecureTrie } from "merkle-patricia-tree" -import { ethers } from "ethers" -import * as rlp from "rlp" -import { randomBytes } from "crypto" +import { BaseTrie, SecureTrie } from "merkle-patricia-tree"; +import { ethers } from "ethers"; +import * as rlp from "rlp"; +import { randomBytes } from "crypto"; type Node = { - key: Buffer - value: Buffer -} + key: Buffer; + value: Buffer; +}; type Root = { - root: Buffer -} + root: Buffer; +}; type Proof = { - proof: string -} + proof: string; +}; type Test = { - node: Node - root: Root - proof: Proof -} + node: Node; + root: Root; + proof: Proof; +}; class MerkleTrie { - public trie: T - public nodes: Node[] = [] - private nodeLength: number - private amountOfNodes: number + public trie: T; + public nodes: Node[] = []; + private nodeLength: number; + private amountOfNodes: number; constructor(amountOfNodes: number, nodeLength: number, f: () => T) { - this.amountOfNodes = amountOfNodes - this.nodeLength = nodeLength - this.trie = f() + this.amountOfNodes = amountOfNodes; + this.nodeLength = nodeLength; + this.trie = f(); } async init() { - this.nodes = [] + this.nodes = []; for (let i = 0; i < this.amountOfNodes; i++) { - this.nodes.push(this.newRandomNode()) + this.nodes.push(this.newRandomNode()); } - await this.build(this.nodes) + await this.build(this.nodes); } newRandomNode(): Node { return { key: randomBytes(this.nodeLength), value: randomBytes(this.nodeLength), - } + }; } async build(nodes: Node[]): Promise { - nodes.map(async (n) => await this.trie.put(n.key, n.value)) + nodes.map(async (n) => await this.trie.put(n.key, n.value)); } async makeTest(key: Buffer): Promise { - const trie = this.trie.copy() - const value = await trie.get(key) - const proof = await BaseTrie.createProof(trie, key) + const trie = this.trie.copy(); + const value = await trie.get(key); + const proof = await BaseTrie.createProof(trie, key); return { node: { @@ -69,7 +69,7 @@ class MerkleTrie { root: { root: trie.root, }, - } + }; } } -export { MerkleTrie } +export { MerkleTrie }; diff --git a/packages/protocol/utils/generate_genesis/erc20.ts b/packages/protocol/utils/generate_genesis/erc20.ts index 27e0d02b9db..887cfd1a4b5 100644 --- a/packages/protocol/utils/generate_genesis/erc20.ts +++ b/packages/protocol/utils/generate_genesis/erc20.ts @@ -1,15 +1,15 @@ -import { ethers } from "ethers" -import { Result } from "./interface" -const path = require("path") -const ARTIFACTS_PATH = path.join(__dirname, "../../artifacts/contracts") +import { ethers } from "ethers"; +import { Result } from "./interface"; +const path = require("path"); +const ARTIFACTS_PATH = path.join(__dirname, "../../artifacts/contracts"); const { computeStorageSlots, getStorageLayout, -} = require("@defi-wonderland/smock/dist/src/utils") +} = require("@defi-wonderland/smock/dist/src/utils"); -export const TOKEN_NAME = "PredeployERC20" -export const TOKEN_SYMBOL = "PRE" -export const PREMINT_SEED_ACCOUNT_BALANCE = ethers.BigNumber.from(1024000) +export const TOKEN_NAME = "PredeployERC20"; +export const TOKEN_SYMBOL = "PRE"; +export const PREMINT_SEED_ACCOUNT_BALANCE = ethers.BigNumber.from(1024000); // deployERC20 generates a L2 genesis alloc of an ERC-20 contract, // and premints some tokens for the seed accounts given in the configurations. @@ -17,22 +17,22 @@ export async function deployERC20( config: any, result: Result ): Promise { - const { contractOwner, chainId, seedAccounts } = config + const { contractOwner, chainId, seedAccounts } = config; - const alloc: any = {} - const storageLayouts: any = {} + const alloc: any = {}; + const storageLayouts: any = {}; const artifact = require(path.join( ARTIFACTS_PATH, "./test/thirdparty/TestERC20.sol/TestERC20.json" - )) + )); - let address: string + let address: string; if ( config.contractAddresses && ethers.utils.isAddress(config.contractAddresses[artifact.contractName]) ) { - address = config.contractAddresses[artifact.contractName] + address = config.contractAddresses[artifact.contractName]; } else { address = ethers.utils.getCreate2Address( contractOwner, @@ -40,7 +40,7 @@ export async function deployERC20( ethers.utils.toUtf8Bytes(`${chainId}${artifact.contractName}`) ), ethers.utils.keccak256(ethers.utils.toUtf8Bytes(artifact.bytecode)) - ) + ); } const variables = { @@ -48,11 +48,11 @@ export async function deployERC20( _symbol: TOKEN_SYMBOL, _totalSupply: PREMINT_SEED_ACCOUNT_BALANCE.mul(seedAccounts.length), _balances: {} as any, - } + }; for (const account of seedAccounts) { variables._balances[Object.keys(account)[0]] = - PREMINT_SEED_ACCOUNT_BALANCE + PREMINT_SEED_ACCOUNT_BALANCE; } alloc[address] = { @@ -60,21 +60,24 @@ export async function deployERC20( storage: {}, code: artifact.deployedBytecode, balance: "0x0", - } + }; storageLayouts[artifact.contractName] = await getStorageLayout( artifact.contractName - ) + ); for (const slot of computeStorageSlots( storageLayouts[artifact.contractName], variables )) { - alloc[address].storage[slot.key] = slot.val + alloc[address].storage[slot.key] = slot.val; } - result.alloc = Object.assign(result.alloc, alloc) - result.storageLayouts = Object.assign(result.storageLayouts, storageLayouts) + result.alloc = Object.assign(result.alloc, alloc); + result.storageLayouts = Object.assign( + result.storageLayouts, + storageLayouts + ); - return result + return result; } diff --git a/packages/protocol/utils/generate_genesis/interface.ts b/packages/protocol/utils/generate_genesis/interface.ts index 234a917d0dc..0b8a1360a4f 100644 --- a/packages/protocol/utils/generate_genesis/interface.ts +++ b/packages/protocol/utils/generate_genesis/interface.ts @@ -1,14 +1,14 @@ export interface Config { - contractOwner: string - chainId: number + contractOwner: string; + chainId: number; seedAccounts: Array<{ - [key: string]: number - }> - predeployERC20: boolean - contractAddresses: Object + [key: string]: number; + }>; + predeployERC20: boolean; + contractAddresses: Object; } export interface Result { - alloc: any - storageLayouts: any + alloc: any; + storageLayouts: any; } diff --git a/packages/protocol/utils/generate_genesis/main.ts b/packages/protocol/utils/generate_genesis/main.ts index 797e484163f..67bce1b5a18 100644 --- a/packages/protocol/utils/generate_genesis/main.ts +++ b/packages/protocol/utils/generate_genesis/main.ts @@ -1,25 +1,25 @@ -import { Config } from "./interface" -const fs = require("fs") -const path = require("path") -const { ethers } = require("ethers") -const { deployTaikoL2 } = require("./taikoL2") -const { deployERC20 } = require("./erc20") +import { Config } from "./interface"; +const fs = require("fs"); +const path = require("path"); +const { ethers } = require("ethers"); +const { deployTaikoL2 } = require("./taikoL2"); +const { deployERC20 } = require("./erc20"); // Generate a L2 genesis JSON based on the given configurations. // ref: https://docs.soliditylang.org/en/latest/internals/layout_in_storage.html async function main() { if (process.argv.length < 3) { - throw new Error("missing config json") + throw new Error("missing config json"); } const config: Config = require(path.isAbsolute(process.argv[2]) ? process.argv[2] - : path.join(process.cwd(), process.argv[2])) + : path.join(process.cwd(), process.argv[2])); - const contractOwner = config.contractOwner - const chainId = config.chainId - const seedAccounts = config.seedAccounts - const predeployERC20 = config.predeployERC20 + const contractOwner = config.contractOwner; + const chainId = config.chainId; + const seedAccounts = config.seedAccounts; + const predeployERC20 = config.predeployERC20; if ( !ethers.utils.isAddress(contractOwner) || @@ -30,7 +30,7 @@ async function main() { Object.keys(seedAccount).length === 1 && ethers.utils.isAddress(Object.keys(seedAccount)[0]) && Number.isInteger(Object.values(seedAccount)[0]) - ) + ); }) || typeof predeployERC20 !== "boolean" ) { @@ -40,44 +40,44 @@ async function main() { chainId, seedAccounts, })}` - ) + ); } - console.log("config: %o", config) + console.log("config: %o", config); - console.log("start deploy TaikoL2 contract") + console.log("start deploy TaikoL2 contract"); let result = await deployTaikoL2(config, { alloc: {}, storageLayouts: {}, - }).catch(console.error) + }).catch(console.error); if (config.predeployERC20) { - console.log("start deploy an ERC-20 token") + console.log("start deploy an ERC-20 token"); - result = await deployERC20(config, result) + result = await deployERC20(config, result); } const allocSavedPath = path.join( __dirname, "../../deployments/genesis_alloc.json" - ) + ); - fs.writeFileSync(allocSavedPath, JSON.stringify(result.alloc, null, 2)) + fs.writeFileSync(allocSavedPath, JSON.stringify(result.alloc, null, 2)); const layoutSavedPath = path.join( __dirname, "../../deployments/genesis_storage_layout.json" - ) + ); fs.writeFileSync( layoutSavedPath, JSON.stringify(result.storageLayouts, null, 2) - ) + ); - console.log("done") - console.log(`alloc JSON saved to ${allocSavedPath}`) - console.log(`layout JSON saved to ${layoutSavedPath}`) + console.log("done"); + console.log(`alloc JSON saved to ${allocSavedPath}`); + console.log(`layout JSON saved to ${layoutSavedPath}`); } -main().catch(console.error) +main().catch(console.error); diff --git a/packages/protocol/utils/generate_genesis/taikoL2.ts b/packages/protocol/utils/generate_genesis/taikoL2.ts index fd384f1e6be..d7e4eb3ccd8 100644 --- a/packages/protocol/utils/generate_genesis/taikoL2.ts +++ b/packages/protocol/utils/generate_genesis/taikoL2.ts @@ -1,88 +1,91 @@ -import { Config, Result } from "./interface" -const path = require("path") -const { ethers } = require("ethers") +import { Config, Result } from "./interface"; +const path = require("path"); +const { ethers } = require("ethers"); // eslint-disable-next-line node/no-extraneous-require -const linker = require("solc/linker") +const linker = require("solc/linker"); const { computeStorageSlots, getStorageLayout, -} = require("@defi-wonderland/smock/dist/src/utils") -const ARTIFACTS_PATH = path.join(__dirname, "../../artifacts/contracts") +} = require("@defi-wonderland/smock/dist/src/utils"); +const ARTIFACTS_PATH = path.join(__dirname, "../../artifacts/contracts"); // deployTaikoL2 generates a L2 genesis alloc of the TaikoL2 contract. export async function deployTaikoL2( config: Config, result: Result ): Promise { - const { contractOwner, chainId, seedAccounts } = config + const { contractOwner, chainId, seedAccounts } = config; - const alloc: any = {} + const alloc: any = {}; - let etherVaultBalance = ethers.BigNumber.from("2").pow(128).sub(1) // MaxUint128 + let etherVaultBalance = ethers.BigNumber.from("2").pow(128).sub(1); // MaxUint128 for (const seedAccount of seedAccounts) { - const accountAddress = Object.keys(seedAccount)[0] + const accountAddress = Object.keys(seedAccount)[0]; const balance = ethers.utils.parseEther( `${Object.values(seedAccount)[0]}` - ) + ); - console.log(`seedAccountAddress: ${accountAddress}`) - console.log(`premintBalance: ${balance}`) + console.log(`seedAccountAddress: ${accountAddress}`); + console.log(`premintBalance: ${balance}`); - alloc[accountAddress] = { balance: balance.toHexString() } + alloc[accountAddress] = { balance: balance.toHexString() }; - etherVaultBalance = etherVaultBalance.sub(balance) + etherVaultBalance = etherVaultBalance.sub(balance); } - console.log({ etherVaultBalance }) - console.log("\n") + console.log({ etherVaultBalance }); + console.log("\n"); const contractConfigs: any = await generateContractConfigs( contractOwner, chainId, config.contractAddresses - ) + ); - const storageLayouts: any = {} + const storageLayouts: any = {}; for (const contractName of Object.keys(contractConfigs)) { - console.log(`generating genesis.alloc for ${contractName}`) + console.log(`generating genesis.alloc for ${contractName}`); - const contractConfig = contractConfigs[contractName] + const contractConfig = contractConfigs[contractName]; alloc[contractConfig.address] = { contractName, storage: {}, code: contractConfig.deployedBytecode, - } + }; // pre-mint ETHs for EtherVault contract alloc[contractConfig.address].balance = contractName === "EtherVault" ? etherVaultBalance.toHexString() - : "0x0" + : "0x0"; // since we enable storageLayout compiler output in hardhat.config.ts, // rollup/artifacts/build-info will contain storage layouts, here // reading it using smock package. - storageLayouts[contractName] = await getStorageLayout(contractName) + storageLayouts[contractName] = await getStorageLayout(contractName); // initialize contract variables, we only care about the variables // that need to be initialized with non-zero value. const slots = computeStorageSlots( storageLayouts[contractName], contractConfigs[contractName].variables - ) + ); for (const slot of slots) { - alloc[contractConfig.address].storage[slot.key] = slot.val + alloc[contractConfig.address].storage[slot.key] = slot.val; } } - result.alloc = Object.assign(result.alloc, alloc) - result.storageLayouts = Object.assign(result.storageLayouts, storageLayouts) + result.alloc = Object.assign(result.alloc, alloc); + result.storageLayouts = Object.assign( + result.storageLayouts, + storageLayouts + ); - return result + return result; } // generateContractConfigs returns all L2 contracts address, deployedBytecode, @@ -131,28 +134,28 @@ async function generateContractConfigs( ARTIFACTS_PATH, "./bridge/EtherVault.sol/EtherVault.json" )), - } + }; - const addressMap: any = {} + const addressMap: any = {}; for (const [contractName, artifact] of Object.entries(contractArtifacts)) { - let bytecode = (artifact as any).bytecode + let bytecode = (artifact as any).bytecode; if (contractName === "TaikoL2") { if (!addressMap.LibTxDecoder) { - throw new Error("LibTxDecoder not initialized") + throw new Error("LibTxDecoder not initialized"); } - bytecode = linkContractLibs(contractArtifacts.TaikoL2, addressMap) + bytecode = linkContractLibs(contractArtifacts.TaikoL2, addressMap); } else if (contractName === "LibBridgeProcess") { if (!addressMap.LibTrieProof) { - throw new Error("LibTrieProof not initialized") + throw new Error("LibTrieProof not initialized"); } bytecode = linkContractLibs( contractArtifacts.LibBridgeProcess, addressMap - ) + ); } else if (contractName === "Bridge") { if ( !addressMap.LibTrieProof || @@ -161,17 +164,17 @@ async function generateContractConfigs( ) { throw new Error( "LibTrieProof/LibBridgeRetry/LibBridgeProcess not initialized" - ) + ); } - bytecode = linkContractLibs(contractArtifacts.Bridge, addressMap) + bytecode = linkContractLibs(contractArtifacts.Bridge, addressMap); } if ( hardCodedAddresses && ethers.utils.isAddress(hardCodedAddresses[contractName]) ) { - addressMap[contractName] = hardCodedAddresses[contractName] + addressMap[contractName] = hardCodedAddresses[contractName]; } else { addressMap[contractName] = ethers.utils.getCreate2Address( contractOwner, @@ -179,12 +182,12 @@ async function generateContractConfigs( ethers.utils.toUtf8Bytes(`${chainId}${contractName}`) ), ethers.utils.keccak256(ethers.utils.toUtf8Bytes(bytecode)) - ) + ); } } - console.log("pre-computed addresses:") - console.log(addressMap) + console.log("pre-computed addresses:"); + console.log(addressMap); return { // Libraries @@ -319,7 +322,7 @@ async function generateContractConfigs( authorizedAddrs: { [`${addressMap.Bridge}`]: true }, }, }, - } + }; } // linkContractLibs tries to link contract deployedBytecode to its libraries. @@ -332,32 +335,32 @@ function linkContractLibs(artifact: any, addressMap: any) { linker.findLinkReferences(artifact.deployedBytecode), addressMap ) - ) + ); if (ethers.utils.toUtf8Bytes(linkedBytecode).includes("$__")) { - throw new Error("failed to link") + throw new Error("failed to link"); } - return linkedBytecode + return linkedBytecode; } // getLinkLibs tries to get all linked libraries addresses from the given address map, and then // assembles a `libraries` param of `linker.linkBytecode(bytecode, libraries)`. function getLinkLibs(artifact: any, linkRefs: any, addressMap: any) { - const result: any = {} + const result: any = {}; Object.values(artifact.deployedLinkReferences).forEach( (linkReference: any) => { - const contractName = Object.keys(linkReference)[0] + const contractName = Object.keys(linkReference)[0]; const linkRefKey: any = Object.keys(linkRefs).find( (key) => linkRefs[key][0].start === linkReference[contractName][0].start + 1 - ) + ); - result[linkRefKey] = addressMap[contractName] + result[linkRefKey] = addressMap[contractName]; } - ) + ); - return result + return result; } diff --git a/packages/website/package.json b/packages/website/package.json index b2e5adef5da..152caba2ae5 100644 --- a/packages/website/package.json +++ b/packages/website/package.json @@ -1,5 +1,5 @@ { - "name": "@taiko/web", + "name": "@taiko/website", "version": "0.0.0", "private": true, "scripts": {