From 7bee3717718059d5a782beb64d7bce3ef152b72c Mon Sep 17 00:00:00 2001 From: Andres Aiello Date: Tue, 14 Nov 2023 16:35:23 -0300 Subject: [PATCH 1/6] Cleanup zetachain repo to be zeta-apps repo --- README.md | 10 +- packages/addresses-tools/.npmignore | 19 - packages/addresses-tools/README.md | 3 - packages/addresses-tools/hardhat.config.ts | 5 - packages/addresses-tools/package.json | 24 - .../addresses-tools/src/add-new-address.ts | 10 - .../addresses-tools/src/add-new-network.ts | 14 - .../addresses-tools/src/addresses.helpers.ts | 299 ------- packages/addresses-tools/src/index.ts | 3 - packages/addresses-tools/src/log-addresses.ts | 38 - .../addresses-tools/src/misc.constants.ts | 1 - packages/addresses-tools/src/misc.helpers.ts | 2 - packages/addresses-tools/src/networks.ts | 84 -- .../src/system-addresses.helpers.ts | 49 -- packages/addresses-tools/tsconfig.json | 14 - packages/addresses/.npmignore | 30 - packages/addresses/README.md | 26 - packages/addresses/package.json | 25 - packages/addresses/src/addresses.athens.json | 162 ---- packages/addresses/src/addresses.helpers.ts | 185 ----- packages/addresses/src/addresses.mainnet.json | 71 -- packages/addresses/src/addresses.troy.json | 94 --- packages/addresses/src/index.ts | 1 - packages/addresses/tsconfig.json | 15 - packages/example-contracts/.env.example | 18 - packages/example-contracts/.eslintrc.js | 23 - packages/example-contracts/README.md | 16 - .../cross-chain-counter/CrossChainCounter.sol | 57 -- .../test/CounterZetaConnectorMock.sol | 63 -- .../cross-chain-message/CrossChainMessage.sol | 85 -- .../test/CrossChainMessageConnector.sol | 63 -- .../CrossChainWarriors.sol | 140 ---- .../test/CrossChainWarriorsMock.sol | 17 - .../CrossChainWarriorsZetaConnectorMock.sol | 63 -- .../multi-chain-swap/MultiChainSwap.sol | 69 -- .../multi-chain-swap/MultiChainSwapErrors.sol | 20 - .../MultiChainSwapTrident.strategy.sol | 295 ------- .../MultiChainSwapUniV2.strategy.sol | 357 -------- .../MultiChainSwapUniV3.strategy.sol | 304 ------- .../test/MultiChainSwapZetaConnector.sol | 76 -- .../shared/ImmutableCreate2Factory.sol | 8 - .../contracts/shared/TestContracts.sol | 10 - .../contracts/shared/ZetaEthMock.sol | 12 - .../contracts/shared/ZetaTestContracts.sol | 8 - .../docs/cross-chain-counter.md | 5 - .../docs/cross-chain-warriors.md | 20 - packages/example-contracts/hardhat.config.ts | 46 -- .../CrossChainCounter.helpers.ts | 62 -- .../CrossChainMessage.helpers.ts | 61 -- .../CrossChainWarriors.helpers.ts | 101 --- .../MultiChainSwap.helpers.ts | 35 - .../shared/ImmutableCreate2Factory.helpers.ts | 75 -- .../lib/shared/address.helpers.ts | 23 - .../lib/shared/deploy.helpers.ts | 96 --- .../lib/shared/network.constants.ts | 104 --- packages/example-contracts/package.json | 42 - .../scripts/add-liquidity-uniswap-v2.ts | 114 --- .../scripts/cross-chain-counter/deploy.ts | 11 - .../scripts/cross-chain-warriors/deploy.ts | 30 - .../deterministic-deploy.ts | 59 -- .../set-cross-chain-data.ts | 34 - .../cross-chain-warriors/verify-contract.ts | 18 - .../deploy-multi-chain-swap-trident.ts | 33 - .../deploy-multi-chain-swap-v3.ts | 39 - .../deploy-multi-chain-swap.ts | 24 - .../scripts/multi-chain-swap/deploy.ts | 14 - .../multi-chain-swap/deterministic-deploy.ts | 59 -- .../multi-chain-swap/do-cross-chain-swap.ts | 42 - .../multi-chain-swap/set-cross-chain-data.ts | 47 -- .../multi-chain-swap/verify-contract.ts | 17 - .../test/CrossChainCounter.spec.ts | 112 --- .../test/CrossChainMessage.spec.ts | 142 ---- .../test/CrossChainWarriors.spec.ts | 304 ------- .../test/MultiChainSwap.constants.ts | 1 - .../test/MultiChainSwap.spec.ts | 628 -------------- .../test/MultiChainSwapUniswapV3.spec.ts | 667 --------------- .../example-contracts/test/test.helpers.ts | 89 -- packages/example-contracts/tsconfig.json | 14 - .../zeta-app-contracts/data/addresses.json | 55 ++ packages/zeta-app-contracts/hardhat.config.ts | 13 +- .../MultiChainValue.helpers.ts | 18 +- .../shared/ImmutableCreate2Factory.helpers.ts | 10 +- .../lib/shared/address.helpers.ts | 23 - packages/zeta-app-contracts/package.json | 5 +- .../scripts/address.helpers.ts | 31 + .../scripts/multi-chain-value/deploy.ts | 41 +- .../multi-chain-value/deterministic-deploy.ts | 17 +- .../scripts/multi-chain-value/send-value.ts | 31 +- .../multi-chain-value/verify-contract.ts | 12 +- .../multi-output/ZetaMultiOutput.sol | 0 .../zevm-app-contracts/data/addresses.json | 10 + packages/zevm-app-contracts/hardhat.config.ts | 13 +- packages/zevm-app-contracts/package.json | 5 +- .../scripts/address.helpers.ts | 39 + .../scripts/disperse/deploy.ts | 6 +- .../liquidity-incentives/add-reward.ts | 30 +- .../scripts/liquidity-incentives/deploy.ts | 6 +- .../liquidity-incentives/read-rewards-data.ts | 12 +- .../scripts/zeta-points/deploy.ts | 11 +- .../scripts/zeta-swap/deploy.ts | 2 +- .../scripts/zeta-swap/get-system-data.ts | 17 +- .../scripts/zeta-swap/send.ts | 9 +- .../scripts/zeta-swap/swap-on-zevm.ts | 18 +- .../scripts/zeta-swap/swap.ts | 25 +- .../test/LiquidityIncentives.spec.ts | 20 +- .../test/MultipleOutput.spec.ts | 20 +- packages/zevm-app-contracts/test/Swap.spec.ts | 22 +- packages/zevm-example-contracts/.env.example | 2 - packages/zevm-example-contracts/.eslintrc.js | 23 - packages/zevm-example-contracts/README.md | 16 - .../contracts/shared/BytesHelperLib.sol | 22 - .../contracts/shared/MockSystemContract.sol | 60 -- .../contracts/shared/MockZRC20.sol | 33 - .../contracts/shared/SwapHelperLib.sol | 93 --- .../contracts/shared/TestContracts.sol | 8 - .../contracts/shared/TestUniswapContracts.sol | 10 - .../zevm-example-contracts/hardhat.config.ts | 46 -- packages/zevm-example-contracts/package.json | 39 - .../scripts/multi-output/deploy.ts | 20 - .../test/test.helpers.ts | 71 -- packages/zevm-example-contracts/tsconfig.json | 14 - yarn.lock | 763 +----------------- 122 files changed, 331 insertions(+), 7466 deletions(-) delete mode 100644 packages/addresses-tools/.npmignore delete mode 100644 packages/addresses-tools/README.md delete mode 100644 packages/addresses-tools/hardhat.config.ts delete mode 100644 packages/addresses-tools/package.json delete mode 100644 packages/addresses-tools/src/add-new-address.ts delete mode 100644 packages/addresses-tools/src/add-new-network.ts delete mode 100644 packages/addresses-tools/src/addresses.helpers.ts delete mode 100644 packages/addresses-tools/src/index.ts delete mode 100644 packages/addresses-tools/src/log-addresses.ts delete mode 100644 packages/addresses-tools/src/misc.constants.ts delete mode 100644 packages/addresses-tools/src/misc.helpers.ts delete mode 100644 packages/addresses-tools/src/networks.ts delete mode 100644 packages/addresses-tools/src/system-addresses.helpers.ts delete mode 100644 packages/addresses-tools/tsconfig.json delete mode 100644 packages/addresses/.npmignore delete mode 100644 packages/addresses/README.md delete mode 100644 packages/addresses/package.json delete mode 100644 packages/addresses/src/addresses.athens.json delete mode 100644 packages/addresses/src/addresses.helpers.ts delete mode 100644 packages/addresses/src/addresses.mainnet.json delete mode 100644 packages/addresses/src/addresses.troy.json delete mode 100644 packages/addresses/src/index.ts delete mode 100644 packages/addresses/tsconfig.json delete mode 100644 packages/example-contracts/.env.example delete mode 100644 packages/example-contracts/.eslintrc.js delete mode 100644 packages/example-contracts/README.md delete mode 100644 packages/example-contracts/contracts/cross-chain-counter/CrossChainCounter.sol delete mode 100644 packages/example-contracts/contracts/cross-chain-counter/test/CounterZetaConnectorMock.sol delete mode 100644 packages/example-contracts/contracts/cross-chain-message/CrossChainMessage.sol delete mode 100644 packages/example-contracts/contracts/cross-chain-message/test/CrossChainMessageConnector.sol delete mode 100644 packages/example-contracts/contracts/cross-chain-warriors/CrossChainWarriors.sol delete mode 100644 packages/example-contracts/contracts/cross-chain-warriors/test/CrossChainWarriorsMock.sol delete mode 100644 packages/example-contracts/contracts/cross-chain-warriors/test/CrossChainWarriorsZetaConnectorMock.sol delete mode 100644 packages/example-contracts/contracts/multi-chain-swap/MultiChainSwap.sol delete mode 100644 packages/example-contracts/contracts/multi-chain-swap/MultiChainSwapErrors.sol delete mode 100644 packages/example-contracts/contracts/multi-chain-swap/MultiChainSwapTrident.strategy.sol delete mode 100644 packages/example-contracts/contracts/multi-chain-swap/MultiChainSwapUniV2.strategy.sol delete mode 100644 packages/example-contracts/contracts/multi-chain-swap/MultiChainSwapUniV3.strategy.sol delete mode 100644 packages/example-contracts/contracts/multi-chain-swap/test/MultiChainSwapZetaConnector.sol delete mode 100644 packages/example-contracts/contracts/shared/ImmutableCreate2Factory.sol delete mode 100644 packages/example-contracts/contracts/shared/TestContracts.sol delete mode 100644 packages/example-contracts/contracts/shared/ZetaEthMock.sol delete mode 100644 packages/example-contracts/contracts/shared/ZetaTestContracts.sol delete mode 100644 packages/example-contracts/docs/cross-chain-counter.md delete mode 100644 packages/example-contracts/docs/cross-chain-warriors.md delete mode 100644 packages/example-contracts/hardhat.config.ts delete mode 100644 packages/example-contracts/lib/cross-chain-counter/CrossChainCounter.helpers.ts delete mode 100644 packages/example-contracts/lib/cross-chain-message/CrossChainMessage.helpers.ts delete mode 100644 packages/example-contracts/lib/cross-chain-warriors/CrossChainWarriors.helpers.ts delete mode 100644 packages/example-contracts/lib/multi-chain-swap/MultiChainSwap.helpers.ts delete mode 100644 packages/example-contracts/lib/shared/ImmutableCreate2Factory.helpers.ts delete mode 100644 packages/example-contracts/lib/shared/address.helpers.ts delete mode 100644 packages/example-contracts/lib/shared/deploy.helpers.ts delete mode 100644 packages/example-contracts/lib/shared/network.constants.ts delete mode 100644 packages/example-contracts/package.json delete mode 100644 packages/example-contracts/scripts/add-liquidity-uniswap-v2.ts delete mode 100644 packages/example-contracts/scripts/cross-chain-counter/deploy.ts delete mode 100644 packages/example-contracts/scripts/cross-chain-warriors/deploy.ts delete mode 100644 packages/example-contracts/scripts/cross-chain-warriors/deterministic-deploy.ts delete mode 100644 packages/example-contracts/scripts/cross-chain-warriors/set-cross-chain-data.ts delete mode 100644 packages/example-contracts/scripts/cross-chain-warriors/verify-contract.ts delete mode 100644 packages/example-contracts/scripts/multi-chain-swap/deploy-multi-chain-swap-trident.ts delete mode 100644 packages/example-contracts/scripts/multi-chain-swap/deploy-multi-chain-swap-v3.ts delete mode 100644 packages/example-contracts/scripts/multi-chain-swap/deploy-multi-chain-swap.ts delete mode 100644 packages/example-contracts/scripts/multi-chain-swap/deploy.ts delete mode 100644 packages/example-contracts/scripts/multi-chain-swap/deterministic-deploy.ts delete mode 100644 packages/example-contracts/scripts/multi-chain-swap/do-cross-chain-swap.ts delete mode 100644 packages/example-contracts/scripts/multi-chain-swap/set-cross-chain-data.ts delete mode 100644 packages/example-contracts/scripts/multi-chain-swap/verify-contract.ts delete mode 100644 packages/example-contracts/test/CrossChainCounter.spec.ts delete mode 100644 packages/example-contracts/test/CrossChainMessage.spec.ts delete mode 100644 packages/example-contracts/test/CrossChainWarriors.spec.ts delete mode 100644 packages/example-contracts/test/MultiChainSwap.constants.ts delete mode 100644 packages/example-contracts/test/MultiChainSwap.spec.ts delete mode 100644 packages/example-contracts/test/MultiChainSwapUniswapV3.spec.ts delete mode 100644 packages/example-contracts/test/test.helpers.ts delete mode 100644 packages/example-contracts/tsconfig.json create mode 100644 packages/zeta-app-contracts/data/addresses.json delete mode 100644 packages/zeta-app-contracts/lib/shared/address.helpers.ts create mode 100644 packages/zeta-app-contracts/scripts/address.helpers.ts rename packages/{zevm-example-contracts => zevm-app-contracts}/contracts/multi-output/ZetaMultiOutput.sol (100%) create mode 100644 packages/zevm-app-contracts/data/addresses.json create mode 100644 packages/zevm-app-contracts/scripts/address.helpers.ts rename packages/{zevm-example-contracts => zevm-app-contracts}/test/MultipleOutput.spec.ts (89%) delete mode 100644 packages/zevm-example-contracts/.env.example delete mode 100644 packages/zevm-example-contracts/.eslintrc.js delete mode 100644 packages/zevm-example-contracts/README.md delete mode 100644 packages/zevm-example-contracts/contracts/shared/BytesHelperLib.sol delete mode 100644 packages/zevm-example-contracts/contracts/shared/MockSystemContract.sol delete mode 100644 packages/zevm-example-contracts/contracts/shared/MockZRC20.sol delete mode 100644 packages/zevm-example-contracts/contracts/shared/SwapHelperLib.sol delete mode 100644 packages/zevm-example-contracts/contracts/shared/TestContracts.sol delete mode 100644 packages/zevm-example-contracts/contracts/shared/TestUniswapContracts.sol delete mode 100644 packages/zevm-example-contracts/hardhat.config.ts delete mode 100644 packages/zevm-example-contracts/package.json delete mode 100644 packages/zevm-example-contracts/scripts/multi-output/deploy.ts delete mode 100644 packages/zevm-example-contracts/test/test.helpers.ts delete mode 100644 packages/zevm-example-contracts/tsconfig.json diff --git a/README.md b/README.md index 3d9cbd34..eadfb67a 100644 --- a/README.md +++ b/README.md @@ -6,8 +6,6 @@ ZetaChain is a public, decentralized blockchain and smart contract platform buil * Utilities to interact with ZetaChain's contracts from your dApp, scripts, or tests. * Interfaces to easily develop omnichain contracts. -* Omnichain dApp example contracts. -* Protocol native contracts (Zeta Token, Zeta Connector). ## Learn more about ZetaChain @@ -34,13 +32,9 @@ ZetaChain is a public, decentralized blockchain and smart contract platform buil ### Packages -#### [Addresses](packages/addresses) +#### [Zeta App contracts](packages/zeta-app-contracts) -#### [Example contracts](packages/example-contracts) - -#### [Protocol contracts](packages/example-contracts) - -#### [ZEVM contracts](packages/zevm-contracts) +#### [ZEVM App contracts](packages/zevm-app-contracts) ### Cross-repo commands diff --git a/packages/addresses-tools/.npmignore b/packages/addresses-tools/.npmignore deleted file mode 100644 index c8886364..00000000 --- a/packages/addresses-tools/.npmignore +++ /dev/null @@ -1,19 +0,0 @@ -# Ignore source files and other development files -src/ -*.tsx -*.map -*.spec.* -*.test.* -*.log -*.lock -.editorconfig -.eslintrc* -.prettierrc* -.jest.config.js -tsconfig.json - -# Include the dist folder and other necessary files -!dist/ -!README.md -!LICENSE -!package.json diff --git a/packages/addresses-tools/README.md b/packages/addresses-tools/README.md deleted file mode 100644 index 5e0a61c6..00000000 --- a/packages/addresses-tools/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# ZetaChain addresses-tools - -This package includes utilities to work with multiple addresses and networks. diff --git a/packages/addresses-tools/hardhat.config.ts b/packages/addresses-tools/hardhat.config.ts deleted file mode 100644 index a3b8359f..00000000 --- a/packages/addresses-tools/hardhat.config.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { HardhatUserConfig } from "hardhat/types"; - -const config: HardhatUserConfig = {}; - -export default config; diff --git a/packages/addresses-tools/package.json b/packages/addresses-tools/package.json deleted file mode 100644 index e77f2b69..00000000 --- a/packages/addresses-tools/package.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "name": "@zetachain/addresses-tools", - "version": "0.0.8", - "license": "MIT", - "author": "zetachain", - "publishConfig": { - "access": "public", - "registry": "https://registry.npmjs.org/" - }, - "main": "./dist/index.js", - "module": "./dist/index.js", - "types": "./dist/index.d.ts", - "files": [ - "dist" - ], - "scripts": { - "tsc:watch": "npx tsc --watch", - "prepublishOnly": "npx tsc" - }, - "devDependencies": { - "@zetachain/addresses": "workspace:^", - "@zetachain/protocol-contracts": "^2.1.0" - } -} diff --git a/packages/addresses-tools/src/add-new-address.ts b/packages/addresses-tools/src/add-new-address.ts deleted file mode 100644 index 1fb9e423..00000000 --- a/packages/addresses-tools/src/add-new-address.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { addNewAddress } from "./addresses.helpers"; - -const name = process.argv[2]; - -if (!name) { - console.log("Usage: 'ts-node src/add-new-address '."); - process.exit(1); -} - -addNewAddress(name); diff --git a/packages/addresses-tools/src/add-new-network.ts b/packages/addresses-tools/src/add-new-network.ts deleted file mode 100644 index 1cf8b198..00000000 --- a/packages/addresses-tools/src/add-new-network.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { isZetaNetworkName } from "@zetachain/addresses"; - -import { addNewNetwork } from "./addresses.helpers"; - -const name = process.argv[2]; -const parsedAddTo = process.argv[3].split(","); - -if (!name || !parsedAddTo.every(isZetaNetworkName)) { - console.log("Usage: 'ts-node src/add-new-network '."); - console.log("Usage e.g.: 'ts-node src/add-new-network rinkeby athens'."); - process.exit(1); -} - -addNewNetwork(name, parsedAddTo); diff --git a/packages/addresses-tools/src/addresses.helpers.ts b/packages/addresses-tools/src/addresses.helpers.ts deleted file mode 100644 index dd7b33b3..00000000 --- a/packages/addresses-tools/src/addresses.helpers.ts +++ /dev/null @@ -1,299 +0,0 @@ -import { - isLocalNetworkName, - isMainnetNetworkName, - isNetworkName, - isTestnetNetworkName, - isZetaLocalnet, - isZetaMainnet, - isZetaNetworkName, - isZetaTestnet, - LocalnetAddressGroup, - LocalNetworkName, - MainnetAddressGroup, - MainnetNetworkName, - NetworkAddresses, - NetworkName, - TestnetAddressGroup, - TestnetNetworkName, - ZetaAddress, - ZetaLocalNetworkName, - ZetaMainnetNetworkName, - ZetaNetworkName, - ZetaTestnetNetworkName -} from "@zetachain/addresses"; -import { ZetaProtocolNetwork } from "@zetachain/protocol-contracts/dist/lib"; -import { ProtocolNetworkNetworkNameMap } from "@zetachain/protocol-contracts/dist/lib/address.helpers"; -import dotenv from "dotenv"; -import { readdirSync, readFileSync, writeFileSync } from "fs"; -import { network } from "hardhat"; -import { join } from "path"; - -import { deepCloneSerializable } from "./misc.helpers"; - -const LOCAL_PKG = "addresses-tools"; -const PUBLIC_PKG = "addresses"; - -const dirname = __dirname.replace(LOCAL_PKG, PUBLIC_PKG).replace("dist", "src"); - -export const getScanVariable = ({ customNetworkName }: { customNetworkName?: string } = {}): string => { - const networkName = customNetworkName || network.name; - if (!isNetworkName(networkName)) throw new Error(); - dotenv.config(); - - const v = { - athens: "", - "bitcoin-test": "", - "bsc-localnet": "", - "bsc-mainnet": process.env.BSCSCAN_API_KEY || "", - "bsc-testnet": process.env.BSCSCAN_API_KEY || "", - "eth-localnet": "", - "eth-mainnet": process.env.ETHERSCAN_API_KEY || "", - goerli: process.env.ETHERSCAN_API_KEY || "", - hardhat: "", - "klaytn-baobab": "", - "klaytn-cypress": "", - "polygon-localnet": "", - "polygon-mumbai": process.env.POLYGONSCAN_API_KEY || "" - }; - - return v[networkName]; -}; - -export const getExplorerUrl = ({ customNetworkName }: { customNetworkName?: string } = {}): string => { - const networkName = customNetworkName || network.name; - if (!isNetworkName(networkName)) throw new Error(); - dotenv.config(); - - const v = { - athens: "", - "bitcoin-test": "", - "bsc-localnet": "", - "bsc-mainnet": "https://bscscan.com/", - "bsc-testnet": "https://testnet.bscscan.com/", - "eth-localnet": "", - "eth-mainnet": "https://etherscan.io/", - goerli: "https://goerli.etherscan.io/", - hardhat: "", - "klaytn-baobab": "https://baobab.scope.klaytn.com/", - "klaytn-cypress": "https://scope.klaytn.com/", - "polygon-localnet": "", - "polygon-mumbai": "https://mumbai.polygonscan.com/" - }; - - return v[networkName]; -}; - -export const getGasSymbolByNetwork = (networkName: NetworkName): string => { - const v = { - athens: "ZETA", - "bitcoin-test": "BTC", - "bsc-localnet": "BNB", - "bsc-mainnet": "BNB", - "bsc-testnet": "BNB", - "eth-localnet": "ETH", - "eth-mainnet": "ETH", - goerli: "ETH", - hardhat: "ETH", - "klaytn-baobab": "KLAY", - "klaytn-cypress": "KLAY", - "polygon-localnet": "MATIC", - "polygon-mumbai": "MATIC" - }; - - return v[networkName]; -}; - -const MissingZetaNetworkError = new Error( - "ZETA_NETWORK is not defined, please set the environment variable (e.g.: ZETA_NETWORK=athens )" -); - -export const saveAddress = (addressName: ZetaAddress, newAddress: string) => { - const { ZETA_NETWORK } = process.env; - const { name: networkName } = network; - - if (!ZETA_NETWORK) throw MissingZetaNetworkError; - - console.log(`Updating ${addressName} address on ${ZETA_NETWORK}: ${networkName}.`); - - const filename = join(dirname, `./addresses.${ZETA_NETWORK}.json`); - - if (isZetaLocalnet(ZETA_NETWORK) && isLocalNetworkName(networkName)) { - const newAddresses: LocalnetAddressGroup = JSON.parse(readFileSync(filename, "utf8")); - if (typeof newAddresses[networkName][addressName] === "undefined") { - console.log( - `The address ${addressName} does not exist, it will get created but make sure to add it to the types.` - ); - } - - newAddresses[networkName][addressName] = newAddress; - - writeFileSync(filename, JSON.stringify(newAddresses, null, 2)); - - console.log(`Updated, new address: ${newAddress}.`); - - return; - } - - if (isZetaTestnet(ZETA_NETWORK) && isTestnetNetworkName(networkName)) { - const newAddresses: TestnetAddressGroup = JSON.parse(readFileSync(filename, "utf8")); - newAddresses[networkName][addressName] = newAddress; - - writeFileSync(filename, JSON.stringify(newAddresses, null, 2)); - - console.log(`Updated, new address: ${newAddress}.`); - - return; - } - - if (isZetaMainnet(ZETA_NETWORK) && isMainnetNetworkName(networkName)) { - const newAddresses: MainnetAddressGroup = JSON.parse(readFileSync(filename, "utf8")); - newAddresses[networkName][addressName] = newAddress; - - writeFileSync(filename, JSON.stringify(newAddresses, null, 2)); - - console.log(`Updated, new address: ${newAddress}.`); - - return; - } - - throw new Error(`Invalid ZETA_NETWORK + network combination ${ZETA_NETWORK} ${networkName}.`); -}; - -export const addNewAddress = (addressName: string, addressValue: string = "") => { - if (!addressName) throw new Error("Emtpy address name."); - - const addressesDirname = join(dirname, `./`); - const addressesFiles = readdirSync(addressesDirname).filter(fileName => fileName.includes(".json")); - - addressesFiles.forEach(addressesFilename => { - const addressPath = join(addressesDirname, addressesFilename); - - const addressesByNetwork = JSON.parse(readFileSync(addressPath, "utf8")); - - Object.keys(addressesByNetwork).forEach(network => { - if (!isNetworkName(network) && !isZetaNetworkName(network)) return; - - addressesByNetwork[network][addressName] = addressValue; - addressesByNetwork[network] = Object.keys(addressesByNetwork[network]) - .sort() - .reduce((obj, key) => { - obj[key as ZetaAddress] = addressesByNetwork[network][key]; - return obj; - }, {} as NetworkAddresses); - }); - - writeFileSync(addressPath, JSON.stringify(addressesByNetwork, null, 2)); - }); - - console.log(`To enable IntelliSense, add the address (${addressName}) to the constants (addresses.helpers.ts).`); -}; - -export const addNewNetwork = (newNetworkName: string, addTo: ZetaNetworkName[]) => { - if (!newNetworkName) throw new Error("Emtpy networkName name."); - const addressesDirname = join(dirname, `./`); - const addressesFiles = readdirSync(addressesDirname).filter(fileName => fileName.includes(".json")); - - addressesFiles.forEach(addressFilename => { - const addressesFilePath = join(addressesDirname, addressFilename); - /** - * Gets the Zeta network name using the filename, e.g.: addresses.athens.json -> athens - */ - const zetaNetworkName = addressFilename.substring( - addressFilename.indexOf(".") + 1, - addressFilename.lastIndexOf(".") - ); - - if (!isZetaNetworkName(zetaNetworkName)) throw new Error("Error getting Zeta network name."); - - if (!addTo.includes(zetaNetworkName)) return; - - const fileNetworks = JSON.parse(readFileSync(addressesFilePath, "utf8")); - - if (Boolean(fileNetworks[newNetworkName])) throw new Error("Network already exists."); - - /** - * Use an existing network object to populate the new one - */ - const randomNetworkName = Object.keys(fileNetworks)[0]; - fileNetworks[newNetworkName] = deepCloneSerializable(fileNetworks[randomNetworkName]); - - const emptyNewNetworkAddresses = () => { - Object.keys(fileNetworks[newNetworkName]).forEach(addressName => { - fileNetworks[newNetworkName][addressName] = ""; - }); - }; - emptyNewNetworkAddresses(); - - /** - * The types below aren't 100% correct - */ - const orderedFileNetworks = Object.keys(fileNetworks) - .sort() - .reduce((obj, key) => { - obj[key as LocalNetworkName | MainnetNetworkName | TestnetNetworkName] = fileNetworks[key]; - return obj; - }, {} as LocalnetAddressGroup & MainnetAddressGroup & TestnetAddressGroup); - - writeFileSync(addressesFilePath, JSON.stringify(orderedFileNetworks, null, 2)); - }); - - console.log(`To enable IntelliSense, add the network (${newNetworkName}) to the constants (addresses.helpers.ts).`); -}; - -export const getLocalnetListFromFile = async (): Promise> => { - const troy = await require("./addresses.troy.json"); - return { - troy: troy as LocalnetAddressGroup - }; -}; - -export const getTestnetListFromFile = async (): Promise> => { - const athens = await require("./addresses.athens.json"); - return { - athens: athens as TestnetAddressGroup - }; -}; - -export const getMainnetListFromFile = async (): Promise> => { - const mainnet = await require("./addresses.mainnet.json"); - return { - mainnet: mainnet as MainnetAddressGroup - }; -}; - -export const loadAddressFromFile = async ( - address: ZetaAddress, - { - customNetworkName, - customZetaNetwork - }: { customNetworkName?: NetworkName; customZetaNetwork?: ZetaNetworkName } = {} -): Promise => { - const { name: _networkName } = network; - const networkName = customNetworkName || _networkName; - - const { ZETA_NETWORK: _ZETA_NETWORK } = process.env; - const ZETA_NETWORK = customZetaNetwork || _ZETA_NETWORK; - - if (!ZETA_NETWORK) throw MissingZetaNetworkError; - - console.log(`Getting ${address} address from ${ZETA_NETWORK}: ${networkName}.`); - - if (isZetaLocalnet(ZETA_NETWORK) && isLocalNetworkName(networkName)) { - return (await getLocalnetListFromFile())[ZETA_NETWORK][networkName][address]; - } - - if (isZetaTestnet(ZETA_NETWORK) && isTestnetNetworkName(networkName)) { - return (await getTestnetListFromFile())[ZETA_NETWORK][networkName][address]; - } - - if (isZetaMainnet(ZETA_NETWORK) && isMainnetNetworkName(networkName)) { - return (await getMainnetListFromFile())[ZETA_NETWORK][networkName][address]; - } - - throw new Error(`Invalid ZETA_NETWORK + network combination ${ZETA_NETWORK} ${networkName}.`); -}; - -export const getProtocolNetwork = (value: NetworkName): ZetaProtocolNetwork | undefined => { - //@ts-expect-error - return Object.keys(ProtocolNetworkNetworkNameMap).find(key => ProtocolNetworkNetworkNameMap[key] === value); -}; diff --git a/packages/addresses-tools/src/index.ts b/packages/addresses-tools/src/index.ts deleted file mode 100644 index c79a885a..00000000 --- a/packages/addresses-tools/src/index.ts +++ /dev/null @@ -1,3 +0,0 @@ -export * from "./addresses.helpers"; -export * from "./networks"; -export * from "./system-addresses.helpers"; diff --git a/packages/addresses-tools/src/log-addresses.ts b/packages/addresses-tools/src/log-addresses.ts deleted file mode 100644 index b8bdf988..00000000 --- a/packages/addresses-tools/src/log-addresses.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { getTestnetList, isZetaNetworkName, ZetaTestnetNetworkName } from "@zetachain/addresses"; - -import { getExplorerUrl } from "./addresses.helpers"; -const network = process.argv[2]; - -const toFilter = process.argv[3].split(",").map(w => w.toLowerCase()); - -if (!isZetaNetworkName(network)) { - console.error(`Invalid network (${network}).`); - process.exit(1); -} - -const capitalizeFirstLetter = (str: string) => str.charAt(0).toUpperCase() + str.slice(1); - -const logAddresses = (zetaNetwork: ZetaTestnetNetworkName) => { - const list = getTestnetList()[zetaNetwork]; - - console.log(`${capitalizeFirstLetter(zetaNetwork)} addresses:`); - - Object.entries(list).map(([networkName, addresses], i) => { - console.log(`--- ${capitalizeFirstLetter(networkName)} ---`); - - Object.entries(addresses).map(([name, address]) => { - if (toFilter.includes(name.toLowerCase())) return; - if (!address) return; - - console.log( - `${capitalizeFirstLetter(name)}: [${address}](${getExplorerUrl({ - customNetworkName: networkName - })}address/${address})` - ); - }); - - console.log("\n"); - }); -}; - -logAddresses("athens"); diff --git a/packages/addresses-tools/src/misc.constants.ts b/packages/addresses-tools/src/misc.constants.ts deleted file mode 100644 index 5f2cf2cf..00000000 --- a/packages/addresses-tools/src/misc.constants.ts +++ /dev/null @@ -1 +0,0 @@ -export type ValueOf = T[keyof T]; diff --git a/packages/addresses-tools/src/misc.helpers.ts b/packages/addresses-tools/src/misc.helpers.ts deleted file mode 100644 index 7848f0fd..00000000 --- a/packages/addresses-tools/src/misc.helpers.ts +++ /dev/null @@ -1,2 +0,0 @@ -export const deepCloneSerializable = (serializableObject: Obj): Obj => - JSON.parse(JSON.stringify(serializableObject)); diff --git a/packages/addresses-tools/src/networks.ts b/packages/addresses-tools/src/networks.ts deleted file mode 100644 index 850eaee4..00000000 --- a/packages/addresses-tools/src/networks.ts +++ /dev/null @@ -1,84 +0,0 @@ -import type { NetworksUserConfig } from "hardhat/types"; - -export const getHardhatConfigNetworks = (PRIVATE_KEYS: string[]): NetworksUserConfig => ({ - "athens": { - accounts: PRIVATE_KEYS, - // chainId: 7001, - gas: 5000000, - gasPrice: 80000000000, - // url: `https://api.athens2.zetachain.com/evm`, //A2 - url: `https://zetachain-athens-evm.blockpi.network/v1/rpc/public`, //A3 - }, - "bsc-localnet": { - gas: 5000000, - gasPrice: 80000000000, - url: "http://localhost:8120", - }, - "bsc-mainnet": { - accounts: PRIVATE_KEYS, - gas: 5000000, - gasPrice: 80000000000, - url: `https://rpc.ankr.com/bsc`, - }, - "bsc-testnet": { - accounts: PRIVATE_KEYS, - gas: 5000000, - gasPrice: 80000000000, - url: `https://rpc.ankr.com/bsc_testnet_chapel`, - }, - "eth-localnet": { - gas: 2100000, - gasPrice: 80000000000, - url: "http://localhost:8100", - }, - "eth-mainnet": { - accounts: PRIVATE_KEYS, - url: "https://rpc.ankr.com/eth", - }, - goerli: { - accounts: PRIVATE_KEYS, - gas: 2100000, - gasPrice: 38000000000, - url: `https://rpc.ankr.com/eth_goerli`, - }, - hardhat: { - chainId: 1337, - forking: { - blockNumber: 14672712, - url: `https://rpc.ankr.com/eth`, - }, - }, - "klaytn-baobab": { - accounts: PRIVATE_KEYS, - chainId: 1001, - gas: 6000000, - gasPrice: 54250000000, - url: "https://api.baobab.klaytn.net:8651" - }, - "klaytn-cypress": { - accounts: PRIVATE_KEYS, - chainId: 8217, - gas: 2100000, - gasPrice: 8000000000, - url: "https://scope.klaytn.com/" - }, - "polygon-localnet": { - gas: 5000000, - gasPrice: 80000000000, - url: "http://localhost:8140", - }, - "polygon-mumbai": { - accounts: PRIVATE_KEYS, - gas: 5000000, - gasPrice: 80000000000, - url: "https://rpc.ankr.com/polygon_mumbai", - }, -}); - -export const getHardhatConfigScanners = () => ({ - apiKey: { - bscTestnet: process.env.BSCSCAN_API_KEY, - goerli: process.env.ETHERSCAN_API_KEY, - polygonMumbai: process.env.POYLGONSCAN_API_KEY - }, -}); diff --git a/packages/addresses-tools/src/system-addresses.helpers.ts b/packages/addresses-tools/src/system-addresses.helpers.ts deleted file mode 100644 index 6bb2e6d9..00000000 --- a/packages/addresses-tools/src/system-addresses.helpers.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { NetworkName } from "@zetachain/addresses"; -import { getAddress, getZRC20Address as getZRC20AddressFromProtocol } from "@zetachain/protocol-contracts/dist/lib"; - -export type AthensVersion = "Athens2" | "Athens3"; - -export type ZRC20 = "gETH" | "tBNB" | "tBTC" | "tMATIC"; - -//@dev: Legacy addresses to make it simple if is needed to run a script pointing to Athens2 -const ATHENS2_SYSTEM_CONTRACT = "0x239e96c8f17C85c30100AC26F635Ea15f23E9c67"; -const ATHENS2_ZRC20Addresses: Record = { - gETH: "0x91d18e54DAf4F677cB28167158d6dd21F6aB3921", - tBNB: "0x13A0c5930C028511Dc02665E7285134B6d11A5f4", - tBTC: "0x48f80608B672DC30DC7e3dbBd0343c5F02C738Eb", - tMATIC: "0xd97B1de3619ed2c6BEb3860147E30cA8A7dC9891" -}; - -export const getSystemContractAddress = (version: AthensVersion = "Athens3") => { - if (version === "Athens2") { - return ATHENS2_SYSTEM_CONTRACT; - } - return getAddress("systemContract", "zeta_testnet"); -}; - -export const getZRC20Address = (version: AthensVersion = "Athens3") => { - if (version === "Athens2") { - return ATHENS2_ZRC20Addresses; - } - const ZRC20Addresses: Record = { - gETH: getZRC20AddressFromProtocol("goerli_testnet"), - tBNB: getZRC20AddressFromProtocol("bsc_testnet"), - // tBTC: getZRC20AddressFromProtocol("bitcoin-test"), - tBTC: "0x0", - tMATIC: getZRC20AddressFromProtocol("mumbai_testnet") - }; - - return ZRC20Addresses; -}; - -export type SwappableNetwork = Extract; - -export const isSwappableNetwork = (network: string): network is SwappableNetwork => - network === "bitcoin-test" || network === "bsc-testnet" || network === "goerli" || network === "polygon-mumbai"; - -export const ChainToZRC20: Record = { - "bitcoin-test": "tBTC", - "bsc-testnet": "tBNB", - goerli: "gETH", - "polygon-mumbai": "tMATIC" -}; diff --git a/packages/addresses-tools/tsconfig.json b/packages/addresses-tools/tsconfig.json deleted file mode 100644 index 588ea357..00000000 --- a/packages/addresses-tools/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "extends": "../../tsconfig.json", - "include": ["./src", "./src/**/*.json"], - "compilerOptions": { - "baseUrl": "./src", - "outDir": "./dist", - "rootDir": "./src", - "paths": { - "~/*": [ - "./*" - ] - } - }, -} diff --git a/packages/addresses/.npmignore b/packages/addresses/.npmignore deleted file mode 100644 index 539a5de3..00000000 --- a/packages/addresses/.npmignore +++ /dev/null @@ -1,30 +0,0 @@ -# source code -src -index.html - -# compiler -tsconfig.json - -# files -*.log -cypress.json -*.code-workspace - -# tests -test - -# lint -.eslintrc.js -.prettierrc - -# IDE - VSCode -.vscode - -# git -.git - -# Include the dist folder and other necessary files -!dist/ -!README.md -!LICENSE -!package.json diff --git a/packages/addresses/README.md b/packages/addresses/README.md deleted file mode 100644 index 8a0e5cae..00000000 --- a/packages/addresses/README.md +++ /dev/null @@ -1,26 +0,0 @@ -# ZetaChain addresses - -This package includes the addresses and networks to use Zetachain. - -## Usage - -```js -import { getAddress } from "@zetachain/addresses"; - -const address = getAddress({ address: "zetaToken", networkName: "goerli", zetaNetwork:"athens" }); -``` - -## API - - -| Method | Description | -| :---- | ------ | -| isTestnetNetworkName = (networkName: string): networkName is TestnetNetworkName | Returns true if it's a valid Testnet name | -| isZetaTestnet = (networkName: string): networkName is ZetaTestnetNetworkName | Returns true if it's a valid ZetaTestnet name | -| isMainnetNetworkName = (networkName: string): networkName is MainnetNetworkName | Returns true if it's a valid Mainnet name | -| isNetworkName = (networkName: string): networkName is NetworkName | Returns true if it's a valid network name | -| isZetaNetworkName = (networkName: string): networkName is ZetaNetworkName | Returns true if it's a valid Zeta network name | -| type ZetaAddress | Valid values for ZetaAddress | -| getAddress = ({ address: ZetaAddress; networkName: string; zetaNetwork: string; }): string | Returns the address of a valid ZetaAddress | - -``` \ No newline at end of file diff --git a/packages/addresses/package.json b/packages/addresses/package.json deleted file mode 100644 index 59ab7864..00000000 --- a/packages/addresses/package.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "name": "@zetachain/addresses", - "version": "0.0.13", - "license": "MIT", - "author": "zetachain", - "publishConfig": { - "access": "public", - "registry": "https://registry.npmjs.org/" - }, - "files": [ - "dist" - ], - "main": "./dist/", - "exports": { - ".": "./dist/index.js" - }, - "scripts": { - "tsc:watch": "npx tsc --watch", - "prepublishOnly": "npx tsc" - }, - "devDependencies": { - "vite": "^3.1.0", - "vite-plugin-dts": "^1.4.1" - } -} diff --git a/packages/addresses/src/addresses.athens.json b/packages/addresses/src/addresses.athens.json deleted file mode 100644 index d7751271..00000000 --- a/packages/addresses/src/addresses.athens.json +++ /dev/null @@ -1,162 +0,0 @@ -{ - "bsc-testnet": { - "connector": "0x0000ecb8cdd25a18f12daa23f6422e07fbf8b9e1", - "crossChainCounter": "", - "crossChainNft": "", - "dai": "", - "disperse": "", - "immutableCreate2Factory": "0x095a03c6a68137fE9a566bBc3e552F299d8b886d", - "multiChainSwap": "0x8BD7144Ddb59c9Fa3Dcf809998521E9cAD946fa1", - "multiChainSwapZetaConnector": "", - "multiChainValue": "0x064516547ECd3b2D1709e1b2798Aae92b1C8a84C", - "rewardDistributorFactory": "", - "tridentPoolFactory": "", - "tss": "0x8531a5aB847ff5B22D855633C25ED1DA3255247e", - "tssUpdater": "0x55122f7590164Ac222504436943FAB17B62F5d7d", - "uniswapV2Factory": "", - "uniswapV2Router02": "0xD99D1c33F9fC3444f8101754aBC46c52416550D1", - "uniswapV3PoolFactory": "", - "uniswapV3Quoter": "0x10ed43c718714eb63d5aa57b78b54704e256024e", - "uniswapV3Router": "0x10ed43c718714eb63d5aa57b78b54704e256024e", - "usdc": "", - "weth9": "0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c", - "zetaSwap": "", - "zetaSwapBtcInbound": "", - "zetaToken": "0x0000c9ec4042283e8139c74f4c64bcd1e0b9b54f", - "zetaTokenConsumerUniV2": "", - "zetaTokenConsumerUniV3": "" - }, - "goerli": { - "connector": "0x00005e3125aba53c5652f9f0ce1a4cf91d8b15ea", - "crossChainCounter": "", - "crossChainNft": "", - "dai": "", - "disperse": "", - "immutableCreate2Factory": "0x095a03c6a68137fE9a566bBc3e552F299d8b886d", - "multiChainSwap": "0x323745f16C93e56a98012970c28788498d8B3a14", - "multiChainSwapZetaConnector": "", - "multiChainValue": "0x14BeC0E4A8e7bF7A02Af54Ad81a57a9fcA4D37Fd", - "rewardDistributorFactory": "", - "tridentPoolFactory": "", - "tss": "0x8531a5aB847ff5B22D855633C25ED1DA3255247e", - "tssUpdater": "0x55122f7590164Ac222504436943FAB17B62F5d7d", - "uniswapV2Factory": "", - "uniswapV2Router02": "0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D", - "uniswapV3PoolFactory": "", - "uniswapV3Quoter": "", - "uniswapV3Router": "", - "usdc": "", - "weth9": "", - "zetaSwap": "", - "zetaSwapBtcInbound": "", - "zetaToken": "0x0000c304d2934c00db1d51995b9f6996affd17c0", - "zetaTokenConsumerUniV2": "", - "zetaTokenConsumerUniV3": "" - }, - "polygon-mumbai": { - "connector": "0x0000ecb8cdd25a18f12daa23f6422e07fbf8b9e1", - "crossChainCounter": "", - "crossChainNft": "", - "dai": "", - "immutableCreate2Factory": "0x095a03c6a68137fE9a566bBc3e552F299d8b886d", - "multiChainSwap": "0xb1b812b664c28E1bA1d35De925Ae88b7Bc7cdCF5", - "rewardDistributorFactory": "", - "tridentPoolFactory": "", - "multiChainSwapZetaConnector": "", - "multiChainValue": "0x14BeC0E4A8e7bF7A02Af54Ad81a57a9fcA4D37Fd", - "tss": "0x8531a5aB847ff5B22D855633C25ED1DA3255247e", - "tssUpdater": "0x55122f7590164Ac222504436943FAB17B62F5d7d", - "uniswapV2Factory": "", - "uniswapV2Router02": "0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D", - "uniswapV3PoolFactory": "0x1F98431c8aD98523631AE4a59f267346ea31F984", - "uniswapV3Quoter": "0xb27308f9F90D607463bb33eA1BeBb41C27CE5AB6", - "uniswapV3Router": "0xE592427A0AEce92De3Edee1F18E0157C05861564", - "usdc": "", - "weth9": "0x9c3C9283D3e44854697Cd22D3Faa240Cfb032889", - "zetaSwap": "", - "zetaSwapBtcInbound": "", - "zetaToken": "0x0000c9ec4042283e8139c74f4c64bcd1e0b9b54f", - "zetaTokenConsumerUniV2": "", - "zetaTokenConsumerUniV3": "" - }, - "klaytn-baobab": { - "connector": "", - "crossChainCounter": "", - "crossChainNft": "", - "dai": "", - "disperse": "", - "immutableCreate2Factory": "", - "multiChainSwap": "", - "multiChainValue": "", - "rewardDistributorFactory": "", - "tridentPoolFactory": "", - "tss": "", - "tssUpdater": "", - "uniswapV2Factory": "", - "uniswapV2Router02": "", - "uniswapV3PoolFactory": "", - "uniswapV3Quoter": "", - "uniswapV3Router": "", - "usdc": "", - "weth9": "", - "zetaSwap": "", - "zetaSwapBtcInbound": "", - "zetaToken": "", - "zetaTokenConsumerUniV2": "", - "zetaTokenConsumerUniV3": "" - }, - "athens": { - "connector": "", - "crossChainCounter": "", - "crossChainNft": "", - "dai": "", - "disperse": "0x1E0F767F48Fb10FcF820703f116E9B0F87319d63", - "immutableCreate2Factory": "", - "multiChainSwap": "", - "multiChainSwapZetaConnector": "", - "multiChainValue": "0x82aC45D07dEe4DBDe050e838beF345347DEd99a8", - "rewardDistributorFactory": "0x667e4C493d40015256BDC89E3ba750B2F90359E1", - "tridentPoolFactory": "", - "tss": "", - "tssUpdater": "", - "uniswapV2Factory": "0x9fd96203f7b22bCF72d9DCb40ff98302376cE09c", - "uniswapV2Router02": "0x2ca7d64A7EFE2D62A725E2B35Cf7230D6677FfEe", - "uniswapV3PoolFactory": "", - "uniswapV3Quoter": "", - "uniswapV3Router": "", - "usdc": "", - "weth9": "0x5F0b1a82749cb4E2278EC87F8BF6B618dC71a8bf", - "zetaSwap": "0x44D1F1f9289DBA1Cf5824bd667184cEBE020aA1c", - "zetaSwapBtcInbound": "0x008b393933D5CA2457Df570CA5D628380FFf6da4", - "zetaToken": "0x5F0b1a82749cb4E2278EC87F8BF6B618dC71a8bf", - "zetaTokenConsumerUniV2": "", - "zetaTokenConsumerUniV3": "" - }, - "bitcoin-test": { - "connector": "", - "crossChainCounter": "", - "crossChainNft": "", - "dai": "", - "disperse": "", - "immutableCreate2Factory": "", - "multiChainSwap": "", - "multiChainSwapZetaConnector": "", - "multiChainValue": "", - "rewardDistributorFactory": "", - "tridentPoolFactory": "", - "tss": "", - "tssUpdater": "", - "uniswapV2Factory": "", - "uniswapV2Router02": "", - "uniswapV3PoolFactory": "", - "uniswapV3Quoter": "", - "uniswapV3Router": "", - "usdc": "", - "weth9": "", - "zetaSwap": "", - "zetaSwapBtcInbound": "", - "zetaToken": "", - "zetaTokenConsumerUniV2": "", - "zetaTokenConsumerUniV3": "" - } -} \ No newline at end of file diff --git a/packages/addresses/src/addresses.helpers.ts b/packages/addresses/src/addresses.helpers.ts deleted file mode 100644 index e77c8c88..00000000 --- a/packages/addresses/src/addresses.helpers.ts +++ /dev/null @@ -1,185 +0,0 @@ -import athens from "./addresses.athens.json"; -import mainnet from "./addresses.mainnet.json"; -import troy from "./addresses.troy.json"; - -export type ZetaAddress = - | "connector" - | "crossChainCounter" - | "crossChainNft" - | "dai" - | "disperse" - | "immutableCreate2Factory" - | "multiChainSwap" - | "multiChainSwapZetaConnector" - | "multiChainValue" - | "rewardDistributorFactory" - | "tridentPoolFactory" - | "tss" - | "tssUpdater" - | "uniswapV2Factory" - | "uniswapV2Router02" - | "uniswapV3PoolFactory" - | "uniswapV3Quoter" - | "uniswapV3Router" - | "usdc" - | "weth9" - | "zetaSwap" - | "zetaSwapBtcInbound" - | "zetaToken" - | "zetaTokenConsumerUniV2" - | "zetaTokenConsumerUniV3"; - -export type NetworkAddresses = Record; -const zetaAddresses: Record = { - connector: true, - crossChainCounter: true, - crossChainNft: true, - dai: true, - disperse: true, - immutableCreate2Factory: true, - multiChainSwap: true, - multiChainSwapZetaConnector: true, - multiChainValue: true, - rewardDistributorFactory: true, - tridentPoolFactory: true, - tss: true, - tssUpdater: true, - uniswapV2Factory: true, - uniswapV2Router02: true, - uniswapV3PoolFactory: true, - uniswapV3Quoter: true, - uniswapV3Router: true, - usdc: true, - weth9: true, - zetaSwap: true, - zetaSwapBtcInbound: true, - zetaToken: true, - zetaTokenConsumerUniV2: true, - zetaTokenConsumerUniV3: true -}; - -export const isZetaAddress = (a: string | undefined): a is ZetaAddress => Boolean(zetaAddresses[a as ZetaAddress]); - -/** - * @description Localnet - */ - -export type LocalNetworkName = "bsc-localnet" | "eth-localnet" | "hardhat" | "polygon-localnet"; -export type ZetaLocalNetworkName = "troy"; -export type LocalnetAddressGroup = Record; -export const isLocalNetworkName = (networkName: string): networkName is LocalNetworkName => - networkName === "hardhat" || - networkName === "eth-localnet" || - networkName === "bsc-localnet" || - networkName === "polygon-localnet"; -export const isZetaLocalnet = (networkName: string | undefined): networkName is ZetaLocalNetworkName => - networkName === "troy"; - -export const getLocalnetList = (): Record => ({ - troy: troy as LocalnetAddressGroup -}); - -/** - * @description Testnet - */ - -export type TestnetNetworkName = - | "athens" - | "bitcoin-test" - | "bsc-testnet" - | "goerli" - | "klaytn-baobab" - | "polygon-mumbai"; -export type ZetaTestnetNetworkName = "athens"; -export type TestnetAddressGroup = Record; -export const isTestnetNetworkName = (networkName: string): networkName is TestnetNetworkName => - networkName === "goerli" || - networkName === "bsc-testnet" || - networkName === "polygon-mumbai" || - networkName === "klaytn-baobab" || - networkName === "athens"; -export const isZetaTestnet = (networkName: string | undefined): networkName is ZetaTestnetNetworkName => - networkName === "athens"; - -export const getTestnetList = (): Record => ({ - athens: athens as TestnetAddressGroup -}); - -/** - * @description Mainnet - */ - -export type MainnetNetworkName = "bsc-mainnet" | "eth-mainnet" | "klaytn-cypress"; -export type ZetaMainnetNetworkName = "mainnet"; -export type MainnetAddressGroup = Record; -export const isMainnetNetworkName = (networkName: string): networkName is MainnetNetworkName => - networkName === "bsc-mainnet" || networkName === "eth-mainnet" || networkName === "klaytn-cypress"; -export const isZetaMainnet = (networkName: string | undefined): networkName is ZetaMainnetNetworkName => - networkName === "mainnet"; - -export const getMainnetList = (): Record => ({ - mainnet: mainnet as MainnetAddressGroup -}); - -/** - * @description Shared - */ - -export type NetworkName = LocalNetworkName | MainnetNetworkName | TestnetNetworkName; -export type ZetaNetworkName = ZetaLocalNetworkName | ZetaMainnetNetworkName | ZetaTestnetNetworkName; - -export const getChainId = (networkName: NetworkName) => { - const chainIds: Record = { - athens: 7001, - "bitcoin-test": 18332, - "bsc-localnet": 97, - "bsc-mainnet": 56, - "bsc-testnet": 97, - "eth-localnet": 5, - "eth-mainnet": 1, - goerli: 5, - hardhat: 1337, - "klaytn-baobab": 1001, - "klaytn-cypress": 8217, - "polygon-localnet": 80001, - "polygon-mumbai": 80001 - }; - - return chainIds[networkName]; -}; - -export const isNetworkName = (str: string): str is NetworkName => - isLocalNetworkName(str) || isTestnetNetworkName(str) || isMainnetNetworkName(str); - -export const isZetaNetworkName = (str: string): str is ZetaNetworkName => - isZetaLocalnet(str) || isZetaTestnet(str) || isZetaMainnet(str); - -const getInvalidNetworkError = (network: string, isZeta: boolean) => - new Error(`Network: ${network} is invalid${isZeta ? " ZetaNetwork" : ""}, please provide a valid value`); - -export const getAddress = ({ - address, - networkName, - zetaNetwork -}: { - address: ZetaAddress; - networkName: string; - zetaNetwork: string; -}): string => { - if (!isNetworkName(networkName)) throw getInvalidNetworkError(networkName, false); - if (!isZetaNetworkName(zetaNetwork)) throw getInvalidNetworkError(networkName, true); - - if (isZetaLocalnet(zetaNetwork) && isLocalNetworkName(networkName)) { - return getLocalnetList()[zetaNetwork][networkName][address]; - } - - if (isZetaTestnet(zetaNetwork) && isTestnetNetworkName(networkName)) { - return getTestnetList()[zetaNetwork][networkName][address]; - } - - if (isZetaMainnet(zetaNetwork) && isMainnetNetworkName(networkName)) { - return getMainnetList()[zetaNetwork][networkName][address]; - } - - throw new Error(`Invalid ZETA_NETWORK + network combination ${zetaNetwork} ${networkName}.`); -}; diff --git a/packages/addresses/src/addresses.mainnet.json b/packages/addresses/src/addresses.mainnet.json deleted file mode 100644 index 6edddb31..00000000 --- a/packages/addresses/src/addresses.mainnet.json +++ /dev/null @@ -1,71 +0,0 @@ -{ - "bsc-mainnet": { - "connector": "", - "crossChainCounter": "", - "crossChainNft": "", - "dai": "", - "multiChainValue": "", - "tss": "", - "tssUpdater": "", - "uniswapV2Router02": "", - "uniswapV3PoolFactory": "", - "uniswapV3Quoter": "", - "uniswapV3Router": "", - "usdc": "", - "weth9": "", - "zetaSwapBtcInbound": "", - "zetaToken": "", - "zetaTokenConsumerUniV2": "", - "immutableCreate2Factory": "", - "multiChainSwapZetaConnector": "", - "multiChainSwap": "", - "uniswapV2Factory": "", - "zetaSwap": "" - }, - "eth-mainnet": { - "connector": "", - "crossChainCounter": "", - "crossChainNft": "", - "dai": "0x6b175474e89094c44da98b954eedeac495271d0f", - "multiChainValue": "", - "tss": "", - "tssUpdater": "", - "uniswapV2Router02": "0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D", - "uniswapV3PoolFactory": "0xC36442b4a4522E871399CD717aBDD847Ab11FE88", - "uniswapV3Quoter": "0xb27308f9F90D607463bb33eA1BeBb41C27CE5AB6", - "uniswapV3Router": "0xE592427A0AEce92De3Edee1F18E0157C05861564", - "usdc": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", - "weth9": "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2", - "zetaSwapBtcInbound": "", - "zetaToken": "", - "zetaTokenConsumerUniV2": "", - "immutableCreate2Factory": "", - "multiChainSwapZetaConnector": "", - "multiChainSwap": "", - "uniswapV2Factory": "0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f", - "zetaSwap": "" - }, - "klaytn-cypress": { - "connector": "", - "crossChainCounter": "", - "crossChainNft": "", - "dai": "", - "multiChainValue": "", - "tss": "", - "tssUpdater": "", - "uniswapV2Router02": "", - "uniswapV3PoolFactory": "", - "uniswapV3Quoter": "", - "uniswapV3Router": "", - "usdc": "", - "weth9": "", - "zetaSwapBtcInbound": "", - "zetaToken": "", - "zetaTokenConsumerUniV2": "", - "immutableCreate2Factory": "", - "multiChainSwapZetaConnector": "", - "multiChainSwap": "", - "uniswapV2Factory": "", - "zetaSwap": "" - } -} \ No newline at end of file diff --git a/packages/addresses/src/addresses.troy.json b/packages/addresses/src/addresses.troy.json deleted file mode 100644 index c254b205..00000000 --- a/packages/addresses/src/addresses.troy.json +++ /dev/null @@ -1,94 +0,0 @@ -{ - "hardhat": { - "connector": "0xB06c856C8eaBd1d8321b687E188204C1018BC4E5", - "crossChainCounter": "", - "crossChainNft": "", - "dai": "", - "multiChainSwap": "0xddE78e6202518FF4936b5302cC2891ec180E8bFf", - "multiChainValue": "", - "tss": "0x70997970c51812dc3a010c7d01b50e0d17dc79c8", - "tssUpdater": "0x70997970c51812dc3a010c7d01b50e0d17dc79c8", - "uniswapV2Router02": "0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D", - "uniswapV3PoolFactory": "", - "uniswapV3Quoter": "", - "uniswapV3Router": "", - "usdc": "", - "weth9": "", - "zetaSwapBtcInbound": "", - "zetaToken": "0xddE78e6202518FF4936b5302cC2891ec180E8bFf", - "immutableCreate2Factory": "", - "multiChainSwapZetaConnector": "", - "uniswapV2Factory": "", - "zetaSwap": "", - "zetaTokenConsumerUniV2": "" - }, - "eth-localnet": { - "connector": "0xD7db1F9D0279876a9dcDb92e06057E0818b9B34b", - "crossChainCounter": "", - "crossChainNft": "", - "dai": "", - "multiChainSwap": "", - "multiChainValue": "", - "tss": "0x8C001e2204000D8ED10cAcf0F68106b68e036A26", - "tssUpdater": "0xfBec4048e09749515110c89D881EcDcA4460D377", - "uniswapV2Router02": "", - "uniswapV3PoolFactory": "", - "uniswapV3Quoter": "", - "uniswapV3Router": "", - "usdc": "", - "weth9": "", - "zetaSwapBtcInbound": "", - "zetaToken": "0xaEF27C0E302005dB3b442edF762EB070Dc2DB9b5", - "immutableCreate2Factory": "", - "multiChainSwapZetaConnector": "", - "uniswapV2Factory": "", - "zetaSwap": "", - "zetaTokenConsumerUniV2": "" - }, - "bsc-localnet": { - "connector": "0x960bd6A9d8424455953a68c17Be7f56e0cf83A9E", - "crossChainCounter": "", - "crossChainNft": "", - "dai": "", - "multiChainSwap": "", - "multiChainValue": "", - "tss": "0x8C001e2204000D8ED10cAcf0F68106b68e036A26", - "tssUpdater": "0x12Dc2227AA4b98b00Ff8148fDA9Ef750929B0F68", - "uniswapV2Router02": "", - "uniswapV3PoolFactory": "", - "uniswapV3Quoter": "", - "uniswapV3Router": "", - "usdc": "", - "weth9": "", - "zetaSwapBtcInbound": "", - "zetaToken": "0x0CF6e5aA211A4b7da5d04e93dC40Ee18202a5f84", - "immutableCreate2Factory": "", - "multiChainSwapZetaConnector": "", - "uniswapV2Factory": "", - "zetaSwap": "", - "zetaTokenConsumerUniV2": "" - }, - "polygon-localnet": { - "connector": "0xa16BD8468d10d28E6c16F03798EEb710fc84F616", - "crossChainCounter": "", - "crossChainNft": "", - "dai": "", - "multiChainSwap": "", - "multiChainValue": "", - "tss": "0x8C001e2204000D8ED10cAcf0F68106b68e036A26", - "tssUpdater": "0x78C18E214174A08Fc32e174fb203Aba05B016789", - "uniswapV2Router02": "", - "uniswapV3PoolFactory": "", - "uniswapV3Quoter": "", - "uniswapV3Router": "", - "usdc": "", - "weth9": "", - "zetaSwapBtcInbound": "", - "zetaToken": "0xD443E93f689a7E1d517Fef799b1d2Fd2FA536d3A", - "immutableCreate2Factory": "", - "multiChainSwapZetaConnector": "", - "uniswapV2Factory": "", - "zetaSwap": "", - "zetaTokenConsumerUniV2": "" - } -} \ No newline at end of file diff --git a/packages/addresses/src/index.ts b/packages/addresses/src/index.ts deleted file mode 100644 index 57e3950d..00000000 --- a/packages/addresses/src/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from "./addresses.helpers"; diff --git a/packages/addresses/tsconfig.json b/packages/addresses/tsconfig.json deleted file mode 100644 index f063f923..00000000 --- a/packages/addresses/tsconfig.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "compilerOptions": { - "typeRoots": ["@types", "./node_modules/@types"], - "target": "es6", - "noImplicitAny": true, - "moduleResolution": "node", - "sourceMap": false, - "outDir": "dist", - "esModuleInterop": true, - "baseUrl": "./", - "declaration": true, - "module": "commonjs", - "resolveJsonModule": true, - } -} diff --git a/packages/example-contracts/.env.example b/packages/example-contracts/.env.example deleted file mode 100644 index 09bb3086..00000000 --- a/packages/example-contracts/.env.example +++ /dev/null @@ -1,18 +0,0 @@ -ALCHEMY_API_KEY_MAINNET= -ALCHEMY_API_KEY_GOERLI= - -PUBLIC_KEY_1= - -PRIVATE_KEY= - -# ETHER -ETHERSCAN_API_KEY=<...> - -# POLYGON -POYLGONSCAN_API_KEY=<...> - -# BSC -BSCSCAN_API_KEY=<...> - -# Deployer address. This is needed to calculate salt in deterministic deployments -DEPLOYER_ADDRESS= diff --git a/packages/example-contracts/.eslintrc.js b/packages/example-contracts/.eslintrc.js deleted file mode 100644 index 77b8f69a..00000000 --- a/packages/example-contracts/.eslintrc.js +++ /dev/null @@ -1,23 +0,0 @@ -const path = require("path"); - -const OFF = 0; - -module.exports = { - env: { - browser: false, - es2021: true, - mocha: true, - node: true, - }, - extends: ["../../.eslintrc.js"], - rules: { - "no-console": OFF, - }, - settings: { - "import/resolver": { - typescript: { - project: path.join(__dirname, "tsconfig.json"), - }, - }, - }, -}; diff --git a/packages/example-contracts/README.md b/packages/example-contracts/README.md deleted file mode 100644 index f14c08bb..00000000 --- a/packages/example-contracts/README.md +++ /dev/null @@ -1,16 +0,0 @@ -# ZetaChain example contracts - -> ⚠️ The contracts **are not audited yet**, use at your own risk. - -## Environment variables - -Follow the template in `.env.example`. - -* The private key should **not** include `0x`. -* To verify your contracts, you'll need api keys both in BSCScan and Etherscan. - -## Running Tests - -```bash - yarn test -``` diff --git a/packages/example-contracts/contracts/cross-chain-counter/CrossChainCounter.sol b/packages/example-contracts/contracts/cross-chain-counter/CrossChainCounter.sol deleted file mode 100644 index c0505300..00000000 --- a/packages/example-contracts/contracts/cross-chain-counter/CrossChainCounter.sol +++ /dev/null @@ -1,57 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity 0.8.7; - -import "@openzeppelin/contracts/access/Ownable.sol"; -import "@zetachain/protocol-contracts/contracts/evm/tools/ZetaInteractor.sol"; -import "@zetachain/protocol-contracts/contracts/evm/interfaces/ZetaInterfaces.sol"; - -interface CrossChainCounterErrors { - error InvalidMessageType(); - - error DecrementOverflow(); -} - -contract CrossChainCounter is ZetaInteractor, ZetaReceiver, CrossChainCounterErrors { - bytes32 public constant CROSS_CHAIN_INCREMENT_MESSAGE = keccak256("CROSS_CHAIN_INCREMENT"); - - mapping(address => uint256) public counter; - - constructor(address connectorAddress_) ZetaInteractor(connectorAddress_) {} - - function crossChainCount(uint256 destinationChainId) external { - if (!_isValidChainId(destinationChainId)) revert InvalidDestinationChainId(); - - counter[msg.sender]++; - connector.send( - ZetaInterfaces.SendInput({ - destinationChainId: destinationChainId, - destinationAddress: interactorsByChainId[destinationChainId], - destinationGasLimit: 2500000, - message: abi.encode(CROSS_CHAIN_INCREMENT_MESSAGE, msg.sender), - zetaValueAndGas: 0, - zetaParams: abi.encode("") - }) - ); - } - - function onZetaMessage( - ZetaInterfaces.ZetaMessage calldata zetaMessage - ) external override isValidMessageCall(zetaMessage) { - (bytes32 messageType, address messageFrom) = abi.decode(zetaMessage.message, (bytes32, address)); - - if (messageType != CROSS_CHAIN_INCREMENT_MESSAGE) revert InvalidMessageType(); - - counter[messageFrom]++; - } - - function onZetaRevert( - ZetaInterfaces.ZetaRevert calldata zetaRevert - ) external override isValidRevertCall(zetaRevert) { - (bytes32 messageType, address messageFrom) = abi.decode(zetaRevert.message, (bytes32, address)); - - if (messageType != CROSS_CHAIN_INCREMENT_MESSAGE) revert InvalidMessageType(); - if (counter[messageFrom] <= 0) revert DecrementOverflow(); - - counter[messageFrom]--; - } -} diff --git a/packages/example-contracts/contracts/cross-chain-counter/test/CounterZetaConnectorMock.sol b/packages/example-contracts/contracts/cross-chain-counter/test/CounterZetaConnectorMock.sol deleted file mode 100644 index 6ceae166..00000000 --- a/packages/example-contracts/contracts/cross-chain-counter/test/CounterZetaConnectorMock.sol +++ /dev/null @@ -1,63 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity 0.8.7; - -import "@zetachain/protocol-contracts/contracts/evm/interfaces/ZetaInterfaces.sol"; - -import "../CrossChainCounter.sol"; - -contract CounterZetaConnectorMock is ZetaConnector { - function callOnZetaMessage( - bytes memory zetaTxSenderAddress, - uint256 sourceChainId, - address destinationAddress, - uint256 zetaValue, - bytes calldata message - ) public { - return - CrossChainCounter(destinationAddress).onZetaMessage( - ZetaInterfaces.ZetaMessage({ - zetaTxSenderAddress: zetaTxSenderAddress, - sourceChainId: sourceChainId, - destinationAddress: destinationAddress, - zetaValue: zetaValue, - message: message - }) - ); - } - - function callOnZetaRevert( - address zetaTxSenderAddress, - uint256 sourceChainId, - uint256 destinationChainId, - bytes calldata destinationAddress, - uint256 remainingZetaValue, - uint256, // destinationGasLimit - bytes calldata message - ) public { - return - CrossChainCounter(zetaTxSenderAddress).onZetaRevert( - ZetaInterfaces.ZetaRevert({ - zetaTxSenderAddress: zetaTxSenderAddress, - sourceChainId: sourceChainId, - destinationAddress: destinationAddress, - destinationChainId: destinationChainId, - remainingZetaValue: remainingZetaValue, - message: message - }) - ); - } - - function send(ZetaInterfaces.SendInput calldata sendInput) external override { - uint256 sourceChainId = sendInput.destinationChainId == 2 ? 1 : 2; - address dest = address(uint160(bytes20(sendInput.destinationAddress))); - - return - callOnZetaMessage( - abi.encodePacked(msg.sender), - sourceChainId, - dest, - sendInput.zetaValueAndGas, - sendInput.message - ); - } -} diff --git a/packages/example-contracts/contracts/cross-chain-message/CrossChainMessage.sol b/packages/example-contracts/contracts/cross-chain-message/CrossChainMessage.sol deleted file mode 100644 index 89c3bd4b..00000000 --- a/packages/example-contracts/contracts/cross-chain-message/CrossChainMessage.sol +++ /dev/null @@ -1,85 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity 0.8.7; - -import "@openzeppelin/contracts/interfaces/IERC20.sol"; -import "@openzeppelin/contracts/access/Ownable.sol"; -import "@zetachain/protocol-contracts/contracts/evm/tools/ZetaInteractor.sol"; -import "@zetachain/protocol-contracts/contracts/evm/interfaces/ZetaInterfaces.sol"; - -interface CrossChainMessageErrors { - error InvalidMessageType(); -} - -/** - * @dev A simple contract able to send and receive Hello World messages from other chains. - * Emits a HelloWorldEvent on successful messages - * Emits a RevertedHelloWorldEvent on failed messages - */ -contract CrossChainMessage is ZetaInteractor, ZetaReceiver, CrossChainMessageErrors { - bytes32 public constant HELLO_WORLD_MESSAGE_TYPE = keccak256("CROSS_CHAIN_HELLO_WORLD"); - - event HelloWorldEvent(string messageData); - event RevertedHelloWorldEvent(string messageData); - - ZetaTokenConsumer private immutable _zetaConsumer; - IERC20 internal immutable _zetaToken; - - constructor( - address connectorAddress, - address zetaTokenAddress, - address zetaConsumerAddress - ) ZetaInteractor(connectorAddress) { - _zetaToken = IERC20(zetaTokenAddress); - _zetaConsumer = ZetaTokenConsumer(zetaConsumerAddress); - } - - function sendHelloWorld(uint256 destinationChainId) external payable { - if (!_isValidChainId(destinationChainId)) revert InvalidDestinationChainId(); - - uint256 crossChainGas = 18 * (10 ** 18); - uint256 zetaValueAndGas = _zetaConsumer.getZetaFromEth{value: msg.value}(address(this), crossChainGas); - _zetaToken.approve(address(connector), zetaValueAndGas); - - connector.send( - ZetaInterfaces.SendInput({ - destinationChainId: destinationChainId, - destinationAddress: interactorsByChainId[destinationChainId], - destinationGasLimit: 2500000, - message: abi.encode(HELLO_WORLD_MESSAGE_TYPE, "Hello, Cross-Chain World!"), - zetaValueAndGas: zetaValueAndGas, - zetaParams: abi.encode("") - }) - ); - } - - function onZetaMessage( - ZetaInterfaces.ZetaMessage calldata zetaMessage - ) external override isValidMessageCall(zetaMessage) { - /** - * @dev Decode should follow the signature of the message provided to zeta.send. - */ - (bytes32 messageType, string memory helloWorldMessage) = abi.decode(zetaMessage.message, (bytes32, string)); - - /** - * @dev Setting a message type is a useful pattern to distinguish between different messages. - */ - if (messageType != HELLO_WORLD_MESSAGE_TYPE) revert InvalidMessageType(); - - emit HelloWorldEvent(helloWorldMessage); - } - - /** - * @dev Called by the Zeta Connector contract when the message fails to be sent. - * Useful to cleanup and leave the application on its initial state. - * Note that the require statements and the functionality are similar to onZetaMessage. - */ - function onZetaRevert( - ZetaInterfaces.ZetaRevert calldata zetaRevert - ) external override isValidRevertCall(zetaRevert) { - (bytes32 messageType, string memory helloWorldMessage) = abi.decode(zetaRevert.message, (bytes32, string)); - - if (messageType != HELLO_WORLD_MESSAGE_TYPE) revert InvalidMessageType(); - - emit RevertedHelloWorldEvent(helloWorldMessage); - } -} diff --git a/packages/example-contracts/contracts/cross-chain-message/test/CrossChainMessageConnector.sol b/packages/example-contracts/contracts/cross-chain-message/test/CrossChainMessageConnector.sol deleted file mode 100644 index 11f9f38a..00000000 --- a/packages/example-contracts/contracts/cross-chain-message/test/CrossChainMessageConnector.sol +++ /dev/null @@ -1,63 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity 0.8.7; - -import "@zetachain/protocol-contracts/contracts/evm/interfaces/ZetaInterfaces.sol"; - -import "../CrossChainMessage.sol"; - -contract CrossChainMessageConnector is ZetaConnector { - function callOnZetaMessage( - bytes memory zetaTxSenderAddress, - uint256 sourceChainId, - address destinationAddress, - uint256 zetaValue, - bytes calldata message - ) public { - return - CrossChainMessage(payable(destinationAddress)).onZetaMessage( - ZetaInterfaces.ZetaMessage({ - zetaTxSenderAddress: zetaTxSenderAddress, - sourceChainId: sourceChainId, - destinationAddress: destinationAddress, - zetaValue: zetaValue, - message: message - }) - ); - } - - function callOnZetaRevert( - address zetaTxSenderAddress, - uint256 sourceChainId, - uint256 destinationChainId, - bytes calldata destinationAddress, - uint256 remainingZetaValue, - uint256, // destinationGasLimit - bytes calldata message - ) public { - return - CrossChainMessage(payable(zetaTxSenderAddress)).onZetaRevert( - ZetaInterfaces.ZetaRevert({ - zetaTxSenderAddress: zetaTxSenderAddress, - sourceChainId: sourceChainId, - destinationAddress: destinationAddress, - destinationChainId: destinationChainId, - remainingZetaValue: remainingZetaValue, - message: message - }) - ); - } - - function send(ZetaInterfaces.SendInput calldata sendInput) external override { - uint256 sourceChainId = sendInput.destinationChainId == 2 ? 1 : 2; - address dest = address(uint160(bytes20(sendInput.destinationAddress))); - - return - callOnZetaMessage( - abi.encodePacked(msg.sender), - sourceChainId, - dest, - sendInput.zetaValueAndGas, - sendInput.message - ); - } -} diff --git a/packages/example-contracts/contracts/cross-chain-warriors/CrossChainWarriors.sol b/packages/example-contracts/contracts/cross-chain-warriors/CrossChainWarriors.sol deleted file mode 100644 index 3a627ae6..00000000 --- a/packages/example-contracts/contracts/cross-chain-warriors/CrossChainWarriors.sol +++ /dev/null @@ -1,140 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity 0.8.7; - -import "@openzeppelin/contracts/interfaces/IERC20.sol"; -import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; -import "@openzeppelin/contracts/utils/Counters.sol"; -import "@openzeppelin/contracts/access/Ownable.sol"; -import "@zetachain/protocol-contracts/contracts/evm/interfaces/ZetaInterfaces.sol"; -import "@zetachain/protocol-contracts/contracts/evm/tools/ZetaInteractor.sol"; - -interface CrossChainWarriorsErrors { - error InvalidMessageType(); - - error InvalidTransferCaller(); - - error ErrorApprovingZeta(); -} - -contract CrossChainWarriors is - ERC721("CrossChainWarriors", "CCWAR"), - ZetaInteractor, - ZetaReceiver, - CrossChainWarriorsErrors -{ - using Counters for Counters.Counter; - using Strings for uint256; - - bytes32 public constant CROSS_CHAIN_TRANSFER_MESSAGE = keccak256("CROSS_CHAIN_TRANSFER"); - - IERC20 internal immutable _zetaToken; - - string public baseURI; - - Counters.Counter public tokenIds; - - ZetaTokenConsumer private immutable _zetaConsumer; - - constructor( - address connectorAddress, - address zetaTokenAddress, - address zetaConsumerAddress, - bool useEven - ) ZetaInteractor(connectorAddress) { - _zetaToken = IERC20(zetaTokenAddress); - _zetaConsumer = ZetaTokenConsumer(zetaConsumerAddress); - - /** - * @dev A simple way to prevent collisions between cross-chain token ids - * As you can see below, the mint function should increase the counter by two - */ - tokenIds.increment(); - if (useEven) tokenIds.increment(); - } - - function setBaseURI(string memory baseURIParam) public onlyOwner { - baseURI = baseURIParam; - } - - function mint(address to) public returns (uint256) { - uint256 newWarriorId = tokenIds.current(); - - /** - * @dev Always increment by two to keep ids even/odd (depending on the chain) - * Check the constructor for further reference - */ - tokenIds.increment(); - tokenIds.increment(); - - _safeMint(to, newWarriorId); - return newWarriorId; - } - - /** - * @dev Useful for cross-chain minting - */ - function _mintId(address to, uint256 tokenId) internal { - _safeMint(to, tokenId); - } - - function _burnWarrior(uint256 burnedWarriorId) internal { - _burn(burnedWarriorId); - } - - /** - * @dev Cross-chain functions - */ - - function crossChainTransfer(uint256 crossChainId, address to, uint256 tokenId) external payable { - if (!_isValidChainId(crossChainId)) revert InvalidDestinationChainId(); - if (!_isApprovedOrOwner(_msgSender(), tokenId)) revert InvalidTransferCaller(); - - uint256 crossChainGas = 18 * (10 ** 18); - uint256 zetaValueAndGas = _zetaConsumer.getZetaFromEth{value: msg.value}(address(this), crossChainGas); - _zetaToken.approve(address(connector), zetaValueAndGas); - - _burnWarrior(tokenId); - - connector.send( - ZetaInterfaces.SendInput({ - destinationChainId: crossChainId, - destinationAddress: interactorsByChainId[crossChainId], - destinationGasLimit: 500000, - message: abi.encode(CROSS_CHAIN_TRANSFER_MESSAGE, tokenId, msg.sender, to), - zetaValueAndGas: zetaValueAndGas, - zetaParams: abi.encode("") - }) - ); - } - - function onZetaMessage( - ZetaInterfaces.ZetaMessage calldata zetaMessage - ) external override isValidMessageCall(zetaMessage) { - ( - bytes32 messageType, - uint256 tokenId, - , - /** - * @dev this extra comma corresponds to address from - */ - address to - ) = abi.decode(zetaMessage.message, (bytes32, uint256, address, address)); - - if (messageType != CROSS_CHAIN_TRANSFER_MESSAGE) revert InvalidMessageType(); - - _mintId(to, tokenId); - } - - function onZetaRevert( - ZetaInterfaces.ZetaRevert calldata zetaRevert - ) external override isValidRevertCall(zetaRevert) { - (bytes32 messageType, uint256 tokenId, address from) = abi.decode( - zetaRevert.message, - (bytes32, uint256, address) - ); - - if (messageType != CROSS_CHAIN_TRANSFER_MESSAGE) revert InvalidMessageType(); - - _mintId(from, tokenId); - } -} diff --git a/packages/example-contracts/contracts/cross-chain-warriors/test/CrossChainWarriorsMock.sol b/packages/example-contracts/contracts/cross-chain-warriors/test/CrossChainWarriorsMock.sol deleted file mode 100644 index 69eff602..00000000 --- a/packages/example-contracts/contracts/cross-chain-warriors/test/CrossChainWarriorsMock.sol +++ /dev/null @@ -1,17 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity 0.8.7; - -import "../CrossChainWarriors.sol"; - -contract CrossChainWarriorsMock is CrossChainWarriors { - constructor( - address connectorAddress, - address zetaTokenAddress, - address zetaConsumerAddress, - bool useEven - ) CrossChainWarriors(connectorAddress, zetaTokenAddress, zetaConsumerAddress, useEven) {} - - function mintId(address to, uint256 tokenId) external { - return _mintId(to, tokenId); - } -} diff --git a/packages/example-contracts/contracts/cross-chain-warriors/test/CrossChainWarriorsZetaConnectorMock.sol b/packages/example-contracts/contracts/cross-chain-warriors/test/CrossChainWarriorsZetaConnectorMock.sol deleted file mode 100644 index b053d914..00000000 --- a/packages/example-contracts/contracts/cross-chain-warriors/test/CrossChainWarriorsZetaConnectorMock.sol +++ /dev/null @@ -1,63 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity 0.8.7; - -import "@zetachain/protocol-contracts/contracts/evm/interfaces/ZetaInterfaces.sol"; - -import "../CrossChainWarriors.sol"; - -contract CrossChainWarriorsZetaConnectorMock is ZetaConnector { - function callOnZetaMessage( - bytes memory zetaTxSenderAddress, - uint256 sourceChainId, - address destinationAddress, - uint256 zetaValue, - bytes calldata message - ) public { - return - CrossChainWarriors(destinationAddress).onZetaMessage( - ZetaInterfaces.ZetaMessage({ - zetaTxSenderAddress: zetaTxSenderAddress, - sourceChainId: sourceChainId, - destinationAddress: destinationAddress, - zetaValue: zetaValue, - message: message - }) - ); - } - - function callOnZetaRevert( - address zetaTxSenderAddress, - uint256 sourceChainId, - uint256 destinationChainId, - bytes calldata destinationAddress, - uint256 remainingZetaValue, - uint256, // destinationGasLimit - bytes calldata message - ) public { - return - CrossChainWarriors(zetaTxSenderAddress).onZetaRevert( - ZetaInterfaces.ZetaRevert({ - zetaTxSenderAddress: zetaTxSenderAddress, - sourceChainId: sourceChainId, - destinationAddress: destinationAddress, - destinationChainId: destinationChainId, - remainingZetaValue: remainingZetaValue, - message: message - }) - ); - } - - function send(ZetaInterfaces.SendInput calldata sendInput) external override { - uint256 sourceChainId = sendInput.destinationChainId == 2 ? 1 : 2; - address dest = address(uint160(bytes20(sendInput.destinationAddress))); - - return - callOnZetaMessage( - abi.encodePacked(msg.sender), - sourceChainId, - dest, - sendInput.zetaValueAndGas, - sendInput.message - ); - } -} diff --git a/packages/example-contracts/contracts/multi-chain-swap/MultiChainSwap.sol b/packages/example-contracts/contracts/multi-chain-swap/MultiChainSwap.sol deleted file mode 100644 index b0a97dfe..00000000 --- a/packages/example-contracts/contracts/multi-chain-swap/MultiChainSwap.sol +++ /dev/null @@ -1,69 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity 0.8.7; - -import "@zetachain/protocol-contracts/contracts/evm/tools/ZetaInteractor.sol"; - -interface MultiChainSwap is ZetaReceiver { - event SentTokenSwap( - address sourceTxOrigin, - address sourceInputToken, - uint256 inputTokenAmount, - address destinationOutToken, - uint256 outTokenMinAmount, - address receiverAddress - ); - - event SentEthSwap( - address sourceTxOrigin, - uint256 inputEthAmount, - address destinationOutToken, - uint256 outTokenMinAmount, - address receiverAddress - ); - - event Swapped( - address sourceTxOrigin, - address sourceInputToken, - uint256 inputTokenAmount, - address destinationOutToken, - uint256 outTokenFinalAmount, - address receiverAddress - ); - - event RevertedSwap( - address sourceTxOrigin, - address sourceInputToken, - uint256 inputTokenAmount, - uint256 inputTokenReturnedAmount - ); - - function swapETHForTokensCrossChain( - bytes calldata receiverAddress, - address destinationOutToken, - bool isDestinationOutETH, - /** - * @dev The minimum amount of tokens that receiverAddress should get, - * if it's not reached, the transaction will revert on the destination chain - */ - uint256 outTokenMinAmount, - uint256 destinationChainId, - uint256 crossChaindestinationGasLimit, - uint deadline - ) external payable; - - function swapTokensForTokensCrossChain( - address sourceInputToken, - uint256 inputTokenAmount, - bytes calldata receiverAddress, - address destinationOutToken, - bool isDestinationOutETH, - /** - * @dev The minimum amount of tokens that receiverAddress should get, - * if it's not reached, the transaction will revert on the destination chain - */ - uint256 outTokenMinAmount, - uint256 destinationChainId, - uint256 crossChaindestinationGasLimit, - uint deadline - ) external; -} diff --git a/packages/example-contracts/contracts/multi-chain-swap/MultiChainSwapErrors.sol b/packages/example-contracts/contracts/multi-chain-swap/MultiChainSwapErrors.sol deleted file mode 100644 index d980f9ea..00000000 --- a/packages/example-contracts/contracts/multi-chain-swap/MultiChainSwapErrors.sol +++ /dev/null @@ -1,20 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity 0.8.7; - -interface MultiChainSwapErrors { - error ErrorTransferringTokens(address token); - - error ErrorApprovingTokens(address token); - - error ErrorSwappingTokens(); - - error ValueShouldBeGreaterThanZero(); - - error OutTokenInvariant(); - - error InsufficientOutToken(); - - error MissingSourceInputTokenAddress(); - - error InvalidMessageType(); -} diff --git a/packages/example-contracts/contracts/multi-chain-swap/MultiChainSwapTrident.strategy.sol b/packages/example-contracts/contracts/multi-chain-swap/MultiChainSwapTrident.strategy.sol deleted file mode 100644 index 5e6b3eda..00000000 --- a/packages/example-contracts/contracts/multi-chain-swap/MultiChainSwapTrident.strategy.sol +++ /dev/null @@ -1,295 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity 0.8.7; - -import "@openzeppelin/contracts/interfaces/IERC20.sol"; -import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; -import "@zetachain/protocol-contracts/contracts/evm/tools/ZetaTokenConsumerTrident.strategy.sol"; - -import "./MultiChainSwapErrors.sol"; -import "./MultiChainSwap.sol"; - -contract MultiChainSwapTrident is MultiChainSwap, ZetaInteractor, MultiChainSwapErrors, ZetaTokenConsumerTrident { - using SafeERC20 for IERC20; - bytes32 public constant CROSS_CHAIN_SWAP_MESSAGE = keccak256("CROSS_CHAIN_SWAP"); - - constructor( - address zetaConnector_, - address zetaToken_, - address uniswapV3Router_, - address WETH9Address_, - address poolFactory_ - ) - ZetaTokenConsumerTrident(zetaToken_, uniswapV3Router_, WETH9Address_, poolFactory_) - ZetaInteractor(zetaConnector_) - {} - - function swapETHForTokensCrossChain( - bytes calldata receiverAddress, - address destinationOutToken, - bool isDestinationOutETH, - /** - * @dev The minimum amount of tokens that receiverAddress should get, - * if it's not reached, the transaction will revert on the destination chain - */ - uint256 outTokenMinAmount, - uint256 destinationChainId, - uint256 crossChaindestinationGasLimit, - uint /* deadline */ - ) external payable override { - _swapETHForTokensCrossChain( - receiverAddress, - destinationOutToken, - isDestinationOutETH, - outTokenMinAmount, - destinationChainId, - crossChaindestinationGasLimit - ); - } - - function _swapETHForTokensCrossChain( - bytes calldata receiverAddress, - address destinationOutToken, - bool isDestinationOutETH, - /** - * @dev The minimum amount of tokens that receiverAddress should get, - * if it's not reached, the transaction will revert on the destination chain - */ - uint256 outTokenMinAmount, - uint256 destinationChainId, - uint256 crossChaindestinationGasLimit - ) internal { - if (!_isValidChainId(destinationChainId)) revert InvalidDestinationChainId(); - - if (msg.value == 0) revert ValueShouldBeGreaterThanZero(); - if ( - (destinationOutToken != address(0) && isDestinationOutETH) || - (destinationOutToken == address(0) && !isDestinationOutETH) - ) revert OutTokenInvariant(); - - uint256 zetaValueAndGas = this.getZetaFromEth{value: msg.value}( - address(this), - 0 /// @todo Add min amount - ); - if (zetaValueAndGas == 0) revert ErrorSwappingTokens(); - - IERC20(zetaToken).safeApprove(address(connector), zetaValueAndGas); - - connector.send( - ZetaInterfaces.SendInput({ - destinationChainId: destinationChainId, - destinationAddress: interactorsByChainId[destinationChainId], - destinationGasLimit: crossChaindestinationGasLimit, - message: abi.encode( - CROSS_CHAIN_SWAP_MESSAGE, - msg.sender, - WETH9Address, - msg.value, - receiverAddress, - destinationOutToken, - isDestinationOutETH, - outTokenMinAmount, - true // inputTokenIsETH - ), - zetaValueAndGas: zetaValueAndGas, - zetaParams: abi.encode("") - }) - ); - } - - function swapTokensForTokensCrossChain( - address sourceInputToken, - uint256 inputTokenAmount, - bytes calldata receiverAddress, - address destinationOutToken, - bool isDestinationOutETH, - /** - * @dev The minimum amount of tokens that receiverAddress should get, - * if it's not reached, the transaction will revert on the destination chain - */ - uint256 outTokenMinAmount, - uint256 destinationChainId, - uint256 crossChaindestinationGasLimit, - uint /* deadline */ - ) external override { - _swapTokensForTokensCrossChain( - sourceInputToken, - inputTokenAmount, - receiverAddress, - destinationOutToken, - isDestinationOutETH, - outTokenMinAmount, - destinationChainId, - crossChaindestinationGasLimit - ); - } - - function _swapTokensForTokensCrossChain( - address sourceInputToken, - uint256 inputTokenAmount, - bytes calldata receiverAddress, - address destinationOutToken, - bool isDestinationOutETH, - /** - * @dev The minimum amount of tokens that receiverAddress should get, - * if it's not reached, the transaction will revert on the destination chain - */ - uint256 outTokenMinAmount, - uint256 destinationChainId, - uint256 crossChaindestinationGasLimit - ) internal { - if (!_isValidChainId(destinationChainId)) revert InvalidDestinationChainId(); - - if (sourceInputToken == address(0)) revert MissingSourceInputTokenAddress(); - if ( - (destinationOutToken != address(0) && isDestinationOutETH) || - (destinationOutToken == address(0) && !isDestinationOutETH) - ) revert OutTokenInvariant(); - - uint256 zetaValueAndGas; - - IERC20(sourceInputToken).safeTransferFrom(msg.sender, address(this), inputTokenAmount); - - if (sourceInputToken == zetaToken) { - zetaValueAndGas = inputTokenAmount; - } else { - IERC20(sourceInputToken).safeApprove(address(this), inputTokenAmount); - zetaValueAndGas = this.getZetaFromToken( - address(this), - 0, /// @todo Add min amount - sourceInputToken, - inputTokenAmount - ); - - if (zetaValueAndGas == 0) revert ErrorSwappingTokens(); - } - - IERC20(zetaToken).safeApprove(address(connector), zetaValueAndGas); - - connector.send( - ZetaInterfaces.SendInput({ - destinationChainId: destinationChainId, - destinationAddress: interactorsByChainId[destinationChainId], - destinationGasLimit: crossChaindestinationGasLimit, - message: abi.encode( - CROSS_CHAIN_SWAP_MESSAGE, - msg.sender, - sourceInputToken, - inputTokenAmount, - receiverAddress, - destinationOutToken, - isDestinationOutETH, - outTokenMinAmount, - false // inputTokenIsETH - ), - zetaValueAndGas: zetaValueAndGas, - zetaParams: abi.encode("") - }) - ); - } - - function onZetaMessage( - ZetaInterfaces.ZetaMessage calldata zetaMessage - ) external override isValidMessageCall(zetaMessage) { - ( - bytes32 messageType, - address sourceTxOrigin, - address sourceInputToken, - uint256 inputTokenAmount, - bytes memory receiverAddressEncoded, - address destinationOutToken, - bool isDestinationOutETH, - uint256 outTokenMinAmount, - - ) = abi.decode(zetaMessage.message, (bytes32, address, address, uint256, bytes, address, bool, uint256, bool)); - if (messageType != CROSS_CHAIN_SWAP_MESSAGE) revert InvalidMessageType(); - - uint256 outTokenFinalAmount; - if (destinationOutToken == zetaToken) { - if (zetaMessage.zetaValue < outTokenMinAmount) revert InsufficientOutToken(); - - IERC20(zetaToken).safeTransfer(address(uint160(bytes20(receiverAddressEncoded))), zetaMessage.zetaValue); - - outTokenFinalAmount = zetaMessage.zetaValue; - } else { - /** - * @dev If the out token is not Zeta, get it using Uniswap - */ - IERC20(zetaToken).safeApprove(address(this), zetaMessage.zetaValue); - - if (isDestinationOutETH) { - outTokenFinalAmount = this.getEthFromZeta( - address(uint160(bytes20(receiverAddressEncoded))), - outTokenMinAmount, - zetaMessage.zetaValue - ); - } else { - outTokenFinalAmount = this.getTokenFromZeta( - address(uint160(bytes20(receiverAddressEncoded))), - outTokenMinAmount, - destinationOutToken, - zetaMessage.zetaValue - ); - } - - if (outTokenFinalAmount == 0) revert ErrorSwappingTokens(); - if (outTokenFinalAmount < outTokenMinAmount) revert InsufficientOutToken(); - } - - emit Swapped( - sourceTxOrigin, - sourceInputToken, - inputTokenAmount, - destinationOutToken, - outTokenFinalAmount, - address(uint160(bytes20(receiverAddressEncoded))) - ); - } - - function onZetaRevert( - ZetaInterfaces.ZetaRevert calldata zetaRevert - ) external override isValidRevertCall(zetaRevert) { - /** - * @dev If something goes wrong we must swap to the source input token - */ - ( - , - address sourceTxOrigin, - address sourceInputToken, - uint256 inputTokenAmount, - , - , - , - , - bool inputTokenIsETH - ) = abi.decode(zetaRevert.message, (bytes32, address, address, uint256, bytes, address, bool, uint256, bool)); - - uint256 inputTokenReturnedAmount; - if (sourceInputToken == zetaToken) { - IERC20(zetaToken).safeApprove(address(this), zetaRevert.remainingZetaValue); - IERC20(zetaToken).safeTransferFrom(address(this), sourceTxOrigin, zetaRevert.remainingZetaValue); - inputTokenReturnedAmount = zetaRevert.remainingZetaValue; - } else { - /** - * @dev If the source input token is not Zeta, trade it using Uniswap - */ - IERC20(zetaToken).safeApprove(address(this), zetaRevert.remainingZetaValue); - - if (inputTokenIsETH) { - inputTokenReturnedAmount = this.getEthFromZeta( - sourceTxOrigin, - 0, /// @todo Add min amount - zetaRevert.remainingZetaValue - ); - } else { - inputTokenReturnedAmount = this.getTokenFromZeta( - sourceTxOrigin, - 0, /// @todo Add min amount - sourceInputToken, - zetaRevert.remainingZetaValue - ); - } - } - - emit RevertedSwap(sourceTxOrigin, sourceInputToken, inputTokenAmount, inputTokenReturnedAmount); - } -} diff --git a/packages/example-contracts/contracts/multi-chain-swap/MultiChainSwapUniV2.strategy.sol b/packages/example-contracts/contracts/multi-chain-swap/MultiChainSwapUniV2.strategy.sol deleted file mode 100644 index 871a7181..00000000 --- a/packages/example-contracts/contracts/multi-chain-swap/MultiChainSwapUniV2.strategy.sol +++ /dev/null @@ -1,357 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity 0.8.7; - -import "@openzeppelin/contracts/interfaces/IERC20.sol"; -import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; -import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol"; - -import "./MultiChainSwapErrors.sol"; -import "./MultiChainSwap.sol"; - -contract MultiChainSwapUniV2 is MultiChainSwap, ZetaInteractor, MultiChainSwapErrors { - using SafeERC20 for IERC20; - uint internal constant MAX_DEADLINE = 200; - bytes32 public constant CROSS_CHAIN_SWAP_MESSAGE = keccak256("CROSS_CHAIN_SWAP"); - - address public immutable uniswapV2RouterAddress; - address internal immutable wETH; - address public immutable zetaToken; - - IUniswapV2Router02 internal uniswapV2Router; - - struct CrossChainCallParams { - address sourceInputToken; - uint256 inputTokenAmount; - bytes receiverAddress; - address destinationOutToken; - bool isDestinationOutETH; - bool inputTokenIsETH; - /** - * @dev The minimum amount of tokens that receiverAddress should get, - * if it's not reached, the transaction will revert on the destination chain - */ - uint256 outTokenMinAmount; - uint256 destinationChainId; - uint256 crossChaindestinationGasLimit; - uint256 zetaValueAndGas; - } - - constructor(address zetaConnector_, address zetaToken_, address uniswapV2Router_) ZetaInteractor(zetaConnector_) { - if (zetaToken_ == address(0) || uniswapV2Router_ == address(0)) revert ZetaCommonErrors.InvalidAddress(); - zetaToken = zetaToken_; - uniswapV2RouterAddress = uniswapV2Router_; - uniswapV2Router = IUniswapV2Router02(uniswapV2Router_); - wETH = uniswapV2Router.WETH(); - } - - function swapETHForTokensCrossChain( - bytes calldata receiverAddress, - address destinationOutToken, - bool isDestinationOutETH, - /** - * @dev The minimum amount of tokens that receiverAddress should get, - * if it's not reached, the transaction will revert on the destination chain - */ - uint256 outTokenMinAmount, - uint256 destinationChainId, - uint256 crossChaindestinationGasLimit, - uint deadline - ) external payable override { - if (!_isValidChainId(destinationChainId)) revert InvalidDestinationChainId(); - if (msg.value == 0) revert ValueShouldBeGreaterThanZero(); - if ( - (destinationOutToken != address(0) && isDestinationOutETH) || - (destinationOutToken == address(0) && !isDestinationOutETH) - ) revert OutTokenInvariant(); - uint256 zetaValueAndGas; - { - address[] memory path = new address[](2); - path[0] = wETH; - path[1] = zetaToken; - uint256[] memory amounts = uniswapV2Router.swapExactETHForTokens{value: msg.value}( - 0, /// @todo Add min amount - path, - address(this), - deadline - ); - zetaValueAndGas = amounts[path.length - 1]; - } - if (zetaValueAndGas == 0) revert ErrorSwappingTokens(); - { - bool success = IERC20(zetaToken).approve(address(connector), zetaValueAndGas); - if (!success) revert ErrorApprovingTokens(zetaToken); - } - - _crossChainCall( - CrossChainCallParams({ - sourceInputToken: wETH, - inputTokenAmount: msg.value, - receiverAddress: receiverAddress, - destinationOutToken: destinationOutToken, - isDestinationOutETH: isDestinationOutETH, - inputTokenIsETH: false, - outTokenMinAmount: outTokenMinAmount, - destinationChainId: destinationChainId, - crossChaindestinationGasLimit: crossChaindestinationGasLimit, - zetaValueAndGas: zetaValueAndGas - }) - ); - } - - function swapTokensForTokensCrossChain( - address sourceInputToken, - uint256 inputTokenAmount, - bytes calldata receiverAddress, - address destinationOutToken, - bool isDestinationOutETH, - /** - * @dev The minimum amount of tokens that receiverAddress should get, - * if it's not reached, the transaction will revert on the destination chain - */ - uint256 outTokenMinAmount, - uint256 destinationChainId, - uint256 crossChaindestinationGasLimit, - uint deadline - ) external override { - if (!_isValidChainId(destinationChainId)) revert InvalidDestinationChainId(); - if (sourceInputToken == address(0)) revert MissingSourceInputTokenAddress(); - if ( - (destinationOutToken != address(0) && isDestinationOutETH) || - (destinationOutToken == address(0) && !isDestinationOutETH) - ) revert OutTokenInvariant(); - uint256 zetaValueAndGas; - if (sourceInputToken == zetaToken) { - bool success1 = IERC20(zetaToken).transferFrom(msg.sender, address(this), inputTokenAmount); - bool success2 = IERC20(zetaToken).approve(address(connector), inputTokenAmount); - if (!success1 || !success2) revert ErrorTransferringTokens(zetaToken); - zetaValueAndGas = inputTokenAmount; - } else { - /** - * @dev If the input token is not Zeta, trade it using Uniswap - */ - { - IERC20(sourceInputToken).safeTransferFrom(msg.sender, address(this), inputTokenAmount); - IERC20(sourceInputToken).safeApprove(uniswapV2RouterAddress, inputTokenAmount); - } - address[] memory path; - if (sourceInputToken == wETH) { - path = new address[](2); - path[0] = wETH; - path[1] = zetaToken; - } else { - path = new address[](3); - path[0] = sourceInputToken; - path[1] = wETH; - path[2] = zetaToken; - } - uint256[] memory amounts = uniswapV2Router.swapExactTokensForTokens( - inputTokenAmount, - 0, /// @todo Add min amount - path, - address(this), - deadline - ); - zetaValueAndGas = amounts[path.length - 1]; - if (zetaValueAndGas == 0) revert ErrorSwappingTokens(); - } - { - bool success = IERC20(zetaToken).approve(address(connector), zetaValueAndGas); - if (!success) revert ErrorApprovingTokens(zetaToken); - } - - _crossChainCall( - CrossChainCallParams({ - sourceInputToken: sourceInputToken, - inputTokenAmount: inputTokenAmount, - receiverAddress: receiverAddress, - destinationOutToken: destinationOutToken, - isDestinationOutETH: isDestinationOutETH, - inputTokenIsETH: false, - outTokenMinAmount: outTokenMinAmount, - destinationChainId: destinationChainId, - crossChaindestinationGasLimit: crossChaindestinationGasLimit, - zetaValueAndGas: zetaValueAndGas - }) - ); - } - - function _crossChainCall(CrossChainCallParams memory params) internal { - connector.send( - ZetaInterfaces.SendInput({ - destinationChainId: params.destinationChainId, - destinationAddress: interactorsByChainId[params.destinationChainId], - destinationGasLimit: params.crossChaindestinationGasLimit, - message: abi.encode( - CROSS_CHAIN_SWAP_MESSAGE, - msg.sender, - params.sourceInputToken, - params.inputTokenAmount, - params.receiverAddress, - params.destinationOutToken, - params.isDestinationOutETH, - params.outTokenMinAmount, - params.inputTokenIsETH - ), - zetaValueAndGas: params.zetaValueAndGas, - zetaParams: abi.encode("") - }) - ); - } - - function onZetaMessage( - ZetaInterfaces.ZetaMessage calldata zetaMessage - ) external override isValidMessageCall(zetaMessage) { - ( - bytes32 messageType, - address sourceTxOrigin, - address sourceInputToken, - uint256 inputTokenAmount, - bytes memory receiverAddressEncoded, - address destinationOutToken, - bool isDestinationOutETH, - uint256 outTokenMinAmount, - - ) = abi.decode(zetaMessage.message, (bytes32, address, address, uint256, bytes, address, bool, uint256, bool)); - - address receiverAddress = address(uint160(bytes20(receiverAddressEncoded))); - - if (messageType != CROSS_CHAIN_SWAP_MESSAGE) revert InvalidMessageType(); - - uint256 outTokenFinalAmount; - if (destinationOutToken == zetaToken) { - if (zetaMessage.zetaValue < outTokenMinAmount) revert InsufficientOutToken(); - - bool success = IERC20(zetaToken).transfer(receiverAddress, zetaMessage.zetaValue); - if (!success) revert ErrorTransferringTokens(zetaToken); - - outTokenFinalAmount = zetaMessage.zetaValue; - } else { - /** - * @dev If the out token is not Zeta, get it using Uniswap - */ - { - bool success = IERC20(zetaToken).approve(uniswapV2RouterAddress, zetaMessage.zetaValue); - if (!success) revert ErrorApprovingTokens(zetaToken); - } - - address[] memory path; - if (destinationOutToken == wETH || isDestinationOutETH) { - path = new address[](2); - path[0] = zetaToken; - path[1] = wETH; - } else { - path = new address[](3); - path[0] = zetaToken; - path[1] = wETH; - path[2] = destinationOutToken; - } - - uint256[] memory amounts; - if (isDestinationOutETH) { - amounts = uniswapV2Router.swapExactTokensForETH( - zetaMessage.zetaValue, - outTokenMinAmount, - path, - receiverAddress, - block.timestamp + MAX_DEADLINE - ); - } else { - amounts = uniswapV2Router.swapExactTokensForTokens( - zetaMessage.zetaValue, - outTokenMinAmount, - path, - receiverAddress, - block.timestamp + MAX_DEADLINE - ); - } - - outTokenFinalAmount = amounts[amounts.length - 1]; - if (outTokenFinalAmount == 0) revert ErrorSwappingTokens(); - if (outTokenFinalAmount < outTokenMinAmount) revert InsufficientOutToken(); - } - - emit Swapped( - sourceTxOrigin, - sourceInputToken, - inputTokenAmount, - destinationOutToken, - outTokenFinalAmount, - receiverAddress - ); - } - - function onZetaRevert( - ZetaInterfaces.ZetaRevert calldata zetaRevert - ) external override isValidRevertCall(zetaRevert) { - /** - * @dev If something goes wrong we must swap to the source input token - */ - ( - , - address sourceTxOrigin, - address sourceInputToken, - uint256 inputTokenAmount, - , - , - , - , - bool inputTokenIsETH - ) = abi.decode(zetaRevert.message, (bytes32, address, address, uint256, bytes, address, bool, uint256, bool)); - - uint256 inputTokenReturnedAmount; - if (sourceInputToken == zetaToken) { - bool success1 = IERC20(zetaToken).approve(address(this), zetaRevert.remainingZetaValue); - bool success2 = IERC20(zetaToken).transferFrom( - address(this), - sourceTxOrigin, - zetaRevert.remainingZetaValue - ); - if (!success1 || !success2) revert ErrorTransferringTokens(zetaToken); - inputTokenReturnedAmount = zetaRevert.remainingZetaValue; - } else { - /** - * @dev If the source input token is not Zeta, trade it using Uniswap - */ - { - bool success = IERC20(zetaToken).approve(uniswapV2RouterAddress, zetaRevert.remainingZetaValue); - if (!success) revert ErrorTransferringTokens(zetaToken); - } - - address[] memory path; - if (sourceInputToken == wETH) { - path = new address[](2); - path[0] = zetaToken; - path[1] = wETH; - } else { - path = new address[](3); - path[0] = zetaToken; - path[1] = wETH; - path[2] = sourceInputToken; - } - { - uint256[] memory amounts; - - if (inputTokenIsETH) { - amounts = uniswapV2Router.swapExactTokensForETH( - zetaRevert.remainingZetaValue, - 0, /// @todo Add min amount - path, - sourceTxOrigin, - block.timestamp + MAX_DEADLINE - ); - } else { - amounts = uniswapV2Router.swapExactTokensForTokens( - zetaRevert.remainingZetaValue, - 0, /// @todo Add min amount - path, - sourceTxOrigin, - block.timestamp + MAX_DEADLINE - ); - } - inputTokenReturnedAmount = amounts[amounts.length - 1]; - } - } - - emit RevertedSwap(sourceTxOrigin, sourceInputToken, inputTokenAmount, inputTokenReturnedAmount); - } -} diff --git a/packages/example-contracts/contracts/multi-chain-swap/MultiChainSwapUniV3.strategy.sol b/packages/example-contracts/contracts/multi-chain-swap/MultiChainSwapUniV3.strategy.sol deleted file mode 100644 index da1f0fc7..00000000 --- a/packages/example-contracts/contracts/multi-chain-swap/MultiChainSwapUniV3.strategy.sol +++ /dev/null @@ -1,304 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity 0.8.7; - -import "@openzeppelin/contracts/interfaces/IERC20.sol"; -import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; -import "@zetachain/protocol-contracts/contracts/evm/tools/ZetaTokenConsumerUniV3.strategy.sol"; - -import "./MultiChainSwapErrors.sol"; -import "./MultiChainSwap.sol"; - -contract MultiChainSwapUniV3 is MultiChainSwap, ZetaInteractor, MultiChainSwapErrors, ZetaTokenConsumerUniV3 { - using SafeERC20 for IERC20; - bytes32 public constant CROSS_CHAIN_SWAP_MESSAGE = keccak256("CROSS_CHAIN_SWAP"); - - constructor( - address zetaConnector_, - address zetaToken_, - address uniswapV3Router_, - address uniswapV3Factory_, - address WETH9Address_, - uint24 zetaPoolFee_, - uint24 tokenPoolFee_ - ) - ZetaTokenConsumerUniV3( - zetaToken_, - uniswapV3Router_, - uniswapV3Factory_, - WETH9Address_, - zetaPoolFee_, - tokenPoolFee_ - ) - ZetaInteractor(zetaConnector_) - {} - - function swapETHForTokensCrossChain( - bytes calldata receiverAddress, - address destinationOutToken, - bool isDestinationOutETH, - /** - * @dev The minimum amount of tokens that receiverAddress should get, - * if it's not reached, the transaction will revert on the destination chain - */ - uint256 outTokenMinAmount, - uint256 destinationChainId, - uint256 crossChaindestinationGasLimit, - uint /* deadline */ - ) external payable override { - _swapETHForTokensCrossChain( - receiverAddress, - destinationOutToken, - isDestinationOutETH, - outTokenMinAmount, - destinationChainId, - crossChaindestinationGasLimit - ); - } - - function _swapETHForTokensCrossChain( - bytes calldata receiverAddress, - address destinationOutToken, - bool isDestinationOutETH, - /** - * @dev The minimum amount of tokens that receiverAddress should get, - * if it's not reached, the transaction will revert on the destination chain - */ - uint256 outTokenMinAmount, - uint256 destinationChainId, - uint256 crossChaindestinationGasLimit - ) internal { - if (!_isValidChainId(destinationChainId)) revert InvalidDestinationChainId(); - - if (msg.value == 0) revert ValueShouldBeGreaterThanZero(); - if ( - (destinationOutToken != address(0) && isDestinationOutETH) || - (destinationOutToken == address(0) && !isDestinationOutETH) - ) revert OutTokenInvariant(); - - uint256 zetaValueAndGas = this.getZetaFromEth{value: msg.value}( - address(this), - 0 /// @todo Add min amount - ); - if (zetaValueAndGas == 0) revert ErrorSwappingTokens(); - - IERC20(zetaToken).safeApprove(address(connector), zetaValueAndGas); - - connector.send( - ZetaInterfaces.SendInput({ - destinationChainId: destinationChainId, - destinationAddress: interactorsByChainId[destinationChainId], - destinationGasLimit: crossChaindestinationGasLimit, - message: abi.encode( - CROSS_CHAIN_SWAP_MESSAGE, - msg.sender, - WETH9Address, - msg.value, - receiverAddress, - destinationOutToken, - isDestinationOutETH, - outTokenMinAmount, - true // inputTokenIsETH - ), - zetaValueAndGas: zetaValueAndGas, - zetaParams: abi.encode("") - }) - ); - } - - function swapTokensForTokensCrossChain( - address sourceInputToken, - uint256 inputTokenAmount, - bytes calldata receiverAddress, - address destinationOutToken, - bool isDestinationOutETH, - /** - * @dev The minimum amount of tokens that receiverAddress should get, - * if it's not reached, the transaction will revert on the destination chain - */ - uint256 outTokenMinAmount, - uint256 destinationChainId, - uint256 crossChaindestinationGasLimit, - uint /* deadline */ - ) external override { - _swapTokensForTokensCrossChain( - sourceInputToken, - inputTokenAmount, - receiverAddress, - destinationOutToken, - isDestinationOutETH, - outTokenMinAmount, - destinationChainId, - crossChaindestinationGasLimit - ); - } - - function _swapTokensForTokensCrossChain( - address sourceInputToken, - uint256 inputTokenAmount, - bytes calldata receiverAddress, - address destinationOutToken, - bool isDestinationOutETH, - /** - * @dev The minimum amount of tokens that receiverAddress should get, - * if it's not reached, the transaction will revert on the destination chain - */ - uint256 outTokenMinAmount, - uint256 destinationChainId, - uint256 crossChaindestinationGasLimit - ) internal { - if (!_isValidChainId(destinationChainId)) revert InvalidDestinationChainId(); - - if (sourceInputToken == address(0)) revert MissingSourceInputTokenAddress(); - if ( - (destinationOutToken != address(0) && isDestinationOutETH) || - (destinationOutToken == address(0) && !isDestinationOutETH) - ) revert OutTokenInvariant(); - - uint256 zetaValueAndGas; - - IERC20(sourceInputToken).safeTransferFrom(msg.sender, address(this), inputTokenAmount); - - if (sourceInputToken == zetaToken) { - zetaValueAndGas = inputTokenAmount; - } else { - IERC20(sourceInputToken).safeApprove(address(this), inputTokenAmount); - zetaValueAndGas = this.getZetaFromToken( - address(this), - 0, /// @todo Add min amount - sourceInputToken, - inputTokenAmount - ); - - if (zetaValueAndGas == 0) revert ErrorSwappingTokens(); - } - - IERC20(zetaToken).safeApprove(address(connector), zetaValueAndGas); - - connector.send( - ZetaInterfaces.SendInput({ - destinationChainId: destinationChainId, - destinationAddress: interactorsByChainId[destinationChainId], - destinationGasLimit: crossChaindestinationGasLimit, - message: abi.encode( - CROSS_CHAIN_SWAP_MESSAGE, - msg.sender, - sourceInputToken, - inputTokenAmount, - receiverAddress, - destinationOutToken, - isDestinationOutETH, - outTokenMinAmount, - false // inputTokenIsETH - ), - zetaValueAndGas: zetaValueAndGas, - zetaParams: abi.encode("") - }) - ); - } - - function onZetaMessage( - ZetaInterfaces.ZetaMessage calldata zetaMessage - ) external override isValidMessageCall(zetaMessage) { - ( - bytes32 messageType, - address sourceTxOrigin, - address sourceInputToken, - uint256 inputTokenAmount, - bytes memory receiverAddressEncoded, - address destinationOutToken, - bool isDestinationOutETH, - uint256 outTokenMinAmount, - - ) = abi.decode(zetaMessage.message, (bytes32, address, address, uint256, bytes, address, bool, uint256, bool)); - if (messageType != CROSS_CHAIN_SWAP_MESSAGE) revert InvalidMessageType(); - - uint256 outTokenFinalAmount; - if (destinationOutToken == zetaToken) { - if (zetaMessage.zetaValue < outTokenMinAmount) revert InsufficientOutToken(); - - IERC20(zetaToken).safeTransfer(address(uint160(bytes20(receiverAddressEncoded))), zetaMessage.zetaValue); - - outTokenFinalAmount = zetaMessage.zetaValue; - } else { - /** - * @dev If the out token is not Zeta, get it using Uniswap - */ - IERC20(zetaToken).safeApprove(address(this), zetaMessage.zetaValue); - - if (isDestinationOutETH) { - outTokenFinalAmount = this.getEthFromZeta( - address(uint160(bytes20(receiverAddressEncoded))), - outTokenMinAmount, - zetaMessage.zetaValue - ); - } else { - outTokenFinalAmount = this.getTokenFromZeta( - address(uint160(bytes20(receiverAddressEncoded))), - outTokenMinAmount, - destinationOutToken, - zetaMessage.zetaValue - ); - } - - if (outTokenFinalAmount == 0) revert ErrorSwappingTokens(); - if (outTokenFinalAmount < outTokenMinAmount) revert InsufficientOutToken(); - } - - emit Swapped( - sourceTxOrigin, - sourceInputToken, - inputTokenAmount, - destinationOutToken, - outTokenFinalAmount, - address(uint160(bytes20(receiverAddressEncoded))) - ); - } - - function onZetaRevert( - ZetaInterfaces.ZetaRevert calldata zetaRevert - ) external override isValidRevertCall(zetaRevert) { - /** - * @dev If something goes wrong we must swap to the source input token - */ - ( - , - address sourceTxOrigin, - address sourceInputToken, - uint256 inputTokenAmount, - , - , - , - , - bool inputTokenIsETH - ) = abi.decode(zetaRevert.message, (bytes32, address, address, uint256, bytes, address, bool, uint256, bool)); - - uint256 inputTokenReturnedAmount; - if (sourceInputToken == zetaToken) { - IERC20(zetaToken).safeApprove(address(this), zetaRevert.remainingZetaValue); - IERC20(zetaToken).safeTransferFrom(address(this), sourceTxOrigin, zetaRevert.remainingZetaValue); - inputTokenReturnedAmount = zetaRevert.remainingZetaValue; - } else { - /** - * @dev If the source input token is not Zeta, trade it using Uniswap - */ - IERC20(zetaToken).safeApprove(address(this), zetaRevert.remainingZetaValue); - - if (inputTokenIsETH) { - inputTokenReturnedAmount = this.getEthFromZeta( - sourceTxOrigin, - 0, /// @todo Add min amount - zetaRevert.remainingZetaValue - ); - } else { - inputTokenReturnedAmount = this.getTokenFromZeta( - sourceTxOrigin, - 0, /// @todo Add min amount - sourceInputToken, - zetaRevert.remainingZetaValue - ); - } - } - - emit RevertedSwap(sourceTxOrigin, sourceInputToken, inputTokenAmount, inputTokenReturnedAmount); - } -} diff --git a/packages/example-contracts/contracts/multi-chain-swap/test/MultiChainSwapZetaConnector.sol b/packages/example-contracts/contracts/multi-chain-swap/test/MultiChainSwapZetaConnector.sol deleted file mode 100644 index 795154f6..00000000 --- a/packages/example-contracts/contracts/multi-chain-swap/test/MultiChainSwapZetaConnector.sol +++ /dev/null @@ -1,76 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity 0.8.7; - -import "@openzeppelin/contracts/interfaces/IERC20.sol"; -import "@zetachain/protocol-contracts/contracts/evm/interfaces/ZetaInterfaces.sol"; - -import "../MultiChainSwap.sol"; - -contract MultiChainSwapZetaConnector is ZetaConnector { - address public immutable zetaToken; - - constructor(address zetaToken_) { - if (zetaToken_ == address(0)) revert ZetaCommonErrors.InvalidAddress(); - zetaToken = zetaToken_; - } - - function callOnZetaMessage( - bytes memory zetaTxSenderAddress, - uint256 sourceChainId, - address destinationAddress, - uint256 zetaValue, - bytes calldata message - ) public { - return - MultiChainSwap(payable(destinationAddress)).onZetaMessage( - ZetaInterfaces.ZetaMessage({ - zetaTxSenderAddress: zetaTxSenderAddress, - sourceChainId: sourceChainId, - destinationAddress: destinationAddress, - zetaValue: zetaValue, - message: message - }) - ); - } - - function callOnZetaRevert( - address zetaTxSenderAddress, - uint256 sourceChainId, - uint256 destinationChainId, - bytes calldata destinationAddress, - uint256 remainingZetaValue, - uint256, // destinationGasLimit - bytes calldata message - ) public { - return - MultiChainSwap(payable(zetaTxSenderAddress)).onZetaRevert( - ZetaInterfaces.ZetaRevert({ - zetaTxSenderAddress: zetaTxSenderAddress, - sourceChainId: sourceChainId, - destinationAddress: destinationAddress, - destinationChainId: destinationChainId, - remainingZetaValue: remainingZetaValue, - message: message - }) - ); - } - - function send(ZetaInterfaces.SendInput calldata sendInput) external override { - uint256 sourceChainId = sendInput.destinationChainId == 2 ? 1 : 2; - address dest = address(uint160(bytes20(sendInput.destinationAddress))); - - if (sendInput.zetaValueAndGas > 0) { - bool success = IERC20(zetaToken).transferFrom(msg.sender, dest, sendInput.zetaValueAndGas); - require(success == true, "MultiChainSwap: error transferring token"); - } - - return - callOnZetaMessage( - abi.encodePacked(msg.sender), - sourceChainId, - dest, - sendInput.zetaValueAndGas, - sendInput.message - ); - } -} diff --git a/packages/example-contracts/contracts/shared/ImmutableCreate2Factory.sol b/packages/example-contracts/contracts/shared/ImmutableCreate2Factory.sol deleted file mode 100644 index b97a3210..00000000 --- a/packages/example-contracts/contracts/shared/ImmutableCreate2Factory.sol +++ /dev/null @@ -1,8 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity 0.5.10; - -/** - * @dev Contracts that need to be compiled for testing purposes - */ - -import "@zetachain/protocol-contracts/contracts/evm/tools/ImmutableCreate2Factory.sol"; diff --git a/packages/example-contracts/contracts/shared/TestContracts.sol b/packages/example-contracts/contracts/shared/TestContracts.sol deleted file mode 100644 index 53520a08..00000000 --- a/packages/example-contracts/contracts/shared/TestContracts.sol +++ /dev/null @@ -1,10 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity 0.6.6; - -/** - * @dev Contracts that need to be compiled for testing purposes - */ - -import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol"; -import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; -import "@uniswap/v2-periphery/contracts/UniswapV2Router02.sol"; diff --git a/packages/example-contracts/contracts/shared/ZetaEthMock.sol b/packages/example-contracts/contracts/shared/ZetaEthMock.sol deleted file mode 100644 index 17d9e2eb..00000000 --- a/packages/example-contracts/contracts/shared/ZetaEthMock.sol +++ /dev/null @@ -1,12 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity 0.8.7; - -import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; -import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; -import "@openzeppelin/contracts/utils/Context.sol"; - -contract ZetaEthMock is ERC20("Zeta", "ZETA") { - constructor(uint256 initialSupply) { - _mint(msg.sender, initialSupply * (10**uint256(decimals()))); - } -} diff --git a/packages/example-contracts/contracts/shared/ZetaTestContracts.sol b/packages/example-contracts/contracts/shared/ZetaTestContracts.sol deleted file mode 100644 index c2d645d4..00000000 --- a/packages/example-contracts/contracts/shared/ZetaTestContracts.sol +++ /dev/null @@ -1,8 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity 0.8.7; - -/** - * @dev Contracts that need to be compiled for testing purposes - */ - -import "@zetachain/protocol-contracts/contracts/evm/tools/ZetaTokenConsumerUniV2.strategy.sol"; diff --git a/packages/example-contracts/docs/cross-chain-counter.md b/packages/example-contracts/docs/cross-chain-counter.md deleted file mode 100644 index 13002629..00000000 --- a/packages/example-contracts/docs/cross-chain-counter.md +++ /dev/null @@ -1,5 +0,0 @@ -# Cross Chain Counter - -[![Docs](https://img.shields.io/badge/Zeta%20docs-🔗-43ad51)](https://docs.zetachain.com/develop/examples/cross-chain-counter) - -A simple cross-chain counter using [Zeta Connector](https://docs.zetachain.com/reference/connector). diff --git a/packages/example-contracts/docs/cross-chain-warriors.md b/packages/example-contracts/docs/cross-chain-warriors.md deleted file mode 100644 index 10b35202..00000000 --- a/packages/example-contracts/docs/cross-chain-warriors.md +++ /dev/null @@ -1,20 +0,0 @@ -# Cross Chain Warriors - -[![Docs](https://img.shields.io/badge/Zeta%20docs-🔗-43ad51)](https://docs.zetachain.com/develop/examples/cross-chain-nft) - -A cross-chain NFT collection using [Zeta Connector](https://docs.zetachain.com/reference/connector). - -## Try it in testnet - -The collection is currently deployed to [BSC Testnet](https://testnet.bscscan.com/address/0xa9016FB99846314E0f96f657E5271cFD7919a244) and [Goerli](https://goerli.etherscan.io/address/0xe08f1d23a68231543a595391D82c39BbaFc22470), the contracts are verified so you can use BSCScan and Etherscan to play with them. - -### Doing a cross-chain NFT transfer - -1. Go to the [BSC Testnet contract's write methods](https://testnet.bscscan.com/address/0xa9016FB99846314E0f96f657E5271cFD7919a244#writeContract). -1. Connect with your wallet. -1. Mint an NFT to your address. -1. View the transaction and copy the TokenId. -1. Call the crossChainTransfer method with the receiver address on the other chain and the TokenId you just minted. -1. After the transaction was mined, go to the contract's read methods and call ownerOf TokenId, you should get an `execution reverted` message since the NFT was burnt by the crossChainTransfer. -1. Go to the [Goerli contract's read methods](https://goerli.etherscan.io/address/0xe08f1d23a68231543a595391D82c39BbaFc22470#readContract). -1. Call the ownerOf method with your TokenId, the owner should be the receiver address you used before. *If it's not, note that the cross-chain transfer may take around 1 minute.* diff --git a/packages/example-contracts/hardhat.config.ts b/packages/example-contracts/hardhat.config.ts deleted file mode 100644 index 53562131..00000000 --- a/packages/example-contracts/hardhat.config.ts +++ /dev/null @@ -1,46 +0,0 @@ -import "@nomiclabs/hardhat-etherscan"; -import "@nomiclabs/hardhat-waffle"; -import "@typechain/hardhat"; -import "hardhat-gas-reporter"; -import "solidity-coverage"; -import "tsconfig-paths/register"; - -import { getHardhatConfigNetworks, getHardhatConfigScanners } from "@zetachain/addresses-tools/src/networks"; -import * as dotenv from "dotenv"; -import type { HardhatUserConfig } from "hardhat/types"; - -dotenv.config(); - -const PRIVATE_KEYS = process.env.PRIVATE_KEY !== undefined ? [`0x${process.env.PRIVATE_KEY}`] : []; - -const config: HardhatUserConfig = { - etherscan: { - ...getHardhatConfigScanners(), - }, - gasReporter: { - currency: "USD", - enabled: process.env.REPORT_GAS !== undefined, - }, - networks: { - ...getHardhatConfigNetworks(PRIVATE_KEYS), - }, - solidity: { - compilers: [ - { version: "0.5.10" /** For create2 factory */ }, - { version: "0.6.6" /** For uniswap v2 */ }, - { version: "0.8.7" }, - ], - settings: { - /** - * @see {@link https://smock.readthedocs.io/en/latest/getting-started.html} - */ - outputSelection: { - "*": { - "*": ["storageLayout"], - }, - }, - }, - }, -}; - -export default config; diff --git a/packages/example-contracts/lib/cross-chain-counter/CrossChainCounter.helpers.ts b/packages/example-contracts/lib/cross-chain-counter/CrossChainCounter.helpers.ts deleted file mode 100644 index 804867ed..00000000 --- a/packages/example-contracts/lib/cross-chain-counter/CrossChainCounter.helpers.ts +++ /dev/null @@ -1,62 +0,0 @@ -import assert from "assert"; -import { ethers, network } from "hardhat"; - -import { - CounterZetaConnectorMock, - CounterZetaConnectorMock__factory as CounterZetaConnectorMockFactory, - CrossChainCounter, - CrossChainCounter__factory as CrossChainCounterFactory, -} from "../../typechain-types"; -import { isNetworkName, networkVariables } from "../shared/network.constants"; - -/** - * @description only for testing or local environment - */ -export const deployTestCrossChainCounter = async ({ - zetaConnectorMockAddress, -}: { - zetaConnectorMockAddress: string; -}) => { - const isLocalEnvironment = network.name === "hardhat"; - - assert(isLocalEnvironment, "This function is only intended to be used in the local environment"); - - const Factory = (await ethers.getContractFactory("CrossChainCounter")) as CrossChainCounterFactory; - - const crossChainCounterContract = (await Factory.deploy(zetaConnectorMockAddress)) as CrossChainCounter; - - await crossChainCounterContract.deployed(); - - return crossChainCounterContract; -}; - -export const getCrossChainCounter = async (existingContractAddress?: string) => { - if (!isNetworkName(network.name)) throw new Error("Invalid network name"); - const isGetExistingContract = typeof existingContractAddress !== "undefined"; - - const _networkVariables = networkVariables[network.name]; - - const Factory = (await ethers.getContractFactory("CrossChainCounter")) as CrossChainCounterFactory; - - if (isGetExistingContract) { - console.log("Getting existing CrossChainCounter"); - return Factory.attach(existingContractAddress) as CrossChainCounter; - } - - console.log("Deploying CrossChainCounter"); - const crossChainCounterContract = (await Factory.deploy(_networkVariables.connectorAddress)) as CrossChainCounter; - - await crossChainCounterContract.deployed(); - - return crossChainCounterContract; -}; - -export const deployZetaConnectorMock = async () => { - const Factory = (await ethers.getContractFactory("CounterZetaConnectorMock")) as CounterZetaConnectorMockFactory; - - const zetaConnectorMockContract = (await Factory.deploy()) as CounterZetaConnectorMock; - - await zetaConnectorMockContract.deployed(); - - return zetaConnectorMockContract; -}; diff --git a/packages/example-contracts/lib/cross-chain-message/CrossChainMessage.helpers.ts b/packages/example-contracts/lib/cross-chain-message/CrossChainMessage.helpers.ts deleted file mode 100644 index 47adfbee..00000000 --- a/packages/example-contracts/lib/cross-chain-message/CrossChainMessage.helpers.ts +++ /dev/null @@ -1,61 +0,0 @@ -import assert from "assert"; -import { ContractFactory, ContractReceipt } from "ethers"; -import { ethers, network } from "hardhat"; - -import { - CrossChainMessage, - CrossChainMessage__factory, - CrossChainMessageConnector, - CrossChainMessageConnector__factory, -} from "../../typechain-types"; - -export type GetContractParams = - | { - deployParams: Parameters; - existingContractAddress?: null; - } - | { - deployParams?: null; - existingContractAddress: string; - }; - -/** - * @description only for testing or local environment - */ -export const deployCrossChainMessageMock = async ({ - zetaConnectorMockAddress, - zetaTokenConsumerAddress, - zetaTokenMockAddress, -}: { - zetaConnectorMockAddress: string; - zetaTokenConsumerAddress: string; - zetaTokenMockAddress: string; -}) => { - const isLocalEnvironment = network.name === "hardhat"; - - assert(isLocalEnvironment, "deployCrossChainMessageMock is only intended to be used in the local environment"); - - const Factory = (await ethers.getContractFactory("CrossChainMessage")) as CrossChainMessage__factory; - - const crossChainMessageContract = (await Factory.deploy( - zetaConnectorMockAddress, - zetaTokenMockAddress, - zetaTokenConsumerAddress - )) as CrossChainMessage; - - await crossChainMessageContract.deployed(); - - return crossChainMessageContract; -}; - -export const deployZetaConnectorMock = async () => { - const Factory = (await ethers.getContractFactory( - "CrossChainMessageConnector" - )) as CrossChainMessageConnector__factory; - - const zetaConnectorMockContract = (await Factory.deploy()) as CrossChainMessageConnector; - - await zetaConnectorMockContract.deployed(); - - return zetaConnectorMockContract; -}; diff --git a/packages/example-contracts/lib/cross-chain-warriors/CrossChainWarriors.helpers.ts b/packages/example-contracts/lib/cross-chain-warriors/CrossChainWarriors.helpers.ts deleted file mode 100644 index fecdd595..00000000 --- a/packages/example-contracts/lib/cross-chain-warriors/CrossChainWarriors.helpers.ts +++ /dev/null @@ -1,101 +0,0 @@ -import assert from "assert"; -import { ContractFactory } from "ethers"; -import { ethers, network } from "hardhat"; - -import { - CrossChainWarriors, - CrossChainWarriors__factory as CrossChainWarriorsFactory, - CrossChainWarriorsMock, - CrossChainWarriorsMock__factory as CrossChainWarriorsMockFactory, - CrossChainWarriorsZetaConnectorMock, - CrossChainWarriorsZetaConnectorMock__factory as CrossChainWarriorsZetaConnectorMockFactory -} from "../../typechain-types"; -import { getAddress } from "../shared/address.helpers"; -import { isNetworkName } from "../shared/network.constants"; - -export type GetContractParams = - | { - deployParams: Parameters; - existingContractAddress?: null; - } - | { - deployParams?: null; - existingContractAddress: string; - }; - -/** - * @description only for testing or local environment - */ -export const deployCrossChainWarriorsMock = async ({ - customUseEven, - zetaConnectorMockAddress, - zetaTokenMockAddress, - zetaTokenConsumerAddress -}: { - customUseEven: boolean; - zetaConnectorMockAddress: string; - zetaTokenConsumerAddress: string; - zetaTokenMockAddress: string; -}) => { - const isLocalEnvironment = network.name === "hardhat"; - - assert(isLocalEnvironment, "localDeployCrossChainWarriors is only intended to be used in the local environment"); - - const Factory = (await ethers.getContractFactory("CrossChainWarriorsMock")) as CrossChainWarriorsMockFactory; - - const useEven = customUseEven; - - const crossChainWarriorsContract = (await Factory.deploy( - zetaConnectorMockAddress, - zetaTokenMockAddress, - zetaTokenConsumerAddress, - useEven - )) as CrossChainWarriorsMock; - - await crossChainWarriorsContract.deployed(); - - return crossChainWarriorsContract; -}; - -export const getCrossChainWarriorsArgs = (): [string, string, string, boolean] => [ - getAddress("connector"), - getAddress("zetaToken"), - getAddress("zetaTokenConsumerUniV2"), - network.name === "goerli" -]; - -export const getCrossChainWarriors = async (existingContractAddress?: string) => { - if (!isNetworkName(network.name)) throw new Error("Invalid network name"); - const isGetExistingContract = typeof existingContractAddress !== "undefined"; - - const Factory = (await ethers.getContractFactory("CrossChainWarriors")) as CrossChainWarriorsFactory; - - if (isGetExistingContract) { - console.log("Getting existing Cross Chain Warriors"); - return Factory.attach(existingContractAddress) as CrossChainWarriors; - } - - console.log("Deploying Cross Chain Warriors"); - const crossChainWarriorsContract = (await Factory.deploy( - getCrossChainWarriorsArgs()[0], - getCrossChainWarriorsArgs()[1], - getCrossChainWarriorsArgs()[2], - getCrossChainWarriorsArgs()[3] - )) as CrossChainWarriors; - - await crossChainWarriorsContract.deployed(); - - return crossChainWarriorsContract; -}; - -export const deployZetaConnectorMock = async () => { - const Factory = (await ethers.getContractFactory( - "CrossChainWarriorsZetaConnectorMock" - )) as CrossChainWarriorsZetaConnectorMockFactory; - - const zetaConnectorMockContract = (await Factory.deploy()) as CrossChainWarriorsZetaConnectorMock; - - await zetaConnectorMockContract.deployed(); - - return zetaConnectorMockContract; -}; diff --git a/packages/example-contracts/lib/multi-chain-swap/MultiChainSwap.helpers.ts b/packages/example-contracts/lib/multi-chain-swap/MultiChainSwap.helpers.ts deleted file mode 100644 index 26ce50b0..00000000 --- a/packages/example-contracts/lib/multi-chain-swap/MultiChainSwap.helpers.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { - MultiChainSwapUniV2, - MultiChainSwapUniV2__factory as MultiChainSwapUniV2Factory, - MultiChainSwapUniV3, - MultiChainSwapUniV3__factory as MultiChainSwapUniV3Factory, - MultiChainSwapZetaConnector, - MultiChainSwapZetaConnector__factory -} from "../../typechain-types"; -import { MultiChainSwapTrident } from "../../typechain-types/contracts/multi-chain-swap/MultiChainSwapTrident.strategy.sol"; -import { MultiChainSwapTrident__factory } from "../../typechain-types/factories/contracts/multi-chain-swap/MultiChainSwapTrident.strategy.sol"; -import { getContract, GetContractParams } from "../shared/deploy.helpers"; - -export const getMultiChainSwapUniV2 = async (params: GetContractParams) => - getContract({ - contractName: "MultiChainSwapUniV2", - ...params - }); - -export const getMultiChainSwapUniV3 = async (params: GetContractParams) => - getContract({ - contractName: "MultiChainSwapUniV3", - ...params - }); - -export const getMultiChainSwapTrident = async (params: GetContractParams) => - getContract({ - contractName: "MultiChainSwapTrident", - ...params - }); - -export const getMultiChainSwapZetaConnector = async (zetaToken: string) => - getContract({ - contractName: "MultiChainSwapZetaConnector", - deployParams: [zetaToken] - }); diff --git a/packages/example-contracts/lib/shared/ImmutableCreate2Factory.helpers.ts b/packages/example-contracts/lib/shared/ImmutableCreate2Factory.helpers.ts deleted file mode 100644 index e180e84f..00000000 --- a/packages/example-contracts/lib/shared/ImmutableCreate2Factory.helpers.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { Provider, TransactionReceipt } from "@ethersproject/providers"; -import { ImmutableCreate2Factory__factory } from "@zetachain/interfaces/typechain-types"; -import { ethers, Signer } from "ethers"; - -export const buildBytecode = (constructorTypes: any[], constructorArgs: any[], contractBytecode: string) => - `${contractBytecode}${encodeParams(constructorTypes, constructorArgs).slice(2)}`; - -export const buildCreate2Address = (saltHex: string, byteCode: string, factoryAddress: string) => { - const payload = ethers.utils.keccak256( - `0x${["ff", factoryAddress, saltHex, ethers.utils.keccak256(byteCode)].map((x) => x.replace(/0x/, "")).join("")}` - ); - - return `0x${payload.slice(-40)}`.toLowerCase(); -}; - -export const numberToUint256 = (value: number) => { - const hex = value.toString(16); - return `0x${"0".repeat(64 - hex.length)}${hex}`; -}; - -export const saltToHex = (salt: string, signerAddress: string) => { - let salthex = ethers.utils.formatBytes32String(salt); - return `${signerAddress}${salthex.slice(2)}`.substring(0, salthex.length); -}; - -export const encodeParam = (dataType: any, data: any) => { - const abiCoder = ethers.utils.defaultAbiCoder; - return abiCoder.encode([dataType], [data]); -}; - -export const encodeParams = (dataTypes: any[], data: any[]) => { - const abiCoder = ethers.utils.defaultAbiCoder; - return abiCoder.encode(dataTypes, data); -}; - -export async function deployContractToAddress({ - factoryAddress, - salt, - contractBytecode, - constructorTypes = [] as string[], - constructorArgs = [] as any[], - signer, -}: { - constructorArgs?: any[]; - constructorTypes?: string[]; - contractBytecode: string; - factoryAddress: string; - salt: string; - signer: Signer; -}) { - const factory = ImmutableCreate2Factory__factory.connect(factoryAddress, signer); - - const bytecode = buildBytecode(constructorTypes, constructorArgs, contractBytecode); - - const computedAddr = await factory.findCreate2Address(salt, bytecode); - - const tx = await factory.safeCreate2(salt, bytecode, { - gasLimit: 6000000, - }); - const result = await tx.wait(); - - return { - address: computedAddr as string, - receipt: result as TransactionReceipt, - txHash: result.transactionHash as string, - }; -} - -/** - * Determines if there's a contract deployed on the provided address. - */ -export async function isDeployed(address: string, provider: Provider) { - const code = await provider.getCode(address); - return code.slice(2).length > 0; -} diff --git a/packages/example-contracts/lib/shared/address.helpers.ts b/packages/example-contracts/lib/shared/address.helpers.ts deleted file mode 100644 index d6c498f2..00000000 --- a/packages/example-contracts/lib/shared/address.helpers.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { getAddress as getAddressLib, NetworkName, ZetaAddress, ZetaNetworkName } from "@zetachain/addresses"; -import { network } from "hardhat"; - -const MissingZetaNetworkError = new Error( - "ZETA_NETWORK is not defined, please set the environment variable (e.g.: ZETA_NETWORK=athens )" -); - -export const getAddress = ( - address: ZetaAddress, - { - customNetworkName, - customZetaNetwork - }: { customNetworkName?: NetworkName; customZetaNetwork?: ZetaNetworkName } = {} -): string => { - const { name: _networkName } = network; - const networkName = customNetworkName || _networkName; - - const { ZETA_NETWORK: _ZETA_NETWORK } = process.env; - const zetaNetwork = customZetaNetwork || _ZETA_NETWORK; - - if (!zetaNetwork) throw MissingZetaNetworkError; - return getAddressLib({ address, networkName, zetaNetwork }); -}; diff --git a/packages/example-contracts/lib/shared/deploy.helpers.ts b/packages/example-contracts/lib/shared/deploy.helpers.ts deleted file mode 100644 index 7e78ddf2..00000000 --- a/packages/example-contracts/lib/shared/deploy.helpers.ts +++ /dev/null @@ -1,96 +0,0 @@ -import { NetworkName, ZetaAddress, ZetaNetworkName } from "@zetachain/addresses"; -import { getScanVariable } from "@zetachain/addresses-tools"; -import { execSync } from "child_process"; -import { BaseContract, ContractFactory } from "ethers"; -import { ethers } from "hardhat"; - -import { - ERC20, - ERC20__factory as ERC20Factory, - UniswapV2Router02, - UniswapV2Router02__factory as UniswapV2Router02Factory, - ZetaEthMock, - ZetaEthMock__factory as ZetaEthMockFactory, - ZetaTokenConsumerUniV2, - ZetaTokenConsumerUniV2__factory -} from "../../typechain-types"; -import { getAddress } from "../shared/address.helpers"; - -export type GetContractParams = - | { - deployParams: Parameters; - existingContractAddress?: null; - } - | { - deployParams?: null; - existingContractAddress: string; - }; - -export const getContract = async ({ - contractName, - deployParams, - existingContractAddress -}: GetContractParams & { contractName: string }): Promise => { - const ContractFactory = (await ethers.getContractFactory(contractName)) as Factory; - - const isGetExistingContract = Boolean(existingContractAddress); - if (isGetExistingContract) { - console.log("Getting existing contract from address:", existingContractAddress); - return ContractFactory.attach(existingContractAddress!) as Contract; - } - - const contract = (await ContractFactory.deploy(...deployParams!)) as Contract; - await contract.deployed(); - - return contract; -}; - -export const getErc20 = async (existingContractAddress?: string) => - getContract({ - contractName: "ERC20", - ...(existingContractAddress ? { existingContractAddress } : { deployParams: ["ERC20Mock", "ERC20Mock"] }) - }); - -export const getZetaMock = async () => - getContract({ - contractName: "ZetaEthMock", - deployParams: ["10000000"] - }); - -export const getNow = async () => { - const block = await ethers.provider.getBlock("latest"); - return block.timestamp; -}; - -export const getUniswapV2Router02 = async () => - getContract({ - contractName: "UniswapV2Router02", - existingContractAddress: getAddress("uniswapV2Router02", { - customNetworkName: "eth-mainnet", - customZetaNetwork: "mainnet" - }) - }); - -export const verifyContract = ( - addressName: ZetaAddress, - { - customNetworkName, - customZetaNetwork - }: { customNetworkName?: NetworkName; customZetaNetwork?: ZetaNetworkName } = {} -) => { - const ZETA_NETWORK = process.env.ZETA_NETWORK || customZetaNetwork; - - console.log(`Verifying ${addressName} address on ${ZETA_NETWORK}: ${customNetworkName}.`); - - const command = `ZETA_NETWORK=${ZETA_NETWORK} SCAN_API_KEY=${getScanVariable()} npx hardhat verify --network ${customNetworkName} --constructor-args lib/args/${addressName}.js ${getAddress( - addressName - )}`; - - execSync(command); -}; - -export const deployZetaTokenConsumerUniV2 = async (zetaToken_: string, uniswapV2Router_: string) => - getContract({ - contractName: "ZetaTokenConsumerUniV2", - ...{ deployParams: [zetaToken_, uniswapV2Router_] } - }); diff --git a/packages/example-contracts/lib/shared/network.constants.ts b/packages/example-contracts/lib/shared/network.constants.ts deleted file mode 100644 index 3fd74ad5..00000000 --- a/packages/example-contracts/lib/shared/network.constants.ts +++ /dev/null @@ -1,104 +0,0 @@ -import { NetworkName } from "@zetachain/addresses"; - -type ChainId = 0 | 1 | 5 | 56 | 97 | 1001 | 1337 | 80001; - -export type NetworkVariables = { - chainId: ChainId; - connectorAddress: string; - crossChainId: ChainId; - crossChainName: NetworkName | ""; -}; - -export const networkVariables: Record = { - athens: { - chainId: 0, - connectorAddress: "", - crossChainId: 0, - crossChainName: "" - }, - "bitcoin-test": { - chainId: 0, - connectorAddress: "", - crossChainId: 0, - crossChainName: "" - }, - "bsc-localnet": { - chainId: 0, - connectorAddress: "", - crossChainId: 0, - crossChainName: "" - }, - "bsc-mainnet": { - chainId: 56, - connectorAddress: "", - crossChainId: 1, - crossChainName: "eth-mainnet" - }, - "bsc-testnet": { - chainId: 97, - connectorAddress: "0xE626402550fB921E4a47c11568F89dF3496fbEF0", - crossChainId: 5, - crossChainName: "goerli" - }, - "eth-localnet": { - chainId: 0, - connectorAddress: "", - crossChainId: 0, - crossChainName: "" - }, - "eth-mainnet": { - chainId: 0, - connectorAddress: "", - crossChainId: 0, - crossChainName: "" - }, - goerli: { - chainId: 5, - connectorAddress: "0x68Bc806414e743D88436AEB771Be387A55B4df70", - crossChainId: 97, - crossChainName: "bsc-testnet" - }, - hardhat: { - chainId: 0, - connectorAddress: "", - crossChainId: 0, - crossChainName: "" - }, - "klaytn-baobab": { - chainId: 1001, - connectorAddress: "", - crossChainId: 5, - crossChainName: "goerli" - }, - "klaytn-cypress": { - chainId: 0, - connectorAddress: "", - crossChainId: 0, - crossChainName: "" - }, - "polygon-localnet": { - chainId: 0, - connectorAddress: "", - crossChainId: 0, - crossChainName: "" - }, - "polygon-mumbai": { - chainId: 0, - connectorAddress: "", - crossChainId: 0, - crossChainName: "" - } -}; - -export const isNetworkName = (str: string): str is NetworkName => str in networkVariables; -export const isEthNetworkName = (networkName: string) => - networkName === "eth-localnet" || networkName === "goerli" || networkName === "eth-mainnet"; - -export type AddressConstants = Partial< - Record< - NetworkName, - { - crossChainWarriorsAddress: string; - } - > ->; diff --git a/packages/example-contracts/package.json b/packages/example-contracts/package.json deleted file mode 100644 index 5a207dbd..00000000 --- a/packages/example-contracts/package.json +++ /dev/null @@ -1,42 +0,0 @@ -{ - "name": "@zetachain/example-contracts", - "version": "0.0.1", - "license": "MIT", - "private": true, - "author": "zetachain", - "publishConfig": { - "access": "public", - "registry": "https://registry.npmjs.org/" - }, - "scripts": { - "clean": "npx hardhat clean", - "compile": "npx hardhat compile", - "prepublishOnly": "echo 'This package has no prepublishOnly tasks.'", - "multi-chain-swap:deploy-local": "ZETA_NETWORK=troy EXECUTE_PROGRAMMATICALLY=true npx hardhat run scripts/multi-chain-swap/deploy.ts --network hardhat", - "multi-chain-swap:deploy": "ZETA_NETWORK=athens EXECUTE_PROGRAMMATICALLY=true npx hardhat run scripts/multi-chain-swap/deploy.ts", - "lint:fix": "npm run lint:js:fix && npm run lint:sol:fix", - "lint:js:fix": "eslint --ext .js,.ts . --fix", - "lint:js": "eslint --ext .js,.ts .", - "lint:sol:fix": "prettier --write \"contracts/**/*.sol\"", - "lint:sol": "solhint 'contracts/**/*.sol' && prettier -c 'contracts/**/*.sol'", - "lint": "npm run lint:js && npm run lint:sol", - "test:watch": "echo You need to install `entr` to run this command && find contracts/**/** lib/**/** test/**/** -iname '*.sol' -o -iname '*.ts' | entr -cnr npx hardhat test", - "test": "npx hardhat test", - "tsc:watch": "npx tsc --watch" - }, - "devDependencies": { - "@defi-wonderland/smock": "^2.3.4", - "hardhat-gas-reporter": "^1.0.8", - "solidity-coverage": "^0.7.20", - "tsconfig-paths": "^3.14.1" - }, - "dependencies": { - "@openzeppelin/contracts": "^4.8.3", - "@uniswap/v2-periphery": "1.1.0-beta.0", - "@uniswap/v3-periphery": "1.1.0", - "@zetachain/addresses": "workspace:^", - "@zetachain/addresses-tools": "workspace:^", - "@zetachain/protocol-contracts": "^2.1.0", - "ethers": "5.6.8" - } -} diff --git a/packages/example-contracts/scripts/add-liquidity-uniswap-v2.ts b/packages/example-contracts/scripts/add-liquidity-uniswap-v2.ts deleted file mode 100644 index 668b423e..00000000 --- a/packages/example-contracts/scripts/add-liquidity-uniswap-v2.ts +++ /dev/null @@ -1,114 +0,0 @@ -import { MaxUint256 } from "@ethersproject/constants"; -import { parseUnits } from "@ethersproject/units"; -import { SignerWithAddress } from "@nomiclabs/hardhat-ethers/signers"; -import { BigNumber } from "ethers"; -import { ethers } from "hardhat"; - -import { getAddress } from "../lib/shared/address.helpers"; -import { getContract } from "../lib/shared/deploy.helpers"; -import { - ERC20__factory, - IUniswapV2Factory__factory, - IUniswapV2Pair__factory, - IUniswapV2Router02, - UniswapV2Router02, - UniswapV2Router02__factory -} from "../typechain-types"; - -const UNISWAP_FACTORY_ADDRESS = "0xb7926c0430afb07aa7defde6da862ae0bde767bc"; - -const ZETA_TO_ADD = parseUnits("19000"); -const ETH_TO_ADD = parseUnits("10"); - -interface Pair { - TokenA: string; - TokenB: string; -} - -export const getNow = async () => { - const block = await ethers.provider.getBlock("latest"); - return block.timestamp; -}; - -export const sortPair = (token1: string, token2: string): Pair => { - if (token1 < token2) { - return { TokenA: token1, TokenB: token2 }; - } - return { TokenA: token2, TokenB: token1 }; -}; - -const addZetaEthLiquidity = async ( - zetaTokenAddress: string, - zetaToAdd: BigNumber, - ETHToAdd: BigNumber, - uniswapRouter: IUniswapV2Router02, - deployer: SignerWithAddress -) => { - const ZetaTokenContract = ERC20__factory.connect(zetaTokenAddress, deployer); - - const tx1 = await ZetaTokenContract.approve(uniswapRouter.address, MaxUint256); - await tx1.wait(); - - const tx2 = await uniswapRouter.addLiquidityETH( - ZetaTokenContract.address, - zetaToAdd, - 0, - 0, - deployer.address, - (await getNow()) + 360, - { gasLimit: 10_000_000, value: ETHToAdd } - ); - await tx2.wait(); -}; - -const estimateEthForZeta = async ( - zetaTokenAddress: string, - zetaToAdd: BigNumber, - uniswapRouter: IUniswapV2Router02, - deployer: SignerWithAddress -) => { - const WETH = await uniswapRouter.WETH(); - - const uniswapV2Factory = IUniswapV2Factory__factory.connect(UNISWAP_FACTORY_ADDRESS, deployer); - - const pair = sortPair(zetaTokenAddress, WETH); - - const poolAddress = await uniswapV2Factory.getPair(pair.TokenA, pair.TokenB); - - const pool = IUniswapV2Pair__factory.connect(poolAddress, deployer); - - const reserves = await pool.getReserves(); - const reservesZeta = WETH < zetaTokenAddress ? reserves.reserve0 : reserves.reserve1; - const reservesETH = WETH > zetaTokenAddress ? reserves.reserve0 : reserves.reserve1; - const ETHValue = await uniswapRouter.quote(zetaToAdd, reservesZeta, reservesETH); - - return ETHValue; -}; - -export const getUniswapV2Router02 = async () => - getContract({ - contractName: "UniswapV2Router02", - existingContractAddress: getAddress("uniswapV2Router02") - }); - -async function main() { - const [deployer] = await ethers.getSigners(); - - const zetaTokenAddress = getAddress("zetaToken"); - - const uniswapRouter = await getUniswapV2Router02(); - - let ethToAdd = ETH_TO_ADD; - if (ETH_TO_ADD.isZero()) { - ethToAdd = await estimateEthForZeta(zetaTokenAddress, ZETA_TO_ADD, uniswapRouter, deployer); - } - - await addZetaEthLiquidity(zetaTokenAddress, ZETA_TO_ADD, ethToAdd, uniswapRouter, deployer); -} - -main() - .then(() => process.exit(0)) - .catch(error => { - console.error(error); - process.exit(1); - }); diff --git a/packages/example-contracts/scripts/cross-chain-counter/deploy.ts b/packages/example-contracts/scripts/cross-chain-counter/deploy.ts deleted file mode 100644 index cb097d3d..00000000 --- a/packages/example-contracts/scripts/cross-chain-counter/deploy.ts +++ /dev/null @@ -1,11 +0,0 @@ -// eslint-disable-next-line no-unused-vars -import hardhat from "hardhat"; - -async function main() { - console.log(`Deploying CrossChainCounter...`); -} - -main().catch((error) => { - console.error(error); - process.exit(1); -}); diff --git a/packages/example-contracts/scripts/cross-chain-warriors/deploy.ts b/packages/example-contracts/scripts/cross-chain-warriors/deploy.ts deleted file mode 100644 index ac857da4..00000000 --- a/packages/example-contracts/scripts/cross-chain-warriors/deploy.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { isNetworkName } from "@zetachain/addresses"; -import { saveAddress } from "@zetachain/addresses-tools"; -import { ethers, network } from "hardhat"; - -import { getCrossChainWarriors } from "../../lib/cross-chain-warriors/CrossChainWarriors.helpers"; - -async function main() { - if (!isNetworkName(network.name)) throw new Error("Invalid network name"); - - const crossChainWarriorsContract = await getCrossChainWarriors(); - - console.log("Setting base URI"); - ( - await crossChainWarriorsContract.setBaseURI( - "https://gateway.pinata.cloud/ipfs/QmNRP9kZ2SJXnFnxwvhQbxQHQuXVWVive3JkCNgG6315iH/" - ) - ).wait(); - - const [deployer] = await ethers.getSigners(); - - console.log("Minting"); - await crossChainWarriorsContract.mint(deployer.address); - - saveAddress("crossChainNft", crossChainWarriorsContract.address); -} - -main().catch((error) => { - console.error(error); - process.exit(1); -}); diff --git a/packages/example-contracts/scripts/cross-chain-warriors/deterministic-deploy.ts b/packages/example-contracts/scripts/cross-chain-warriors/deterministic-deploy.ts deleted file mode 100644 index ccb4a045..00000000 --- a/packages/example-contracts/scripts/cross-chain-warriors/deterministic-deploy.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { isNetworkName } from "@zetachain/addresses"; -import { saveAddress } from "@zetachain/addresses-tools"; -import { BigNumber } from "ethers"; -import { ethers, network } from "hardhat"; - -import { getAddress } from "../../lib/shared/address.helpers"; -import { deployContractToAddress, saltToHex } from "../../lib/shared/ImmutableCreate2Factory.helpers"; -import { isEthNetworkName } from "../../lib/shared/network.constants"; -import { CrossChainWarriors__factory } from "../../typechain-types"; - -const DEPLOYER_ADDRESS = process.env.DEPLOYER_ADDRESS ?? ""; -const SALT_NUMBER = "0"; - -export async function deterministicDeployCrossChainNft() { - if (!isNetworkName(network.name)) { - throw new Error(`network.name: ${network.name} isn't supported.`); - } - - const accounts = await ethers.getSigners(); - const [signer] = accounts; - - const saltNumber = SALT_NUMBER; - const saltStr = BigNumber.from(saltNumber).toHexString(); - - const connector = getAddress("connector"); - const zetaToken = getAddress("zetaToken"); - const zetaTokenConsumerUniV2 = getAddress("zetaTokenConsumerUniV2"); - - const immutableCreate2Factory = getAddress("immutableCreate2Factory"); - - const salthex = saltToHex(saltStr, DEPLOYER_ADDRESS); - - const useEven = isEthNetworkName(network.name); - const constructorTypes = ["address", "address", "address", "bool"]; - const constructorArgs = [connector, zetaToken, zetaTokenConsumerUniV2, useEven]; - - const contractBytecode = CrossChainWarriors__factory.bytecode; - - const { address } = await deployContractToAddress({ - constructorArgs, - constructorTypes, - contractBytecode, - factoryAddress: immutableCreate2Factory, - salt: salthex, - signer - }); - - saveAddress("crossChainNft", address); - console.log("Deployed crossChainNft. Address:", address); -} - -if (!process.env.EXECUTE_PROGRAMMATICALLY) { - deterministicDeployCrossChainNft() - .then(() => process.exit(0)) - .catch(error => { - console.error(error); - process.exit(1); - }); -} diff --git a/packages/example-contracts/scripts/cross-chain-warriors/set-cross-chain-data.ts b/packages/example-contracts/scripts/cross-chain-warriors/set-cross-chain-data.ts deleted file mode 100644 index fa10c9de..00000000 --- a/packages/example-contracts/scripts/cross-chain-warriors/set-cross-chain-data.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { ethers, network } from "hardhat"; - -import { getCrossChainWarriors } from "../../lib/cross-chain-warriors/CrossChainWarriors.helpers"; -import { getAddress } from "../../lib/shared/address.helpers"; -import { isNetworkName, networkVariables } from "../../lib/shared/network.constants"; - -async function main() { - if (!isNetworkName(network.name)) throw new Error("Invalid network name"); - - const _networkVariables = networkVariables[network.name]; - - const crossChainWarriorsAddress = getAddress("crossChainNft"); - - const crossChainWarriorsContract = await getCrossChainWarriors(crossChainWarriorsAddress); - - if (_networkVariables.crossChainName === "") throw new Error("Invalid crossChainName"); - - const crossChainAddress = getAddress("crossChainNft", { - customNetworkName: _networkVariables.crossChainName - }); - - const encodedCrossChainAddress = ethers.utils.solidityPack(["address"], [crossChainAddress]); - - console.log("Setting cross-chain data:", _networkVariables.crossChainId, encodedCrossChainAddress); - - await ( - await crossChainWarriorsContract.setInteractorByChainId(_networkVariables.crossChainId, encodedCrossChainAddress) - ).wait(); -} - -main().catch(error => { - console.error(error); - process.exit(1); -}); diff --git a/packages/example-contracts/scripts/cross-chain-warriors/verify-contract.ts b/packages/example-contracts/scripts/cross-chain-warriors/verify-contract.ts deleted file mode 100644 index 2c33ee86..00000000 --- a/packages/example-contracts/scripts/cross-chain-warriors/verify-contract.ts +++ /dev/null @@ -1,18 +0,0 @@ -import hardhat from "hardhat"; - -import { getCrossChainWarriorsArgs } from "../../lib/cross-chain-warriors/CrossChainWarriors.helpers"; -import { getAddress } from "../../lib/shared/address.helpers"; - -async function main() { - await hardhat.run("verify:verify", { - address: getAddress("crossChainNft"), - constructorArguments: getCrossChainWarriorsArgs() - }); -} - -main() - .then(() => process.exit(0)) - .catch(error => { - console.error(error); - process.exit(1); - }); diff --git a/packages/example-contracts/scripts/multi-chain-swap/deploy-multi-chain-swap-trident.ts b/packages/example-contracts/scripts/multi-chain-swap/deploy-multi-chain-swap-trident.ts deleted file mode 100644 index c7a53537..00000000 --- a/packages/example-contracts/scripts/multi-chain-swap/deploy-multi-chain-swap-trident.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { isNetworkName } from "@zetachain/addresses"; -import { saveAddress } from "@zetachain/addresses-tools"; -import { network } from "hardhat"; - -import { getMultiChainSwapTrident } from "../../lib/multi-chain-swap/MultiChainSwap.helpers"; -import { getAddress } from "../../lib/shared/address.helpers"; - -export async function deployMultiChainSwap() { - if (!isNetworkName(network.name) || !network.name) throw new Error("Invalid network name"); - - const CONNECTOR = getAddress("connector"); - - const ZETA_TOKEN = getAddress("zetaToken"); - - const UNI_ROUTER_V3 = getAddress("uniswapV3Router"); - - const WETH = getAddress("weth9"); - - const TRIDENT_POOL_FACTORY = getAddress("tridentPoolFactory"); - - const multiChainSwapContract = await getMultiChainSwapTrident({ - deployParams: [CONNECTOR, ZETA_TOKEN, UNI_ROUTER_V3, WETH, TRIDENT_POOL_FACTORY] - }); - - saveAddress("multiChainSwap", multiChainSwapContract.address); -} - -if (!process.env.EXECUTE_PROGRAMMATICALLY) { - deployMultiChainSwap().catch(error => { - console.error(error); - process.exit(1); - }); -} diff --git a/packages/example-contracts/scripts/multi-chain-swap/deploy-multi-chain-swap-v3.ts b/packages/example-contracts/scripts/multi-chain-swap/deploy-multi-chain-swap-v3.ts deleted file mode 100644 index 6c82f687..00000000 --- a/packages/example-contracts/scripts/multi-chain-swap/deploy-multi-chain-swap-v3.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { isNetworkName } from "@zetachain/addresses"; -import { saveAddress } from "@zetachain/addresses-tools"; -import { network } from "hardhat"; - -import { getMultiChainSwapUniV3 } from "../../lib/multi-chain-swap/MultiChainSwap.helpers"; -import { getAddress } from "../../lib/shared/address.helpers"; -import { GetContractParams } from "../../lib/shared/deploy.helpers"; -import { MultiChainSwapUniV3__factory } from "../../typechain-types"; - -export async function deployMultiChainSwap() { - if (!isNetworkName(network.name) || !network.name) throw new Error("Invalid network name"); - - const CONNECTOR = getAddress("connector"); - - const ZETA_TOKEN = getAddress("zetaToken"); - - const UNI_FACTORY_V3 = getAddress("uniswapV3PoolFactory"); - - const UNI_ROUTER_V3 = getAddress("uniswapV3Router"); - - const WETH = getAddress("weth9"); - - const deployParams: GetContractParams = { - deployParams: [CONNECTOR, ZETA_TOKEN, UNI_ROUTER_V3, UNI_FACTORY_V3, WETH, 500, 3000] - }; - - console.log(deployParams); - - const multiChainSwapContract = await getMultiChainSwapUniV3(deployParams); - - saveAddress("multiChainSwap", multiChainSwapContract.address); -} - -if (!process.env.EXECUTE_PROGRAMMATICALLY) { - deployMultiChainSwap().catch(error => { - console.error(error); - process.exit(1); - }); -} diff --git a/packages/example-contracts/scripts/multi-chain-swap/deploy-multi-chain-swap.ts b/packages/example-contracts/scripts/multi-chain-swap/deploy-multi-chain-swap.ts deleted file mode 100644 index 15adea60..00000000 --- a/packages/example-contracts/scripts/multi-chain-swap/deploy-multi-chain-swap.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { isNetworkName } from "@zetachain/addresses"; -import { saveAddress } from "@zetachain/addresses-tools"; -import { network } from "hardhat"; - -import { getMultiChainSwapUniV2 } from "../../lib/multi-chain-swap/MultiChainSwap.helpers"; -import { getAddress } from "../../lib/shared/address.helpers"; - -export async function deployMultiChainSwap() { - if (!isNetworkName(network.name) || !network.name) throw new Error("Invalid network name"); - console.log([getAddress("connector"), getAddress("zetaToken"), getAddress("uniswapV2Router02")]); - - const multiChainSwapContract = await getMultiChainSwapUniV2({ - deployParams: [getAddress("connector"), getAddress("zetaToken"), getAddress("uniswapV2Router02")] - }); - - saveAddress("multiChainSwap", multiChainSwapContract.address); -} - -if (!process.env.EXECUTE_PROGRAMMATICALLY) { - deployMultiChainSwap().catch(error => { - console.error(error); - process.exit(1); - }); -} diff --git a/packages/example-contracts/scripts/multi-chain-swap/deploy.ts b/packages/example-contracts/scripts/multi-chain-swap/deploy.ts deleted file mode 100644 index c0152840..00000000 --- a/packages/example-contracts/scripts/multi-chain-swap/deploy.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { deployMultiChainSwap } from "./deploy-multi-chain-swap"; -import { setMultiChainSwapCrossChainData } from "./set-cross-chain-data"; - -async function main() { - await deployMultiChainSwap(); - await setMultiChainSwapCrossChainData(); -} - -main() - .then(() => process.exit(0)) - .catch((error) => { - console.error(error); - process.exit(1); - }); diff --git a/packages/example-contracts/scripts/multi-chain-swap/deterministic-deploy.ts b/packages/example-contracts/scripts/multi-chain-swap/deterministic-deploy.ts deleted file mode 100644 index c6728ec4..00000000 --- a/packages/example-contracts/scripts/multi-chain-swap/deterministic-deploy.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { isNetworkName } from "@zetachain/addresses"; -import { saveAddress } from "@zetachain/addresses-tools"; -import { BigNumber } from "ethers"; -import { ethers, network } from "hardhat"; - -import { getAddress } from "../../lib/shared/address.helpers"; -import { deployContractToAddress, saltToHex } from "../../lib/shared/ImmutableCreate2Factory.helpers"; -import { isEthNetworkName } from "../../lib/shared/network.constants"; -import { MultiChainSwapUniV2__factory } from "../../typechain-types"; -import { setMultiChainSwapCrossChainData } from "./set-cross-chain-data"; - -const DEPLOYER_ADDRESS = process.env.DEPLOYER_ADDRESS ?? ""; -const SALT_NUMBER = "0"; - -export async function deterministicDeployMultiChainSwap() { - if (!isNetworkName(network.name)) { - throw new Error(`network.name: ${network.name} isn't supported.`); - } - - const accounts = await ethers.getSigners(); - const [signer] = accounts; - - const saltNumber = SALT_NUMBER; - const saltStr = BigNumber.from(saltNumber).toHexString(); - - const connector = getAddress("connector"); - const zetaToken = getAddress("zetaToken"); - const uniswapV2Router02 = getAddress("uniswapV2Router02"); - - const immutableCreate2Factory = getAddress("immutableCreate2Factory"); - - const salthex = saltToHex(saltStr, DEPLOYER_ADDRESS); - - const constructorTypes = ["address", "address", "address"]; - const constructorArgs = [connector, zetaToken, uniswapV2Router02]; - - const contractBytecode = MultiChainSwapUniV2__factory.bytecode; - - const { address } = await deployContractToAddress({ - constructorArgs, - constructorTypes, - contractBytecode, - factoryAddress: immutableCreate2Factory, - salt: salthex, - signer - }); - - saveAddress("multiChainSwap", address); - console.log("Deployed MultiChainSwap. Address:", address); -} - -if (!process.env.EXECUTE_PROGRAMMATICALLY) { - deterministicDeployMultiChainSwap() - .then(() => process.exit(0)) - .catch(error => { - console.error(error); - process.exit(1); - }); -} diff --git a/packages/example-contracts/scripts/multi-chain-swap/do-cross-chain-swap.ts b/packages/example-contracts/scripts/multi-chain-swap/do-cross-chain-swap.ts deleted file mode 100644 index 9084edc5..00000000 --- a/packages/example-contracts/scripts/multi-chain-swap/do-cross-chain-swap.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { isNetworkName } from "@zetachain/addresses"; -import { parseUnits } from "ethers/lib/utils"; -import { ethers, network } from "hardhat"; - -import { getMultiChainSwapUniV2 } from "../../lib/multi-chain-swap/MultiChainSwap.helpers"; -import { getAddress } from "../../lib/shared/address.helpers"; -import { networkVariables } from "../../lib/shared/network.constants"; - -export async function doCrossChainSwap() { - if (!isNetworkName(network.name)) throw new Error("Invalid network name"); - - const _networkVariables = networkVariables[network.name]; - - if (!_networkVariables.crossChainName) throw new Error("Invalid crossChainName"); - - const multiChainSwapContract = await getMultiChainSwapUniV2({ - existingContractAddress: getAddress("multiChainSwap") - }); - - const [account1] = await ethers.getSigners(); - - await ( - await multiChainSwapContract.swapETHForTokensCrossChain( - ethers.utils.solidityPack(["address"], [account1.address]), - getAddress("zetaToken", { customNetworkName: _networkVariables.crossChainName }), - false, - 0, - _networkVariables.crossChainId, - 1_000_000, - { - value: parseUnits("1") - } - ) - ).wait(); -} - -if (!process.env.EXECUTE_PROGRAMMATICALLY) { - doCrossChainSwap().catch(error => { - console.error(error); - process.exit(1); - }); -} diff --git a/packages/example-contracts/scripts/multi-chain-swap/set-cross-chain-data.ts b/packages/example-contracts/scripts/multi-chain-swap/set-cross-chain-data.ts deleted file mode 100644 index cfffc696..00000000 --- a/packages/example-contracts/scripts/multi-chain-swap/set-cross-chain-data.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { isNetworkName } from "@zetachain/addresses"; -import { ethers, network } from "hardhat"; - -import { getMultiChainSwapUniV2 } from "../../lib/multi-chain-swap/MultiChainSwap.helpers"; -import { getAddress } from "../../lib/shared/address.helpers"; -import { networkVariables } from "../../lib/shared/network.constants"; - -export async function setMultiChainSwapCrossChainData() { - if (!isNetworkName(network.name)) throw new Error("Invalid network name"); - - const _networkVariables = networkVariables[network.name]; - - if (!_networkVariables.crossChainName) throw new Error("Invalid crossChainName"); - - const crossChainMultiChainSwapAddress = getAddress("multiChainSwap"); - - const crossChainMultiChainSwapContract = await getMultiChainSwapUniV2({ - existingContractAddress: crossChainMultiChainSwapAddress - }); - - const crossChainAddress = getAddress("multiChainSwap", { - customNetworkName: _networkVariables.crossChainName - }); - - const encodedCrossChainAddress = ethers.utils.solidityPack(["address"], [crossChainAddress]); - - console.log( - "Setting cross-chain address:", - encodedCrossChainAddress, - "cross-chain id:", - _networkVariables.crossChainId - ); - - await ( - await crossChainMultiChainSwapContract.setInteractorByChainId( - _networkVariables.crossChainId, - encodedCrossChainAddress - ) - ).wait(); -} - -if (!process.env.EXECUTE_PROGRAMMATICALLY) { - setMultiChainSwapCrossChainData().catch(error => { - console.error(error); - process.exit(1); - }); -} diff --git a/packages/example-contracts/scripts/multi-chain-swap/verify-contract.ts b/packages/example-contracts/scripts/multi-chain-swap/verify-contract.ts deleted file mode 100644 index 0db23288..00000000 --- a/packages/example-contracts/scripts/multi-chain-swap/verify-contract.ts +++ /dev/null @@ -1,17 +0,0 @@ -import hardhat from "hardhat"; - -import { getAddress } from "../../lib/shared/address.helpers"; - -async function main() { - await hardhat.run("verify:verify", { - address: getAddress("multiChainSwap"), - constructorArguments: [getAddress("connector"), getAddress("zetaToken"), getAddress("uniswapV2Router02")] - }); -} - -main() - .then(() => process.exit(0)) - .catch(error => { - console.error(error); - process.exit(1); - }); diff --git a/packages/example-contracts/test/CrossChainCounter.spec.ts b/packages/example-contracts/test/CrossChainCounter.spec.ts deleted file mode 100644 index 77480c51..00000000 --- a/packages/example-contracts/test/CrossChainCounter.spec.ts +++ /dev/null @@ -1,112 +0,0 @@ -import { SignerWithAddress } from "@nomiclabs/hardhat-ethers/signers"; -import { expect } from "chai"; -import { ethers } from "hardhat"; - -import { - deployTestCrossChainCounter, - deployZetaConnectorMock -} from "../lib/cross-chain-counter/CrossChainCounter.helpers"; -import { CounterZetaConnectorMock, CrossChainCounter } from "../typechain-types"; - -describe("CrossChainCounter tests", () => { - let crossChainCounterContractA: CrossChainCounter; - const chainAId = 1; - - let crossChainCounterContractB: CrossChainCounter; - const chainBId = 2; - - let zetaConnectorMockContract: CounterZetaConnectorMock; - - let accounts: SignerWithAddress[]; - let deployer: SignerWithAddress; - let deployerAddress: string; - - const encoder = new ethers.utils.AbiCoder(); - - beforeEach(async () => { - zetaConnectorMockContract = await deployZetaConnectorMock(); - crossChainCounterContractA = await deployTestCrossChainCounter({ - zetaConnectorMockAddress: zetaConnectorMockContract.address - }); - crossChainCounterContractB = await deployTestCrossChainCounter({ - zetaConnectorMockAddress: zetaConnectorMockContract.address - }); - - await crossChainCounterContractA.setInteractorByChainId( - chainBId, - ethers.utils.solidityPack(["address"], [crossChainCounterContractB.address]) - ); - await crossChainCounterContractB.setInteractorByChainId( - chainAId, - ethers.utils.solidityPack(["address"], [crossChainCounterContractA.address]) - ); - - accounts = await ethers.getSigners(); - [deployer] = accounts; - deployerAddress = deployer.address; - }); - - describe("crossChainCount", () => { - it("Should revert if the cross chain address wasn't set", async () => { - const unsetContract = await deployTestCrossChainCounter({ - zetaConnectorMockAddress: zetaConnectorMockContract.address - }); - - await expect(unsetContract.crossChainCount(chainAId)).to.be.revertedWith("InvalidDestinationChainId"); - }); - }); - - describe("onZetaMessage", () => { - it("Should revert if the caller is not the Connector contract", async () => { - await expect( - crossChainCounterContractA.onZetaMessage({ - destinationAddress: crossChainCounterContractB.address, - message: encoder.encode(["address"], [deployerAddress]), - sourceChainId: 1, - zetaTxSenderAddress: ethers.utils.solidityPack(["address"], [crossChainCounterContractA.address]), - zetaValue: 0 - }) - ) - .to.be.revertedWith("InvalidCaller") - .withArgs(deployer.address); - }); - - it("Should revert if the cross-chain address doesn't match with the stored one", async () => { - await expect( - zetaConnectorMockContract.callOnZetaMessage( - ethers.utils.solidityPack(["address"], [deployerAddress]), - 1, - crossChainCounterContractB.address, - 0, - encoder.encode(["address"], [zetaConnectorMockContract.address]) - ) - ).to.be.revertedWith("InvalidZetaMessageCall"); - }); - - describe("Given a valid message", () => { - it("Should increment the counter", async () => { - const messageType = await crossChainCounterContractA.CROSS_CHAIN_INCREMENT_MESSAGE(); - - const originalValue = await crossChainCounterContractB.counter(deployerAddress); - expect(originalValue.toNumber()).to.equal(0); - - await ( - await zetaConnectorMockContract.callOnZetaMessage( - ethers.utils.solidityPack(["address"], [crossChainCounterContractA.address]), - 1, - crossChainCounterContractB.address, - 0, - encoder.encode(["bytes32", "address"], [messageType, deployer.address]) - ) - ).wait(); - - const newValue = await crossChainCounterContractB.counter(deployerAddress); - expect(newValue.toNumber()).to.equal(1); - }); - }); - }); - - describe("onZetaRevert", () => { - it("Should work", async () => {}); - }); -}); diff --git a/packages/example-contracts/test/CrossChainMessage.spec.ts b/packages/example-contracts/test/CrossChainMessage.spec.ts deleted file mode 100644 index 9365138e..00000000 --- a/packages/example-contracts/test/CrossChainMessage.spec.ts +++ /dev/null @@ -1,142 +0,0 @@ -import { SignerWithAddress } from "@nomiclabs/hardhat-ethers/signers"; -import { ZetaTokenConsumerUniV2 } from "@zetachain/protocol-contracts/dist/typechain-types"; -import { expect } from "chai"; -import { parseEther } from "ethers/lib/utils"; -import { ethers } from "hardhat"; - -import { - deployCrossChainMessageMock, - deployZetaConnectorMock -} from "../lib/cross-chain-message/CrossChainMessage.helpers"; -import { getAddress } from "../lib/shared/address.helpers"; -import { deployZetaTokenConsumerUniV2, getZetaMock } from "../lib/shared/deploy.helpers"; -import { CrossChainMessage, CrossChainMessageConnector, ZetaEthMock } from "../typechain-types"; -import { addZetaEthLiquidityTest } from "./test.helpers"; - -describe("CrossChainMessage tests", () => { - let zetaConnectorMockContract: CrossChainMessageConnector; - let zetaEthTokenMockContract: ZetaEthMock; - let zetaTokenConsumerUniV2: ZetaTokenConsumerUniV2; - - let crossChainMessageContractChainA: CrossChainMessage; - const chainAId = 1; - - let crossChainMessageContractChainB: CrossChainMessage; - const chainBId = 2; - - let accounts: SignerWithAddress[]; - let deployer: SignerWithAddress; - let deployerAddress: string; - - const SAMPLE_TEXT = "Hello, Cross-Chain World!"; - const encoder = new ethers.utils.AbiCoder(); - - beforeEach(async () => { - accounts = await ethers.getSigners(); - [deployer] = accounts; - deployerAddress = deployer.address; - - zetaEthTokenMockContract = await getZetaMock(); - zetaConnectorMockContract = await deployZetaConnectorMock(); - - const uniswapRouterAddr = getAddress("uniswapV2Router02", { - customNetworkName: "eth-mainnet", - customZetaNetwork: "mainnet" - }); - - await addZetaEthLiquidityTest(zetaEthTokenMockContract.address, parseEther("200000"), parseEther("100"), deployer); - // @dev: guarantee that the account has no zeta balance but still can use the protocol :D - const zetaBalance = await zetaEthTokenMockContract.balanceOf(deployer.address); - await zetaEthTokenMockContract.transfer(accounts[5].address, zetaBalance); - - zetaTokenConsumerUniV2 = await deployZetaTokenConsumerUniV2(zetaEthTokenMockContract.address, uniswapRouterAddr); - - crossChainMessageContractChainA = await deployCrossChainMessageMock({ - zetaConnectorMockAddress: zetaConnectorMockContract.address, - zetaTokenConsumerAddress: zetaTokenConsumerUniV2.address, - zetaTokenMockAddress: zetaEthTokenMockContract.address - }); - - crossChainMessageContractChainB = await deployCrossChainMessageMock({ - zetaConnectorMockAddress: zetaConnectorMockContract.address, - zetaTokenConsumerAddress: zetaTokenConsumerUniV2.address, - zetaTokenMockAddress: zetaEthTokenMockContract.address - }); - - await crossChainMessageContractChainB.setInteractorByChainId( - chainAId, - ethers.utils.solidityPack(["address"], [crossChainMessageContractChainA.address]) - ); - - await crossChainMessageContractChainA.setInteractorByChainId( - chainBId, - ethers.utils.solidityPack(["address"], [crossChainMessageContractChainB.address]) - ); - }); - - describe("sendHelloWorld", () => { - it("Should revert if the cross chain address wasn't set", async () => { - const unsetContract = await deployCrossChainMessageMock({ - zetaConnectorMockAddress: zetaConnectorMockContract.address, - zetaTokenConsumerAddress: zetaTokenConsumerUniV2.address, - zetaTokenMockAddress: zetaEthTokenMockContract.address - }); - - await expect(unsetContract.sendHelloWorld(chainAId)).to.be.revertedWith("InvalidDestinationChainId"); - }); - - it("Should send hello world", async () => { - await expect(crossChainMessageContractChainA.sendHelloWorld(chainBId, { value: parseEther("1") })).to.be.not - .reverted; - }); - }); - - describe("onZetaMessage", () => { - it("Should revert if the caller is not the Connector contract", async () => { - await expect( - crossChainMessageContractChainA.onZetaMessage({ - destinationAddress: crossChainMessageContractChainB.address, - message: encoder.encode(["address", "string"], [deployerAddress, SAMPLE_TEXT]), - sourceChainId: 1, - zetaTxSenderAddress: ethers.utils.solidityPack(["address"], [crossChainMessageContractChainA.address]), - zetaValue: 0 - }) - ) - .to.be.revertedWith("InvalidCaller") - .withArgs(deployer.address); - }); - - it("Should revert if the cross-chain address doesn't match with the stored one", async () => { - await expect( - zetaConnectorMockContract.callOnZetaMessage( - ethers.utils.solidityPack(["address"], [deployerAddress]), - 1, - crossChainMessageContractChainB.address, - 0, - encoder.encode(["address", "string"], [zetaConnectorMockContract.address, SAMPLE_TEXT]) - ) - ).to.be.revertedWith("InvalidZetaMessageCall"); - }); - - describe("Given a valid message", () => { - it("Should emit `HelloWorldEvent`", async () => { - const messageType = await crossChainMessageContractChainA.HELLO_WORLD_MESSAGE_TYPE(); - - const tx = await zetaConnectorMockContract.callOnZetaMessage( - ethers.utils.solidityPack(["address"], [crossChainMessageContractChainA.address]), - 1, - crossChainMessageContractChainB.address, - 0, - encoder.encode(["bytes32", "string"], [messageType, SAMPLE_TEXT]) - ); - - await tx.wait(); - - const helloWorldEventFilter = crossChainMessageContractChainB.filters.HelloWorldEvent(); - const e1 = await crossChainMessageContractChainB.queryFilter(helloWorldEventFilter, tx.blockHash); - expect(e1.length).to.equal(1); - expect(e1[0].transactionHash).to.equal(tx.hash); - }); - }); - }); -}); diff --git a/packages/example-contracts/test/CrossChainWarriors.spec.ts b/packages/example-contracts/test/CrossChainWarriors.spec.ts deleted file mode 100644 index 86343711..00000000 --- a/packages/example-contracts/test/CrossChainWarriors.spec.ts +++ /dev/null @@ -1,304 +0,0 @@ -import { SignerWithAddress } from "@nomiclabs/hardhat-ethers/signers"; -import { expect } from "chai"; -import { parseEther } from "ethers/lib/utils"; -import { ethers } from "hardhat"; - -import { - deployCrossChainWarriorsMock, - deployZetaConnectorMock -} from "../lib/cross-chain-warriors/CrossChainWarriors.helpers"; -import { getAddress } from "../lib/shared/address.helpers"; -import { deployZetaTokenConsumerUniV2, getZetaMock } from "../lib/shared/deploy.helpers"; -import { CrossChainWarriorsMock, CrossChainWarriorsZetaConnectorMock, ZetaEthMock } from "../typechain-types"; -import { ZetaTokenConsumerUniV2 } from "../typechain-types/@zetachain/protocol-contracts/contracts/ZetaTokenConsumerUniV2.strategy.sol"; -import { addZetaEthLiquidityTest, getMintTokenId } from "./test.helpers"; - -describe("CrossChainWarriors tests", () => { - let zetaConnectorMockContract: CrossChainWarriorsZetaConnectorMock; - let zetaEthTokenMockContract: ZetaEthMock; - let zetaTokenConsumerUniV2: ZetaTokenConsumerUniV2; - - let crossChainWarriorsContractChainA: CrossChainWarriorsMock; - const chainAId = 1; - - let crossChainWarriorsContractChainB: CrossChainWarriorsMock; - const chainBId = 2; - - let accounts: SignerWithAddress[]; - let deployer: SignerWithAddress; - let account1: SignerWithAddress; - let deployerAddress: string; - let account1Address: string; - const encoder = new ethers.utils.AbiCoder(); - - beforeEach(async () => { - accounts = await ethers.getSigners(); - [deployer, account1] = accounts; - deployerAddress = deployer.address; - account1Address = account1.address; - - zetaEthTokenMockContract = await getZetaMock(); - zetaConnectorMockContract = await deployZetaConnectorMock(); - - const uniswapRouterAddr = getAddress("uniswapV2Router02", { - customNetworkName: "eth-mainnet", - customZetaNetwork: "mainnet" - }); - - await addZetaEthLiquidityTest(zetaEthTokenMockContract.address, parseEther("200000"), parseEther("100"), deployer); - // @dev: guarantee that the account has no zeta balance but still can use the protocol :D - const zetaBalance = await zetaEthTokenMockContract.balanceOf(deployer.address); - await zetaEthTokenMockContract.transfer(accounts[5].address, zetaBalance); - - zetaTokenConsumerUniV2 = await deployZetaTokenConsumerUniV2(zetaEthTokenMockContract.address, uniswapRouterAddr); - - crossChainWarriorsContractChainA = await deployCrossChainWarriorsMock({ - customUseEven: false, - zetaConnectorMockAddress: zetaConnectorMockContract.address, - zetaTokenConsumerAddress: zetaTokenConsumerUniV2.address, - zetaTokenMockAddress: zetaEthTokenMockContract.address - }); - - crossChainWarriorsContractChainB = await deployCrossChainWarriorsMock({ - customUseEven: true, - zetaConnectorMockAddress: zetaConnectorMockContract.address, - zetaTokenConsumerAddress: zetaTokenConsumerUniV2.address, - zetaTokenMockAddress: zetaEthTokenMockContract.address - }); - - await crossChainWarriorsContractChainB.setInteractorByChainId( - chainAId, - ethers.utils.solidityPack(["address"], [crossChainWarriorsContractChainA.address]) - ); - - await crossChainWarriorsContractChainA.setInteractorByChainId( - chainBId, - ethers.utils.solidityPack(["address"], [crossChainWarriorsContractChainB.address]) - ); - }); - - describe("constructor", () => { - it("Should set the tokenIds counter to 1 when useEven is false", async () => { - expect(await crossChainWarriorsContractChainA.tokenIds()).to.equal(1); - }); - - it("Should set the tokenIds counter to 2 when useEven is true", async () => { - expect(await crossChainWarriorsContractChainB.tokenIds()).to.equal(2); - }); - }); - - describe("mint", () => { - it("Should increment tokenIds by two", async () => { - expect(await crossChainWarriorsContractChainA.tokenIds()).to.equal(1); - - await (await crossChainWarriorsContractChainA.mint(account1Address)).wait(); - - expect(await crossChainWarriorsContractChainA.tokenIds()).to.equal(3); - }); - - it("Should create a new NFT owned by the input address", async () => { - const result = await (await crossChainWarriorsContractChainA.mint(account1Address)).wait(); - - const tokenId = getMintTokenId(result); - - expect(await crossChainWarriorsContractChainA.ownerOf(tokenId)).to.equal(account1Address); - }); - }); - - describe("mintId", () => { - it("Should mint an NFT with the given input id owned by the input address", async () => { - const id = 10; - - await (await crossChainWarriorsContractChainA.mintId(account1Address, id)).wait(); - - expect(await crossChainWarriorsContractChainA.ownerOf(id)).to.equal(account1Address); - }); - }); - - describe("crossChainTransfer", () => { - it("Should revert if the caller is not the NFT owner nor approved", async () => { - const id = 10; - - await (await crossChainWarriorsContractChainA.mintId(account1Address, id)).wait(); - - /** - * The caller is the contract deployer and the NFT owner is account1 - */ - expect( - crossChainWarriorsContractChainA.crossChainTransfer(chainBId, account1Address, id, { value: parseEther("1") }) - ).to.be.revertedWith("Transfer caller is not owner nor approved"); - }); - - it("Should burn the tokenId", async () => { - const id = 10; - - await (await crossChainWarriorsContractChainA.mintId(deployerAddress, id)).wait(); - - expect(await crossChainWarriorsContractChainA.ownerOf(id)).to.equal(deployerAddress); - - await ( - await crossChainWarriorsContractChainA.crossChainTransfer(chainBId, account1Address, id, { - value: parseEther("1") - }) - ).wait(); - - expect(crossChainWarriorsContractChainA.ownerOf(id)).to.be.revertedWith( - "ERC721: owner query for nonexistent token" - ); - }); - - it("Should mint tokenId in the destination chain", async () => { - const id = 10; - - await (await crossChainWarriorsContractChainA.mintId(deployerAddress, id)).wait(); - - await ( - await crossChainWarriorsContractChainA.crossChainTransfer(chainBId, account1Address, id, { - value: parseEther("1") - }) - ).wait(); - - expect(await crossChainWarriorsContractChainB.ownerOf(id)).to.equal(account1Address); - }); - }); - - describe("onZetaMessage", () => { - it("Should revert if the caller is not the Connector contract", async () => { - await expect( - crossChainWarriorsContractChainA.onZetaMessage({ - destinationAddress: crossChainWarriorsContractChainB.address, - message: encoder.encode(["address"], [deployerAddress]), - sourceChainId: 1, - zetaTxSenderAddress: ethers.utils.solidityPack(["address"], [crossChainWarriorsContractChainA.address]), - zetaValue: 0 - }) - ) - .to.be.revertedWith("InvalidCaller") - .withArgs(deployer.address); - }); - - it("Should revert if the cross-chain address doesn't match with the stored one", async () => { - await expect( - zetaConnectorMockContract.callOnZetaMessage( - ethers.utils.solidityPack(["address"], [deployerAddress]), - 1, - crossChainWarriorsContractChainB.address, - 0, - encoder.encode(["address"], [zetaConnectorMockContract.address]) - ) - ).to.be.revertedWith("InvalidZetaMessageCall"); - }); - - it("Should revert if the message type doesn't match with CROSS_CHAIN_TRANSFER_MESSAGE", async () => { - const messageType = await crossChainWarriorsContractChainA.CROSS_CHAIN_TRANSFER_MESSAGE(); - - const invalidMessageType = messageType.replace("9", "8"); - - await expect( - zetaConnectorMockContract.callOnZetaMessage( - ethers.utils.solidityPack(["address"], [crossChainWarriorsContractChainA.address]), - 1, - crossChainWarriorsContractChainB.address, - 0, - encoder.encode( - ["bytes32", "uint256 ", "address", "address"], - [invalidMessageType, 1, deployerAddress, deployerAddress] - ) - ) - ).to.be.revertedWith("InvalidMessageType"); - }); - - it("Should revert if the token already exists", async () => { - const messageType = await crossChainWarriorsContractChainA.CROSS_CHAIN_TRANSFER_MESSAGE(); - - await crossChainWarriorsContractChainB.mintId(deployerAddress, 1); - - await expect( - zetaConnectorMockContract.callOnZetaMessage( - ethers.utils.solidityPack(["address"], [crossChainWarriorsContractChainA.address]), - 1, - crossChainWarriorsContractChainB.address, - 0, - encoder.encode( - ["bytes32", "uint256 ", "address", "address"], - [messageType, 1, deployerAddress, deployerAddress] - ) - ) - ).to.be.revertedWith("ERC721: token already minted"); - }); - - describe("Given a valid input", () => { - it("Should mint a new token in the destination chain", async () => { - const messageType = await crossChainWarriorsContractChainA.CROSS_CHAIN_TRANSFER_MESSAGE(); - - await zetaConnectorMockContract.callOnZetaMessage( - ethers.utils.solidityPack(["address"], [crossChainWarriorsContractChainA.address]), - 1, - crossChainWarriorsContractChainB.address, - 0, - encoder.encode( - ["bytes32", "uint256 ", "address", "address"], - [messageType, 1, deployerAddress, deployerAddress] - ) - ); - - expect(await crossChainWarriorsContractChainB.ownerOf(1)).to.equal(deployerAddress); - }); - - it("Should mint a new token in the destination chain, owned by the provided 'to' address", async () => { - const messageType = await crossChainWarriorsContractChainA.CROSS_CHAIN_TRANSFER_MESSAGE(); - - await zetaConnectorMockContract.callOnZetaMessage( - ethers.utils.solidityPack(["address"], [crossChainWarriorsContractChainA.address]), - 1, - crossChainWarriorsContractChainB.address, - 0, - encoder.encode( - ["bytes32", "uint256 ", "address", "address"], - [messageType, 1, deployerAddress, account1Address] - ) - ); - - expect(await crossChainWarriorsContractChainB.ownerOf(1)).to.equal(account1Address); - }); - }); - }); - - describe("onZetaRevert", () => { - /** - * @description note that given how this test was implemented, the NFT will exist in the two chains - * that's not the real-world behavior but it's ok for this unit test - */ - it("Should give the NFT back to the sourceTxOriginAddress", async () => { - const nftId = 1; - - await (await crossChainWarriorsContractChainA.mintId(deployerAddress, nftId)).wait(); - - await ( - await crossChainWarriorsContractChainA.crossChainTransfer(chainBId, deployerAddress, nftId, { - value: parseEther("1") - }) - ).wait(); - - // Make sure that the NFT was removed from the source chain - await expect(crossChainWarriorsContractChainA.ownerOf(nftId)).to.be.revertedWith("ERC721: invalid token ID"); - - const messageType = await crossChainWarriorsContractChainA.CROSS_CHAIN_TRANSFER_MESSAGE(); - - await zetaConnectorMockContract.callOnZetaRevert( - crossChainWarriorsContractChainA.address, - 1337, - chainBId, - ethers.utils.solidityPack(["address"], [crossChainWarriorsContractChainB.address]), - 0, - 2500000, - encoder.encode( - ["bytes32", "uint256 ", "address", "address"], - [messageType, nftId, deployerAddress, account1Address] - ) - ); - - expect(await crossChainWarriorsContractChainB.ownerOf(nftId)).to.equal(deployerAddress); - }); - }); -}); diff --git a/packages/example-contracts/test/MultiChainSwap.constants.ts b/packages/example-contracts/test/MultiChainSwap.constants.ts deleted file mode 100644 index 34b201ac..00000000 --- a/packages/example-contracts/test/MultiChainSwap.constants.ts +++ /dev/null @@ -1 +0,0 @@ -export const USDC_ADDR = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"; diff --git a/packages/example-contracts/test/MultiChainSwap.spec.ts b/packages/example-contracts/test/MultiChainSwap.spec.ts deleted file mode 100644 index 2c27c52f..00000000 --- a/packages/example-contracts/test/MultiChainSwap.spec.ts +++ /dev/null @@ -1,628 +0,0 @@ -import { FakeContract, smock } from "@defi-wonderland/smock"; -import { BigNumber } from "@ethersproject/bignumber"; -import { AddressZero, MaxUint256 } from "@ethersproject/constants"; -import { parseEther, parseUnits } from "@ethersproject/units"; -import { SignerWithAddress } from "@nomiclabs/hardhat-ethers/signers"; -import chai, { expect } from "chai"; -import { ethers } from "hardhat"; - -import { getMultiChainSwapUniV2, getMultiChainSwapZetaConnector } from "../lib/multi-chain-swap/MultiChainSwap.helpers"; -import { getAddress } from "../lib/shared/address.helpers"; -import { getNow, getZetaMock } from "../lib/shared/deploy.helpers"; -import { - ERC20__factory, - IERC20, - IUniswapV2Router02, - MultiChainSwapUniV2, - MultiChainSwapZetaConnector, - UniswapV2Router02__factory -} from "../typechain-types"; -import { USDC_ADDR } from "./MultiChainSwap.constants"; -import { parseUniswapLog, parseZetaLog } from "./test.helpers"; - -chai.should(); -chai.use(smock.matchers); - -const HARDHAT_CHAIN_ID = 1337; - -describe("MultiChainSwap tests", () => { - let uniswapRouterFork: IUniswapV2Router02; - let WETH: string; - let zetaTokenMock: IERC20; - let USDCTokenContract: IERC20; - let zetaConnectorMock: MultiChainSwapZetaConnector; - - let multiChainSwapContractA: MultiChainSwapUniV2; - const chainAId = 1; - - let multiChainSwapContractB: MultiChainSwapUniV2; - const chainBId = 2; - - let zetaConnectorSmock: FakeContract; - let multiChainSwapContractWithSmock: MultiChainSwapUniV2; - - let accounts: SignerWithAddress[]; - let deployer: SignerWithAddress; - let account1: SignerWithAddress; - - const encoder = new ethers.utils.AbiCoder(); - - const ZETA_USDC_PRICE = BigNumber.from("1455462180"); - - const addZetaEthLiquidity = async () => { - const tx1 = await zetaTokenMock.approve(uniswapRouterFork.address, MaxUint256); - await tx1.wait(); - - // 2 ZETA = 1 ETH - const tx2 = await uniswapRouterFork.addLiquidityETH( - zetaTokenMock.address, - parseUnits("1000"), - 0, - 0, - deployer.address, - (await getNow()) + 360, - { value: parseUnits("500") } - ); - await tx2.wait(); - }; - - const clearUSDCBalance = async (account: SignerWithAddress) => { - const balance = await USDCTokenContract.balanceOf(account.address); - const w = ethers.Wallet.createRandom(); - const tx = await USDCTokenContract.connect(account).transfer(w.address, balance); - await tx.wait(); - }; - - const swapZetaToUSDC = async (signer: SignerWithAddress, zetaValueAndGas: BigNumber) => { - const path = [zetaTokenMock.address, WETH, USDC_ADDR]; - const tx = await uniswapRouterFork - .connect(signer) - .swapExactTokensForTokens(zetaValueAndGas, 0, path, signer.address, (await getNow()) + 360); - - await tx.wait(); - }; - - beforeEach(async () => { - const uniswapRouterAddr = getAddress("uniswapV2Router02", { - customNetworkName: "eth-mainnet", - customZetaNetwork: "mainnet" - }); - accounts = await ethers.getSigners(); - [deployer, account1] = accounts; - - const uniswapRouterFactory = new UniswapV2Router02__factory(deployer); - uniswapRouterFork = uniswapRouterFactory.attach(uniswapRouterAddr); - - WETH = await uniswapRouterFork.WETH(); - - zetaTokenMock = await getZetaMock(); - zetaConnectorMock = await getMultiChainSwapZetaConnector(zetaTokenMock.address); - - const ERC20Factory = new ERC20__factory(deployer); - USDCTokenContract = ERC20Factory.attach(USDC_ADDR); - - multiChainSwapContractA = await getMultiChainSwapUniV2({ - deployParams: [zetaConnectorMock.address, zetaTokenMock.address, uniswapRouterAddr] - }); - - multiChainSwapContractB = await getMultiChainSwapUniV2({ - deployParams: [zetaConnectorMock.address, zetaTokenMock.address, uniswapRouterAddr] - }); - - zetaConnectorSmock = await smock.fake("MultiChainSwapZetaConnector"); - multiChainSwapContractWithSmock = await getMultiChainSwapUniV2({ - deployParams: [zetaConnectorSmock.address, zetaTokenMock.address, uniswapRouterAddr] - }); - - const encodedCrossChainAddressB = ethers.utils.solidityPack(["address"], [multiChainSwapContractB.address]); - multiChainSwapContractA.setInteractorByChainId(chainBId, encodedCrossChainAddressB); - multiChainSwapContractWithSmock.setInteractorByChainId(chainBId, encodedCrossChainAddressB); - - const encodedCrossChainAddressA = ethers.utils.solidityPack(["address"], [multiChainSwapContractA.address]); - multiChainSwapContractB.setInteractorByChainId(chainAId, encodedCrossChainAddressA); - - await clearUSDCBalance(deployer); - await clearUSDCBalance(account1); - }); - - describe("swapTokensForTokensCrossChain", () => { - it("Should revert if the destinationChainId is not in the storage", async () => { - await expect( - multiChainSwapContractA.swapETHForTokensCrossChain( - ethers.utils.solidityPack(["address"], [account1.address]), - zetaTokenMock.address, - false, - 0, - 10, - MaxUint256, - MaxUint256, - { - value: parseUnits("1") - } - ) - ).to.be.revertedWith("InvalidDestinationChainId"); - }); - - it("Should revert if the sourceInputToken isn't provided", async () => { - await expect( - multiChainSwapContractA.swapTokensForTokensCrossChain( - AddressZero, - BigNumber.from(10), - ethers.utils.solidityPack(["address"], [account1.address]), - zetaTokenMock.address, - false, - 0, - chainBId, - MaxUint256, - MaxUint256 - ) - ).to.be.revertedWith("MissingSourceInputTokenAddress"); - }); - - it("Should revert if the destinationOutToken isn't provided", async () => { - await expect( - multiChainSwapContractA.swapTokensForTokensCrossChain( - zetaTokenMock.address, - BigNumber.from(10), - ethers.utils.solidityPack(["address"], [account1.address]), - AddressZero, - false, - 0, - chainBId, - MaxUint256, - MaxUint256 - ) - ).to.be.revertedWith("OutTokenInvariant"); - }); - - it("Should not perform any trade if the input token is Zeta", async () => { - await addZetaEthLiquidity(); - await swapZetaToUSDC(deployer, parseUnits("10")); - - expect(await zetaTokenMock.balanceOf(account1.address)).to.be.eq(0); - - const ZETA_TO_TRANSFER = parseUnits("1"); - - const tx1 = await zetaTokenMock.approve(multiChainSwapContractA.address, ZETA_TO_TRANSFER); - await tx1.wait(); - - const tx3 = await USDCTokenContract.approve(multiChainSwapContractA.address, ZETA_USDC_PRICE); - await tx3.wait(); - - const tx2 = await multiChainSwapContractA.swapTokensForTokensCrossChain( - zetaTokenMock.address, - ZETA_USDC_PRICE, - ethers.utils.solidityPack(["address"], [account1.address]), - zetaTokenMock.address, - false, - 0, - chainBId, - MaxUint256, - MaxUint256 - ); - - const result = await tx2.wait(); - const eventNames = parseUniswapLog(result.logs); - expect(eventNames.filter(e => e === "Swap")).to.have.lengthOf(0); - }); - - it("Should trade the input token for Zeta", async () => { - await addZetaEthLiquidity(); - await swapZetaToUSDC(deployer, parseUnits("10")); - - expect(await zetaTokenMock.balanceOf(account1.address)).to.be.eq(0); - - const ZETA_TO_TRANSFER = parseUnits("1"); - - const tx1 = await zetaTokenMock.approve(multiChainSwapContractA.address, ZETA_TO_TRANSFER); - await tx1.wait(); - - const tx3 = await USDCTokenContract.approve(multiChainSwapContractA.address, ZETA_USDC_PRICE); - await tx3.wait(); - - const tx2 = await multiChainSwapContractA.swapTokensForTokensCrossChain( - USDC_ADDR, - ZETA_USDC_PRICE, - ethers.utils.solidityPack(["address"], [account1.address]), - zetaTokenMock.address, - false, - 0, - chainBId, - MaxUint256, - MaxUint256 - ); - - const result = await tx2.wait(); - const eventNames = parseUniswapLog(result.logs); - expect(eventNames.filter(e => e === "Swap")).to.have.lengthOf(2); - }); - - it("Should trade zeta for the output token", async () => { - await addZetaEthLiquidity(); - await swapZetaToUSDC(deployer, parseUnits("10")); - - expect(await zetaTokenMock.balanceOf(account1.address)).to.be.eq(0); - - const ZETA_TO_TRANSFER = parseUnits("1"); - - const tx1 = await zetaTokenMock.approve(multiChainSwapContractA.address, ZETA_TO_TRANSFER); - await tx1.wait(); - - const tx3 = await USDCTokenContract.approve(multiChainSwapContractA.address, ZETA_USDC_PRICE); - await tx3.wait(); - - const tx2 = await multiChainSwapContractA.swapTokensForTokensCrossChain( - zetaTokenMock.address, - ZETA_USDC_PRICE, - ethers.utils.solidityPack(["address"], [account1.address]), - USDC_ADDR, - false, - 0, - chainBId, - MaxUint256, - MaxUint256 - ); - - const result = await tx2.wait(); - const eventNames = parseUniswapLog(result.logs); - expect(eventNames.filter(e => e === "Swap")).to.have.lengthOf(2); - }); - - it("Should trade input token for zeta and zeta for the output token", async () => { - await addZetaEthLiquidity(); - await swapZetaToUSDC(deployer, parseUnits("10")); - - expect(await zetaTokenMock.balanceOf(account1.address)).to.be.eq(0); - - const ZETA_TO_TRANSFER = parseUnits("1"); - - const tx1 = await zetaTokenMock.approve(multiChainSwapContractA.address, ZETA_TO_TRANSFER); - await tx1.wait(); - - const tx3 = await USDCTokenContract.approve(multiChainSwapContractA.address, ZETA_USDC_PRICE); - await tx3.wait(); - - const tx2 = await multiChainSwapContractA.swapTokensForTokensCrossChain( - USDC_ADDR, - ZETA_USDC_PRICE, - ethers.utils.solidityPack(["address"], [account1.address]), - USDC_ADDR, - false, - 0, - chainBId, - MaxUint256, - MaxUint256 - ); - - const result = await tx2.wait(); - const eventNames = parseUniswapLog(result.logs); - expect(eventNames.filter(e => e === "Swap")).to.have.lengthOf(4); - }); - - it("Should call connector.send", async () => { - await addZetaEthLiquidity(); - await swapZetaToUSDC(deployer, parseUnits("10")); - - expect(await zetaTokenMock.balanceOf(account1.address)).to.be.eq(0); - - const ZETA_TO_TRANSFER = parseUnits("1"); - - const tx1 = await zetaTokenMock.approve(multiChainSwapContractWithSmock.address, ZETA_TO_TRANSFER); - await tx1.wait(); - - const tx3 = await USDCTokenContract.approve(multiChainSwapContractWithSmock.address, ZETA_USDC_PRICE); - await tx3.wait(); - - const tx2 = await multiChainSwapContractWithSmock.swapTokensForTokensCrossChain( - USDC_ADDR, - ZETA_USDC_PRICE, - ethers.utils.solidityPack(["address"], [account1.address]), - USDC_ADDR, - false, - 0, - chainBId, - MaxUint256, - MaxUint256 - ); - - zetaConnectorSmock.send.atCall(0).should.be.called; - }); - - it("Should emit a SentTokenSwap event", async () => { - await addZetaEthLiquidity(); - await swapZetaToUSDC(deployer, parseUnits("10")); - - const originAddressInitialZetaBalance = await zetaTokenMock.balanceOf(deployer.address); - expect(await zetaTokenMock.balanceOf(account1.address)).to.be.eq(0); - - const ZETA_TO_TRANSFER = parseUnits("1"); - - const tx1 = await zetaTokenMock.approve(multiChainSwapContractA.address, ZETA_TO_TRANSFER); - await tx1.wait(); - - const tx3 = await USDCTokenContract.approve(multiChainSwapContractA.address, ZETA_USDC_PRICE); - await tx3.wait(); - - const tx2 = await multiChainSwapContractA.swapTokensForTokensCrossChain( - USDC_ADDR, - ZETA_USDC_PRICE, - ethers.utils.solidityPack(["address"], [account1.address]), - USDC_ADDR, - false, - 0, - chainBId, - MaxUint256, - MaxUint256 - ); - - const result = await tx2.wait(); - const eventNames = parseZetaLog(result.logs); - - expect(eventNames.filter(e => e === "Swapped")).to.have.lengthOf(1); - }); - - it("Should revert if the destinationChainId is not in the storage", async () => { - const call = multiChainSwapContractA.swapTokensForTokensCrossChain( - USDC_ADDR, - ZETA_USDC_PRICE, - ethers.utils.solidityPack(["address"], [account1.address]), - USDC_ADDR, - false, - 0, - chainBId + 5, - MaxUint256, - MaxUint256 - ); - - await expect(call).to.be.revertedWith("InvalidDestinationChainId"); - }); - - it("Should revert if the sourceInputToken isn't provided", async () => { - const call = multiChainSwapContractA.swapTokensForTokensCrossChain( - AddressZero, - ZETA_USDC_PRICE, - ethers.utils.solidityPack(["address"], [account1.address]), - USDC_ADDR, - false, - 0, - chainBId, - MaxUint256, - MaxUint256 - ); - - await expect(call).to.be.revertedWith("MissingSourceInputTokenAddress"); - }); - - it("Should revert if the destinationOutToken isn't provided", async () => { - const call = multiChainSwapContractA.swapTokensForTokensCrossChain( - USDC_ADDR, - ZETA_USDC_PRICE, - ethers.utils.solidityPack(["address"], [account1.address]), - AddressZero, - false, - 0, - chainBId, - MaxUint256, - MaxUint256 - ); - - await expect(call).to.be.revertedWith("OutTokenInvariant"); - }); - }); - - describe("onZetaMessage", () => { - it("Should revert if the caller is not ZetaConnector", async () => { - await expect( - multiChainSwapContractA.onZetaMessage({ - destinationAddress: multiChainSwapContractB.address, - message: encoder.encode(["address"], [multiChainSwapContractA.address]), - sourceChainId: chainBId, - zetaTxSenderAddress: ethers.utils.solidityPack(["address"], [multiChainSwapContractA.address]), - zetaValue: 0 - }) - ) - .to.be.revertedWith("InvalidCaller") - .withArgs(deployer.address); - }); - - it("Should revert if the zetaTxSenderAddress it not in interactorsByChainId", async () => { - await expect( - zetaConnectorMock.callOnZetaMessage( - ethers.utils.solidityPack(["address"], [multiChainSwapContractB.address]), - chainAId, - multiChainSwapContractB.address, - 0, - encoder.encode(["address"], [multiChainSwapContractB.address]) - ) - ).to.be.revertedWith("InvalidZetaMessageCall"); - }); - }); - - describe("onZetaRevert", () => { - it("Should revert if the caller is not ZetaConnector", async () => { - await expect( - multiChainSwapContractA.onZetaRevert({ - destinationAddress: ethers.utils.solidityPack(["address"], [multiChainSwapContractB.address]), - destinationChainId: chainBId, - message: encoder.encode(["address"], [multiChainSwapContractA.address]), - remainingZetaValue: 0, - sourceChainId: chainAId, - zetaTxSenderAddress: deployer.address - }) - ) - .to.be.revertedWith("InvalidCaller") - .withArgs(deployer.address); - }); - - it("Should trade the returned Zeta back for the input zeta token", async () => { - await addZetaEthLiquidity(); - await swapZetaToUSDC(deployer, parseUnits("10")); - - const tx1 = await zetaTokenMock.transfer(multiChainSwapContractA.address, parseUnits("100")); - await tx1.wait(); - - const originAddressInitialZetaBalance = await zetaTokenMock.balanceOf(deployer.address); - - const message = encoder.encode( - ["bytes32", "address", "address", "uint256", "bytes", "address", "bool", "uint256", "bool"], - [ - "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", - deployer.address, - zetaTokenMock.address, - 0, - "0xffffffff", - multiChainSwapContractA.address, - true, - 0, - false - ] - ); - - const tx2 = await zetaConnectorMock.callOnZetaRevert( - multiChainSwapContractA.address, - HARDHAT_CHAIN_ID, - chainBId, - encoder.encode(["address"], [multiChainSwapContractB.address]), - 10, - 0, - message - ); - - await tx2.wait(); - - const originAddressFinalZetaBalance = await zetaTokenMock.balanceOf(deployer.address); - expect(originAddressFinalZetaBalance).to.be.eq(originAddressInitialZetaBalance.add(10)); - }); - - it("Should trade the returned Zeta back for the input token", async () => { - await addZetaEthLiquidity(); - await swapZetaToUSDC(deployer, parseUnits("10")); - - const tx1 = await zetaTokenMock.transfer(multiChainSwapContractA.address, parseUnits("100")); - await tx1.wait(); - - const originAddressInitialUSDCBalance = await USDCTokenContract.balanceOf(deployer.address); - - const message = encoder.encode( - ["bytes32", "address", "address", "uint256", "bytes", "address", "bool", "uint256", "bool"], - [ - "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", - deployer.address, - USDCTokenContract.address, - 0, - "0xffffffff", - multiChainSwapContractA.address, - true, - 0, - false - ] - ); - - const tx2 = await zetaConnectorMock.callOnZetaRevert( - multiChainSwapContractA.address, - HARDHAT_CHAIN_ID, - chainBId, - encoder.encode(["address"], [multiChainSwapContractB.address]), - parseUnits("1"), - 0, - message - ); - - await tx2.wait(); - - const originAddressFinalUSDCBalance = await USDCTokenContract.balanceOf(deployer.address); - expect(originAddressFinalUSDCBalance).to.be.lt(originAddressInitialUSDCBalance.add(ZETA_USDC_PRICE)); - expect(originAddressFinalUSDCBalance).to.be.gt( - originAddressInitialUSDCBalance - .add(ZETA_USDC_PRICE) - .mul(995) - .div(1000) - ); - }); - - it("Should trade the returned ETH back to the caller", async () => { - await addZetaEthLiquidity(); - await swapZetaToUSDC(deployer, parseUnits("10")); - - const tx1 = await zetaTokenMock.transfer(multiChainSwapContractA.address, parseUnits("100")); - await tx1.wait(); - - const originAddressInitialETHBalance = await ethers.provider.getBalance(deployer.address); - - const message = encoder.encode( - ["bytes32", "address", "address", "uint256", "bytes", "address", "bool", "uint256", "bool"], - [ - "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", - deployer.address, - WETH, - 0, - "0xffffffff", - multiChainSwapContractA.address, - true, - 0, - true - ] - ); - - const tx2 = await zetaConnectorMock.callOnZetaRevert( - multiChainSwapContractA.address, - HARDHAT_CHAIN_ID, - chainBId, - encoder.encode(["address"], [multiChainSwapContractB.address]), - parseUnits("2"), - 0, - message - ); - - await tx2.wait(); - - const originAddressFinalETHBalance = await ethers.provider.getBalance(deployer.address); - expect(originAddressFinalETHBalance).to.be.gt(originAddressInitialETHBalance.add("1")); - expect(originAddressFinalETHBalance).to.be.lt( - originAddressInitialETHBalance - .add("1") - .mul(1005) - .div(1000) - ); - }); - - it("Should emit a RevertedSwap event", async () => { - await addZetaEthLiquidity(); - await swapZetaToUSDC(deployer, parseUnits("10")); - - const tx1 = await zetaTokenMock.transfer(multiChainSwapContractA.address, parseUnits("100")); - await tx1.wait(); - - const originAddressInitialETHBalance = await ethers.provider.getBalance(deployer.address); - - const message = encoder.encode( - ["bytes32", "address", "address", "uint256", "bytes", "address", "bool", "uint256", "bool"], - [ - "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", - deployer.address, - WETH, - 0, - "0xffffffff", - multiChainSwapContractA.address, - true, - 0, - true - ] - ); - - const tx2 = await zetaConnectorMock.callOnZetaRevert( - multiChainSwapContractA.address, - HARDHAT_CHAIN_ID, - chainBId, - encoder.encode(["address"], [multiChainSwapContractB.address]), - parseUnits("2"), - 0, - message - ); - - const result = await tx2.wait(); - const eventNames = parseZetaLog(result.logs); - expect(eventNames.filter(e => e === "RevertedSwap")).to.have.lengthOf(1); - }); - }); -}); diff --git a/packages/example-contracts/test/MultiChainSwapUniswapV3.spec.ts b/packages/example-contracts/test/MultiChainSwapUniswapV3.spec.ts deleted file mode 100644 index 7e88e2f9..00000000 --- a/packages/example-contracts/test/MultiChainSwapUniswapV3.spec.ts +++ /dev/null @@ -1,667 +0,0 @@ -import { FakeContract, smock } from "@defi-wonderland/smock"; -import { BigNumber } from "@ethersproject/bignumber"; -import { AddressZero, MaxUint256 } from "@ethersproject/constants"; -import { parseEther, parseUnits } from "@ethersproject/units"; -import { SignerWithAddress } from "@nomiclabs/hardhat-ethers/signers"; -import chai, { expect } from "chai"; -import { ethers } from "hardhat"; - -import { getMultiChainSwapUniV3, getMultiChainSwapZetaConnector } from "../lib/multi-chain-swap/MultiChainSwap.helpers"; -import { getAddress } from "../lib/shared/address.helpers"; -import { getNow } from "../lib/shared/deploy.helpers"; -import { - ERC20__factory, - IERC20, - IERC20__factory, - MultiChainSwapUniV3, - MultiChainSwapZetaConnector, - UniswapV2Router02__factory -} from "../typechain-types"; -import { parseInteractorLog } from "./test.helpers"; - -chai.should(); -chai.use(smock.matchers); - -const swapToken = async (signer: SignerWithAddress, tokenAddress: string, expectedAmount: BigNumber) => { - const uniswapV2RouterAddr = getAddress("uniswapV2Router02", { - customNetworkName: "eth-mainnet", - customZetaNetwork: "mainnet" - }); - - const uniswapRouter = UniswapV2Router02__factory.connect(uniswapV2RouterAddr, signer); - - const WETH = await uniswapRouter.WETH(); - const path = [WETH, tokenAddress]; - const tx = await uniswapRouter - .connect(signer) - .swapETHForExactTokens(expectedAmount, path, signer.address, (await getNow()) + 360, { value: parseEther("10") }); - - await tx.wait(); -}; - -const encoder = new ethers.utils.AbiCoder(); -const HARDHAT_CHAIN_ID = 1337; - -const ZETA_TO_TRANSFER = parseUnits("1"); -const USDC_TO_TRANSFER = parseUnits("1", 6); - -describe("MultiChainSwap tests", () => { - let WETH: string; - let zetaTokenMock: IERC20; - let zetaTokenNonEthAddress: string; - let USDCTokenContract: IERC20; - let zetaConnectorMock: MultiChainSwapZetaConnector; - - let multiChainSwapContractA: MultiChainSwapUniV3; - const chainAId = 1; - - let multiChainSwapContractB: MultiChainSwapUniV3; - const chainBId = 2; - - let zetaConnectorSmock: FakeContract; - let multiChainSwapContractWithSmock: MultiChainSwapUniV3; - - let accounts: SignerWithAddress[]; - let deployer: SignerWithAddress; - let account1: SignerWithAddress; - - const clearUSDCBalance = async (account: SignerWithAddress) => { - const balance = await USDCTokenContract.balanceOf(account.address); - const w = ethers.Wallet.createRandom(); - const tx = await USDCTokenContract.connect(account).transfer(w.address, balance); - await tx.wait(); - }; - - const clearZetaBalance = async (account: SignerWithAddress) => { - const balance = await zetaTokenMock.balanceOf(account.address); - const w = ethers.Wallet.createRandom(); - const tx = await zetaTokenMock.connect(account).transfer(w.address, balance); - await tx.wait(); - }; - - beforeEach(async () => { - accounts = await ethers.getSigners(); - [deployer, account1] = accounts; - - const DAI = getAddress("dai", { - customNetworkName: "eth-mainnet", - customZetaNetwork: "mainnet" - }); - - const UNI_QUOTER_V3 = getAddress("uniswapV3Quoter", { - customNetworkName: "eth-mainnet", - customZetaNetwork: "mainnet" - }); - - const UNI_ROUTER_V3 = getAddress("uniswapV3Router", { - customNetworkName: "eth-mainnet", - customZetaNetwork: "mainnet" - }); - - WETH = getAddress("weth9", { - customNetworkName: "eth-mainnet", - customZetaNetwork: "mainnet" - }); - - const USDC_ADDR = getAddress("usdc", { - customNetworkName: "eth-mainnet", - customZetaNetwork: "mainnet" - }); - - const ERC20Factory = new ERC20__factory(deployer); - USDCTokenContract = ERC20Factory.attach(USDC_ADDR); - - // For testing purposes we use an existing uni v3 pool - await swapToken(deployer, DAI, parseEther("10000")); - - zetaTokenNonEthAddress = DAI; - zetaTokenMock = IERC20__factory.connect(zetaTokenNonEthAddress, deployer); - zetaConnectorMock = await getMultiChainSwapZetaConnector(zetaTokenMock.address); - multiChainSwapContractA = await getMultiChainSwapUniV3({ - deployParams: [zetaConnectorMock.address, zetaTokenNonEthAddress, UNI_ROUTER_V3, UNI_QUOTER_V3, WETH, 3000, 3000] - }); - - multiChainSwapContractB = await getMultiChainSwapUniV3({ - deployParams: [zetaConnectorMock.address, zetaTokenNonEthAddress, UNI_ROUTER_V3, UNI_QUOTER_V3, WETH, 3000, 3000] - }); - - zetaConnectorSmock = await smock.fake("MultiChainSwapZetaConnector"); - multiChainSwapContractWithSmock = await getMultiChainSwapUniV3({ - deployParams: [zetaConnectorSmock.address, zetaTokenNonEthAddress, UNI_ROUTER_V3, UNI_QUOTER_V3, WETH, 3000, 3000] - }); - - const encodedCrossChainAddressB = ethers.utils.solidityPack(["address"], [multiChainSwapContractB.address]); - multiChainSwapContractA.setInteractorByChainId(chainBId, encodedCrossChainAddressB); - - const encodedCrossChainAddressA = ethers.utils.solidityPack(["address"], [multiChainSwapContractA.address]); - multiChainSwapContractB.setInteractorByChainId(chainAId, encodedCrossChainAddressA); - - multiChainSwapContractWithSmock.setInteractorByChainId(chainBId, encodedCrossChainAddressB); - - await clearUSDCBalance(deployer); - await clearUSDCBalance(account1); - await clearZetaBalance(account1); - }); - - describe("swapTokensForTokensCrossChainUniswapV3", () => { - it("Should revert if the destinationChainId is not in the storage", async () => { - await expect( - multiChainSwapContractA.swapETHForTokensCrossChain( - ethers.utils.solidityPack(["address"], [account1.address]), - zetaTokenMock.address, - false, - 0, - 10, - MaxUint256, - MaxUint256, - { - value: parseUnits("1") - } - ) - ).to.be.revertedWith("InvalidDestinationChainId"); - }); - - it("Should revert if the sourceInputToken isn't provided", async () => { - await expect( - multiChainSwapContractA.swapTokensForTokensCrossChain( - AddressZero, - BigNumber.from(10), - ethers.utils.solidityPack(["address"], [account1.address]), - zetaTokenMock.address, - false, - 0, - chainBId, - MaxUint256, - MaxUint256 - ) - ).to.be.revertedWith("MissingSourceInputTokenAddress"); - }); - - it("Should revert if the destinationOutToken isn't provided", async () => { - await expect( - multiChainSwapContractA.swapTokensForTokensCrossChain( - zetaTokenMock.address, - BigNumber.from(10), - ethers.utils.solidityPack(["address"], [account1.address]), - AddressZero, - false, - 0, - chainBId, - MaxUint256, - MaxUint256 - ) - ).to.be.revertedWith("OutTokenInvariant"); - }); - - it("Should trade ETH for Zeta", async () => { - await swapToken(deployer, USDCTokenContract.address, USDC_TO_TRANSFER); - - expect(await zetaTokenMock.balanceOf(account1.address)).to.be.eq(0); - - const tx1 = await zetaTokenMock.approve(multiChainSwapContractA.address, ZETA_TO_TRANSFER); - await tx1.wait(); - - const tx2 = await USDCTokenContract.approve(multiChainSwapContractA.address, USDC_TO_TRANSFER); - await tx2.wait(); - - const tx3 = await multiChainSwapContractA.swapETHForTokensCrossChain( - ethers.utils.solidityPack(["address"], [account1.address]), - zetaTokenMock.address, - false, - 0, - chainBId, - MaxUint256, - MaxUint256, - { value: ZETA_TO_TRANSFER } - ); - const result = await tx3.wait(); - expect(await zetaTokenMock.balanceOf(account1.address)).to.be.gt(0); - - const eventNames = parseInteractorLog(result.logs); - expect(eventNames.filter(e => e === "EthExchangedForZeta")).to.have.lengthOf(1); - expect(eventNames.filter(e => e === "TokenExchangedForZeta")).to.have.lengthOf(0); - expect(eventNames.filter(e => e === "ZetaExchangedForEth")).to.have.lengthOf(0); - expect(eventNames.filter(e => e === "ZetaExchangedForToken")).to.have.lengthOf(0); - - const swappedFilter = multiChainSwapContractB.filters.Swapped(); - const e1 = await multiChainSwapContractB.queryFilter(swappedFilter, tx3.blockHash); - expect(e1.length).to.equal(1); - }); - - it("Should trade Zeta for ETH", async () => { - await swapToken(deployer, USDCTokenContract.address, USDC_TO_TRANSFER); - - const initialETHbalance = await ethers.provider.getBalance(account1.address); - - const tx1 = await zetaTokenMock.approve(multiChainSwapContractA.address, ZETA_TO_TRANSFER); - await tx1.wait(); - - const tx2 = await USDCTokenContract.approve(multiChainSwapContractA.address, USDC_TO_TRANSFER); - await tx2.wait(); - - const tx3 = await multiChainSwapContractA.swapTokensForTokensCrossChain( - zetaTokenMock.address, - ZETA_TO_TRANSFER, - ethers.utils.solidityPack(["address"], [account1.address]), - AddressZero, - true, - 0, - chainBId, - MaxUint256, - MaxUint256 - ); - const result = await tx3.wait(); - expect(await ethers.provider.getBalance(account1.address)).to.be.gt(initialETHbalance); - - const eventNames = parseInteractorLog(result.logs); - expect(eventNames.filter(e => e === "EthExchangedForZeta")).to.have.lengthOf(0); - expect(eventNames.filter(e => e === "TokenExchangedForZeta")).to.have.lengthOf(0); - expect(eventNames.filter(e => e === "ZetaExchangedForEth")).to.have.lengthOf(1); - expect(eventNames.filter(e => e === "ZetaExchangedForToken")).to.have.lengthOf(0); - - const swappedFilter = multiChainSwapContractB.filters.Swapped(); - const e1 = await multiChainSwapContractB.queryFilter(swappedFilter, tx3.blockHash); - expect(e1.length).to.equal(1); - }); - - it("Should not perform any trade if the input token is Zeta", async () => { - expect(await zetaTokenMock.balanceOf(account1.address)).to.be.eq(0); - - const tx1 = await zetaTokenMock.approve(multiChainSwapContractA.address, ZETA_TO_TRANSFER); - await tx1.wait(); - - const tx2 = await USDCTokenContract.approve(multiChainSwapContractA.address, USDC_TO_TRANSFER); - await tx2.wait(); - - const tx3 = await multiChainSwapContractA.swapTokensForTokensCrossChain( - zetaTokenMock.address, - ZETA_TO_TRANSFER, - ethers.utils.solidityPack(["address"], [account1.address]), - zetaTokenMock.address, - false, - 0, - chainBId, - MaxUint256, - MaxUint256 - ); - await tx3.wait(); - expect(await zetaTokenMock.balanceOf(account1.address)).to.be.gt(0); - - const result = await tx3.wait(); - const eventNames = parseInteractorLog(result.logs); - expect(eventNames.filter(e => e === "EthExchangedForZeta")).to.have.lengthOf(0); - expect(eventNames.filter(e => e === "TokenExchangedForZeta")).to.have.lengthOf(0); - expect(eventNames.filter(e => e === "ZetaExchangedForEth")).to.have.lengthOf(0); - expect(eventNames.filter(e => e === "ZetaExchangedForToken")).to.have.lengthOf(0); - - const swappedFilter = multiChainSwapContractB.filters.Swapped(); - const e1 = await multiChainSwapContractB.queryFilter(swappedFilter, tx3.blockHash); - expect(e1.length).to.equal(1); - }); - - it("Should trade the input token for Zeta", async () => { - await swapToken(deployer, USDCTokenContract.address, USDC_TO_TRANSFER); - - expect(await zetaTokenMock.balanceOf(account1.address)).to.be.eq(0); - - const tx1 = await zetaTokenMock.approve(multiChainSwapContractA.address, ZETA_TO_TRANSFER); - await tx1.wait(); - - const tx2 = await USDCTokenContract.approve(multiChainSwapContractA.address, USDC_TO_TRANSFER); - await tx2.wait(); - - const tx3 = await multiChainSwapContractA.swapTokensForTokensCrossChain( - USDCTokenContract.address, - USDC_TO_TRANSFER, - ethers.utils.solidityPack(["address"], [account1.address]), - zetaTokenMock.address, - false, - 0, - chainBId, - MaxUint256, - MaxUint256 - ); - const result = await tx3.wait(); - expect(await zetaTokenMock.balanceOf(account1.address)).to.be.gt(0); - - const eventNames = parseInteractorLog(result.logs); - expect(eventNames.filter(e => e === "EthExchangedForZeta")).to.have.lengthOf(0); - expect(eventNames.filter(e => e === "TokenExchangedForZeta")).to.have.lengthOf(1); - expect(eventNames.filter(e => e === "ZetaExchangedForEth")).to.have.lengthOf(0); - expect(eventNames.filter(e => e === "ZetaExchangedForToken")).to.have.lengthOf(0); - - const swappedFilter = multiChainSwapContractB.filters.Swapped(); - const e1 = await multiChainSwapContractB.queryFilter(swappedFilter, tx3.blockHash); - expect(e1.length).to.equal(1); - }); - - it("Should trade zeta for the output token", async () => { - await swapToken(deployer, USDCTokenContract.address, USDC_TO_TRANSFER); - - expect(await USDCTokenContract.balanceOf(account1.address)).to.be.eq(0); - - const tx1 = await zetaTokenMock.approve(multiChainSwapContractA.address, ZETA_TO_TRANSFER); - await tx1.wait(); - - const tx2 = await USDCTokenContract.approve(multiChainSwapContractA.address, USDC_TO_TRANSFER); - await tx2.wait(); - - const tx3 = await multiChainSwapContractA.swapTokensForTokensCrossChain( - zetaTokenMock.address, - ZETA_TO_TRANSFER, - ethers.utils.solidityPack(["address"], [account1.address]), - USDCTokenContract.address, - false, - 0, - chainBId, - MaxUint256, - MaxUint256 - ); - const result = await tx3.wait(); - expect(await USDCTokenContract.balanceOf(account1.address)).to.be.gt(0); - - const eventNames = parseInteractorLog(result.logs); - expect(eventNames.filter(e => e === "EthExchangedForZeta")).to.have.lengthOf(0); - expect(eventNames.filter(e => e === "TokenExchangedForZeta")).to.have.lengthOf(0); - expect(eventNames.filter(e => e === "ZetaExchangedForEth")).to.have.lengthOf(0); - expect(eventNames.filter(e => e === "ZetaExchangedForToken")).to.have.lengthOf(1); - - const swappedFilter = multiChainSwapContractB.filters.Swapped(); - const e1 = await multiChainSwapContractB.queryFilter(swappedFilter, tx3.blockHash); - expect(e1.length).to.equal(1); - }); - - it("Should trade input token for zeta and zeta for the output token", async () => { - await swapToken(deployer, USDCTokenContract.address, USDC_TO_TRANSFER); - - expect(await USDCTokenContract.balanceOf(account1.address)).to.be.eq(0); - - const tx1 = await zetaTokenMock.approve(multiChainSwapContractA.address, ZETA_TO_TRANSFER); - await tx1.wait(); - - const tx2 = await USDCTokenContract.approve(multiChainSwapContractA.address, USDC_TO_TRANSFER); - await tx2.wait(); - - const tx3 = await multiChainSwapContractA.swapTokensForTokensCrossChain( - USDCTokenContract.address, - USDC_TO_TRANSFER, - ethers.utils.solidityPack(["address"], [account1.address]), - USDCTokenContract.address, - false, - 0, - chainBId, - MaxUint256, - MaxUint256 - ); - const result = await tx3.wait(); - expect(await USDCTokenContract.balanceOf(account1.address)).to.be.gt(0); - - const eventNames = parseInteractorLog(result.logs); - expect(eventNames.filter(e => e === "EthExchangedForZeta")).to.have.lengthOf(0); - expect(eventNames.filter(e => e === "TokenExchangedForZeta")).to.have.lengthOf(1); - expect(eventNames.filter(e => e === "ZetaExchangedForEth")).to.have.lengthOf(0); - expect(eventNames.filter(e => e === "ZetaExchangedForToken")).to.have.lengthOf(1); - - const swappedFilter = multiChainSwapContractB.filters.Swapped(); - const e1 = await multiChainSwapContractB.queryFilter(swappedFilter, tx3.blockHash); - expect(e1.length).to.equal(1); - }); - - it("Should call connector.send", async () => { - await swapToken(deployer, USDCTokenContract.address, USDC_TO_TRANSFER); - - expect(await USDCTokenContract.balanceOf(account1.address)).to.be.eq(0); - - const tx1 = await zetaTokenMock.approve(multiChainSwapContractWithSmock.address, ZETA_TO_TRANSFER); - await tx1.wait(); - - const tx2 = await USDCTokenContract.approve(multiChainSwapContractWithSmock.address, USDC_TO_TRANSFER); - await tx2.wait(); - - const tx3 = await multiChainSwapContractWithSmock.swapTokensForTokensCrossChain( - USDCTokenContract.address, - USDC_TO_TRANSFER, - ethers.utils.solidityPack(["address"], [account1.address]), - USDCTokenContract.address, - false, - 0, - chainBId, - MaxUint256, - MaxUint256 - ); - - zetaConnectorSmock.send.atCall(0).should.be.called; - }); - - it("Should emit a SentTokenSwap event", async () => { - await swapToken(deployer, USDCTokenContract.address, USDC_TO_TRANSFER); - - expect(await USDCTokenContract.balanceOf(account1.address)).to.be.eq(0); - - const tx1 = await zetaTokenMock.approve(multiChainSwapContractA.address, ZETA_TO_TRANSFER); - await tx1.wait(); - - const tx2 = await USDCTokenContract.approve(multiChainSwapContractA.address, USDC_TO_TRANSFER); - await tx2.wait(); - - const tx3 = await multiChainSwapContractA.swapTokensForTokensCrossChain( - USDCTokenContract.address, - USDC_TO_TRANSFER, - ethers.utils.solidityPack(["address"], [account1.address]), - USDCTokenContract.address, - false, - 0, - chainBId, - MaxUint256, - MaxUint256 - ); - await tx3.wait(); - - const swappedFilter = multiChainSwapContractB.filters.Swapped(); - const e1 = await multiChainSwapContractB.queryFilter(swappedFilter, tx3.blockHash); - expect(e1.length).to.equal(1); - }); - - describe("onZetaMessage", () => { - it("Should revert if the caller is not ZetaConnector", async () => { - await expect( - multiChainSwapContractA.onZetaMessage({ - destinationAddress: multiChainSwapContractB.address, - message: encoder.encode(["address"], [multiChainSwapContractA.address]), - sourceChainId: chainBId, - zetaTxSenderAddress: ethers.utils.solidityPack(["address"], [multiChainSwapContractA.address]), - zetaValue: 0 - }) - ) - .to.be.revertedWith("InvalidCaller") - .withArgs(deployer.address); - }); - - it("Should revert if the zetaTxSenderAddress it not in interactorsByChainId", async () => { - await expect( - zetaConnectorMock.callOnZetaMessage( - ethers.utils.solidityPack(["address"], [multiChainSwapContractB.address]), - chainAId, - multiChainSwapContractB.address, - 0, - encoder.encode(["address"], [multiChainSwapContractB.address]) - ) - ).to.be.revertedWith("InvalidZetaMessageCall"); - }); - }); - - describe("onZetaRevert", () => { - it("Should revert if the caller is not ZetaConnector", async () => { - await expect( - multiChainSwapContractA.onZetaRevert({ - destinationAddress: ethers.utils.solidityPack(["address"], [multiChainSwapContractB.address]), - destinationChainId: chainBId, - message: encoder.encode(["address"], [multiChainSwapContractA.address]), - remainingZetaValue: 0, - sourceChainId: chainAId, - zetaTxSenderAddress: deployer.address - }) - ) - .to.be.revertedWith("InvalidCaller") - .withArgs(deployer.address); - }); - - it("Should trade the returned Zeta back for the input zeta token", async () => { - const tx1 = await zetaTokenMock.transfer(multiChainSwapContractA.address, parseUnits("10")); - await tx1.wait(); - - const originAddressInitialZetaBalance = await zetaTokenMock.balanceOf(deployer.address); - - const message = encoder.encode( - ["bytes32", "address", "address", "uint256", "bytes", "address", "bool", "uint256", "bool"], - [ - "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", - deployer.address, - zetaTokenMock.address, - 0, - "0xffffffff", - multiChainSwapContractA.address, - true, - 0, - false - ] - ); - - const tx2 = await zetaConnectorMock.callOnZetaRevert( - multiChainSwapContractA.address, - HARDHAT_CHAIN_ID, - chainBId, - encoder.encode(["address"], [multiChainSwapContractB.address]), - 10, - 0, - message - ); - - await tx2.wait(); - - const originAddressFinalZetaBalance = await zetaTokenMock.balanceOf(deployer.address); - expect(originAddressFinalZetaBalance).to.be.eq(originAddressInitialZetaBalance.add(10)); - }); - - it("Should trade the returned Zeta back for the input token", async () => { - const tx1 = await zetaTokenMock.transfer(multiChainSwapContractA.address, parseUnits("100")); - await tx1.wait(); - - const originAddressInitialUSDCBalance = await USDCTokenContract.balanceOf(deployer.address); - - const message = encoder.encode( - ["bytes32", "address", "address", "uint256", "bytes", "address", "bool", "uint256", "bool"], - [ - "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", - deployer.address, - USDCTokenContract.address, - 0, - "0xffffffff", - multiChainSwapContractA.address, - true, - 0, - false - ] - ); - - const tx2 = await zetaConnectorMock.callOnZetaRevert( - multiChainSwapContractA.address, - HARDHAT_CHAIN_ID, - chainBId, - encoder.encode(["address"], [multiChainSwapContractB.address]), - ZETA_TO_TRANSFER, - 0, - message - ); - - await tx2.wait(); - - const originAddressFinalUSDCBalance = await USDCTokenContract.balanceOf(deployer.address); - expect(originAddressFinalUSDCBalance).to.be.lt(originAddressInitialUSDCBalance.add(USDC_TO_TRANSFER)); - expect(originAddressFinalUSDCBalance).to.be.gt( - originAddressInitialUSDCBalance - .add(USDC_TO_TRANSFER) - .mul(990) - .div(1000) - ); - }); - - it("Should trade the returned ETH back to the caller", async () => { - const tx1 = await zetaTokenMock.transfer(multiChainSwapContractA.address, parseUnits("100")); - await tx1.wait(); - - const originAddressInitialETHBalance = await ethers.provider.getBalance(deployer.address); - - const message = encoder.encode( - ["bytes32", "address", "address", "uint256", "bytes", "address", "bool", "uint256", "bool"], - [ - "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", - deployer.address, - WETH, - 0, - "0xffffffff", - multiChainSwapContractA.address, - true, - 0, - true - ] - ); - - const tx2 = await zetaConnectorMock.callOnZetaRevert( - multiChainSwapContractA.address, - HARDHAT_CHAIN_ID, - chainBId, - encoder.encode(["address"], [multiChainSwapContractB.address]), - parseUnits("2"), - 0, - message - ); - - await tx2.wait(); - - const originAddressFinalETHBalance = await ethers.provider.getBalance(deployer.address); - expect(originAddressFinalETHBalance).to.be.gt(originAddressInitialETHBalance.add("1")); - expect(originAddressFinalETHBalance).to.be.lt( - originAddressInitialETHBalance - .add("1") - .mul(1005) - .div(1000) - ); - }); - - it("Should emit a RevertedSwap event", async () => { - const tx1 = await zetaTokenMock.transfer(multiChainSwapContractA.address, parseUnits("10")); - await tx1.wait(); - - const message = encoder.encode( - ["bytes32", "address", "address", "uint256", "bytes", "address", "bool", "uint256", "bool"], - [ - "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", - deployer.address, - WETH, - 0, - "0xffffffff", - multiChainSwapContractA.address, - true, - 0, - true - ] - ); - - const tx2 = await zetaConnectorMock.callOnZetaRevert( - multiChainSwapContractA.address, - HARDHAT_CHAIN_ID, - chainBId, - encoder.encode(["address"], [multiChainSwapContractB.address]), - parseUnits("2"), - 0, - message - ); - - const swappedFilter = multiChainSwapContractA.filters.RevertedSwap(); - const e1 = await multiChainSwapContractA.queryFilter(swappedFilter, tx2.blockHash); - expect(e1.length).to.equal(1); - }); - }); - }); -}); diff --git a/packages/example-contracts/test/test.helpers.ts b/packages/example-contracts/test/test.helpers.ts deleted file mode 100644 index 9603bcba..00000000 --- a/packages/example-contracts/test/test.helpers.ts +++ /dev/null @@ -1,89 +0,0 @@ -import { MaxUint256 } from "@ethersproject/constants"; -import { SignerWithAddress } from "@nomiclabs/hardhat-ethers/signers"; -import { BigNumber, ContractReceipt } from "ethers"; - -import { getAddress } from "../lib/shared/address.helpers"; -import { getNow } from "../lib/shared/deploy.helpers"; -import { - ERC20__factory, - IUniswapV2Pair__factory, - MultiChainSwapUniV2__factory, - UniswapV2Router02__factory, - ZetaTokenConsumerUniV3__factory -} from "../typechain-types"; - -export const getMintTokenId = (mintTx: ContractReceipt) => mintTx.events?.[0].args?.tokenId; - -export const parseUniswapLog = (logs: ContractReceipt["logs"]) => { - const iface = IUniswapV2Pair__factory.createInterface(); - - const eventNames = logs.map(log => { - try { - const parsedLog = iface.parseLog(log); - - return parsedLog.name; - } catch (e) { - return "NO_UNI_LOG"; - } - }); - - return eventNames; -}; - -export const parseZetaLog = (logs: ContractReceipt["logs"]) => { - const iface = MultiChainSwapUniV2__factory.createInterface(); - - const eventNames = logs.map(log => { - try { - const parsedLog = iface.parseLog(log); - - return parsedLog.name; - } catch (e) { - return "NO_ZETA_LOG"; - } - }); - - return eventNames; -}; - -export const parseInteractorLog = (logs: ContractReceipt["logs"]) => { - const iface = ZetaTokenConsumerUniV3__factory.createInterface(); - const eventNames = logs.map(log => { - try { - const parsedLog = iface.parseLog(log); - return parsedLog.name; - } catch (e) { - return "NO_ZETA_LOG"; - } - }); - return eventNames; -}; - -export const addZetaEthLiquidityTest = async ( - zetaTokenAddress: string, - zetaToAdd: BigNumber, - ETHToAdd: BigNumber, - deployer: SignerWithAddress -) => { - const uniswapRouterAddr = getAddress("uniswapV2Router02", { - customNetworkName: "eth-mainnet", - customZetaNetwork: "mainnet" - }); - const uniswapRouter = UniswapV2Router02__factory.connect(uniswapRouterAddr, deployer); - - const ZetaTokenContract = ERC20__factory.connect(zetaTokenAddress, deployer); - - const tx1 = await ZetaTokenContract.approve(uniswapRouter.address, MaxUint256); - await tx1.wait(); - - const tx2 = await uniswapRouter.addLiquidityETH( - ZetaTokenContract.address, - zetaToAdd, - 0, - 0, - deployer.address, - (await getNow()) + 360, - { gasLimit: 10_000_000, value: ETHToAdd } - ); - await tx2.wait(); -}; diff --git a/packages/example-contracts/tsconfig.json b/packages/example-contracts/tsconfig.json deleted file mode 100644 index 355cfda5..00000000 --- a/packages/example-contracts/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "extends": "../../tsconfig.json", - "include": ["./scripts", "./lib", "./test", "./tests", "./typechain", "./**/*.json", "typechain-types"], - "exclude": ["artifacts", "cache"], - "files": ["./hardhat.config.ts"], - "compilerOptions": { - "baseUrl": ".", - "paths": { - "@zetachain/addresses": ["../addresses/src/index"], - "@zetachain/addresses/*": ["../addresses/src/*"], - "@zetachain/interfaces": ["../interfaces/src/index"] - } - } -} diff --git a/packages/zeta-app-contracts/data/addresses.json b/packages/zeta-app-contracts/data/addresses.json new file mode 100644 index 00000000..27c51e4a --- /dev/null +++ b/packages/zeta-app-contracts/data/addresses.json @@ -0,0 +1,55 @@ +{ + "ccm": { + "baobab_testnet": { + "multiChainSwap": "", + "multiChainValue": "", + "zetaTokenConsumerUniV2": "", + "zetaTokenConsumerUniV3": "" + }, + "bsc_mainnet": { + "multiChainSwap": "", + "multiChainValue": "", + "zetaTokenConsumerUniV2": "", + "zetaTokenConsumerUniV3": "" + }, + "bsc_testnet": { + "multiChainSwap": "0x8BD7144Ddb59c9Fa3Dcf809998521E9cAD946fa1", + "multiChainValue": "0x064516547ECd3b2D1709e1b2798Aae92b1C8a84C", + "zetaTokenConsumerUniV2": "", + "zetaTokenConsumerUniV3": "" + }, + "btc_testnet": { + "multiChainSwap": "", + "multiChainValue": "", + "zetaTokenConsumerUniV2": "", + "zetaTokenConsumerUniV3": "" + }, + "eth_mainnet": { + "multiChainSwap": "", + "multiChainValue": "", + "zetaTokenConsumerUniV2": "", + "zetaTokenConsumerUniV3": "" + }, + "goerli_testnet": { + "multiChainSwap": "0x323745f16C93e56a98012970c28788498d8B3a14", + "multiChainValue": "0x14BeC0E4A8e7bF7A02Af54Ad81a57a9fcA4D37Fd", + "zetaTokenConsumerUniV2": "", + "zetaTokenConsumerUniV3": "" + }, + "mumbai_testnet": { + "multiChainSwap": "0xb1b812b664c28E1bA1d35De925Ae88b7Bc7cdCF5", + "multiChainValue": "0x14BeC0E4A8e7bF7A02Af54Ad81a57a9fcA4D37Fd", + "zetaTokenConsumerUniV2": "", + "zetaTokenConsumerUniV3": "" + }, + "zeta_testnet": { + "multiChainSwap": "", + "multiChainValue": "0x82aC45D07dEe4DBDe050e838beF345347DEd99a8", + "zetaTokenConsumerUniV2": "", + "zetaTokenConsumerUniV3": "" + } + }, + "zevm": { + "zeta_testnet": {} + } +} \ No newline at end of file diff --git a/packages/zeta-app-contracts/hardhat.config.ts b/packages/zeta-app-contracts/hardhat.config.ts index 62cb5c23..f40cd212 100644 --- a/packages/zeta-app-contracts/hardhat.config.ts +++ b/packages/zeta-app-contracts/hardhat.config.ts @@ -5,7 +5,7 @@ import "hardhat-gas-reporter"; import "solidity-coverage"; import "tsconfig-paths/register"; -import { getHardhatConfigNetworks, getHardhatConfigScanners } from "@zetachain/addresses-tools/src/networks"; +import { getHardhatConfigNetworks } from "@zetachain/networks"; import * as dotenv from "dotenv"; import type { HardhatUserConfig } from "hardhat/types"; @@ -14,15 +14,22 @@ dotenv.config(); const PRIVATE_KEYS = process.env.PRIVATE_KEY !== undefined ? [`0x${process.env.PRIVATE_KEY}`] : []; const config: HardhatUserConfig = { + //@ts-ignore etherscan: { - ...getHardhatConfigScanners(), + apiKey: { + // BSC + bscTestnet: process.env.BSCSCAN_API_KEY || "", + // ETH + goerli: process.env.ETHERSCAN_API_KEY || "", + mainnet: process.env.ETHERSCAN_API_KEY || "", + }, }, gasReporter: { currency: "USD", enabled: process.env.REPORT_GAS !== undefined, }, networks: { - ...getHardhatConfigNetworks(PRIVATE_KEYS), + ...getHardhatConfigNetworks(), }, solidity: { compilers: [ diff --git a/packages/zeta-app-contracts/lib/multi-chain-value/MultiChainValue.helpers.ts b/packages/zeta-app-contracts/lib/multi-chain-value/MultiChainValue.helpers.ts index 43daf6f9..e24b1833 100644 --- a/packages/zeta-app-contracts/lib/multi-chain-value/MultiChainValue.helpers.ts +++ b/packages/zeta-app-contracts/lib/multi-chain-value/MultiChainValue.helpers.ts @@ -1,4 +1,5 @@ -import { ZetaEth, ZetaEth__factory as ZetaEthFactory } from "@zetachain/interfaces/typechain-types"; +import { getAddress, isProtocolNetworkName } from "@zetachain/protocol-contracts"; +import { ZetaEth, ZetaEth__factory as ZetaEthFactory } from "@zetachain/protocol-contracts/dist/typechain-types"; import assert from "assert"; import { ethers, network } from "hardhat"; @@ -11,8 +12,8 @@ import { ZetaConnectorMockValue, ZetaConnectorMockValue__factory as ZetaConnectorMockValueFactory } from "../../typechain-types"; -import { getAddress } from "../shared/address.helpers"; +const networkName = network.name; /** * @description only for testing or local environment */ @@ -39,13 +40,16 @@ export const deployMultiChainValueMock = async ({ return multiChainValueContract; }; -export const getMultiChainValue = (existingContractAddress?: string) => - getContract({ +export const getMultiChainValue = (existingContractAddress?: string) => { + if (!isProtocolNetworkName(networkName)) throw new Error("Invalid network name"); + + return getContract({ contractName: "MultiChainValue", ...(existingContractAddress ? { existingContractAddress } - : { deployParams: [getAddress("connector"), getAddress("zetaToken")] }) + : { deployParams: [getAddress("connector", networkName), getAddress("zetaToken", networkName)] }) }); +}; export const deployZetaConnectorMock = async () => { const Factory = (await ethers.getContractFactory("ZetaConnectorMockValue")) as ZetaConnectorMockValueFactory; @@ -58,9 +62,11 @@ export const deployZetaConnectorMock = async () => { }; export const deployZetaEthMock = async () => { + const [signer] = await ethers.getSigners(); + const Factory = (await ethers.getContractFactory("ZetaEthMock")) as ZetaEthFactory; - const zetaConnectorMockContract = (await Factory.deploy(100_000)) as ZetaEth; + const zetaConnectorMockContract = (await Factory.deploy(signer.address, 100_000)) as ZetaEth; await zetaConnectorMockContract.deployed(); diff --git a/packages/zeta-app-contracts/lib/shared/ImmutableCreate2Factory.helpers.ts b/packages/zeta-app-contracts/lib/shared/ImmutableCreate2Factory.helpers.ts index e180e84f..cff737a7 100644 --- a/packages/zeta-app-contracts/lib/shared/ImmutableCreate2Factory.helpers.ts +++ b/packages/zeta-app-contracts/lib/shared/ImmutableCreate2Factory.helpers.ts @@ -1,5 +1,5 @@ import { Provider, TransactionReceipt } from "@ethersproject/providers"; -import { ImmutableCreate2Factory__factory } from "@zetachain/interfaces/typechain-types"; +import { ImmutableCreate2Factory__factory } from "@zetachain/protocol-contracts/dist/typechain-types"; import { ethers, Signer } from "ethers"; export const buildBytecode = (constructorTypes: any[], constructorArgs: any[], contractBytecode: string) => @@ -7,7 +7,7 @@ export const buildBytecode = (constructorTypes: any[], constructorArgs: any[], c export const buildCreate2Address = (saltHex: string, byteCode: string, factoryAddress: string) => { const payload = ethers.utils.keccak256( - `0x${["ff", factoryAddress, saltHex, ethers.utils.keccak256(byteCode)].map((x) => x.replace(/0x/, "")).join("")}` + `0x${["ff", factoryAddress, saltHex, ethers.utils.keccak256(byteCode)].map(x => x.replace(/0x/, "")).join("")}` ); return `0x${payload.slice(-40)}`.toLowerCase(); @@ -39,7 +39,7 @@ export async function deployContractToAddress({ contractBytecode, constructorTypes = [] as string[], constructorArgs = [] as any[], - signer, + signer }: { constructorArgs?: any[]; constructorTypes?: string[]; @@ -55,14 +55,14 @@ export async function deployContractToAddress({ const computedAddr = await factory.findCreate2Address(salt, bytecode); const tx = await factory.safeCreate2(salt, bytecode, { - gasLimit: 6000000, + gasLimit: 6000000 }); const result = await tx.wait(); return { address: computedAddr as string, receipt: result as TransactionReceipt, - txHash: result.transactionHash as string, + txHash: result.transactionHash as string }; } diff --git a/packages/zeta-app-contracts/lib/shared/address.helpers.ts b/packages/zeta-app-contracts/lib/shared/address.helpers.ts deleted file mode 100644 index d6c498f2..00000000 --- a/packages/zeta-app-contracts/lib/shared/address.helpers.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { getAddress as getAddressLib, NetworkName, ZetaAddress, ZetaNetworkName } from "@zetachain/addresses"; -import { network } from "hardhat"; - -const MissingZetaNetworkError = new Error( - "ZETA_NETWORK is not defined, please set the environment variable (e.g.: ZETA_NETWORK=athens )" -); - -export const getAddress = ( - address: ZetaAddress, - { - customNetworkName, - customZetaNetwork - }: { customNetworkName?: NetworkName; customZetaNetwork?: ZetaNetworkName } = {} -): string => { - const { name: _networkName } = network; - const networkName = customNetworkName || _networkName; - - const { ZETA_NETWORK: _ZETA_NETWORK } = process.env; - const zetaNetwork = customZetaNetwork || _ZETA_NETWORK; - - if (!zetaNetwork) throw MissingZetaNetworkError; - return getAddressLib({ address, networkName, zetaNetwork }); -}; diff --git a/packages/zeta-app-contracts/package.json b/packages/zeta-app-contracts/package.json index 792cfb8e..f2536706 100644 --- a/packages/zeta-app-contracts/package.json +++ b/packages/zeta-app-contracts/package.json @@ -30,9 +30,8 @@ }, "dependencies": { "@openzeppelin/contracts": "^4.8.3", - "@zetachain/addresses": "workspace:^", - "@zetachain/addresses-tools": "workspace:^", - "@zetachain/protocol-contracts": "^2.1.0", + "@zetachain/networks": "^2.4.3", + "@zetachain/protocol-contracts": "^3.0.0", "ethers": "5.6.8" } } diff --git a/packages/zeta-app-contracts/scripts/address.helpers.ts b/packages/zeta-app-contracts/scripts/address.helpers.ts new file mode 100644 index 00000000..9a067b94 --- /dev/null +++ b/packages/zeta-app-contracts/scripts/address.helpers.ts @@ -0,0 +1,31 @@ +import { networks } from "@zetachain/networks"; +import { isProtocolNetworkName, ZetaProtocolNetwork } from "@zetachain/protocol-contracts"; +import { readFileSync, writeFileSync } from "fs"; +import { network } from "hardhat"; +import { join } from "path"; + +import addresses from "../data/addresses.json"; + +export const getAppAddress = (address: string, network: ZetaProtocolNetwork): string => { + return (addresses["ccm"] as any)[network][address]; +}; + +export const getChainId = (network: ZetaProtocolNetwork): number => { + //@ts-ignore + return networks[network].chain_id; +}; + +export const saveAddress = (name: string, address: string) => { + const networkName = network.name; + if (!isProtocolNetworkName(networkName)) throw new Error("Invalid network name"); + + console.log(`Updating ${name} address on ${networkName}.`); + + const filename = join(__dirname, `./data/addresses.json`); + + const newAddresses = JSON.parse(readFileSync(filename, "utf8")); + + newAddresses["ccm"][networkName][name] = address; + + writeFileSync(filename, JSON.stringify(newAddresses, null, 2)); +}; diff --git a/packages/zeta-app-contracts/scripts/multi-chain-value/deploy.ts b/packages/zeta-app-contracts/scripts/multi-chain-value/deploy.ts index cdc2158a..88c23931 100644 --- a/packages/zeta-app-contracts/scripts/multi-chain-value/deploy.ts +++ b/packages/zeta-app-contracts/scripts/multi-chain-value/deploy.ts @@ -1,21 +1,16 @@ -import { getChainId, isNetworkName, isZetaTestnet, NetworkName } from "@zetachain/addresses"; -import { getProtocolNetwork, saveAddress } from "@zetachain/addresses-tools"; -import { getAddress } from "@zetachain/protocol-contracts/dist/lib"; +import { getAddress, isProtocolNetworkName } from "@zetachain/protocol-contracts/dist/lib"; import { ethers, network } from "hardhat"; import { MultiChainValue, MultiChainValue__factory } from "../../typechain-types"; +import { getChainId, saveAddress } from "../address.helpers"; const networkName = network.name; -const { ZETA_NETWORK } = process.env; async function main() { - if (!isNetworkName(networkName)) throw new Error("Invalid network name"); + if (!isProtocolNetworkName(networkName)) throw new Error("Invalid network name"); - const protocolNetwork = getProtocolNetwork(networkName); - if (!protocolNetwork) throw new Error("Invalid network name"); - - const connectorAddress = getAddress("connector", protocolNetwork); - const zetaTokenAddress = getAddress("zetaToken", protocolNetwork); + const connectorAddress = getAddress("connector", networkName); + const zetaTokenAddress = getAddress("zetaToken", networkName); const Factory = (await ethers.getContractFactory("MultiChainValue")) as MultiChainValue__factory; const contract = (await Factory.deploy(connectorAddress, zetaTokenAddress)) as MultiChainValue; @@ -23,23 +18,21 @@ async function main() { console.log("MultiChainValue deployed to:", contract.address); - if (isZetaTestnet(ZETA_NETWORK)) { - networkName !== "goerli" && - (await (await contract.addAvailableChainId(getChainId("goerli"))).wait().catch((e: any) => console.error(e))); + networkName !== "goerli_testnet" && + (await (await contract.addAvailableChainId(getChainId("goerli_testnet"))) + .wait() + .catch((e: any) => console.error(e))); - networkName !== "polygon-mumbai" && - (await (await contract.addAvailableChainId(getChainId("polygon-mumbai"))) - .wait() - .catch((e: any) => console.error(e))); + networkName !== "mumbai_testnet" && + (await (await contract.addAvailableChainId(getChainId("mumbai_testnet"))) + .wait() + .catch((e: any) => console.error(e))); - networkName !== "bsc-testnet" && - (await (await contract.addAvailableChainId(getChainId("bsc-testnet"))) - .wait() - .catch((e: any) => console.error(e))); + networkName !== "bsc_testnet" && + (await (await contract.addAvailableChainId(getChainId("bsc_testnet"))).wait().catch((e: any) => console.error(e))); - networkName !== "athens" && - (await (await contract.addAvailableChainId(getChainId("athens"))).wait().catch((e: any) => console.error(e))); - } + networkName !== "zeta_testnet" && + (await (await contract.addAvailableChainId(getChainId("zeta_testnet"))).wait().catch((e: any) => console.error(e))); saveAddress("multiChainValue", contract.address); } diff --git a/packages/zeta-app-contracts/scripts/multi-chain-value/deterministic-deploy.ts b/packages/zeta-app-contracts/scripts/multi-chain-value/deterministic-deploy.ts index 42fbbc46..22761b99 100644 --- a/packages/zeta-app-contracts/scripts/multi-chain-value/deterministic-deploy.ts +++ b/packages/zeta-app-contracts/scripts/multi-chain-value/deterministic-deploy.ts @@ -1,19 +1,18 @@ -import { isNetworkName } from "@zetachain/addresses"; -import { saveAddress } from "@zetachain/addresses-tools"; +import { getAddress, isProtocolNetworkName } from "@zetachain/protocol-contracts"; import { BigNumber } from "ethers"; import { ethers, network } from "hardhat"; -import { getAddress } from "../../lib/shared/address.helpers"; import { deployContractToAddress, saltToHex } from "../../lib/shared/ImmutableCreate2Factory.helpers"; import { MultiChainValue__factory } from "../../typechain-types"; +import { saveAddress } from "../address.helpers"; const DEPLOYER_ADDRESS = process.env.DEPLOYER_ADDRESS ?? ""; const SALT_NUMBER = "0"; +const networkName = network.name; + export async function deterministicDeployMultiChainValue() { - if (!isNetworkName(network.name)) { - throw new Error(`network.name: ${network.name} isn't supported.`); - } + if (!isProtocolNetworkName(networkName)) throw new Error("Invalid network name"); const accounts = await ethers.getSigners(); const [signer] = accounts; @@ -21,10 +20,10 @@ export async function deterministicDeployMultiChainValue() { const saltNumber = SALT_NUMBER; const saltStr = BigNumber.from(saltNumber).toHexString(); - const connector = getAddress("connector"); - const zetaToken = getAddress("zetaToken"); + const connector = getAddress("connector", networkName); + const zetaToken = getAddress("zetaToken", networkName); - const immutableCreate2Factory = getAddress("immutableCreate2Factory"); + const immutableCreate2Factory = getAddress("immutableCreate2Factory", networkName); const salthex = saltToHex(saltStr, DEPLOYER_ADDRESS); diff --git a/packages/zeta-app-contracts/scripts/multi-chain-value/send-value.ts b/packages/zeta-app-contracts/scripts/multi-chain-value/send-value.ts index efb1bb41..d5924523 100644 --- a/packages/zeta-app-contracts/scripts/multi-chain-value/send-value.ts +++ b/packages/zeta-app-contracts/scripts/multi-chain-value/send-value.ts @@ -1,26 +1,26 @@ -import { getChainId, isNetworkName, isZetaTestnet, NetworkName } from "@zetachain/addresses"; +import { getAddress, isProtocolNetworkName, ZetaProtocolNetwork } from "@zetachain/protocol-contracts"; import { BigNumber } from "ethers"; import { parseEther } from "ethers/lib/utils"; import { ethers, network } from "hardhat"; import { getMultiChainValue } from "../../lib/multi-chain-value/MultiChainValue.helpers"; -import { getAddress } from "../../lib/shared/address.helpers"; import { getErc20 } from "../../lib/shared/deploy.helpers"; import { MultiChainValue } from "../../typechain-types"; +import { getAppAddress, getChainId } from "../address.helpers"; const networkName = network.name; -const { ZETA_NETWORK } = process.env; const doTranfer = async ( - sourceChain: NetworkName, + sourceChain: ZetaProtocolNetwork, multiChainValueContract: MultiChainValue, chainId: number, amount: BigNumber, destinationAddress: string ) => { + //@ts-ignore if (getChainId(sourceChain) == chainId) return; - if (sourceChain === "athens") { + if (sourceChain === "zeta_testnet") { const tx = await multiChainValueContract.sendZeta(chainId, destinationAddress, { value: amount }); await tx.wait(); return; @@ -31,28 +31,25 @@ const doTranfer = async ( }; const main = async () => { - if (!isNetworkName(networkName)) throw new Error("Invalid network name"); - const multiChainValueContract = await getMultiChainValue(getAddress("multiChainValue")); + if (!isProtocolNetworkName(networkName)) throw new Error("Invalid network name"); + const multiChainValueContract = await getMultiChainValue(getAppAddress("multiChainValue", networkName)); const [signer] = await ethers.getSigners(); const amount = parseEther("1"); - if (networkName !== "athens") { - const zetaToken = await getErc20(getAddress("zetaToken")); + if (networkName !== "zeta_testnet") { + const zetaToken = await getErc20(getAddress("zetaToken", networkName)); const tx = await zetaToken.approve(multiChainValueContract.address, amount.mul(10)); await tx.wait(); } - if (isZetaTestnet(ZETA_NETWORK)) { - const destinationAddress = ethers.utils.solidityPack(["address"], [process.env.PUBLIC_KEY_1 ?? signer.address]); + const destinationAddress = ethers.utils.solidityPack(["address"], [process.env.PUBLIC_KEY_1 ?? signer.address]); - await doTranfer(networkName, multiChainValueContract, getChainId("goerli"), amount, destinationAddress); - // await doTranfer(networkName, multiChainValueContract, getChainId("klaytn-baobab"), amount, destinationAddress); - await doTranfer(networkName, multiChainValueContract, getChainId("polygon-mumbai"), amount, destinationAddress); - await doTranfer(networkName, multiChainValueContract, getChainId("bsc-testnet"), amount, destinationAddress); - await doTranfer(networkName, multiChainValueContract, getChainId("athens"), amount, destinationAddress); - } + await doTranfer(networkName, multiChainValueContract, getChainId("goerli_testnet"), amount, destinationAddress); + await doTranfer(networkName, multiChainValueContract, getChainId("mumbai_testnet"), amount, destinationAddress); + await doTranfer(networkName, multiChainValueContract, getChainId("bsc_testnet"), amount, destinationAddress); + await doTranfer(networkName, multiChainValueContract, getChainId("zeta_testnet"), amount, destinationAddress); }; main().catch(error => { diff --git a/packages/zeta-app-contracts/scripts/multi-chain-value/verify-contract.ts b/packages/zeta-app-contracts/scripts/multi-chain-value/verify-contract.ts index 6b16b1c5..3a0760df 100644 --- a/packages/zeta-app-contracts/scripts/multi-chain-value/verify-contract.ts +++ b/packages/zeta-app-contracts/scripts/multi-chain-value/verify-contract.ts @@ -1,11 +1,17 @@ +import { getAddress, isProtocolNetworkName } from "@zetachain/protocol-contracts"; import hardhat from "hardhat"; +import { network } from "hardhat"; -import { getAddress } from "../../lib/shared/address.helpers"; +import { getAppAddress } from "../address.helpers"; + +const networkName = network.name; async function main() { + if (!isProtocolNetworkName(networkName)) throw new Error("Invalid network name"); + await hardhat.run("verify:verify", { - address: getAddress("multiChainValue"), - constructorArguments: [getAddress("connector"), getAddress("zetaToken")], + address: getAppAddress("multiChainValue", networkName), + constructorArguments: [getAddress("connector", networkName), getAddress("zetaToken", networkName)], contract: "contracts/multi-chain-value/MultiChainValue.sol:MultiChainValue" }); } diff --git a/packages/zevm-example-contracts/contracts/multi-output/ZetaMultiOutput.sol b/packages/zevm-app-contracts/contracts/multi-output/ZetaMultiOutput.sol similarity index 100% rename from packages/zevm-example-contracts/contracts/multi-output/ZetaMultiOutput.sol rename to packages/zevm-app-contracts/contracts/multi-output/ZetaMultiOutput.sol diff --git a/packages/zevm-app-contracts/data/addresses.json b/packages/zevm-app-contracts/data/addresses.json new file mode 100644 index 00000000..d13e9e23 --- /dev/null +++ b/packages/zevm-app-contracts/data/addresses.json @@ -0,0 +1,10 @@ +{ + "zevm": { + "zeta_testnet": { + "disperse": "0x1E0F767F48Fb10FcF820703f116E9B0F87319d63", + "rewardDistributorFactory": "0x667e4C493d40015256BDC89E3ba750B2F90359E1", + "zetaSwap": "0x44D1F1f9289DBA1Cf5824bd667184cEBE020aA1c", + "zetaSwapBtcInbound": "0x008b393933D5CA2457Df570CA5D628380FFf6da4" + } + } +} \ No newline at end of file diff --git a/packages/zevm-app-contracts/hardhat.config.ts b/packages/zevm-app-contracts/hardhat.config.ts index 53562131..d495af66 100644 --- a/packages/zevm-app-contracts/hardhat.config.ts +++ b/packages/zevm-app-contracts/hardhat.config.ts @@ -5,7 +5,7 @@ import "hardhat-gas-reporter"; import "solidity-coverage"; import "tsconfig-paths/register"; -import { getHardhatConfigNetworks, getHardhatConfigScanners } from "@zetachain/addresses-tools/src/networks"; +import { getHardhatConfigNetworks } from "@zetachain/networks"; import * as dotenv from "dotenv"; import type { HardhatUserConfig } from "hardhat/types"; @@ -14,15 +14,22 @@ dotenv.config(); const PRIVATE_KEYS = process.env.PRIVATE_KEY !== undefined ? [`0x${process.env.PRIVATE_KEY}`] : []; const config: HardhatUserConfig = { + //@ts-ignore etherscan: { - ...getHardhatConfigScanners(), + apiKey: { + // BSC + bscTestnet: process.env.BSCSCAN_API_KEY || "", + // ETH + goerli: process.env.ETHERSCAN_API_KEY || "", + mainnet: process.env.ETHERSCAN_API_KEY || "", + }, }, gasReporter: { currency: "USD", enabled: process.env.REPORT_GAS !== undefined, }, networks: { - ...getHardhatConfigNetworks(PRIVATE_KEYS), + ...getHardhatConfigNetworks(), }, solidity: { compilers: [ diff --git a/packages/zevm-app-contracts/package.json b/packages/zevm-app-contracts/package.json index 129277e9..cae9c87e 100644 --- a/packages/zevm-app-contracts/package.json +++ b/packages/zevm-app-contracts/package.json @@ -31,9 +31,8 @@ "dependencies": { "@openzeppelin/contracts": "4.8.3", "@uniswap/v2-periphery": "1.1.0-beta.0", - "@zetachain/addresses": "workspace:^", - "@zetachain/addresses-tools": "workspace:^", - "@zetachain/protocol-contracts": "^2.1.0", + "@zetachain/networks": "^2.4.3", + "@zetachain/protocol-contracts": "^3.0.0", "ethers": "5.6.8" } } diff --git a/packages/zevm-app-contracts/scripts/address.helpers.ts b/packages/zevm-app-contracts/scripts/address.helpers.ts new file mode 100644 index 00000000..e3758887 --- /dev/null +++ b/packages/zevm-app-contracts/scripts/address.helpers.ts @@ -0,0 +1,39 @@ +import { networks } from "@zetachain/networks"; +import { isProtocolNetworkName, ZetaProtocolNetwork } from "@zetachain/protocol-contracts"; +import protocolAddresses from "@zetachain/protocol-contracts/dist/data/addresses.json"; +import { readFileSync, writeFileSync } from "fs"; +import { join } from "path"; + +import addresses from "../data/addresses.json"; + +export const getZEVMAppAddress = (address: string): string => { + return (addresses["zevm"] as any)["zeta_testnet"][address]; +}; + +export const getChainId = (network: ZetaProtocolNetwork): number => { + //@ts-ignore + return networks[network].chain_id; +}; + +export const getGasSymbolByNetwork = (network: ZetaProtocolNetwork): number => { + //@ts-ignore + return networks[network].gas_symbol; +}; + +export const getSystemContractAddress = () => { + return protocolAddresses["zevm"]["zeta_testnet"].systemContract; +}; + +export const saveAddress = (name: string, address: string) => { + const networkName = "zeta_testnet"; + + console.log(`Updating ${name} address on ${networkName}.`); + + const filename = join(__dirname, `./data/addresses.json`); + + const newAddresses = JSON.parse(readFileSync(filename, "utf8")); + + newAddresses["zevm"]["zeta_testnet"][name] = address; + + writeFileSync(filename, JSON.stringify(newAddresses, null, 2)); +}; diff --git a/packages/zevm-app-contracts/scripts/disperse/deploy.ts b/packages/zevm-app-contracts/scripts/disperse/deploy.ts index 8b8a28b7..007390c2 100644 --- a/packages/zevm-app-contracts/scripts/disperse/deploy.ts +++ b/packages/zevm-app-contracts/scripts/disperse/deploy.ts @@ -1,13 +1,13 @@ -import { isNetworkName } from "@zetachain/addresses"; -import { saveAddress } from "@zetachain/addresses-tools"; +import { isProtocolNetworkName } from "@zetachain/protocol-contracts"; import { ethers, network } from "hardhat"; import { Disperse__factory } from "../../typechain-types"; +import { saveAddress } from "../address.helpers"; const networkName = network.name; async function main() { - if (!isNetworkName(networkName)) throw new Error("Invalid network name"); + if (!isProtocolNetworkName(networkName)) throw new Error("Invalid network name"); const DisperseFactory = (await ethers.getContractFactory("Disperse")) as Disperse__factory; diff --git a/packages/zevm-app-contracts/scripts/liquidity-incentives/add-reward.ts b/packages/zevm-app-contracts/scripts/liquidity-incentives/add-reward.ts index f1c987c2..3ebd8dad 100644 --- a/packages/zevm-app-contracts/scripts/liquidity-incentives/add-reward.ts +++ b/packages/zevm-app-contracts/scripts/liquidity-incentives/add-reward.ts @@ -1,8 +1,6 @@ import { BigNumber } from "@ethersproject/bignumber"; import { SignerWithAddress } from "@nomiclabs/hardhat-ethers/signers"; -import { getChainId, isNetworkName, NetworkName } from "@zetachain/addresses"; -import { getAddress } from "@zetachain/addresses"; -import { getSystemContractAddress } from "@zetachain/addresses-tools"; +import { isProtocolNetworkName, ZetaProtocolNetwork } from "@zetachain/protocol-contracts"; import { parseEther } from "ethers/lib/utils"; import { ethers, network } from "hardhat"; @@ -14,6 +12,7 @@ import { SystemContract, SystemContract__factory } from "../../typechain-types"; +import { getChainId, getSystemContractAddress, getZEVMAppAddress } from "../address.helpers"; const SYSTEM_CONTRACT = getSystemContractAddress(); @@ -21,7 +20,7 @@ const networkName = network.name; const REWARD_DURATION = BigNumber.from("604800").mul(8); // 1 week * 8 const REWARDS_AMOUNT = parseEther("500"); -const getZRC20Address = async (systemContract: SystemContract, network: NetworkName) => { +const getZRC20Address = async (systemContract: SystemContract, network: ZetaProtocolNetwork) => { const tokenAddress = await systemContract.gasCoinZRC20ByChainId(getChainId(network)); return tokenAddress; }; @@ -29,7 +28,7 @@ const getZRC20Address = async (systemContract: SystemContract, network: NetworkN const deployRewardByNetwork = async ( deployer: SignerWithAddress, systemContract: SystemContract, - networkName: NetworkName, + networkName: ZetaProtocolNetwork, rewardDistributorFactory: RewardDistributorFactory ) => { const tokenAddress = await getZRC20Address(systemContract, networkName); @@ -78,40 +77,41 @@ const addReward = async ( async function main() { const [deployer] = await ethers.getSigners(); - if (!isNetworkName(networkName)) throw new Error("Invalid network name"); + if (!isProtocolNetworkName(networkName)) throw new Error("Invalid network name"); const systemContract = await SystemContract__factory.connect(SYSTEM_CONTRACT, deployer); - const factoryContractAddress = getAddress({ - address: "rewardDistributorFactory", - networkName: network.name, - zetaNetwork: "athens" - }); + const factoryContractAddress = getZEVMAppAddress("rewardDistributorFactory"); const rewardDistributorFactory = RewardDistributorFactory__factory.connect(factoryContractAddress, deployer); let rewardContractAddress = ""; // @dev: you can write your own address here to add reward to an existing contract // rewardContractAddress = "0x0dee8b6e2d2035a798b67c68d47f941718a62263"; - rewardContractAddress = await deployRewardByNetwork(deployer, systemContract, "goerli", rewardDistributorFactory); + rewardContractAddress = await deployRewardByNetwork( + deployer, + systemContract, + "goerli_testnet", + rewardDistributorFactory + ); await addReward(deployer, systemContract, rewardContractAddress); rewardContractAddress = await deployRewardByNetwork( deployer, systemContract, - "bsc-testnet", + "bsc_testnet", rewardDistributorFactory ); await addReward(deployer, systemContract, rewardContractAddress); rewardContractAddress = await deployRewardByNetwork( deployer, systemContract, - "bitcoin-test", + "btc_testnet", rewardDistributorFactory ); await addReward(deployer, systemContract, rewardContractAddress); rewardContractAddress = await deployRewardByNetwork( deployer, systemContract, - "polygon-mumbai", + "mumbai_testnet", rewardDistributorFactory ); await addReward(deployer, systemContract, rewardContractAddress); diff --git a/packages/zevm-app-contracts/scripts/liquidity-incentives/deploy.ts b/packages/zevm-app-contracts/scripts/liquidity-incentives/deploy.ts index 1dea2854..92f3d0b9 100644 --- a/packages/zevm-app-contracts/scripts/liquidity-incentives/deploy.ts +++ b/packages/zevm-app-contracts/scripts/liquidity-incentives/deploy.ts @@ -1,8 +1,8 @@ -import { isNetworkName } from "@zetachain/addresses"; -import { getSystemContractAddress, saveAddress } from "@zetachain/addresses-tools"; +import { isProtocolNetworkName } from "@zetachain/protocol-contracts"; import { ethers, network } from "hardhat"; import { RewardDistributorFactory__factory, SystemContract__factory } from "../../typechain-types"; +import { getSystemContractAddress, saveAddress } from "../address.helpers"; const networkName = network.name; @@ -10,7 +10,7 @@ const SYSTEM_CONTRACT = getSystemContractAddress(); async function main() { const [deployer] = await ethers.getSigners(); - if (!isNetworkName(networkName)) throw new Error("Invalid network name"); + if (!isProtocolNetworkName(networkName)) throw new Error("Invalid network name"); const systemContract = await SystemContract__factory.connect(SYSTEM_CONTRACT, deployer); const zetaTokenAddress = await systemContract.wZetaContractAddress(); diff --git a/packages/zevm-app-contracts/scripts/liquidity-incentives/read-rewards-data.ts b/packages/zevm-app-contracts/scripts/liquidity-incentives/read-rewards-data.ts index 3095f11c..ee0b4141 100644 --- a/packages/zevm-app-contracts/scripts/liquidity-incentives/read-rewards-data.ts +++ b/packages/zevm-app-contracts/scripts/liquidity-incentives/read-rewards-data.ts @@ -1,8 +1,8 @@ -import { isNetworkName } from "@zetachain/addresses"; -import { getAddress } from "@zetachain/addresses"; +import { isProtocolNetworkName } from "@zetachain/protocol-contracts"; import { ethers, network } from "hardhat"; import { RewardDistributor__factory, RewardDistributorFactory__factory } from "../../typechain-types"; +import { getZEVMAppAddress } from "../address.helpers"; const networkName = network.name; @@ -37,13 +37,9 @@ const readRewardData = async (rewardContractAddress: string) => { async function main() { const [deployer] = await ethers.getSigners(); - if (!isNetworkName(networkName)) throw new Error("Invalid network name"); + if (!isProtocolNetworkName(networkName)) throw new Error("Invalid network name"); - const factoryContractAddress = getAddress({ - address: "rewardDistributorFactory", - networkName: network.name, - zetaNetwork: "athens" - }); + const factoryContractAddress = getZEVMAppAddress("rewardDistributorFactory"); const rewardDistributorFactory = RewardDistributorFactory__factory.connect(factoryContractAddress, deployer); const incentivesContractsLen = await rewardDistributorFactory.incentivesContractsLen(); diff --git a/packages/zevm-app-contracts/scripts/zeta-points/deploy.ts b/packages/zevm-app-contracts/scripts/zeta-points/deploy.ts index d7cefbbe..40c5bf10 100644 --- a/packages/zevm-app-contracts/scripts/zeta-points/deploy.ts +++ b/packages/zevm-app-contracts/scripts/zeta-points/deploy.ts @@ -1,8 +1,8 @@ -import { isNetworkName } from "@zetachain/addresses"; -import { saveAddress } from "@zetachain/addresses-tools"; +import { isProtocolNetworkName } from "@zetachain/protocol-contracts"; import { ethers, network } from "hardhat"; -import { InvitationManager__factory, UserVerificationRegistry__factory } from "../../typechain-types"; +import { InvitationManager__factory } from "../../typechain-types"; +import { saveAddress } from "../address.helpers"; const networkName = network.name; @@ -11,12 +11,13 @@ const invitationManager = async () => { const invitationManager = await InvitationManagerFactory.deploy(); await invitationManager.deployed(); + console.log("InvitationManager deployed to:", invitationManager.address); - // saveAddress("invitationManager", invitationManager.address); + saveAddress("invitationManager", invitationManager.address); }; const main = async () => { - if (!isNetworkName(networkName)) throw new Error("Invalid network name"); + if (!isProtocolNetworkName(networkName)) throw new Error("Invalid network name"); await invitationManager(); }; diff --git a/packages/zevm-app-contracts/scripts/zeta-swap/deploy.ts b/packages/zevm-app-contracts/scripts/zeta-swap/deploy.ts index 292ed069..b1ee2c23 100644 --- a/packages/zevm-app-contracts/scripts/zeta-swap/deploy.ts +++ b/packages/zevm-app-contracts/scripts/zeta-swap/deploy.ts @@ -1,7 +1,7 @@ -import { getSystemContractAddress, saveAddress } from "@zetachain/addresses-tools"; import { ethers } from "hardhat"; import { ZetaSwap, ZetaSwap__factory, ZetaSwapBtcInbound, ZetaSwapBtcInbound__factory } from "../../typechain-types"; +import { getSystemContractAddress, saveAddress } from "../address.helpers"; const main = async () => { console.log(`Deploying ZetaSwap...`); diff --git a/packages/zevm-app-contracts/scripts/zeta-swap/get-system-data.ts b/packages/zevm-app-contracts/scripts/zeta-swap/get-system-data.ts index 2e7db88c..63a64072 100644 --- a/packages/zevm-app-contracts/scripts/zeta-swap/get-system-data.ts +++ b/packages/zevm-app-contracts/scripts/zeta-swap/get-system-data.ts @@ -1,11 +1,10 @@ -import { getChainId } from "@zetachain/addresses"; -import { NetworkName } from "@zetachain/addresses"; -import { getGasSymbolByNetwork, getSystemContractAddress } from "@zetachain/addresses-tools"; +import { ZetaProtocolNetwork } from "@zetachain/protocol-contracts"; import { ethers } from "hardhat"; import { SystemContract, SystemContract__factory } from "../../typechain-types"; +import { getChainId, getGasSymbolByNetwork, getSystemContractAddress } from "../address.helpers"; -const getZRC20Address = async (systemContract: SystemContract, network: NetworkName) => { +const getZRC20Address = async (systemContract: SystemContract, network: ZetaProtocolNetwork) => { const tokenAddress = await systemContract.gasCoinZRC20ByChainId(getChainId(network)); console.log(`${getGasSymbolByNetwork(network)}`, tokenAddress); const tokenAddressLP = await systemContract.gasZetaPoolByChainId(getChainId(network)); @@ -25,11 +24,11 @@ async function main() { const WZETAAddress = await systemContract.wZetaContractAddress(); console.log(`WZETA:`, WZETAAddress); - await getZRC20Address(systemContract, "bitcoin-test"); - await getZRC20Address(systemContract, "goerli"); - await getZRC20Address(systemContract, "klaytn-baobab"); - await getZRC20Address(systemContract, "bsc-testnet"); - await getZRC20Address(systemContract, "polygon-mumbai"); + await getZRC20Address(systemContract, "btc_testnet"); + await getZRC20Address(systemContract, "goerli_testnet"); + // await getZRC20Address(systemContract, "klaytn-baobab"); + await getZRC20Address(systemContract, "bsc_testnet"); + await getZRC20Address(systemContract, "mumbai_testnet"); } main() diff --git a/packages/zevm-app-contracts/scripts/zeta-swap/send.ts b/packages/zevm-app-contracts/scripts/zeta-swap/send.ts index 56e46fe9..bf95f9f2 100644 --- a/packages/zevm-app-contracts/scripts/zeta-swap/send.ts +++ b/packages/zevm-app-contracts/scripts/zeta-swap/send.ts @@ -1,18 +1,15 @@ import { parseEther } from "@ethersproject/units"; -import { getAddress } from "@zetachain/addresses"; +import { getAddress, isProtocolNetworkName } from "@zetachain/protocol-contracts"; import { ethers } from "hardhat"; import { network } from "hardhat"; const main = async () => { + if (!isProtocolNetworkName(network.name)) throw new Error("Invalid network name"); console.log(`Sending native token...`); const [signer] = await ethers.getSigners(); - const tssAddress = getAddress({ - address: "tss", - networkName: network.name, - zetaNetwork: "athens" - }); + const tssAddress = getAddress("tss", network.name); const tx = await signer.sendTransaction({ to: tssAddress, diff --git a/packages/zevm-app-contracts/scripts/zeta-swap/swap-on-zevm.ts b/packages/zevm-app-contracts/scripts/zeta-swap/swap-on-zevm.ts index 14d660c9..f72149e5 100644 --- a/packages/zevm-app-contracts/scripts/zeta-swap/swap-on-zevm.ts +++ b/packages/zevm-app-contracts/scripts/zeta-swap/swap-on-zevm.ts @@ -1,29 +1,25 @@ import { BigNumber } from "@ethersproject/bignumber"; import { parseUnits } from "@ethersproject/units"; -import { getAddress, isZetaNetworkName } from "@zetachain/addresses"; -import { getZRC20Address } from "@zetachain/addresses-tools"; +import { getZRC20Address, isProtocolNetworkName } from "@zetachain/protocol-contracts"; import { ethers } from "hardhat"; import { network } from "hardhat"; import { ERC20__factory, ZetaSwap__factory, ZetaSwapBtcInbound__factory } from "../../typechain-types"; +import { getZEVMAppAddress } from "../address.helpers"; import { getSwapParams } from "./helpers"; +const networkName = network.name; const USE_BTC_SWAP = true; const SAMPLE_MEMO = "0x25A92a5853702F199bb2d805Bba05d67025214A800000005"; // 0xADDRESS + FFFF chain id (05 for goerli) const main = async () => { - if (!isZetaNetworkName(network.name) || !network.name) throw new Error("Invalid network name"); + if (!isProtocolNetworkName(networkName)) throw new Error("Invalid network name"); const [signer] = await ethers.getSigners(); - const ZRC20Addresses = getZRC20Address(); - const zetaSwap = getAddress({ - address: USE_BTC_SWAP ? "zetaSwapBtcInbound" : "zetaSwap", - networkName: "athens", - zetaNetwork: "athens" - }); + const zetaSwap = getZEVMAppAddress(USE_BTC_SWAP ? "zetaSwapBtcInbound" : "zetaSwap"); const amount = parseUnits("0.00001", 8); - const sourceToken = ZRC20Addresses["tBTC"]; + const sourceToken = getZRC20Address("btc_testnet"); const zrc20Contract = ERC20__factory.connect(sourceToken, signer); const tx0 = await zrc20Contract.transfer(zetaSwap, amount); @@ -38,7 +34,7 @@ const main = async () => { params = ethers.utils.arrayify(SAMPLE_MEMO); zetaSwapContract = ZetaSwapBtcInbound__factory.connect(zetaSwap, signer); } else { - params = getSwapParams(signer.address, ZRC20Addresses["gETH"], BigNumber.from("0")); + params = getSwapParams(signer.address, getZRC20Address("goerli_testnet"), BigNumber.from("0")); zetaSwapContract = ZetaSwap__factory.connect(zetaSwap, signer); } const tx1 = await zetaSwapContract.onCrossChainCall(sourceToken, amount, params); diff --git a/packages/zevm-app-contracts/scripts/zeta-swap/swap.ts b/packages/zevm-app-contracts/scripts/zeta-swap/swap.ts index 970af04c..cc315cf0 100644 --- a/packages/zevm-app-contracts/scripts/zeta-swap/swap.ts +++ b/packages/zevm-app-contracts/scripts/zeta-swap/swap.ts @@ -1,33 +1,24 @@ import { BigNumber } from "@ethersproject/bignumber"; import { parseEther } from "@ethersproject/units"; -import { getAddress, isNetworkName } from "@zetachain/addresses"; -import { getZRC20Address } from "@zetachain/addresses-tools"; -import { ethers } from "hardhat"; -import { network } from "hardhat"; +import { getAddress, getZRC20Address, isProtocolNetworkName } from "@zetachain/protocol-contracts"; +import { ethers, network } from "hardhat"; +import { getZEVMAppAddress } from "../address.helpers"; import { getSwapData } from "./helpers"; const main = async () => { - if (!isNetworkName(network.name) || !network.name) throw new Error("Invalid network name"); - const ZRC20Addresses = getZRC20Address(); + if (!isProtocolNetworkName(network.name)) throw new Error("Invalid network name"); - const destinationToken = network.name == "goerli" ? ZRC20Addresses["tMATIC"] : ZRC20Addresses["gETH"]; + const destinationToken = + network.name == "goerli_testnet" ? getZRC20Address("mumbai_testnet") : getZRC20Address("goerli_testnet"); console.log(`Swapping native token...`); const [signer] = await ethers.getSigners(); - const zetaSwapAddress = getAddress({ - address: "zetaSwap", - networkName: "athens", - zetaNetwork: "athens" - }); + const zetaSwapAddress = getZEVMAppAddress("zetaSwap"); - const tssAddress = getAddress({ - address: "tss", - networkName: network.name, - zetaNetwork: "athens" - }); + const tssAddress = getAddress("tss", network.name); const data = getSwapData(zetaSwapAddress, signer.address, destinationToken, BigNumber.from("0")); diff --git a/packages/zevm-app-contracts/test/LiquidityIncentives.spec.ts b/packages/zevm-app-contracts/test/LiquidityIncentives.spec.ts index 743460f8..28892388 100644 --- a/packages/zevm-app-contracts/test/LiquidityIncentives.spec.ts +++ b/packages/zevm-app-contracts/test/LiquidityIncentives.spec.ts @@ -2,7 +2,7 @@ import { BigNumber } from "@ethersproject/bignumber"; import { AddressZero } from "@ethersproject/constants"; import { parseUnits } from "@ethersproject/units"; import { SignerWithAddress } from "@nomiclabs/hardhat-ethers/signers"; -import { getAddress as getAddressLib } from "@zetachain/addresses"; +import { getNonZetaAddress } from "@zetachain/protocol-contracts"; import { expect } from "chai"; import { parseEther } from "ethers/lib/utils"; import { ethers, network } from "hardhat"; @@ -52,23 +52,11 @@ describe("LiquidityIncentives tests", () => { await network.provider.send("hardhat_setBalance", [deployer.address, parseUnits("1000000").toHexString()]); - const uniswapRouterAddr = getAddressLib({ - address: "uniswapV2Router02", - networkName: "eth-mainnet", - zetaNetwork: "mainnet" - }); + const uniswapRouterAddr = getNonZetaAddress("uniswapV2Router02", "eth_mainnet"); - const uniswapFactoryAddr = getAddressLib({ - address: "uniswapV2Factory", - networkName: "eth-mainnet", - zetaNetwork: "mainnet" - }); + const uniswapFactoryAddr = "0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f"; // getNonZetaAddress("uniswapV2Factory02", "etherum_mainnet"); - const wGasToken = getAddressLib({ - address: "weth9", - networkName: "eth-mainnet", - zetaNetwork: "mainnet" - }); + const wGasToken = getNonZetaAddress("weth9", "eth_mainnet"); ZETA = (await ethers.getContractAt("IWETH", wGasToken)) as IWETH; ZETA_ERC20 = (await ethers.getContractAt("ERC20", wGasToken)) as ERC20; diff --git a/packages/zevm-example-contracts/test/MultipleOutput.spec.ts b/packages/zevm-app-contracts/test/MultipleOutput.spec.ts similarity index 89% rename from packages/zevm-example-contracts/test/MultipleOutput.spec.ts rename to packages/zevm-app-contracts/test/MultipleOutput.spec.ts index 0d5be5bb..70b0d4ec 100644 --- a/packages/zevm-example-contracts/test/MultipleOutput.spec.ts +++ b/packages/zevm-app-contracts/test/MultipleOutput.spec.ts @@ -1,6 +1,6 @@ import { parseUnits } from "@ethersproject/units"; import { SignerWithAddress } from "@nomiclabs/hardhat-ethers/signers"; -import { getAddress as getAddressLib } from "@zetachain/addresses"; +import { getNonZetaAddress } from "@zetachain/protocol-contracts"; import { expect } from "chai"; import { ethers, network } from "hardhat"; @@ -22,23 +22,11 @@ describe("ZetaSwap tests", () => { await network.provider.send("hardhat_setBalance", [deployer.address, parseUnits("1000000").toHexString()]); - const uniswapRouterAddr = getAddressLib({ - address: "uniswapV2Router02", - networkName: "eth-mainnet", - zetaNetwork: "mainnet" - }); + const uniswapRouterAddr = getNonZetaAddress("uniswapV2Router02", "eth_mainnet"); - const uniswapFactoryAddr = getAddressLib({ - address: "uniswapV2Factory", - networkName: "eth-mainnet", - zetaNetwork: "mainnet" - }); + const uniswapFactoryAddr = "0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f"; // getNonZetaAddress("uniswapV2Factory02", "etherum_mainnet"); - const wGasToken = getAddressLib({ - address: "weth9", - networkName: "eth-mainnet", - zetaNetwork: "mainnet" - }); + const wGasToken = getNonZetaAddress("weth9", "eth_mainnet"); const evmSetupResult = await evmSetup(wGasToken, uniswapFactoryAddr, uniswapRouterAddr); ZRC20Contracts = evmSetupResult.ZRC20Contracts; diff --git a/packages/zevm-app-contracts/test/Swap.spec.ts b/packages/zevm-app-contracts/test/Swap.spec.ts index 355b2f85..97b05346 100644 --- a/packages/zevm-app-contracts/test/Swap.spec.ts +++ b/packages/zevm-app-contracts/test/Swap.spec.ts @@ -1,11 +1,10 @@ import { BigNumber } from "@ethersproject/bignumber"; import { parseUnits } from "@ethersproject/units"; import { SignerWithAddress } from "@nomiclabs/hardhat-ethers/signers"; -import { getAddress as getAddressLib } from "@zetachain/addresses"; +import { getNonZetaAddress } from "@zetachain/protocol-contracts"; import { expect } from "chai"; import { ethers, network } from "hardhat"; -import { evmSetup } from "../../zevm-example-contracts/test/test.helpers"; import { MockSystemContract, MockZRC20, @@ -15,6 +14,7 @@ import { ZetaSwapBtcInbound__factory } from "../../zevm-example-contracts/typechain-types"; import { getBitcoinTxMemoForTest, getSwapParams } from "../scripts/zeta-swap/helpers"; +import { evmSetup } from "./test.helpers"; describe("ZetaSwap tests", () => { let zetaSwapContract: ZetaSwap; @@ -31,23 +31,11 @@ describe("ZetaSwap tests", () => { await network.provider.send("hardhat_setBalance", [deployer.address, parseUnits("1000000").toHexString()]); - const uniswapRouterAddr = getAddressLib({ - address: "uniswapV2Router02", - networkName: "eth-mainnet", - zetaNetwork: "mainnet" - }); + const uniswapRouterAddr = getNonZetaAddress("uniswapV2Router02", "eth_mainnet"); - const uniswapFactoryAddr = getAddressLib({ - address: "uniswapV2Factory", - networkName: "eth-mainnet", - zetaNetwork: "mainnet" - }); + const uniswapFactoryAddr = "0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f"; // getNonZetaAddress("uniswapV2Factory02", "etherum_mainnet"); - const wGasToken = getAddressLib({ - address: "weth9", - networkName: "eth-mainnet", - zetaNetwork: "mainnet" - }); + const wGasToken = getNonZetaAddress("weth9", "eth_mainnet"); const evmSetupResult = await evmSetup(wGasToken, uniswapFactoryAddr, uniswapRouterAddr); ZRC20Contracts = evmSetupResult.ZRC20Contracts; diff --git a/packages/zevm-example-contracts/.env.example b/packages/zevm-example-contracts/.env.example deleted file mode 100644 index d53e3d1a..00000000 --- a/packages/zevm-example-contracts/.env.example +++ /dev/null @@ -1,2 +0,0 @@ -ALCHEMY_API_KEY_MAINNET= -ALCHEMY_API_KEY_GOERLI= \ No newline at end of file diff --git a/packages/zevm-example-contracts/.eslintrc.js b/packages/zevm-example-contracts/.eslintrc.js deleted file mode 100644 index 77b8f69a..00000000 --- a/packages/zevm-example-contracts/.eslintrc.js +++ /dev/null @@ -1,23 +0,0 @@ -const path = require("path"); - -const OFF = 0; - -module.exports = { - env: { - browser: false, - es2021: true, - mocha: true, - node: true, - }, - extends: ["../../.eslintrc.js"], - rules: { - "no-console": OFF, - }, - settings: { - "import/resolver": { - typescript: { - project: path.join(__dirname, "tsconfig.json"), - }, - }, - }, -}; diff --git a/packages/zevm-example-contracts/README.md b/packages/zevm-example-contracts/README.md deleted file mode 100644 index 84728dbb..00000000 --- a/packages/zevm-example-contracts/README.md +++ /dev/null @@ -1,16 +0,0 @@ -# ZetaEVM Example contracts - -> ⚠️ The contracts **are not audited yet**, use at your own risk. - -## Environment variables - -Follow the template in `.env.example`. - -* The private key should **not** include `0x`. -* To verify your contracts, you'll need api keys both in BSCScan and Etherscan. - -## Running Tests - -```bash - yarn test -``` diff --git a/packages/zevm-example-contracts/contracts/shared/BytesHelperLib.sol b/packages/zevm-example-contracts/contracts/shared/BytesHelperLib.sol deleted file mode 100644 index 122de889..00000000 --- a/packages/zevm-example-contracts/contracts/shared/BytesHelperLib.sol +++ /dev/null @@ -1,22 +0,0 @@ -// SPDX-License-Identifier: UNLICENSED -pragma solidity =0.8.7; - -library BytesHelperLib { - function bytesToAddress(bytes calldata data, uint256 offset) internal pure returns (address output) { - bytes memory b = data[offset:offset + 20]; - assembly { - output := mload(add(b, 20)) - } - } - - function bytesToUint32(bytes calldata data, uint256 offset) internal pure returns (uint32 output) { - bytes memory b = data[offset:offset + 4]; - assembly { - output := mload(add(b, 4)) - } - } - - function addressToBytes(address someAddress) internal pure returns (bytes32) { - return bytes32(uint256(uint160(someAddress))); - } -} diff --git a/packages/zevm-example-contracts/contracts/shared/MockSystemContract.sol b/packages/zevm-example-contracts/contracts/shared/MockSystemContract.sol deleted file mode 100644 index 0687e73a..00000000 --- a/packages/zevm-example-contracts/contracts/shared/MockSystemContract.sol +++ /dev/null @@ -1,60 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity 0.8.7; - -import "@zetachain/protocol-contracts/contracts/zevm/interfaces/zContract.sol"; -import "@zetachain/protocol-contracts/contracts/zevm/interfaces/IZRC20.sol"; - -interface SystemContractErrors { - error CallerIsNotFungibleModule(); - - error InvalidTarget(); - - error CantBeIdenticalAddresses(); - - error CantBeZeroAddress(); -} - -contract MockSystemContract is SystemContractErrors { - mapping(uint256 => uint256) public gasPriceByChainId; - mapping(uint256 => address) public gasCoinZRC20ByChainId; - mapping(uint256 => address) public gasZetaPoolByChainId; - - address public wZetaContractAddress; - address public uniswapv2FactoryAddress; - address public uniswapv2Router02Address; - - event SystemContractDeployed(); - event SetGasPrice(uint256, uint256); - event SetGasCoin(uint256, address); - event SetGasZetaPool(uint256, address); - event SetWZeta(address); - - constructor(address wzeta_, address uniswapv2Factory_, address uniswapv2Router02_) { - wZetaContractAddress = wzeta_; - uniswapv2FactoryAddress = uniswapv2Factory_; - uniswapv2Router02Address = uniswapv2Router02_; - emit SystemContractDeployed(); - } - - // fungible module updates the gas price oracle periodically - function setGasPrice(uint256 chainID, uint256 price) external { - gasPriceByChainId[chainID] = price; - emit SetGasPrice(chainID, price); - } - - function setGasCoinZRC20(uint256 chainID, address zrc20) external { - gasCoinZRC20ByChainId[chainID] = zrc20; - emit SetGasCoin(chainID, zrc20); - } - - function setWZETAContractAddress(address addr) external { - wZetaContractAddress = addr; - emit SetWZeta(wZetaContractAddress); - } - - function onCrossChainCall(address target, address zrc20, uint256 amount, bytes calldata message) external { - zContext memory context = zContext({sender: msg.sender, origin: "", chainID: block.chainid}); - IZRC20(zrc20).transfer(target, amount); - zContract(target).onCrossChainCall(context, zrc20, amount, message); - } -} diff --git a/packages/zevm-example-contracts/contracts/shared/MockZRC20.sol b/packages/zevm-example-contracts/contracts/shared/MockZRC20.sol deleted file mode 100644 index 49f5f334..00000000 --- a/packages/zevm-example-contracts/contracts/shared/MockZRC20.sol +++ /dev/null @@ -1,33 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity =0.8.7; - -import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; -import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; - -import "./BytesHelperLib.sol"; - -contract MockZRC20 is ERC20 { - constructor(uint256 initialSupply, string memory name, string memory symbol) ERC20(name, symbol) { - _mint(msg.sender, initialSupply * (10 ** uint256(decimals()))); - } - - function deposit(address to, uint256 amount) external returns (bool) { - return true; - } - - function bytesToAddress(bytes calldata data, uint256 offset, uint256 size) public pure returns (address output) { - bytes memory b = data[offset:offset + size]; - assembly { - output := mload(add(b, size)) - } - } - - function withdraw(bytes calldata to, uint256 amount) external returns (bool) { - address toAddress = BytesHelperLib.bytesToAddress(to, 12); - return transfer(toAddress, amount); - } - - function withdrawGasFee() external view returns (address, uint256) { - return (address(this), 0); - } -} diff --git a/packages/zevm-example-contracts/contracts/shared/SwapHelperLib.sol b/packages/zevm-example-contracts/contracts/shared/SwapHelperLib.sol deleted file mode 100644 index 59f18880..00000000 --- a/packages/zevm-example-contracts/contracts/shared/SwapHelperLib.sol +++ /dev/null @@ -1,93 +0,0 @@ -// SPDX-License-Identifier: UNLICENSED -pragma solidity =0.8.7; - -import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol"; -import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol"; -import "@zetachain/protocol-contracts/contracts/zevm/interfaces/IZRC20.sol"; - -library SwapHelperLib { - uint16 internal constant MAX_DEADLINE = 200; - - error WrongGasContract(); - - error NotEnoughToPayGasFee(); - - error CantBeIdenticalAddresses(); - - error CantBeZeroAddress(); - - // returns sorted token addresses, used to handle return values from pairs sorted in this order - function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { - if (tokenA == tokenB) revert CantBeIdenticalAddresses(); - (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); - if (token0 == address(0)) revert CantBeZeroAddress(); - } - - // calculates the CREATE2 address for a pair without making any external calls - function uniswapv2PairFor(address factory, address tokenA, address tokenB) public pure returns (address pair) { - (address token0, address token1) = sortTokens(tokenA, tokenB); - pair = address( - uint160( - uint256( - keccak256( - abi.encodePacked( - hex"ff", - factory, - keccak256(abi.encodePacked(token0, token1)), - hex"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f" // init code hash - ) - ) - ) - ) - ); - } - - function _doWithdrawal(address targetZRC20, uint256 amount, bytes32 receipient) internal { - (address gasZRC20, uint256 gasFee) = IZRC20(targetZRC20).withdrawGasFee(); - - if (gasZRC20 != targetZRC20) revert WrongGasContract(); - if (gasFee >= amount) revert NotEnoughToPayGasFee(); - - IZRC20(targetZRC20).approve(targetZRC20, gasFee); - IZRC20(targetZRC20).withdraw(abi.encodePacked(receipient), amount - gasFee); - } - - function _existsPairPool(address uniswapV2Factory, address zrc20A, address zrc20B) internal view returns (bool) { - address uniswapPool = uniswapv2PairFor(uniswapV2Factory, zrc20A, zrc20B); - return IZRC20(zrc20A).balanceOf(uniswapPool) > 0 && IZRC20(zrc20B).balanceOf(uniswapPool) > 0; - } - - function _doSwap( - address zetaToken, - address uniswapV2Factory, - address uniswapV2Router, - address zrc20, - uint256 amount, - address targetZRC20, - uint256 minAmountOut - ) internal returns (uint256) { - bool existsPairPool = _existsPairPool(uniswapV2Factory, zrc20, targetZRC20); - - address[] memory path; - if (existsPairPool) { - path = new address[](2); - path[0] = zrc20; - path[1] = targetZRC20; - } else { - path = new address[](3); - path[0] = zrc20; - path[1] = zetaToken; - path[2] = targetZRC20; - } - - IZRC20(zrc20).approve(address(uniswapV2Router), amount); - uint256[] memory amounts = IUniswapV2Router01(uniswapV2Router).swapExactTokensForTokens( - amount, - minAmountOut, - path, - address(this), - block.timestamp + MAX_DEADLINE - ); - return amounts[path.length - 1]; - } -} diff --git a/packages/zevm-example-contracts/contracts/shared/TestContracts.sol b/packages/zevm-example-contracts/contracts/shared/TestContracts.sol deleted file mode 100644 index 2c222aa8..00000000 --- a/packages/zevm-example-contracts/contracts/shared/TestContracts.sol +++ /dev/null @@ -1,8 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity 0.8.7; - -/** - * @dev Contracts that need to be compiled for testing purposes - */ - -import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; diff --git a/packages/zevm-example-contracts/contracts/shared/TestUniswapContracts.sol b/packages/zevm-example-contracts/contracts/shared/TestUniswapContracts.sol deleted file mode 100644 index 53520a08..00000000 --- a/packages/zevm-example-contracts/contracts/shared/TestUniswapContracts.sol +++ /dev/null @@ -1,10 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity 0.6.6; - -/** - * @dev Contracts that need to be compiled for testing purposes - */ - -import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol"; -import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; -import "@uniswap/v2-periphery/contracts/UniswapV2Router02.sol"; diff --git a/packages/zevm-example-contracts/hardhat.config.ts b/packages/zevm-example-contracts/hardhat.config.ts deleted file mode 100644 index 53562131..00000000 --- a/packages/zevm-example-contracts/hardhat.config.ts +++ /dev/null @@ -1,46 +0,0 @@ -import "@nomiclabs/hardhat-etherscan"; -import "@nomiclabs/hardhat-waffle"; -import "@typechain/hardhat"; -import "hardhat-gas-reporter"; -import "solidity-coverage"; -import "tsconfig-paths/register"; - -import { getHardhatConfigNetworks, getHardhatConfigScanners } from "@zetachain/addresses-tools/src/networks"; -import * as dotenv from "dotenv"; -import type { HardhatUserConfig } from "hardhat/types"; - -dotenv.config(); - -const PRIVATE_KEYS = process.env.PRIVATE_KEY !== undefined ? [`0x${process.env.PRIVATE_KEY}`] : []; - -const config: HardhatUserConfig = { - etherscan: { - ...getHardhatConfigScanners(), - }, - gasReporter: { - currency: "USD", - enabled: process.env.REPORT_GAS !== undefined, - }, - networks: { - ...getHardhatConfigNetworks(PRIVATE_KEYS), - }, - solidity: { - compilers: [ - { version: "0.5.10" /** For create2 factory */ }, - { version: "0.6.6" /** For uniswap v2 */ }, - { version: "0.8.7" }, - ], - settings: { - /** - * @see {@link https://smock.readthedocs.io/en/latest/getting-started.html} - */ - outputSelection: { - "*": { - "*": ["storageLayout"], - }, - }, - }, - }, -}; - -export default config; diff --git a/packages/zevm-example-contracts/package.json b/packages/zevm-example-contracts/package.json deleted file mode 100644 index 1a91e45d..00000000 --- a/packages/zevm-example-contracts/package.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "name": "@zetachain/zevm-example-contracts", - "version": "0.0.1", - "license": "MIT", - "author": "zetachain", - "publishConfig": { - "access": "public", - "registry": "https://registry.npmjs.org/" - }, - "scripts": { - "clean": "npx hardhat clean", - "compile": "npx hardhat compile", - "prepublishOnly": "echo 'This package has no prepublishOnly tasks.'", - "multi-chain-swap:deploy-local": "ZETA_NETWORK=troy EXECUTE_PROGRAMMATICALLY=true npx hardhat run scripts/multi-chain-swap/deploy.ts --network hardhat", - "multi-chain-swap:deploy": "ZETA_NETWORK=athens EXECUTE_PROGRAMMATICALLY=true npx hardhat run scripts/multi-chain-swap/deploy.ts", - "lint:fix": "npm run lint:js:fix && npm run lint:sol:fix", - "lint:js:fix": "eslint --ext .js,.ts . --fix", - "lint:js": "eslint --ext .js,.ts .", - "lint:sol:fix": "prettier --write \"contracts/**/*.sol\"", - "lint:sol": "solhint 'contracts/**/*.sol' && prettier -c 'contracts/**/*.sol'", - "lint": "npm run lint:js && npm run lint:sol", - "test:watch": "echo You need to install `entr` to run this command && find contracts/**/** lib/**/** test/**/** -iname '*.sol' -o -iname '*.ts' | entr -cnr npx hardhat test", - "test": "npx hardhat test", - "tsc:watch": "npx tsc --watch" - }, - "devDependencies": { - "hardhat-gas-reporter": "^1.0.8", - "solidity-coverage": "^0.7.20", - "tsconfig-paths": "^3.14.1" - }, - "dependencies": { - "@openzeppelin/contracts": "^4.8.3", - "@uniswap/v2-periphery": "1.1.0-beta.0", - "@zetachain/addresses": "workspace:^", - "@zetachain/addresses-tools": "workspace:^", - "@zetachain/protocol-contracts": "^2.1.0", - "ethers": "5.6.8" - } -} diff --git a/packages/zevm-example-contracts/scripts/multi-output/deploy.ts b/packages/zevm-example-contracts/scripts/multi-output/deploy.ts deleted file mode 100644 index 63847095..00000000 --- a/packages/zevm-example-contracts/scripts/multi-output/deploy.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { getSystemContractAddress } from "@zetachain/addresses-tools"; -import { ethers } from "hardhat"; - -import { ZetaMultiOutput, ZetaMultiOutput__factory } from "../../typechain-types"; - -const main = async () => { - console.log(`Deploying MultiOutput...`); - const SYSTEM_CONTRACT = getSystemContractAddress(); - - const Factory = (await ethers.getContractFactory("ZetaMultiOutput")) as ZetaMultiOutput__factory; - const contract = (await Factory.deploy(SYSTEM_CONTRACT)) as ZetaMultiOutput; - await contract.deployed(); - - console.log("Deployed MultiOutput. Address:", contract.address); -}; - -main().catch(error => { - console.error(error); - process.exit(1); -}); diff --git a/packages/zevm-example-contracts/test/test.helpers.ts b/packages/zevm-example-contracts/test/test.helpers.ts deleted file mode 100644 index 2cb1ae33..00000000 --- a/packages/zevm-example-contracts/test/test.helpers.ts +++ /dev/null @@ -1,71 +0,0 @@ -import { MaxUint256 } from "@ethersproject/constants"; -import { parseUnits } from "@ethersproject/units"; -import { SignerWithAddress } from "@nomiclabs/hardhat-ethers/signers"; -import { ethers } from "hardhat"; - -import { - MockSystemContract, - MockSystemContract__factory, - MockZRC20, - MockZRC20__factory, - UniswapV2Router02__factory -} from "../typechain-types"; - -const addZetaEthLiquidity = async (signer: SignerWithAddress, token: MockZRC20, uniswapRouterAddr: string) => { - const block = await ethers.provider.getBlock("latest"); - - const tx1 = await token.approve(uniswapRouterAddr, MaxUint256); - await tx1.wait(); - - const uniswapRouterFork = UniswapV2Router02__factory.connect(uniswapRouterAddr, signer); - - const tx2 = await uniswapRouterFork.addLiquidityETH( - token.address, - parseUnits("1000"), - 0, - 0, - signer.address, - block.timestamp + 360, - { value: parseUnits("1000") } - ); - await tx2.wait(); -}; - -interface EvmSetupResult { - ZRC20Contracts: MockZRC20[]; - systemContract: MockSystemContract; -} - -export const evmSetup = async ( - wGasToken: string, - uniswapFactoryAddr: string, - uniswapRouterAddr: string -): Promise => { - const [signer] = await ethers.getSigners(); - - const ZRC20Factory = (await ethers.getContractFactory("MockZRC20")) as MockZRC20__factory; - - const token1Contract = (await ZRC20Factory.deploy(parseUnits("1000000"), "tBNB", "tBNB")) as MockZRC20; - const token2Contract = (await ZRC20Factory.deploy(parseUnits("1000000"), "gETH", "gETH")) as MockZRC20; - const token3Contract = (await ZRC20Factory.deploy(parseUnits("1000000"), "tMATIC", "tMATIC")) as MockZRC20; - - const ZRC20Contracts = [token1Contract, token2Contract, token3Contract]; - - const SystemContractFactory = (await ethers.getContractFactory("MockSystemContract")) as MockSystemContract__factory; - - const systemContract = (await SystemContractFactory.deploy( - wGasToken, - uniswapFactoryAddr, - uniswapRouterAddr - )) as MockSystemContract; - - await systemContract.setGasCoinZRC20(97, ZRC20Contracts[0].address); - await systemContract.setGasCoinZRC20(5, ZRC20Contracts[1].address); - await systemContract.setGasCoinZRC20(80001, ZRC20Contracts[2].address); - - await addZetaEthLiquidity(signer, ZRC20Contracts[0], uniswapRouterAddr); - await addZetaEthLiquidity(signer, ZRC20Contracts[1], uniswapRouterAddr); - await addZetaEthLiquidity(signer, ZRC20Contracts[2], uniswapRouterAddr); - - return { ZRC20Contracts, systemContract }; -}; diff --git a/packages/zevm-example-contracts/tsconfig.json b/packages/zevm-example-contracts/tsconfig.json deleted file mode 100644 index 355cfda5..00000000 --- a/packages/zevm-example-contracts/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "extends": "../../tsconfig.json", - "include": ["./scripts", "./lib", "./test", "./tests", "./typechain", "./**/*.json", "typechain-types"], - "exclude": ["artifacts", "cache"], - "files": ["./hardhat.config.ts"], - "compilerOptions": { - "baseUrl": ".", - "paths": { - "@zetachain/addresses": ["../addresses/src/index"], - "@zetachain/addresses/*": ["../addresses/src/*"], - "@zetachain/interfaces": ["../interfaces/src/index"] - } - } -} diff --git a/yarn.lock b/yarn.lock index b95cdf61..d4c1af80 100644 --- a/yarn.lock +++ b/yarn.lock @@ -308,13 +308,6 @@ __metadata: languageName: node linkType: hard -"@esbuild/linux-loong64@npm:0.15.7": - version: 0.15.7 - resolution: "@esbuild/linux-loong64@npm:0.15.7" - conditions: os=linux & cpu=loong64 - languageName: node - linkType: hard - "@eslint/eslintrc@npm:^1.2.1": version: 1.2.1 resolution: "@eslint/eslintrc@npm:1.2.1" @@ -1310,58 +1303,6 @@ __metadata: languageName: node linkType: hard -"@microsoft/api-extractor-model@npm:7.24.0": - version: 7.24.0 - resolution: "@microsoft/api-extractor-model@npm:7.24.0" - dependencies: - "@microsoft/tsdoc": 0.14.1 - "@microsoft/tsdoc-config": ~0.16.1 - "@rushstack/node-core-library": 3.51.1 - checksum: d683ca227ed79f0bd8725caba190bb281b1f2088602268cbecd5d8dd690c601034c447a35e22f63866f79544f9648bc46631e0d724c3e54bc7438591e1f4312f - languageName: node - linkType: hard - -"@microsoft/api-extractor@npm:^7.20.0": - version: 7.30.0 - resolution: "@microsoft/api-extractor@npm:7.30.0" - dependencies: - "@microsoft/api-extractor-model": 7.24.0 - "@microsoft/tsdoc": 0.14.1 - "@microsoft/tsdoc-config": ~0.16.1 - "@rushstack/node-core-library": 3.51.1 - "@rushstack/rig-package": 0.3.14 - "@rushstack/ts-command-line": 4.12.2 - colors: ~1.2.1 - lodash: ~4.17.15 - resolve: ~1.17.0 - semver: ~7.3.0 - source-map: ~0.6.1 - typescript: ~4.7.4 - bin: - api-extractor: bin/api-extractor - checksum: e53ec885d0c645a7202d2e5849bb4a62dbdbb894c66cc21b118e74a043bb0a121fa7f846d08ab4924cb7a5c8eb5cef244d9ba55758718f6670f27604a1894a16 - languageName: node - linkType: hard - -"@microsoft/tsdoc-config@npm:~0.16.1": - version: 0.16.1 - resolution: "@microsoft/tsdoc-config@npm:0.16.1" - dependencies: - "@microsoft/tsdoc": 0.14.1 - ajv: ~6.12.6 - jju: ~1.4.0 - resolve: ~1.19.0 - checksum: 2b2121803caf6584fe0264ad16f8fa10de68438c0b82bd25f918606052af5312050f38b6abd4bcf3d40f120713aab144762a7a280fa22dd12e5571cd08e348e1 - languageName: node - linkType: hard - -"@microsoft/tsdoc@npm:0.14.1": - version: 0.14.1 - resolution: "@microsoft/tsdoc@npm:0.14.1" - checksum: e4ad038ccff2cd96e0d53ee42e2136f0f5a925b16cfda14261f1c2eb55ba0088a0e3b08ff819b476ddc69b2242a391925fab7f6ae2afabb19b96f87e19c114fc - languageName: node - linkType: hard - "@noble/hashes@npm:1.0.0, @noble/hashes@npm:~1.0.0": version: 1.0.0 resolution: "@noble/hashes@npm:1.0.0" @@ -1730,13 +1671,6 @@ __metadata: languageName: node linkType: hard -"@openzeppelin/contracts@npm:3.4.1-solc-0.7-2": - version: 3.4.1-solc-0.7-2 - resolution: "@openzeppelin/contracts@npm:3.4.1-solc-0.7-2" - checksum: 3608a4065f65946117caa543ef72477ce637bd5cc4f4853303b5f5b6c26516f8b50898ea3a8486e2877689cae81453ce22c72c8624c77c363c63f019b4086ffa - languageName: node - linkType: hard - "@openzeppelin/contracts@npm:4.8.3, @openzeppelin/contracts@npm:^4.8.3": version: 4.8.3 resolution: "@openzeppelin/contracts@npm:4.8.3" @@ -1789,44 +1723,6 @@ __metadata: languageName: node linkType: hard -"@rushstack/node-core-library@npm:3.51.1, @rushstack/node-core-library@npm:^3.45.1": - version: 3.51.1 - resolution: "@rushstack/node-core-library@npm:3.51.1" - dependencies: - "@types/node": 12.20.24 - colors: ~1.2.1 - fs-extra: ~7.0.1 - import-lazy: ~4.0.0 - jju: ~1.4.0 - resolve: ~1.17.0 - semver: ~7.3.0 - z-schema: ~5.0.2 - checksum: 92f7e39f03f4931a7007b4a79427d82bfe078146133a138219205abf873607898f7667fa368e3cb28c93bb1a2b9dc70ddaf2d316bc47a9a17b591d69d1025068 - languageName: node - linkType: hard - -"@rushstack/rig-package@npm:0.3.14": - version: 0.3.14 - resolution: "@rushstack/rig-package@npm:0.3.14" - dependencies: - resolve: ~1.17.0 - strip-json-comments: ~3.1.1 - checksum: 3e9c6bdfc79b4a408fbb3248593fe34e23164c4997c68b6cb905ad4a38f53ac628f90fc715c9225348cba1cf0af410bfa55ed5a58c833aa53fdde6cf4a2e0a33 - languageName: node - linkType: hard - -"@rushstack/ts-command-line@npm:4.12.2": - version: 4.12.2 - resolution: "@rushstack/ts-command-line@npm:4.12.2" - dependencies: - "@types/argparse": 1.0.38 - argparse: ~1.0.9 - colors: ~1.2.1 - string-argv: ~0.3.1 - checksum: 6ee016c7dcdc9c55cfaea5b71d8b34d942404764de72a51f2f4d50d4db51f1cc5e0df496de6b96eb9f086ab500f366f63afc33699adecf601f02bfe9a4d157f6 - languageName: node - linkType: hard - "@scure/base@npm:~1.0.0": version: 1.0.0 resolution: "@scure/base@npm:1.0.0" @@ -2018,18 +1914,6 @@ __metadata: languageName: node linkType: hard -"@ts-morph/common@npm:~0.13.0": - version: 0.13.0 - resolution: "@ts-morph/common@npm:0.13.0" - dependencies: - fast-glob: ^3.2.11 - minimatch: ^5.0.1 - mkdirp: ^1.0.4 - path-browserify: ^1.0.1 - checksum: 88b3d4b82dc6aca12741e55c6bf037f2243d14f4b9c42bbe28ed4a773ae9cd8d3ca6a6f9f827b5830c188037b0781d881a002ddb73e094fa5d5ff2a3352dc842 - languageName: node - linkType: hard - "@tsconfig/node10@npm:^1.0.7": version: 1.0.9 resolution: "@tsconfig/node10@npm:1.0.9" @@ -2099,13 +1983,6 @@ __metadata: languageName: node linkType: hard -"@types/argparse@npm:1.0.38": - version: 1.0.38 - resolution: "@types/argparse@npm:1.0.38" - checksum: 26ed7e3f1e3595efdb883a852f5205f971b798e4c28b7e30a32c5298eee596e8b45834ce831f014d250b9730819ab05acff5b31229666d3af4ba465b4697d0eb - languageName: node - linkType: hard - "@types/async-eventemitter@npm:^0.2.1": version: 0.2.1 resolution: "@types/async-eventemitter@npm:0.2.1" @@ -2294,13 +2171,6 @@ __metadata: languageName: node linkType: hard -"@types/node@npm:12.20.24": - version: 12.20.24 - resolution: "@types/node@npm:12.20.24" - checksum: e7a13460e2f5b0b5a32c0f3af7daf1a05201552a66d542d3cc3b1ea8b52d4730250f9eb1961d755e31cfe5d03c78340911a6242657a0a9a17d6f7e341fc9f366 - languageName: node - linkType: hard - "@types/node@npm:^10.0.3": version: 10.17.60 resolution: "@types/node@npm:10.17.60" @@ -2646,13 +2516,6 @@ __metadata: languageName: node linkType: hard -"@uniswap/lib@npm:^4.0.1-alpha": - version: 4.0.1-alpha - resolution: "@uniswap/lib@npm:4.0.1-alpha" - checksum: d7bbacccef40966af16c7e215ab085f575686d316b2802c9e1cfd03f7ad351970e547535670a28b2279c3cfcc4fb02888614c46f94efe2987af2309f3ec86127 - languageName: node - linkType: hard - "@uniswap/v2-core@npm:1.0.0": version: 1.0.0 resolution: "@uniswap/v2-core@npm:1.0.0" @@ -2660,13 +2523,6 @@ __metadata: languageName: node linkType: hard -"@uniswap/v2-core@npm:1.0.1": - version: 1.0.1 - resolution: "@uniswap/v2-core@npm:1.0.1" - checksum: eaa118fe45eac2e80b7468547ce2cde12bd3c8157555d2e40e0462a788c9506c6295247b511382da85e44a89ad92aff7bb3433b23bfbd2eeea23942ecd46e979 - languageName: node - linkType: hard - "@uniswap/v2-periphery@npm:1.1.0-beta.0": version: 1.1.0-beta.0 resolution: "@uniswap/v2-periphery@npm:1.1.0-beta.0" @@ -2677,67 +2533,19 @@ __metadata: languageName: node linkType: hard -"@uniswap/v3-core@npm:1.0.0": - version: 1.0.0 - resolution: "@uniswap/v3-core@npm:1.0.0" - checksum: 0e7654cfbf9885f1ca94446c3b220aeddb039af7892bc4ae94669512570ceefdf1ce6c2b0703396927d5a203d7c6c5ccaf8bd61426e52372aafb6ada64141055 - languageName: node - linkType: hard - -"@uniswap/v3-periphery@npm:1.1.0": - version: 1.1.0 - resolution: "@uniswap/v3-periphery@npm:1.1.0" +"@zetachain/networks@npm:^2.4.3": + version: 2.5.0 + resolution: "@zetachain/networks@npm:2.5.0" dependencies: - "@openzeppelin/contracts": 3.4.1-solc-0.7-2 - "@uniswap/lib": ^4.0.1-alpha - "@uniswap/v2-core": 1.0.1 - "@uniswap/v3-core": 1.0.0 - base64-sol: 1.0.1 - hardhat-watcher: ^2.1.1 - checksum: 8716e168ea04f56400a9affe579b06422778eb6c096e8d4117f6ff43aec232d224be9799f3ad3adb421894f330b17548956cf25fb5a8f95ae291e5b311ec427f + dotenv: ^16.1.4 + checksum: f208dbaa2b38e71069f8eb6ddd2b0a6d11f6f987579fcf4242b4398befa61eea381162984f14f339cee61f3a34e9463df20bfd53f3e670bb721b76c09d9840ac languageName: node linkType: hard -"@zetachain/addresses-tools@workspace:^, @zetachain/addresses-tools@workspace:packages/addresses-tools": - version: 0.0.0-use.local - resolution: "@zetachain/addresses-tools@workspace:packages/addresses-tools" - dependencies: - "@zetachain/addresses": "workspace:^" - "@zetachain/protocol-contracts": ^2.1.0 - languageName: unknown - linkType: soft - -"@zetachain/addresses@workspace:^, @zetachain/addresses@workspace:packages/addresses": - version: 0.0.0-use.local - resolution: "@zetachain/addresses@workspace:packages/addresses" - dependencies: - vite: ^3.1.0 - vite-plugin-dts: ^1.4.1 - languageName: unknown - linkType: soft - -"@zetachain/example-contracts@workspace:packages/example-contracts": - version: 0.0.0-use.local - resolution: "@zetachain/example-contracts@workspace:packages/example-contracts" - dependencies: - "@defi-wonderland/smock": ^2.3.4 - "@openzeppelin/contracts": ^4.8.3 - "@uniswap/v2-periphery": 1.1.0-beta.0 - "@uniswap/v3-periphery": 1.1.0 - "@zetachain/addresses": "workspace:^" - "@zetachain/addresses-tools": "workspace:^" - "@zetachain/protocol-contracts": ^2.1.0 - ethers: 5.6.8 - hardhat-gas-reporter: ^1.0.8 - solidity-coverage: ^0.7.20 - tsconfig-paths: ^3.14.1 - languageName: unknown - linkType: soft - -"@zetachain/protocol-contracts@npm:^2.1.0": - version: 2.1.0 - resolution: "@zetachain/protocol-contracts@npm:2.1.0" - checksum: 0b9a7c869c351eca415b6e6097f79243a3d150b57da8161ab7f7ccb969d0315e2c48d417fcdb8d71375227e58560481e3a4572e6c689224e89bd404ab519e37b +"@zetachain/protocol-contracts@npm:^3.0.0": + version: 3.0.0 + resolution: "@zetachain/protocol-contracts@npm:3.0.0" + checksum: 2bfc8fe05e5e5145cecfb76dd7fe72c22388f7303ebab6039bfa11c92fe89d1bcbe562741dc3d7b3e3819393515c641c4034ebce55bed11f4667be384dddb652 languageName: node linkType: hard @@ -2747,9 +2555,8 @@ __metadata: dependencies: "@defi-wonderland/smock": ^2.3.4 "@openzeppelin/contracts": ^4.8.3 - "@zetachain/addresses": "workspace:^" - "@zetachain/addresses-tools": "workspace:^" - "@zetachain/protocol-contracts": ^2.1.0 + "@zetachain/networks": ^2.4.3 + "@zetachain/protocol-contracts": ^3.0.0 ethers: 5.6.8 hardhat-gas-reporter: ^1.0.8 solidity-coverage: ^0.7.20 @@ -2763,9 +2570,8 @@ __metadata: dependencies: "@openzeppelin/contracts": 4.8.3 "@uniswap/v2-periphery": 1.1.0-beta.0 - "@zetachain/addresses": "workspace:^" - "@zetachain/addresses-tools": "workspace:^" - "@zetachain/protocol-contracts": ^2.1.0 + "@zetachain/networks": ^2.4.3 + "@zetachain/protocol-contracts": ^3.0.0 ethers: 5.6.8 hardhat-gas-reporter: ^1.0.8 solidity-coverage: ^0.7.20 @@ -2779,9 +2585,8 @@ __metadata: dependencies: "@openzeppelin/contracts": ^4.8.3 "@uniswap/v2-periphery": 1.1.0-beta.0 - "@zetachain/addresses": "workspace:^" - "@zetachain/addresses-tools": "workspace:^" - "@zetachain/protocol-contracts": ^2.1.0 + "@zetachain/networks": ^2.4.3 + "@zetachain/protocol-contracts": ^3.0.0 ethers: 5.6.8 hardhat-gas-reporter: ^1.0.8 solidity-coverage: ^0.7.20 @@ -2971,7 +2776,7 @@ __metadata: languageName: node linkType: hard -"ajv@npm:^6.10.0, ajv@npm:^6.12.3, ajv@npm:^6.12.4, ajv@npm:~6.12.6": +"ajv@npm:^6.10.0, ajv@npm:^6.12.3, ajv@npm:^6.12.4": version: 6.12.6 resolution: "ajv@npm:6.12.6" dependencies: @@ -3100,7 +2905,7 @@ __metadata: languageName: node linkType: hard -"argparse@npm:^1.0.7, argparse@npm:~1.0.9": +"argparse@npm:^1.0.7": version: 1.0.10 resolution: "argparse@npm:1.0.10" dependencies: @@ -3326,13 +3131,6 @@ __metadata: languageName: node linkType: hard -"base64-sol@npm:1.0.1": - version: 1.0.1 - resolution: "base64-sol@npm:1.0.1" - checksum: be0f9e8cf3c744256913223fbae8187773f530cc096e98a77f49ef0bd6cedeb294d15a784e439419f7cb99f07bf85b08999169feafafa1a9e29c3affc0bc6d0a - languageName: node - linkType: hard - "bcrypt-pbkdf@npm:^1.0.0": version: 1.0.2 resolution: "bcrypt-pbkdf@npm:1.0.2" @@ -3925,7 +3723,7 @@ __metadata: languageName: node linkType: hard -"chokidar@npm:3.5.3, chokidar@npm:^3.4.0, chokidar@npm:^3.5.3": +"chokidar@npm:3.5.3, chokidar@npm:^3.4.0": version: 3.5.3 resolution: "chokidar@npm:3.5.3" dependencies: @@ -4109,13 +3907,6 @@ __metadata: languageName: node linkType: hard -"code-block-writer@npm:^11.0.0": - version: 11.0.3 - resolution: "code-block-writer@npm:11.0.3" - checksum: f0a2605f19963d7087267c9b0fd0b05a6638a50e7b29b70f97aa01a514f59475b0626f8aa092188df853ee6d96745426dfa132d6a677795df462c6ce32c21639 - languageName: node - linkType: hard - "color-convert@npm:^1.9.0": version: 1.9.3 resolution: "color-convert@npm:1.9.3" @@ -4164,13 +3955,6 @@ __metadata: languageName: node linkType: hard -"colors@npm:~1.2.1": - version: 1.2.5 - resolution: "colors@npm:1.2.5" - checksum: b6e23de735f68b72d5cdf6fd854ca43d1b66d82dcf54bda0b788083b910164a040f2c4edf23c670d36a7a2d8f1b7d6e62e3292703e4642691e6ccaa1c62d8f74 - languageName: node - linkType: hard - "combined-stream@npm:^1.0.6, combined-stream@npm:^1.0.8, combined-stream@npm:~1.0.6": version: 1.0.8 resolution: "combined-stream@npm:1.0.8" @@ -4218,13 +4002,6 @@ __metadata: languageName: node linkType: hard -"commander@npm:^2.20.3": - version: 2.20.3 - resolution: "commander@npm:2.20.3" - checksum: ab8c07884e42c3a8dbc5dd9592c606176c7eb5c1ca5ff274bcf907039b2c41de3626f684ea75ccf4d361ba004bbaff1f577d5384c155f3871e456bdf27becf9e - languageName: node - linkType: hard - "commander@npm:^8.1.0": version: 8.3.0 resolution: "commander@npm:8.3.0" @@ -4789,6 +4566,13 @@ __metadata: languageName: node linkType: hard +"dotenv@npm:^16.1.4": + version: 16.3.1 + resolution: "dotenv@npm:16.3.1" + checksum: 15d75e7279018f4bafd0ee9706593dd14455ddb71b3bcba9c52574460b7ccaf67d5cf8b2c08a5af1a9da6db36c956a04a1192b101ee102a3e0cf8817bbcf3dfd + languageName: node + linkType: hard + "drbg.js@npm:^1.0.1": version: 1.0.1 resolution: "drbg.js@npm:1.0.1" @@ -5051,220 +4835,6 @@ __metadata: languageName: node linkType: hard -"esbuild-android-64@npm:0.15.7": - version: 0.15.7 - resolution: "esbuild-android-64@npm:0.15.7" - conditions: os=android & cpu=x64 - languageName: node - linkType: hard - -"esbuild-android-arm64@npm:0.15.7": - version: 0.15.7 - resolution: "esbuild-android-arm64@npm:0.15.7" - conditions: os=android & cpu=arm64 - languageName: node - linkType: hard - -"esbuild-darwin-64@npm:0.15.7": - version: 0.15.7 - resolution: "esbuild-darwin-64@npm:0.15.7" - conditions: os=darwin & cpu=x64 - languageName: node - linkType: hard - -"esbuild-darwin-arm64@npm:0.15.7": - version: 0.15.7 - resolution: "esbuild-darwin-arm64@npm:0.15.7" - conditions: os=darwin & cpu=arm64 - languageName: node - linkType: hard - -"esbuild-freebsd-64@npm:0.15.7": - version: 0.15.7 - resolution: "esbuild-freebsd-64@npm:0.15.7" - conditions: os=freebsd & cpu=x64 - languageName: node - linkType: hard - -"esbuild-freebsd-arm64@npm:0.15.7": - version: 0.15.7 - resolution: "esbuild-freebsd-arm64@npm:0.15.7" - conditions: os=freebsd & cpu=arm64 - languageName: node - linkType: hard - -"esbuild-linux-32@npm:0.15.7": - version: 0.15.7 - resolution: "esbuild-linux-32@npm:0.15.7" - conditions: os=linux & cpu=ia32 - languageName: node - linkType: hard - -"esbuild-linux-64@npm:0.15.7": - version: 0.15.7 - resolution: "esbuild-linux-64@npm:0.15.7" - conditions: os=linux & cpu=x64 - languageName: node - linkType: hard - -"esbuild-linux-arm64@npm:0.15.7": - version: 0.15.7 - resolution: "esbuild-linux-arm64@npm:0.15.7" - conditions: os=linux & cpu=arm64 - languageName: node - linkType: hard - -"esbuild-linux-arm@npm:0.15.7": - version: 0.15.7 - resolution: "esbuild-linux-arm@npm:0.15.7" - conditions: os=linux & cpu=arm - languageName: node - linkType: hard - -"esbuild-linux-mips64le@npm:0.15.7": - version: 0.15.7 - resolution: "esbuild-linux-mips64le@npm:0.15.7" - conditions: os=linux & cpu=mips64el - languageName: node - linkType: hard - -"esbuild-linux-ppc64le@npm:0.15.7": - version: 0.15.7 - resolution: "esbuild-linux-ppc64le@npm:0.15.7" - conditions: os=linux & cpu=ppc64 - languageName: node - linkType: hard - -"esbuild-linux-riscv64@npm:0.15.7": - version: 0.15.7 - resolution: "esbuild-linux-riscv64@npm:0.15.7" - conditions: os=linux & cpu=riscv64 - languageName: node - linkType: hard - -"esbuild-linux-s390x@npm:0.15.7": - version: 0.15.7 - resolution: "esbuild-linux-s390x@npm:0.15.7" - conditions: os=linux & cpu=s390x - languageName: node - linkType: hard - -"esbuild-netbsd-64@npm:0.15.7": - version: 0.15.7 - resolution: "esbuild-netbsd-64@npm:0.15.7" - conditions: os=netbsd & cpu=x64 - languageName: node - linkType: hard - -"esbuild-openbsd-64@npm:0.15.7": - version: 0.15.7 - resolution: "esbuild-openbsd-64@npm:0.15.7" - conditions: os=openbsd & cpu=x64 - languageName: node - linkType: hard - -"esbuild-sunos-64@npm:0.15.7": - version: 0.15.7 - resolution: "esbuild-sunos-64@npm:0.15.7" - conditions: os=sunos & cpu=x64 - languageName: node - linkType: hard - -"esbuild-windows-32@npm:0.15.7": - version: 0.15.7 - resolution: "esbuild-windows-32@npm:0.15.7" - conditions: os=win32 & cpu=ia32 - languageName: node - linkType: hard - -"esbuild-windows-64@npm:0.15.7": - version: 0.15.7 - resolution: "esbuild-windows-64@npm:0.15.7" - conditions: os=win32 & cpu=x64 - languageName: node - linkType: hard - -"esbuild-windows-arm64@npm:0.15.7": - version: 0.15.7 - resolution: "esbuild-windows-arm64@npm:0.15.7" - conditions: os=win32 & cpu=arm64 - languageName: node - linkType: hard - -"esbuild@npm:^0.15.6": - version: 0.15.7 - resolution: "esbuild@npm:0.15.7" - dependencies: - "@esbuild/linux-loong64": 0.15.7 - esbuild-android-64: 0.15.7 - esbuild-android-arm64: 0.15.7 - esbuild-darwin-64: 0.15.7 - esbuild-darwin-arm64: 0.15.7 - esbuild-freebsd-64: 0.15.7 - esbuild-freebsd-arm64: 0.15.7 - esbuild-linux-32: 0.15.7 - esbuild-linux-64: 0.15.7 - esbuild-linux-arm: 0.15.7 - esbuild-linux-arm64: 0.15.7 - esbuild-linux-mips64le: 0.15.7 - esbuild-linux-ppc64le: 0.15.7 - esbuild-linux-riscv64: 0.15.7 - esbuild-linux-s390x: 0.15.7 - esbuild-netbsd-64: 0.15.7 - esbuild-openbsd-64: 0.15.7 - esbuild-sunos-64: 0.15.7 - esbuild-windows-32: 0.15.7 - esbuild-windows-64: 0.15.7 - esbuild-windows-arm64: 0.15.7 - dependenciesMeta: - "@esbuild/linux-loong64": - optional: true - esbuild-android-64: - optional: true - esbuild-android-arm64: - optional: true - esbuild-darwin-64: - optional: true - esbuild-darwin-arm64: - optional: true - esbuild-freebsd-64: - optional: true - esbuild-freebsd-arm64: - optional: true - esbuild-linux-32: - optional: true - esbuild-linux-64: - optional: true - esbuild-linux-arm: - optional: true - esbuild-linux-arm64: - optional: true - esbuild-linux-mips64le: - optional: true - esbuild-linux-ppc64le: - optional: true - esbuild-linux-riscv64: - optional: true - esbuild-linux-s390x: - optional: true - esbuild-netbsd-64: - optional: true - esbuild-openbsd-64: - optional: true - esbuild-sunos-64: - optional: true - esbuild-windows-32: - optional: true - esbuild-windows-64: - optional: true - esbuild-windows-arm64: - optional: true - bin: - esbuild: bin/esbuild - checksum: 54ddaa6cf96798d817861b4f68cb8d176075dc09b6e0ed511c57e5db6fd86d2c673ac2ec631ad9b11678d58ad4a77cd6b7a3853b9c6eac29b7f5c6d38e42f92e - languageName: node - linkType: hard - "escalade@npm:^3.1.1": version: 3.1.1 resolution: "escalade@npm:3.1.1" @@ -6087,7 +5657,7 @@ __metadata: languageName: node linkType: hard -"fast-glob@npm:^3.0.3, fast-glob@npm:^3.2.11, fast-glob@npm:^3.2.9": +"fast-glob@npm:^3.0.3, fast-glob@npm:^3.2.9": version: 3.2.11 resolution: "fast-glob@npm:3.2.11" dependencies: @@ -6364,17 +5934,6 @@ __metadata: languageName: node linkType: hard -"fs-extra@npm:^10.0.1": - version: 10.1.0 - resolution: "fs-extra@npm:10.1.0" - dependencies: - graceful-fs: ^4.2.0 - jsonfile: ^6.0.1 - universalify: ^2.0.0 - checksum: dc94ab37096f813cc3ca12f0f1b5ad6744dfed9ed21e953d72530d103cea193c2f81584a39e9dee1bea36de5ee66805678c0dddc048e8af1427ac19c00fffc50 - languageName: node - linkType: hard - "fs-extra@npm:^4.0.2": version: 4.0.3 resolution: "fs-extra@npm:4.0.3" @@ -6386,7 +5945,7 @@ __metadata: languageName: node linkType: hard -"fs-extra@npm:^7.0.0, fs-extra@npm:^7.0.1, fs-extra@npm:~7.0.1": +"fs-extra@npm:^7.0.0, fs-extra@npm:^7.0.1": version: 7.0.1 resolution: "fs-extra@npm:7.0.1" dependencies: @@ -6912,17 +6471,6 @@ __metadata: languageName: node linkType: hard -"hardhat-watcher@npm:^2.1.1": - version: 2.3.0 - resolution: "hardhat-watcher@npm:2.3.0" - dependencies: - chokidar: ^3.5.3 - peerDependencies: - hardhat: ^2.0.0 - checksum: 9c99c8f3f476990b4b8f452d5257d2060bc0bbe21e24cd4472c0f2eb63fd71c28ca054353ccdf27947198303be768b12185ffd902d470d7a8e750945a4249eb1 - languageName: node - linkType: hard - "hardhat@npm:2.12.6": version: 2.12.6 resolution: "hardhat@npm:2.12.6" @@ -7322,13 +6870,6 @@ __metadata: languageName: node linkType: hard -"import-lazy@npm:~4.0.0": - version: 4.0.0 - resolution: "import-lazy@npm:4.0.0" - checksum: 22f5e51702134aef78890156738454f620e5fe7044b204ebc057c614888a1dd6fdf2ede0fdcca44d5c173fd64f65c985f19a51775b06967ef58cc3d26898df07 - languageName: node - linkType: hard - "imurmurhash@npm:^0.1.4": version: 0.1.4 resolution: "imurmurhash@npm:0.1.4" @@ -7508,15 +7049,6 @@ __metadata: languageName: node linkType: hard -"is-core-module@npm:^2.1.0, is-core-module@npm:^2.9.0": - version: 2.10.0 - resolution: "is-core-module@npm:2.10.0" - dependencies: - has: ^1.0.3 - checksum: 0f3f77811f430af3256fa7bbc806f9639534b140f8ee69476f632c3e1eb4e28a38be0b9d1b8ecf596179c841b53576129279df95e7051d694dac4ceb6f967593 - languageName: node - linkType: hard - "is-core-module@npm:^2.8.1": version: 2.8.1 resolution: "is-core-module@npm:2.8.1" @@ -7787,13 +7319,6 @@ __metadata: languageName: node linkType: hard -"jju@npm:~1.4.0": - version: 1.4.0 - resolution: "jju@npm:1.4.0" - checksum: 3790481bd2b7827dd6336e6e3dc2dcc6d425679ba7ebde7b679f61dceb4457ea0cda330972494de608571f4973c6dfb5f70fab6f3c5037dbab19ac449a60424f - languageName: node - linkType: hard - "js-sha3@npm:0.5.7, js-sha3@npm:^0.5.7": version: 0.5.7 resolution: "js-sha3@npm:0.5.7" @@ -8286,13 +7811,6 @@ __metadata: languageName: node linkType: hard -"lodash.get@npm:^4.4.2": - version: 4.4.2 - resolution: "lodash.get@npm:4.4.2" - checksum: e403047ddb03181c9d0e92df9556570e2b67e0f0a930fcbbbd779370972368f5568e914f913e93f3b08f6d492abc71e14d4e9b7a18916c31fa04bd2306efe545 - languageName: node - linkType: hard - "lodash.isequal@npm:^4.5.0": version: 4.5.0 resolution: "lodash.isequal@npm:4.5.0" @@ -8321,7 +7839,7 @@ __metadata: languageName: node linkType: hard -"lodash@npm:^4.17.11, lodash@npm:^4.17.14, lodash@npm:^4.17.15, lodash@npm:^4.17.19, lodash@npm:^4.17.21, lodash@npm:~4.17.15": +"lodash@npm:^4.17.11, lodash@npm:^4.17.14, lodash@npm:^4.17.15, lodash@npm:^4.17.19, lodash@npm:^4.17.21": version: 4.17.21 resolution: "lodash@npm:4.17.21" checksum: eb835a2e51d381e561e508ce932ea50a8e5a68f4ebdd771ea240d3048244a8d13658acbd502cd4829768c56f2e16bdd4340b9ea141297d472517b83868e677f7 @@ -8700,15 +8218,6 @@ __metadata: languageName: node linkType: hard -"minimatch@npm:^5.0.1": - version: 5.1.0 - resolution: "minimatch@npm:5.1.0" - dependencies: - brace-expansion: ^2.0.1 - checksum: 15ce53d31a06361e8b7a629501b5c75491bc2b59712d53e802b1987121d91b433d73fcc5be92974fde66b2b51d8fb28d75a9ae900d249feb792bb1ba2a4f0a90 - languageName: node - linkType: hard - "minimist-options@npm:^4.0.2": version: 4.1.0 resolution: "minimist-options@npm:4.1.0" @@ -9063,15 +8572,6 @@ __metadata: languageName: node linkType: hard -"nanoid@npm:^3.3.4": - version: 3.3.4 - resolution: "nanoid@npm:3.3.4" - bin: - nanoid: bin/nanoid.cjs - checksum: 2fddd6dee994b7676f008d3ffa4ab16035a754f4bb586c61df5a22cf8c8c94017aadd360368f47d653829e0569a92b129979152ff97af23a558331e47e37cd9c - languageName: node - linkType: hard - "napi-macros@npm:~2.0.0": version: 2.0.0 resolution: "napi-macros@npm:2.0.0" @@ -9647,7 +9147,7 @@ __metadata: languageName: node linkType: hard -"path-browserify@npm:^1.0.0, path-browserify@npm:^1.0.1": +"path-browserify@npm:^1.0.0": version: 1.0.1 resolution: "path-browserify@npm:1.0.1" checksum: c6d7fa376423fe35b95b2d67990060c3ee304fc815ff0a2dc1c6c3cfaff2bd0d572ee67e18f19d0ea3bbe32e8add2a05021132ac40509416459fffee35200699 @@ -9730,13 +9230,6 @@ __metadata: languageName: node linkType: hard -"picocolors@npm:^1.0.0": - version: 1.0.0 - resolution: "picocolors@npm:1.0.0" - checksum: a2e8092dd86c8396bdba9f2b5481032848525b3dc295ce9b57896f931e63fc16f79805144321f72976383fc249584672a75cc18d6777c6b757603f372f745981 - languageName: node - linkType: hard - "picomatch@npm:^2.0.4, picomatch@npm:^2.2.1, picomatch@npm:^2.3.1": version: 2.3.1 resolution: "picomatch@npm:2.3.1" @@ -9760,17 +9253,6 @@ __metadata: languageName: node linkType: hard -"postcss@npm:^8.4.16": - version: 8.4.16 - resolution: "postcss@npm:8.4.16" - dependencies: - nanoid: ^3.3.4 - picocolors: ^1.0.0 - source-map-js: ^1.0.2 - checksum: 10eee25efd77868036403858577da0cefaf2e0905feeaba5770d5438ccdddba3d01cba8063e96b8aac4c6daa0ed413dd5ae0554a433a3c4db38df1d134cffc1f - languageName: node - linkType: hard - "preferred-pm@npm:^3.0.0": version: 3.0.3 resolution: "preferred-pm@npm:3.0.3" @@ -10324,7 +9806,7 @@ __metadata: languageName: node linkType: hard -"resolve@npm:1.17.0, resolve@npm:~1.17.0": +"resolve@npm:1.17.0": version: 1.17.0 resolution: "resolve@npm:1.17.0" dependencies: @@ -10346,29 +9828,6 @@ __metadata: languageName: node linkType: hard -"resolve@npm:^1.22.1": - version: 1.22.1 - resolution: "resolve@npm:1.22.1" - dependencies: - is-core-module: ^2.9.0 - path-parse: ^1.0.7 - supports-preserve-symlinks-flag: ^1.0.0 - bin: - resolve: bin/resolve - checksum: 07af5fc1e81aa1d866cbc9e9460fbb67318a10fa3c4deadc35c3ad8a898ee9a71a86a65e4755ac3195e0ea0cfbe201eb323ebe655ce90526fd61917313a34e4e - languageName: node - linkType: hard - -"resolve@npm:~1.19.0": - version: 1.19.0 - resolution: "resolve@npm:1.19.0" - dependencies: - is-core-module: ^2.1.0 - path-parse: ^1.0.6 - checksum: a05b356e47b85ad3613d9e2a39a824f3c27f4fcad9c9ff6c7cc71a2e314c5904a90ab37481ad0069d03cab9eaaac6eb68aca1bc3355fdb05f1045cd50e2aacea - languageName: node - linkType: hard - "resolve@patch:resolve@1.1.x#~builtin": version: 1.1.7 resolution: "resolve@patch:resolve@npm%3A1.1.7#~builtin::version=1.1.7&hash=07638b" @@ -10376,7 +9835,7 @@ __metadata: languageName: node linkType: hard -"resolve@patch:resolve@1.17.0#~builtin, resolve@patch:resolve@~1.17.0#~builtin": +"resolve@patch:resolve@1.17.0#~builtin": version: 1.17.0 resolution: "resolve@patch:resolve@npm%3A1.17.0#~builtin::version=1.17.0&hash=07638b" dependencies: @@ -10398,29 +9857,6 @@ __metadata: languageName: node linkType: hard -"resolve@patch:resolve@^1.22.1#~builtin": - version: 1.22.1 - resolution: "resolve@patch:resolve@npm%3A1.22.1#~builtin::version=1.22.1&hash=07638b" - dependencies: - is-core-module: ^2.9.0 - path-parse: ^1.0.7 - supports-preserve-symlinks-flag: ^1.0.0 - bin: - resolve: bin/resolve - checksum: 5656f4d0bedcf8eb52685c1abdf8fbe73a1603bb1160a24d716e27a57f6cecbe2432ff9c89c2bd57542c3a7b9d14b1882b73bfe2e9d7849c9a4c0b8b39f02b8b - languageName: node - linkType: hard - -"resolve@patch:resolve@~1.19.0#~builtin": - version: 1.19.0 - resolution: "resolve@patch:resolve@npm%3A1.19.0#~builtin::version=1.19.0&hash=07638b" - dependencies: - is-core-module: ^2.1.0 - path-parse: ^1.0.6 - checksum: 2443b94d347e6946c87c85faf13071f605e609e0b54784829b0ed2b917d050bfc1cbaf4ecc6453f224cfa7d0c5dcd97cbb273454cd210bee68e4af15c1a5abc9 - languageName: node - linkType: hard - "responselike@npm:^1.0.2": version: 1.0.2 resolution: "responselike@npm:1.0.2" @@ -10508,20 +9944,6 @@ __metadata: languageName: node linkType: hard -"rollup@npm:~2.78.0": - version: 2.78.1 - resolution: "rollup@npm:2.78.1" - dependencies: - fsevents: ~2.3.2 - dependenciesMeta: - fsevents: - optional: true - bin: - rollup: dist/bin/rollup - checksum: 9034814383ca5bdb4bea6d499270aeb31cdb0bb884f81b0c6a1d19c63cc973f040e6ee09b7af8a7169dd231c090f4b44ef8b99c4bfdf884aceeb3dcefb8cfa14 - languageName: node - linkType: hard - "run-async@npm:^2.4.0": version: 2.4.1 resolution: "run-async@npm:2.4.1" @@ -10694,7 +10116,7 @@ __metadata: languageName: node linkType: hard -"semver@npm:^7.3.7, semver@npm:~7.3.0": +"semver@npm:^7.3.7": version: 7.3.7 resolution: "semver@npm:7.3.7" dependencies: @@ -11025,13 +10447,6 @@ __metadata: languageName: node linkType: hard -"source-map-js@npm:^1.0.2": - version: 1.0.2 - resolution: "source-map-js@npm:1.0.2" - checksum: c049a7fc4deb9a7e9b481ae3d424cc793cb4845daa690bc5a05d428bf41bf231ced49b4cf0c9e77f9d42fdb3d20d6187619fc586605f5eabe995a316da8d377c - languageName: node - linkType: hard - "source-map-support@npm:^0.5.13, source-map-support@npm:^0.5.6": version: 0.5.21 resolution: "source-map-support@npm:0.5.21" @@ -11042,7 +10457,7 @@ __metadata: languageName: node linkType: hard -"source-map@npm:^0.6.0, source-map@npm:^0.6.1, source-map@npm:~0.6.1": +"source-map@npm:^0.6.0, source-map@npm:^0.6.1": version: 0.6.1 resolution: "source-map@npm:0.6.1" checksum: 59ce8640cf3f3124f64ac289012c2b8bd377c238e316fb323ea22fbfe83da07d81e000071d7242cad7a23cd91c7de98e4df8830ec3f133cb6133a5f6e9f67bc2 @@ -11192,13 +10607,6 @@ __metadata: languageName: node linkType: hard -"string-argv@npm:~0.3.1": - version: 0.3.1 - resolution: "string-argv@npm:0.3.1" - checksum: efbd0289b599bee808ce80820dfe49c9635610715429c6b7cc50750f0437e3c2f697c81e5c390208c13b5d5d12d904a1546172a88579f6ee5cbaaaa4dc9ec5cf - languageName: node - linkType: hard - "string-format@npm:^2.0.0": version: 2.0.0 resolution: "string-format@npm:2.0.0" @@ -11357,7 +10765,7 @@ __metadata: languageName: node linkType: hard -"strip-json-comments@npm:3.1.1, strip-json-comments@npm:^3.1.0, strip-json-comments@npm:^3.1.1, strip-json-comments@npm:~3.1.1": +"strip-json-comments@npm:3.1.1, strip-json-comments@npm:^3.1.0, strip-json-comments@npm:^3.1.1": version: 3.1.1 resolution: "strip-json-comments@npm:3.1.1" checksum: 492f73e27268f9b1c122733f28ecb0e7e8d8a531a6662efbd08e22cccb3f9475e90a1b82cab06a392f6afae6d2de636f977e231296400d0ec5304ba70f166443 @@ -11639,16 +11047,6 @@ __metadata: languageName: node linkType: hard -"ts-morph@npm:^14.0.0": - version: 14.0.0 - resolution: "ts-morph@npm:14.0.0" - dependencies: - "@ts-morph/common": ~0.13.0 - code-block-writer: ^11.0.0 - checksum: e975fb245ae558c638e94014dcbbad828b904dee5a7309bfb4ef2b2922d0d7ad902ec00874a959be58991043ce655f78ae78df0d0e0d6fb3800b991b95be08ce - languageName: node - linkType: hard - "ts-node@npm:10.8.1": version: 10.8.1 resolution: "ts-node@npm:10.8.1" @@ -11935,16 +11333,6 @@ __metadata: languageName: node linkType: hard -"typescript@npm:~4.7.4": - version: 4.7.4 - resolution: "typescript@npm:4.7.4" - bin: - tsc: bin/tsc - tsserver: bin/tsserver - checksum: 5750181b1cd7e6482c4195825547e70f944114fb47e58e4aa7553e62f11b3f3173766aef9c281783edfd881f7b8299cf35e3ca8caebe73d8464528c907a164df - languageName: node - linkType: hard - "typescript@patch:typescript@^4.6.3#~builtin": version: 4.6.3 resolution: "typescript@patch:typescript@npm%3A4.6.3#~builtin::version=4.6.3&hash=bda367" @@ -11955,16 +11343,6 @@ __metadata: languageName: node linkType: hard -"typescript@patch:typescript@~4.7.4#~builtin": - version: 4.7.4 - resolution: "typescript@patch:typescript@npm%3A4.7.4#~builtin::version=4.7.4&hash=bda367" - bin: - tsc: bin/tsc - tsserver: bin/tsserver - checksum: 96d3030cb01143570567cb4f3a616b10df65f658f0e74e853e77a089a6a954e35c800be7db8b9bfe9a1ae05d9c2897e281359f65e4caa1caf266368e1c4febd3 - languageName: node - linkType: hard - "typical@npm:^4.0.0": version: 4.0.0 resolution: "typical@npm:4.0.0" @@ -12238,13 +11616,6 @@ __metadata: languageName: node linkType: hard -"validator@npm:^13.7.0": - version: 13.7.0 - resolution: "validator@npm:13.7.0" - checksum: 2b83283de1222ca549a7ef57f46e8d49c6669213348db78b7045bce36a3b5843ff1e9f709ebf74574e06223461ee1f264f8cc9a26a0060a79a27de079d8286ef - languageName: node - linkType: hard - "varint@npm:^5.0.0": version: 5.0.2 resolution: "varint@npm:5.0.2" @@ -12270,55 +11641,6 @@ __metadata: languageName: node linkType: hard -"vite-plugin-dts@npm:^1.4.1": - version: 1.4.1 - resolution: "vite-plugin-dts@npm:1.4.1" - dependencies: - "@microsoft/api-extractor": ^7.20.0 - "@rushstack/node-core-library": ^3.45.1 - chalk: ^4.1.2 - debug: ^4.3.4 - fast-glob: ^3.2.11 - fs-extra: ^10.0.1 - ts-morph: ^14.0.0 - peerDependencies: - vite: ">=2.4.4" - checksum: 39a5d25f1e5de984f85e09c85f0b6b16de82c209bfc55f59a2d6b30996f14c683462895814ec388406116a7fad4a1d374efacbf51d76a7bdaad9c9708307f982 - languageName: node - linkType: hard - -"vite@npm:^3.1.0": - version: 3.1.0 - resolution: "vite@npm:3.1.0" - dependencies: - esbuild: ^0.15.6 - fsevents: ~2.3.2 - postcss: ^8.4.16 - resolve: ^1.22.1 - rollup: ~2.78.0 - peerDependencies: - less: "*" - sass: "*" - stylus: "*" - terser: ^5.4.0 - dependenciesMeta: - fsevents: - optional: true - peerDependenciesMeta: - less: - optional: true - sass: - optional: true - stylus: - optional: true - terser: - optional: true - bin: - vite: bin/vite.js - checksum: 1a343e3d46450181f79f34ff49cca5ff59bb7472de51ea2c4a042aa076f597d27d25c49f48405e82f607af7d8c1c13a9e789402ccb1b23570132382132ec3903 - languageName: node - linkType: hard - "wcwidth@npm:^1.0.1": version: 1.0.1 resolution: "wcwidth@npm:1.0.1" @@ -13094,23 +12416,6 @@ __metadata: languageName: node linkType: hard -"z-schema@npm:~5.0.2": - version: 5.0.4 - resolution: "z-schema@npm:5.0.4" - dependencies: - commander: ^2.20.3 - lodash.get: ^4.4.2 - lodash.isequal: ^4.5.0 - validator: ^13.7.0 - dependenciesMeta: - commander: - optional: true - bin: - z-schema: bin/z-schema - checksum: afa4e0039a104a53eeb6977bf754ef44e32042aecbf3b5eb18b82649763abd5c2608e47d6d6902291359b41e76130594d7f2b6132316d819c3529f17d4d3464d - languageName: node - linkType: hard - "zetachain@workspace:.": version: 0.0.0-use.local resolution: "zetachain@workspace:." From 07a0b9a2fc98cfbd7700afba7c9c2e291f6520c4 Mon Sep 17 00:00:00 2001 From: Andres Aiello Date: Tue, 14 Nov 2023 16:37:54 -0300 Subject: [PATCH 2/6] update docker --- Dockerfile | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/Dockerfile b/Dockerfile index 01784859..955672f6 100644 --- a/Dockerfile +++ b/Dockerfile @@ -9,11 +9,8 @@ RUN apk add --update python3 yarn git nodejs make g++ ## Install node modules before the code is copied to the container WORKDIR /home/zetachain/ COPY package*.json ./ -COPY packages/addresses-tools/package.json ./packages/addresses-tools/package.json -COPY packages/zevm-example-contracts/package.json ./packages/zevm-example-contracts/package.json -COPY packages/addresses/package.json packages/addresses/package.json -COPY packages/example-contracts/package.json ./packages/example-contracts/package.json COPY packages/zeta-app-contracts/package.json ./packages/zeta-app-contracts/package.json +COPY packages/zevm-app-contracts/package.json ./packages/zevm-app-contracts/package.json RUN yarn install ; exit 0 COPY . ./ @@ -21,9 +18,8 @@ RUN yarn install RUN yarn add solc@0.5.10 solc@0.6.6 solc@0.7.6 solc@0.8.7 -RUN cd packages/example-contracts && npx hardhat compile && cd - RUN cd packages/zeta-app-contracts && npx hardhat compile && cd - -RUN cd packages/zevm-example-contracts && npx hardhat compile && cd - +RUN cd packages/zevm-app-contracts && npx hardhat compile && cd - WORKDIR /home/zetachain/ From c7df37010199b3fbfccfa169b66ce0afbef98592 Mon Sep 17 00:00:00 2001 From: Andres Aiello Date: Tue, 14 Nov 2023 16:56:37 -0300 Subject: [PATCH 3/6] update uniswap scripts --- .../uniswap/add-liquidity-zeta-uniswap.ts | 51 ++++++------------- .../uniswap/remove-liquidity-zeta-uniswap.ts | 39 +++++--------- .../scripts/uniswap/sell-token.ts | 41 ++++++--------- .../scripts/uniswap/sell-zeta.ts | 39 +++++--------- .../scripts/zeta-swap/stress-swap.ts | 2 +- packages/zevm-app-contracts/test/Swap.spec.ts | 4 +- 6 files changed, 62 insertions(+), 114 deletions(-) diff --git a/packages/zevm-app-contracts/scripts/uniswap/add-liquidity-zeta-uniswap.ts b/packages/zevm-app-contracts/scripts/uniswap/add-liquidity-zeta-uniswap.ts index 32731630..599ba402 100644 --- a/packages/zevm-app-contracts/scripts/uniswap/add-liquidity-zeta-uniswap.ts +++ b/packages/zevm-app-contracts/scripts/uniswap/add-liquidity-zeta-uniswap.ts @@ -1,12 +1,9 @@ import { MaxUint256 } from "@ethersproject/constants"; -import { formatUnits, parseUnits } from "@ethersproject/units"; +import { parseUnits } from "@ethersproject/units"; import { SignerWithAddress } from "@nomiclabs/hardhat-ethers/signers"; -import { getChainId } from "@zetachain/addresses"; -import { NetworkName } from "@zetachain/addresses"; -import { getAddress } from "@zetachain/addresses"; -import { getGasSymbolByNetwork, getSystemContractAddress } from "@zetachain/addresses-tools"; +import { getNonZetaAddress, isProtocolNetworkName, ZetaProtocolNetwork } from "@zetachain/protocol-contracts"; import { BigNumber } from "ethers"; -import { ethers } from "hardhat"; +import { ethers, network } from "hardhat"; import { ERC20, @@ -17,8 +14,11 @@ import { SystemContract__factory, UniswapV2Router02__factory } from "../../typechain-types"; +import { getChainId, getSystemContractAddress } from "../address.helpers"; import { getNow, printReserves, sortPair } from "./uniswap.helpers"; +const networkName = network.name; + const SYSTEM_CONTRACT = getSystemContractAddress(); const BTC_TO_ADD = parseUnits("0", 8); @@ -53,7 +53,6 @@ const addTokenEthLiquidity = async ( }; const estimateZetaForToken = async ( - network: NetworkName, WZETAAddress: string, uniswapFactoryAddress: string, tokenContract: ERC20, @@ -79,7 +78,7 @@ const estimateZetaForToken = async ( }; async function addLiquidity( - network: NetworkName, + network: ZetaProtocolNetwork, tokenAmountToAdd: BigNumber, WZETAAddress: string, uniswapFactoryAddress: string, @@ -98,49 +97,31 @@ async function addLiquidity( const zetaToAdd = initLiquidityPool ? ZETA_TO_ADD - : await estimateZetaForToken( - network, - WZETAAddress, - uniswapFactoryAddress, - tokenContract, - tokenAmountToAdd, - deployer - ); + : await estimateZetaForToken(WZETAAddress, uniswapFactoryAddress, tokenContract, tokenAmountToAdd, deployer); await printReserves(tokenContract, WZETAAddress, uniswapFactoryAddress, deployer); // await addTokenEthLiquidity(tokenContract, tokenAmountToAdd, zetaToAdd, uniswapRouter, deployer); await printReserves(tokenContract, WZETAAddress, uniswapFactoryAddress, deployer); } async function main() { - const WZETA_ADDRESS = getAddress({ - address: "weth9", - networkName: "athens", - zetaNetwork: "athens" - }); + if (!isProtocolNetworkName(networkName)) throw new Error("Invalid network name"); + const WZETA_ADDRESS = getNonZetaAddress("weth9", networkName); - const UNISWAP_FACTORY_ADDRESS = getAddress({ - address: "uniswapV2Factory", - networkName: "athens", - zetaNetwork: "athens" - }); + const UNISWAP_FACTORY_ADDRESS = getNonZetaAddress("uniswapV2Factory", networkName); - const UNISWAP_ROUTER_ADDRESS = getAddress({ - address: "uniswapV2Router02", - networkName: "athens", - zetaNetwork: "athens" - }); + const UNISWAP_ROUTER_ADDRESS = getNonZetaAddress("uniswapV2Router02", networkName); if (!ETH_TO_ADD.isZero()) { - await addLiquidity("goerli", ETH_TO_ADD, WZETA_ADDRESS, UNISWAP_FACTORY_ADDRESS, UNISWAP_ROUTER_ADDRESS); + await addLiquidity("goerli_testnet", ETH_TO_ADD, WZETA_ADDRESS, UNISWAP_FACTORY_ADDRESS, UNISWAP_ROUTER_ADDRESS); } if (!MATIC_TO_ADD.isZero()) { - await addLiquidity("polygon-mumbai", MATIC_TO_ADD, WZETA_ADDRESS, UNISWAP_FACTORY_ADDRESS, UNISWAP_ROUTER_ADDRESS); + await addLiquidity("mumbai_testnet", MATIC_TO_ADD, WZETA_ADDRESS, UNISWAP_FACTORY_ADDRESS, UNISWAP_ROUTER_ADDRESS); } if (!BNB_TO_ADD.isZero()) { - await addLiquidity("bsc-testnet", BNB_TO_ADD, WZETA_ADDRESS, UNISWAP_FACTORY_ADDRESS, UNISWAP_ROUTER_ADDRESS); + await addLiquidity("bsc_testnet", BNB_TO_ADD, WZETA_ADDRESS, UNISWAP_FACTORY_ADDRESS, UNISWAP_ROUTER_ADDRESS); } if (!BTC_TO_ADD.isZero()) { - await addLiquidity("bitcoin-test", BTC_TO_ADD, WZETA_ADDRESS, UNISWAP_FACTORY_ADDRESS, UNISWAP_ROUTER_ADDRESS); + await addLiquidity("btc_testnet", BTC_TO_ADD, WZETA_ADDRESS, UNISWAP_FACTORY_ADDRESS, UNISWAP_ROUTER_ADDRESS); } } diff --git a/packages/zevm-app-contracts/scripts/uniswap/remove-liquidity-zeta-uniswap.ts b/packages/zevm-app-contracts/scripts/uniswap/remove-liquidity-zeta-uniswap.ts index 896f0293..5c3b873a 100644 --- a/packages/zevm-app-contracts/scripts/uniswap/remove-liquidity-zeta-uniswap.ts +++ b/packages/zevm-app-contracts/scripts/uniswap/remove-liquidity-zeta-uniswap.ts @@ -1,12 +1,9 @@ import { MaxUint256 } from "@ethersproject/constants"; import { formatUnits } from "@ethersproject/units"; import { SignerWithAddress } from "@nomiclabs/hardhat-ethers/signers"; -import { getChainId } from "@zetachain/addresses"; -import { NetworkName } from "@zetachain/addresses"; -import { getAddress } from "@zetachain/addresses"; -import { getSystemContractAddress } from "@zetachain/addresses-tools"; +import { getNonZetaAddress, isProtocolNetworkName, ZetaProtocolNetwork } from "@zetachain/protocol-contracts"; import { BigNumber } from "ethers"; -import { ethers } from "hardhat"; +import { ethers, network } from "hardhat"; import { ERC20, @@ -18,8 +15,10 @@ import { SystemContract__factory, UniswapV2Router02__factory } from "../../typechain-types"; +import { getChainId, getSystemContractAddress } from "../address.helpers"; import { getNow, printReserves, sortPair } from "./uniswap.helpers"; +const networkName = network.name; const SYSTEM_CONTRACT = getSystemContractAddress(); const removeTokenEthLiquidity = async ( @@ -47,7 +46,7 @@ const removeTokenEthLiquidity = async ( }; async function removeLiquidity( - network: NetworkName, + network: ZetaProtocolNetwork, WZETAAddress: string, uniswapFactoryAddress: string, uniswapRouterAddress: string @@ -78,28 +77,18 @@ async function removeLiquidity( await printReserves(tokenContract, WZETAAddress, uniswapFactoryAddress, deployer); } async function main() { - const WZETA_ADDRESS = getAddress({ - address: "weth9", - networkName: "athens", - zetaNetwork: "athens" - }); + if (!isProtocolNetworkName(networkName)) throw new Error("Invalid network name"); - const UNISWAP_FACTORY_ADDRESS = getAddress({ - address: "uniswapV2Factory", - networkName: "athens", - zetaNetwork: "athens" - }); + const WZETA_ADDRESS = getNonZetaAddress("weth9", networkName); - const UNISWAP_ROUTER_ADDRESS = getAddress({ - address: "uniswapV2Router02", - networkName: "athens", - zetaNetwork: "athens" - }); + const UNISWAP_FACTORY_ADDRESS = getNonZetaAddress("uniswapV2Factory", networkName); + + const UNISWAP_ROUTER_ADDRESS = getNonZetaAddress("uniswapV2Router02", networkName); - await removeLiquidity("goerli", WZETA_ADDRESS, UNISWAP_FACTORY_ADDRESS, UNISWAP_ROUTER_ADDRESS); - await removeLiquidity("polygon-mumbai", WZETA_ADDRESS, UNISWAP_FACTORY_ADDRESS, UNISWAP_ROUTER_ADDRESS); - await removeLiquidity("bsc-testnet", WZETA_ADDRESS, UNISWAP_FACTORY_ADDRESS, UNISWAP_ROUTER_ADDRESS); - await removeLiquidity("bitcoin-test", WZETA_ADDRESS, UNISWAP_FACTORY_ADDRESS, UNISWAP_ROUTER_ADDRESS); + await removeLiquidity("goerli_testnet", WZETA_ADDRESS, UNISWAP_FACTORY_ADDRESS, UNISWAP_ROUTER_ADDRESS); + await removeLiquidity("mumbai_testnet", WZETA_ADDRESS, UNISWAP_FACTORY_ADDRESS, UNISWAP_ROUTER_ADDRESS); + await removeLiquidity("bsc_testnet", WZETA_ADDRESS, UNISWAP_FACTORY_ADDRESS, UNISWAP_ROUTER_ADDRESS); + await removeLiquidity("btc_testnet", WZETA_ADDRESS, UNISWAP_FACTORY_ADDRESS, UNISWAP_ROUTER_ADDRESS); } main() diff --git a/packages/zevm-app-contracts/scripts/uniswap/sell-token.ts b/packages/zevm-app-contracts/scripts/uniswap/sell-token.ts index 6d8ed6ea..94a9d877 100644 --- a/packages/zevm-app-contracts/scripts/uniswap/sell-token.ts +++ b/packages/zevm-app-contracts/scripts/uniswap/sell-token.ts @@ -1,12 +1,9 @@ import { MaxUint256 } from "@ethersproject/constants"; -import { formatUnits, parseUnits } from "@ethersproject/units"; +import { parseUnits } from "@ethersproject/units"; import { SignerWithAddress } from "@nomiclabs/hardhat-ethers/signers"; -import { getChainId } from "@zetachain/addresses"; -import { NetworkName } from "@zetachain/addresses"; -import { getAddress } from "@zetachain/addresses"; -import { getSystemContractAddress } from "@zetachain/addresses-tools"; +import { getNonZetaAddress, isProtocolNetworkName, ZetaProtocolNetwork } from "@zetachain/protocol-contracts"; import { BigNumber } from "ethers"; -import { ethers } from "hardhat"; +import { ethers, network } from "hardhat"; import { ERC20, @@ -15,8 +12,10 @@ import { SystemContract__factory, UniswapV2Router02__factory } from "../../typechain-types"; +import { getChainId, getSystemContractAddress } from "../address.helpers"; import { getNow, printReserves } from "./uniswap.helpers"; +const networkName = network.name; const SYSTEM_CONTRACT = getSystemContractAddress(); const BTC_TO_SELL = parseUnits("0", 8); @@ -50,7 +49,7 @@ const swapZeta = async ( }; async function sellToken( - network: NetworkName, + network: ZetaProtocolNetwork, tokenAmountToSell: BigNumber, WZETAAddress: string, uniswapFactoryAddress: string, @@ -71,35 +70,25 @@ async function sellToken( await printReserves(tokenContract, WZETAAddress, uniswapFactoryAddress, deployer); } async function main() { - const WZETA_ADDRESS = getAddress({ - address: "weth9", - networkName: "athens", - zetaNetwork: "athens" - }); + if (!isProtocolNetworkName(networkName)) throw new Error("Invalid network name"); - const UNISWAP_FACTORY_ADDRESS = getAddress({ - address: "uniswapV2Factory", - networkName: "athens", - zetaNetwork: "athens" - }); + const WZETA_ADDRESS = getNonZetaAddress("weth9", networkName); - const UNISWAP_ROUTER_ADDRESS = getAddress({ - address: "uniswapV2Router02", - networkName: "athens", - zetaNetwork: "athens" - }); + const UNISWAP_FACTORY_ADDRESS = getNonZetaAddress("uniswapV2Factory", networkName); + + const UNISWAP_ROUTER_ADDRESS = getNonZetaAddress("uniswapV2Router02", networkName); if (!ETH_TO_SELL.isZero()) { - await sellToken("goerli", ETH_TO_SELL, WZETA_ADDRESS, UNISWAP_FACTORY_ADDRESS, UNISWAP_ROUTER_ADDRESS); + await sellToken("goerli_testnet", ETH_TO_SELL, WZETA_ADDRESS, UNISWAP_FACTORY_ADDRESS, UNISWAP_ROUTER_ADDRESS); } if (!MATIC_TO_SELL.isZero()) { - await sellToken("polygon-mumbai", MATIC_TO_SELL, WZETA_ADDRESS, UNISWAP_FACTORY_ADDRESS, UNISWAP_ROUTER_ADDRESS); + await sellToken("mumbai_testnet", MATIC_TO_SELL, WZETA_ADDRESS, UNISWAP_FACTORY_ADDRESS, UNISWAP_ROUTER_ADDRESS); } if (!BNB_TO_SELL.isZero()) { - await sellToken("bsc-testnet", BNB_TO_SELL, WZETA_ADDRESS, UNISWAP_FACTORY_ADDRESS, UNISWAP_ROUTER_ADDRESS); + await sellToken("bsc_testnet", BNB_TO_SELL, WZETA_ADDRESS, UNISWAP_FACTORY_ADDRESS, UNISWAP_ROUTER_ADDRESS); } if (!BTC_TO_SELL.isZero()) { - await sellToken("bitcoin-test", BTC_TO_SELL, WZETA_ADDRESS, UNISWAP_FACTORY_ADDRESS, UNISWAP_ROUTER_ADDRESS); + await sellToken("btc_testnet", BTC_TO_SELL, WZETA_ADDRESS, UNISWAP_FACTORY_ADDRESS, UNISWAP_ROUTER_ADDRESS); } } diff --git a/packages/zevm-app-contracts/scripts/uniswap/sell-zeta.ts b/packages/zevm-app-contracts/scripts/uniswap/sell-zeta.ts index f990c074..4ecc5c61 100644 --- a/packages/zevm-app-contracts/scripts/uniswap/sell-zeta.ts +++ b/packages/zevm-app-contracts/scripts/uniswap/sell-zeta.ts @@ -1,12 +1,9 @@ import { MaxUint256 } from "@ethersproject/constants"; import { formatUnits, parseUnits } from "@ethersproject/units"; import { SignerWithAddress } from "@nomiclabs/hardhat-ethers/signers"; -import { getChainId } from "@zetachain/addresses"; -import { NetworkName } from "@zetachain/addresses"; -import { getAddress } from "@zetachain/addresses"; -import { getSystemContractAddress } from "@zetachain/addresses-tools"; +import { getNonZetaAddress, isProtocolNetworkName, ZetaProtocolNetwork } from "@zetachain/protocol-contracts"; import { BigNumber } from "ethers"; -import { ethers } from "hardhat"; +import { ethers, network } from "hardhat"; import { ERC20, @@ -15,8 +12,10 @@ import { SystemContract__factory, UniswapV2Router02__factory } from "../../typechain-types"; +import { getChainId, getSystemContractAddress } from "../address.helpers"; import { getNow, printReserves } from "./uniswap.helpers"; +const networkName = network.name; const SYSTEM_CONTRACT = getSystemContractAddress(); const ZETA_TO_SELL = parseUnits("0.001"); @@ -41,7 +40,7 @@ const swapZeta = async ( }; async function sellZeta( - network: NetworkName, + network: ZetaProtocolNetwork, WZETAAddress: string, uniswapFactoryAddress: string, uniswapRouterAddress: string @@ -61,28 +60,18 @@ async function sellZeta( await printReserves(tokenContract, WZETAAddress, uniswapFactoryAddress, deployer); } async function main() { - const WZETA_ADDRESS = getAddress({ - address: "weth9", - networkName: "athens", - zetaNetwork: "athens" - }); + if (!isProtocolNetworkName(networkName)) throw new Error("Invalid network name"); - const UNISWAP_FACTORY_ADDRESS = getAddress({ - address: "uniswapV2Factory", - networkName: "athens", - zetaNetwork: "athens" - }); + const WZETA_ADDRESS = getNonZetaAddress("weth9", networkName); - const UNISWAP_ROUTER_ADDRESS = getAddress({ - address: "uniswapV2Router02", - networkName: "athens", - zetaNetwork: "athens" - }); + const UNISWAP_FACTORY_ADDRESS = getNonZetaAddress("uniswapV2Factory", networkName); + + const UNISWAP_ROUTER_ADDRESS = getNonZetaAddress("uniswapV2Router02", networkName); - await sellZeta("goerli", WZETA_ADDRESS, UNISWAP_FACTORY_ADDRESS, UNISWAP_ROUTER_ADDRESS); - await sellZeta("polygon-mumbai", WZETA_ADDRESS, UNISWAP_FACTORY_ADDRESS, UNISWAP_ROUTER_ADDRESS); - await sellZeta("bsc-testnet", WZETA_ADDRESS, UNISWAP_FACTORY_ADDRESS, UNISWAP_ROUTER_ADDRESS); - await sellZeta("bitcoin-test", WZETA_ADDRESS, UNISWAP_FACTORY_ADDRESS, UNISWAP_ROUTER_ADDRESS); + await sellZeta("goerli_testnet", WZETA_ADDRESS, UNISWAP_FACTORY_ADDRESS, UNISWAP_ROUTER_ADDRESS); + await sellZeta("mumbai_testnet", WZETA_ADDRESS, UNISWAP_FACTORY_ADDRESS, UNISWAP_ROUTER_ADDRESS); + await sellZeta("bsc_testnet", WZETA_ADDRESS, UNISWAP_FACTORY_ADDRESS, UNISWAP_ROUTER_ADDRESS); + await sellZeta("btc_testnet", WZETA_ADDRESS, UNISWAP_FACTORY_ADDRESS, UNISWAP_ROUTER_ADDRESS); } main() diff --git a/packages/zevm-app-contracts/scripts/zeta-swap/stress-swap.ts b/packages/zevm-app-contracts/scripts/zeta-swap/stress-swap.ts index 3c55596b..8e02e66f 100644 --- a/packages/zevm-app-contracts/scripts/zeta-swap/stress-swap.ts +++ b/packages/zevm-app-contracts/scripts/zeta-swap/stress-swap.ts @@ -51,7 +51,7 @@ const main = async () => { const swappableNetwork: SwappableNetwork = network.name; // @dev: bitcoin is invalid as destination - const invalidDestinations: SwappableNetwork[] = [swappableNetwork, "bitcoin-test"]; + const invalidDestinations: SwappableNetwork[] = [swappableNetwork, "btc_testnet"]; const networks = Object.keys(ChainToZRC20).map(c => c as SwappableNetwork); const destinationNetworks = networks.filter(e => !invalidDestinations.includes(e)); diff --git a/packages/zevm-app-contracts/test/Swap.spec.ts b/packages/zevm-app-contracts/test/Swap.spec.ts index 97b05346..bd6850ce 100644 --- a/packages/zevm-app-contracts/test/Swap.spec.ts +++ b/packages/zevm-app-contracts/test/Swap.spec.ts @@ -5,6 +5,7 @@ import { getNonZetaAddress } from "@zetachain/protocol-contracts"; import { expect } from "chai"; import { ethers, network } from "hardhat"; +import { getBitcoinTxMemoForTest, getSwapParams } from "../scripts/zeta-swap/helpers"; import { MockSystemContract, MockZRC20, @@ -12,8 +13,7 @@ import { ZetaSwap__factory, ZetaSwapBtcInbound, ZetaSwapBtcInbound__factory -} from "../../zevm-example-contracts/typechain-types"; -import { getBitcoinTxMemoForTest, getSwapParams } from "../scripts/zeta-swap/helpers"; +} from "../typechain-types"; import { evmSetup } from "./test.helpers"; describe("ZetaSwap tests", () => { From 93de470a44bdb5d880d03a769a33d8cc577242e1 Mon Sep 17 00:00:00 2001 From: Andres Aiello Date: Thu, 16 Nov 2023 14:33:09 -0300 Subject: [PATCH 4/6] refactor --- packages/zeta-app-contracts/package.json | 2 +- .../scripts/address.helpers.ts | 2 +- .../scripts/multi-chain-value/deploy.ts | 5 ++- .../test/MultiChainValue.spec.ts | 2 +- .../Synthetixio/StakingRewards.sol | 30 +++++++++------ .../zevm-app-contracts/data/addresses.json | 3 +- packages/zevm-app-contracts/package.json | 2 +- .../scripts/address.helpers.ts | 4 +- .../scripts/uniswap/uniswap.helpers.ts | 2 +- .../scripts/zeta-points/deploy.ts | 2 - .../scripts/zeta-swap/get-system-data.ts | 1 - .../scripts/zeta-swap/stress-swap.ts | 37 +++++++++---------- .../scripts/zeta-swap/swap-on-zevm.ts | 7 +++- .../test/LiquidityIncentives.spec.ts | 2 +- .../test/MultipleOutput.spec.ts | 2 +- packages/zevm-app-contracts/test/Swap.spec.ts | 2 +- yarn.lock | 27 +++----------- 17 files changed, 64 insertions(+), 68 deletions(-) diff --git a/packages/zeta-app-contracts/package.json b/packages/zeta-app-contracts/package.json index f2536706..5e7f9fe4 100644 --- a/packages/zeta-app-contracts/package.json +++ b/packages/zeta-app-contracts/package.json @@ -31,7 +31,7 @@ "dependencies": { "@openzeppelin/contracts": "^4.8.3", "@zetachain/networks": "^2.4.3", - "@zetachain/protocol-contracts": "^3.0.0", + "@zetachain/protocol-contracts": "^3.0.1", "ethers": "5.6.8" } } diff --git a/packages/zeta-app-contracts/scripts/address.helpers.ts b/packages/zeta-app-contracts/scripts/address.helpers.ts index 9a067b94..2587137d 100644 --- a/packages/zeta-app-contracts/scripts/address.helpers.ts +++ b/packages/zeta-app-contracts/scripts/address.helpers.ts @@ -21,7 +21,7 @@ export const saveAddress = (name: string, address: string) => { console.log(`Updating ${name} address on ${networkName}.`); - const filename = join(__dirname, `./data/addresses.json`); + const filename = join(__dirname, `../data/addresses.json`); const newAddresses = JSON.parse(readFileSync(filename, "utf8")); diff --git a/packages/zeta-app-contracts/scripts/multi-chain-value/deploy.ts b/packages/zeta-app-contracts/scripts/multi-chain-value/deploy.ts index 88c23931..8edb153c 100644 --- a/packages/zeta-app-contracts/scripts/multi-chain-value/deploy.ts +++ b/packages/zeta-app-contracts/scripts/multi-chain-value/deploy.ts @@ -17,6 +17,9 @@ async function main() { await contract.deployed(); console.log("MultiChainValue deployed to:", contract.address); + saveAddress("multiChainValue", contract.address); + + console.log("MultiChainValue post rutine..."); networkName !== "goerli_testnet" && (await (await contract.addAvailableChainId(getChainId("goerli_testnet"))) @@ -34,7 +37,7 @@ async function main() { networkName !== "zeta_testnet" && (await (await contract.addAvailableChainId(getChainId("zeta_testnet"))).wait().catch((e: any) => console.error(e))); - saveAddress("multiChainValue", contract.address); + console.log("MultiChainValue post rutine finish"); } main().catch(error => { diff --git a/packages/zeta-app-contracts/test/MultiChainValue.spec.ts b/packages/zeta-app-contracts/test/MultiChainValue.spec.ts index c37f9ced..de760887 100644 --- a/packages/zeta-app-contracts/test/MultiChainValue.spec.ts +++ b/packages/zeta-app-contracts/test/MultiChainValue.spec.ts @@ -1,5 +1,5 @@ import { SignerWithAddress } from "@nomiclabs/hardhat-ethers/signers"; -import { ZetaEth } from "@zetachain/interfaces/typechain-types"; +import { ZetaEth } from "@zetachain/protocol-contracts/dist/typechain-types"; import { expect } from "chai"; import { parseEther } from "ethers/lib/utils"; import { ethers } from "hardhat"; diff --git a/packages/zevm-app-contracts/contracts/liquidity-incentives/Synthetixio/StakingRewards.sol b/packages/zevm-app-contracts/contracts/liquidity-incentives/Synthetixio/StakingRewards.sol index d2e39461..a0b31474 100644 --- a/packages/zevm-app-contracts/contracts/liquidity-incentives/Synthetixio/StakingRewards.sol +++ b/packages/zevm-app-contracts/contracts/liquidity-incentives/Synthetixio/StakingRewards.sol @@ -31,6 +31,16 @@ contract StakingRewards is RewardsDistributionRecipient, ReentrancyGuard, Pausab uint256 internal _totalSupply; mapping(address => uint256) internal _balances; + /* ========== CUSTOM ERRORS ========== */ + + error CannotStakeZero(); + error CannotWithdrawZero(); + error PreviousRewardsPeriodNotComplete(); + error ProvidedRewardTooHigh(); + error CannotWithdrawStakingToken(); + error RewardIsNotAWrappedAsset(); + error TransferFailed(); + /* ========== CONSTRUCTOR ========== */ constructor( @@ -82,7 +92,7 @@ contract StakingRewards is RewardsDistributionRecipient, ReentrancyGuard, Pausab /* ========== MUTATIVE FUNCTIONS ========== */ function stake(uint256 amount) public virtual nonReentrant notPaused updateReward(msg.sender) { - require(amount > 0, "Cannot stake 0"); + if (amount == 0) revert CannotStakeZero(); _totalSupply = _totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); stakingToken.safeTransferFrom(msg.sender, address(this), amount); @@ -91,14 +101,14 @@ contract StakingRewards is RewardsDistributionRecipient, ReentrancyGuard, Pausab ///@dev This function is added to support staking from the same contract without the need of an extra transfer function _stakeFromContract(uint256 amount) internal notPaused updateReward(msg.sender) { - require(amount > 0, "Cannot stake 0"); + if (amount == 0) revert CannotStakeZero(); _totalSupply = _totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); emit Staked(msg.sender, amount); } function withdraw(uint256 amount) public virtual nonReentrant updateReward(msg.sender) { - require(amount > 0, "Cannot withdraw 0"); + if (amount == 0) revert CannotWithdrawZero(); _totalSupply = _totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); stakingToken.safeTransfer(msg.sender, amount); @@ -120,10 +130,11 @@ contract StakingRewards is RewardsDistributionRecipient, ReentrancyGuard, Pausab // Make the low-level call (bool success, ) = address(rewardsToken).call(data); - require(success, "Reward is not a wrapped asset"); + + if (!success) revert RewardIsNotAWrappedAsset(); (success, ) = msg.sender.call{value: reward}(""); - require(success, "Transfer failed"); + if (!success) revert TransferFailed(); } else rewardsToken.safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } @@ -150,7 +161,7 @@ contract StakingRewards is RewardsDistributionRecipient, ReentrancyGuard, Pausab // very high values of rewardRate in the earned and rewardsPerToken functions; // Reward + leftover must be less than 2^256 / 10^18 to avoid overflow. uint balance = rewardsToken.balanceOf(address(this)); - require(rewardRate <= balance.div(rewardsDuration), "Provided reward too high"); + if (rewardRate > balance.div(rewardsDuration)) revert ProvidedRewardTooHigh(); lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(rewardsDuration); @@ -159,16 +170,13 @@ contract StakingRewards is RewardsDistributionRecipient, ReentrancyGuard, Pausab // Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyOwner { - require(tokenAddress != address(stakingToken), "Cannot withdraw the staking token"); + if (tokenAddress == address(stakingToken)) revert CannotWithdrawStakingToken(); IERC20(tokenAddress).safeTransfer(owner, tokenAmount); emit Recovered(tokenAddress, tokenAmount); } function setRewardsDuration(uint256 _rewardsDuration) external onlyOwner { - require( - block.timestamp > periodFinish, - "Previous rewards period must be complete before changing the duration for the new period" - ); + if (block.timestamp <= periodFinish) revert PreviousRewardsPeriodNotComplete(); rewardsDuration = _rewardsDuration; emit RewardsDurationUpdated(rewardsDuration); } diff --git a/packages/zevm-app-contracts/data/addresses.json b/packages/zevm-app-contracts/data/addresses.json index d13e9e23..08869c18 100644 --- a/packages/zevm-app-contracts/data/addresses.json +++ b/packages/zevm-app-contracts/data/addresses.json @@ -4,7 +4,8 @@ "disperse": "0x1E0F767F48Fb10FcF820703f116E9B0F87319d63", "rewardDistributorFactory": "0x667e4C493d40015256BDC89E3ba750B2F90359E1", "zetaSwap": "0x44D1F1f9289DBA1Cf5824bd667184cEBE020aA1c", - "zetaSwapBtcInbound": "0x008b393933D5CA2457Df570CA5D628380FFf6da4" + "zetaSwapBtcInbound": "0x008b393933D5CA2457Df570CA5D628380FFf6da4", + "invitationManager": "0xF4cF881A3d23936e3710ef2Cbbe93f71C4389918" } } } \ No newline at end of file diff --git a/packages/zevm-app-contracts/package.json b/packages/zevm-app-contracts/package.json index cae9c87e..5eb0760b 100644 --- a/packages/zevm-app-contracts/package.json +++ b/packages/zevm-app-contracts/package.json @@ -32,7 +32,7 @@ "@openzeppelin/contracts": "4.8.3", "@uniswap/v2-periphery": "1.1.0-beta.0", "@zetachain/networks": "^2.4.3", - "@zetachain/protocol-contracts": "^3.0.0", + "@zetachain/protocol-contracts": "^3.0.1", "ethers": "5.6.8" } } diff --git a/packages/zevm-app-contracts/scripts/address.helpers.ts b/packages/zevm-app-contracts/scripts/address.helpers.ts index e3758887..6b19fac2 100644 --- a/packages/zevm-app-contracts/scripts/address.helpers.ts +++ b/packages/zevm-app-contracts/scripts/address.helpers.ts @@ -1,5 +1,5 @@ import { networks } from "@zetachain/networks"; -import { isProtocolNetworkName, ZetaProtocolNetwork } from "@zetachain/protocol-contracts"; +import { ZetaProtocolNetwork } from "@zetachain/protocol-contracts"; import protocolAddresses from "@zetachain/protocol-contracts/dist/data/addresses.json"; import { readFileSync, writeFileSync } from "fs"; import { join } from "path"; @@ -29,7 +29,7 @@ export const saveAddress = (name: string, address: string) => { console.log(`Updating ${name} address on ${networkName}.`); - const filename = join(__dirname, `./data/addresses.json`); + const filename = join(__dirname, `../data/addresses.json`); const newAddresses = JSON.parse(readFileSync(filename, "utf8")); diff --git a/packages/zevm-app-contracts/scripts/uniswap/uniswap.helpers.ts b/packages/zevm-app-contracts/scripts/uniswap/uniswap.helpers.ts index 9fcfd3b2..85724b7a 100644 --- a/packages/zevm-app-contracts/scripts/uniswap/uniswap.helpers.ts +++ b/packages/zevm-app-contracts/scripts/uniswap/uniswap.helpers.ts @@ -2,7 +2,7 @@ import { SignerWithAddress } from "@nomiclabs/hardhat-ethers/signers"; import { formatUnits, parseUnits } from "ethers/lib/utils"; import { ethers } from "hardhat"; -import { IUniswapV2Factory__factory } from "../../../zevm-example-contracts/typechain-types"; +import { IUniswapV2Factory__factory } from "../../typechain-types"; import { ERC20, IUniswapV2Pair__factory } from "../../typechain-types"; export interface Pair { diff --git a/packages/zevm-app-contracts/scripts/zeta-points/deploy.ts b/packages/zevm-app-contracts/scripts/zeta-points/deploy.ts index 40c5bf10..bae20752 100644 --- a/packages/zevm-app-contracts/scripts/zeta-points/deploy.ts +++ b/packages/zevm-app-contracts/scripts/zeta-points/deploy.ts @@ -8,10 +8,8 @@ const networkName = network.name; const invitationManager = async () => { const InvitationManagerFactory = (await ethers.getContractFactory("InvitationManager")) as InvitationManager__factory; - const invitationManager = await InvitationManagerFactory.deploy(); await invitationManager.deployed(); - console.log("InvitationManager deployed to:", invitationManager.address); saveAddress("invitationManager", invitationManager.address); }; diff --git a/packages/zevm-app-contracts/scripts/zeta-swap/get-system-data.ts b/packages/zevm-app-contracts/scripts/zeta-swap/get-system-data.ts index 63a64072..945c0d0b 100644 --- a/packages/zevm-app-contracts/scripts/zeta-swap/get-system-data.ts +++ b/packages/zevm-app-contracts/scripts/zeta-swap/get-system-data.ts @@ -26,7 +26,6 @@ async function main() { console.log(`WZETA:`, WZETAAddress); await getZRC20Address(systemContract, "btc_testnet"); await getZRC20Address(systemContract, "goerli_testnet"); - // await getZRC20Address(systemContract, "klaytn-baobab"); await getZRC20Address(systemContract, "bsc_testnet"); await getZRC20Address(systemContract, "mumbai_testnet"); } diff --git a/packages/zevm-app-contracts/scripts/zeta-swap/stress-swap.ts b/packages/zevm-app-contracts/scripts/zeta-swap/stress-swap.ts index 8e02e66f..e4ad914b 100644 --- a/packages/zevm-app-contracts/scripts/zeta-swap/stress-swap.ts +++ b/packages/zevm-app-contracts/scripts/zeta-swap/stress-swap.ts @@ -10,16 +10,22 @@ import { BigNumber } from "@ethersproject/bignumber"; import { formatEther, parseEther } from "@ethersproject/units"; import { SignerWithAddress } from "@nomiclabs/hardhat-ethers/signers"; -import { getAddress } from "@zetachain/addresses"; -import { ChainToZRC20, getZRC20Address, isSwappableNetwork, SwappableNetwork } from "@zetachain/addresses-tools"; +import { + getAddress, + getZRC20Address, + isProtocolNetworkName, + ZetaProtocolNetwork, + zetaProtocolNetworks +} from "@zetachain/protocol-contracts"; import { ethers, network } from "hardhat"; +import { getZEVMAppAddress } from "../address.helpers"; import { getSwapData } from "./helpers"; -const ZRC20Addresses = getZRC20Address(); +const networkName = network.name; interface SwapToChainParams { - destinationNetwork: SwappableNetwork; + destinationNetwork: ZetaProtocolNetwork; nonce: number; signer: SignerWithAddress; tssAddress: string; @@ -35,8 +41,7 @@ const swapToChain = async ({ value, nonce }: SwapToChainParams) => { - const zrc20 = ChainToZRC20[destinationNetwork]; - const data = getSwapData(zetaSwapAddress, signer.address, ZRC20Addresses[zrc20], BigNumber.from("0")); + const data = getSwapData(zetaSwapAddress, signer.address, getZRC20Address(destinationNetwork), BigNumber.from("0")); const tx = await signer.sendTransaction({ data, nonce, @@ -47,12 +52,12 @@ const swapToChain = async ({ }; const main = async () => { - if (!isSwappableNetwork(network.name) || !network.name) throw new Error("Invalid network name"); - const swappableNetwork: SwappableNetwork = network.name; + if (!isProtocolNetworkName(networkName)) throw new Error("Invalid network name"); + const swappableNetwork: ZetaProtocolNetwork = networkName; // @dev: bitcoin is invalid as destination - const invalidDestinations: SwappableNetwork[] = [swappableNetwork, "btc_testnet"]; - const networks = Object.keys(ChainToZRC20).map(c => c as SwappableNetwork); + const invalidDestinations: ZetaProtocolNetwork[] = [swappableNetwork, "btc_testnet"]; + const networks = zetaProtocolNetworks.map(c => c as ZetaProtocolNetwork); const destinationNetworks = networks.filter(e => !invalidDestinations.includes(e)); @@ -60,17 +65,9 @@ const main = async () => { const [signer] = await ethers.getSigners(); - const zetaSwapAddress = getAddress({ - address: "zetaSwap", - networkName: "athens", - zetaNetwork: "athens" - }); + const zetaSwapAddress = getZEVMAppAddress("zetaSwap"); - const tssAddress = getAddress({ - address: "tss", - networkName: network.name, - zetaNetwork: "athens" - }); + const tssAddress = getAddress("tss", swappableNetwork); const nonce = await signer.getTransactionCount(); diff --git a/packages/zevm-app-contracts/scripts/zeta-swap/swap-on-zevm.ts b/packages/zevm-app-contracts/scripts/zeta-swap/swap-on-zevm.ts index f72149e5..5a677893 100644 --- a/packages/zevm-app-contracts/scripts/zeta-swap/swap-on-zevm.ts +++ b/packages/zevm-app-contracts/scripts/zeta-swap/swap-on-zevm.ts @@ -37,7 +37,12 @@ const main = async () => { params = getSwapParams(signer.address, getZRC20Address("goerli_testnet"), BigNumber.from("0")); zetaSwapContract = ZetaSwap__factory.connect(zetaSwap, signer); } - const tx1 = await zetaSwapContract.onCrossChainCall(sourceToken, amount, params); + const zContextStruct = { + chainID: ethers.BigNumber.from("0"), + origin: ethers.constants.HashZero, + sender: ethers.constants.AddressZero + }; + const tx1 = await zetaSwapContract.onCrossChainCall(zContextStruct, sourceToken, amount, params); await tx1.wait(); console.log("tx:", tx1.hash); diff --git a/packages/zevm-app-contracts/test/LiquidityIncentives.spec.ts b/packages/zevm-app-contracts/test/LiquidityIncentives.spec.ts index 28892388..55c92d3c 100644 --- a/packages/zevm-app-contracts/test/LiquidityIncentives.spec.ts +++ b/packages/zevm-app-contracts/test/LiquidityIncentives.spec.ts @@ -54,7 +54,7 @@ describe("LiquidityIncentives tests", () => { const uniswapRouterAddr = getNonZetaAddress("uniswapV2Router02", "eth_mainnet"); - const uniswapFactoryAddr = "0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f"; // getNonZetaAddress("uniswapV2Factory02", "etherum_mainnet"); + const uniswapFactoryAddr = getNonZetaAddress("uniswapV2Factory", "eth_mainnet"); const wGasToken = getNonZetaAddress("weth9", "eth_mainnet"); diff --git a/packages/zevm-app-contracts/test/MultipleOutput.spec.ts b/packages/zevm-app-contracts/test/MultipleOutput.spec.ts index 70b0d4ec..fa48e54c 100644 --- a/packages/zevm-app-contracts/test/MultipleOutput.spec.ts +++ b/packages/zevm-app-contracts/test/MultipleOutput.spec.ts @@ -24,7 +24,7 @@ describe("ZetaSwap tests", () => { const uniswapRouterAddr = getNonZetaAddress("uniswapV2Router02", "eth_mainnet"); - const uniswapFactoryAddr = "0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f"; // getNonZetaAddress("uniswapV2Factory02", "etherum_mainnet"); + const uniswapFactoryAddr = getNonZetaAddress("uniswapV2Factory", "eth_mainnet"); const wGasToken = getNonZetaAddress("weth9", "eth_mainnet"); diff --git a/packages/zevm-app-contracts/test/Swap.spec.ts b/packages/zevm-app-contracts/test/Swap.spec.ts index bd6850ce..a784c744 100644 --- a/packages/zevm-app-contracts/test/Swap.spec.ts +++ b/packages/zevm-app-contracts/test/Swap.spec.ts @@ -33,7 +33,7 @@ describe("ZetaSwap tests", () => { const uniswapRouterAddr = getNonZetaAddress("uniswapV2Router02", "eth_mainnet"); - const uniswapFactoryAddr = "0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f"; // getNonZetaAddress("uniswapV2Factory02", "etherum_mainnet"); + const uniswapFactoryAddr = getNonZetaAddress("uniswapV2Factory", "eth_mainnet"); const wGasToken = getNonZetaAddress("weth9", "eth_mainnet"); diff --git a/yarn.lock b/yarn.lock index d4c1af80..be28d256 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2542,10 +2542,10 @@ __metadata: languageName: node linkType: hard -"@zetachain/protocol-contracts@npm:^3.0.0": - version: 3.0.0 - resolution: "@zetachain/protocol-contracts@npm:3.0.0" - checksum: 2bfc8fe05e5e5145cecfb76dd7fe72c22388f7303ebab6039bfa11c92fe89d1bcbe562741dc3d7b3e3819393515c641c4034ebce55bed11f4667be384dddb652 +"@zetachain/protocol-contracts@npm:^3.0.1": + version: 3.0.1 + resolution: "@zetachain/protocol-contracts@npm:3.0.1" + checksum: 5a833dc9f59b69b83654754f4587aad57f4c9859908bc3fd9b5f3f6329cf803bf68e66aff4f355a99fb7e23726526196610e43987d15ec60208cc5564bc94259 languageName: node linkType: hard @@ -2556,7 +2556,7 @@ __metadata: "@defi-wonderland/smock": ^2.3.4 "@openzeppelin/contracts": ^4.8.3 "@zetachain/networks": ^2.4.3 - "@zetachain/protocol-contracts": ^3.0.0 + "@zetachain/protocol-contracts": ^3.0.1 ethers: 5.6.8 hardhat-gas-reporter: ^1.0.8 solidity-coverage: ^0.7.20 @@ -2571,22 +2571,7 @@ __metadata: "@openzeppelin/contracts": 4.8.3 "@uniswap/v2-periphery": 1.1.0-beta.0 "@zetachain/networks": ^2.4.3 - "@zetachain/protocol-contracts": ^3.0.0 - ethers: 5.6.8 - hardhat-gas-reporter: ^1.0.8 - solidity-coverage: ^0.7.20 - tsconfig-paths: ^3.14.1 - languageName: unknown - linkType: soft - -"@zetachain/zevm-example-contracts@workspace:packages/zevm-example-contracts": - version: 0.0.0-use.local - resolution: "@zetachain/zevm-example-contracts@workspace:packages/zevm-example-contracts" - dependencies: - "@openzeppelin/contracts": ^4.8.3 - "@uniswap/v2-periphery": 1.1.0-beta.0 - "@zetachain/networks": ^2.4.3 - "@zetachain/protocol-contracts": ^3.0.0 + "@zetachain/protocol-contracts": ^3.0.1 ethers: 5.6.8 hardhat-gas-reporter: ^1.0.8 solidity-coverage: ^0.7.20 From 2a17f4a04412cffb0a5737eeb82aa75f719a5af0 Mon Sep 17 00:00:00 2001 From: Andres Aiello Date: Thu, 16 Nov 2023 14:38:25 -0300 Subject: [PATCH 5/6] remove unused code --- .../Synthetixio/StakingRewards.sol | 30 +++++++------------ .../scripts/uniswap/sell-zeta.ts | 3 +- 2 files changed, 12 insertions(+), 21 deletions(-) diff --git a/packages/zevm-app-contracts/contracts/liquidity-incentives/Synthetixio/StakingRewards.sol b/packages/zevm-app-contracts/contracts/liquidity-incentives/Synthetixio/StakingRewards.sol index a0b31474..d2e39461 100644 --- a/packages/zevm-app-contracts/contracts/liquidity-incentives/Synthetixio/StakingRewards.sol +++ b/packages/zevm-app-contracts/contracts/liquidity-incentives/Synthetixio/StakingRewards.sol @@ -31,16 +31,6 @@ contract StakingRewards is RewardsDistributionRecipient, ReentrancyGuard, Pausab uint256 internal _totalSupply; mapping(address => uint256) internal _balances; - /* ========== CUSTOM ERRORS ========== */ - - error CannotStakeZero(); - error CannotWithdrawZero(); - error PreviousRewardsPeriodNotComplete(); - error ProvidedRewardTooHigh(); - error CannotWithdrawStakingToken(); - error RewardIsNotAWrappedAsset(); - error TransferFailed(); - /* ========== CONSTRUCTOR ========== */ constructor( @@ -92,7 +82,7 @@ contract StakingRewards is RewardsDistributionRecipient, ReentrancyGuard, Pausab /* ========== MUTATIVE FUNCTIONS ========== */ function stake(uint256 amount) public virtual nonReentrant notPaused updateReward(msg.sender) { - if (amount == 0) revert CannotStakeZero(); + require(amount > 0, "Cannot stake 0"); _totalSupply = _totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); stakingToken.safeTransferFrom(msg.sender, address(this), amount); @@ -101,14 +91,14 @@ contract StakingRewards is RewardsDistributionRecipient, ReentrancyGuard, Pausab ///@dev This function is added to support staking from the same contract without the need of an extra transfer function _stakeFromContract(uint256 amount) internal notPaused updateReward(msg.sender) { - if (amount == 0) revert CannotStakeZero(); + require(amount > 0, "Cannot stake 0"); _totalSupply = _totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); emit Staked(msg.sender, amount); } function withdraw(uint256 amount) public virtual nonReentrant updateReward(msg.sender) { - if (amount == 0) revert CannotWithdrawZero(); + require(amount > 0, "Cannot withdraw 0"); _totalSupply = _totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); stakingToken.safeTransfer(msg.sender, amount); @@ -130,11 +120,10 @@ contract StakingRewards is RewardsDistributionRecipient, ReentrancyGuard, Pausab // Make the low-level call (bool success, ) = address(rewardsToken).call(data); - - if (!success) revert RewardIsNotAWrappedAsset(); + require(success, "Reward is not a wrapped asset"); (success, ) = msg.sender.call{value: reward}(""); - if (!success) revert TransferFailed(); + require(success, "Transfer failed"); } else rewardsToken.safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } @@ -161,7 +150,7 @@ contract StakingRewards is RewardsDistributionRecipient, ReentrancyGuard, Pausab // very high values of rewardRate in the earned and rewardsPerToken functions; // Reward + leftover must be less than 2^256 / 10^18 to avoid overflow. uint balance = rewardsToken.balanceOf(address(this)); - if (rewardRate > balance.div(rewardsDuration)) revert ProvidedRewardTooHigh(); + require(rewardRate <= balance.div(rewardsDuration), "Provided reward too high"); lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(rewardsDuration); @@ -170,13 +159,16 @@ contract StakingRewards is RewardsDistributionRecipient, ReentrancyGuard, Pausab // Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyOwner { - if (tokenAddress == address(stakingToken)) revert CannotWithdrawStakingToken(); + require(tokenAddress != address(stakingToken), "Cannot withdraw the staking token"); IERC20(tokenAddress).safeTransfer(owner, tokenAmount); emit Recovered(tokenAddress, tokenAmount); } function setRewardsDuration(uint256 _rewardsDuration) external onlyOwner { - if (block.timestamp <= periodFinish) revert PreviousRewardsPeriodNotComplete(); + require( + block.timestamp > periodFinish, + "Previous rewards period must be complete before changing the duration for the new period" + ); rewardsDuration = _rewardsDuration; emit RewardsDurationUpdated(rewardsDuration); } diff --git a/packages/zevm-app-contracts/scripts/uniswap/sell-zeta.ts b/packages/zevm-app-contracts/scripts/uniswap/sell-zeta.ts index 4ecc5c61..49cdefce 100644 --- a/packages/zevm-app-contracts/scripts/uniswap/sell-zeta.ts +++ b/packages/zevm-app-contracts/scripts/uniswap/sell-zeta.ts @@ -1,5 +1,4 @@ -import { MaxUint256 } from "@ethersproject/constants"; -import { formatUnits, parseUnits } from "@ethersproject/units"; +import { parseUnits } from "@ethersproject/units"; import { SignerWithAddress } from "@nomiclabs/hardhat-ethers/signers"; import { getNonZetaAddress, isProtocolNetworkName, ZetaProtocolNetwork } from "@zetachain/protocol-contracts"; import { BigNumber } from "ethers"; From 9a9d91a0cc3b6e2dd70a787304add17dbfe65bf1 Mon Sep 17 00:00:00 2001 From: Andres Aiello Date: Fri, 24 Nov 2023 16:34:45 -0300 Subject: [PATCH 6/6] add type to getAppAddress --- packages/zeta-app-contracts/scripts/address.helpers.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/zeta-app-contracts/scripts/address.helpers.ts b/packages/zeta-app-contracts/scripts/address.helpers.ts index 2587137d..8aa86ff9 100644 --- a/packages/zeta-app-contracts/scripts/address.helpers.ts +++ b/packages/zeta-app-contracts/scripts/address.helpers.ts @@ -6,7 +6,9 @@ import { join } from "path"; import addresses from "../data/addresses.json"; -export const getAppAddress = (address: string, network: ZetaProtocolNetwork): string => { +export type AppAddress = "multiChainSwap" | "multiChainValue" | "zetaTokenConsumerUniV2" | "zetaTokenConsumerUniV3"; + +export const getAppAddress = (address: AppAddress, network: ZetaProtocolNetwork): string => { return (addresses["ccm"] as any)[network][address]; };