Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Gateway localnet examples #189

Merged
merged 18 commits into from
Aug 31, 2024
10 changes: 5 additions & 5 deletions omnichain/swap/tasks/deploy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@ import { HardhatRuntimeEnvironment } from "hardhat/types";
const main = async (args: any, hre: HardhatRuntimeEnvironment) => {
const network = hre.network.name as ParamChainName;

if (!/zeta_(testnet|mainnet)/.test(network)) {
throw new Error(
'🚨 Please use either "zeta_testnet" or "zeta_mainnet" network to deploy to ZetaChain.'
);
}
// if (!/zeta_(testnet|mainnet)/.test(network)) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if it's no longer valid just delete it, let's try to keep code clean

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reverted, because it's still relevant: 4095527

// throw new Error(
// '🚨 Please use either "zeta_testnet" or "zeta_mainnet" network to deploy to ZetaChain.'
// );
// }

const [signer] = await hre.ethers.getSigners();
if (signer === undefined) {
Expand Down
6 changes: 6 additions & 0 deletions universal/hello/.eslintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
.yarn
artifacts
cache
coverage
node_modules
typechain-types
47 changes: 47 additions & 0 deletions universal/hello/.eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
const path = require("path");

/**
* @type {import("eslint").Linter.Config}
*/
module.exports = {
env: {
browser: false,
es2021: true,
mocha: true,
node: true,
},
extends: ["plugin:prettier/recommended"],
parser: "@typescript-eslint/parser",
parserOptions: {
ecmaVersion: 12,
},
plugins: [
"@typescript-eslint",
"prettier",
"simple-import-sort",
"sort-keys-fix",
"typescript-sort-keys",
],
rules: {
"@typescript-eslint/sort-type-union-intersection-members": "error",
camelcase: "off",
"simple-import-sort/exports": "error",
"simple-import-sort/imports": "error",
"sort-keys-fix/sort-keys-fix": "error",
"typescript-sort-keys/interface": "error",
"typescript-sort-keys/string-enum": "error",
},
settings: {
"import/parsers": {
"@typescript-eslint/parser": [".js", ".jsx", ".ts", ".tsx", ".d.ts"],
},
"import/resolver": {
node: {
extensions: [".js", ".jsx", ".ts", ".tsx", ".d.ts"],
},
typescript: {
project: path.join(__dirname, "tsconfig.json"),
},
},
},
};
17 changes: 17 additions & 0 deletions universal/hello/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
node_modules
.env
coverage
coverage.json
typechain
typechain-types
dependencies

# Hardhat files
cache
artifacts

# Foundry files
out
cache_forge

access_token
21 changes: 21 additions & 0 deletions universal/hello/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 ZetaChain

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
15 changes: 15 additions & 0 deletions universal/hello/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# ZetaChain Contracts Template

## Getting Started

Install dependencies:

```
yarn
```

## Next Steps

Ready to dive in? Follow our [**🚀 smart contract
tutorials**](https://www.zetachain.com/docs/developers/tutorials/intro/) to
start building universal app contracts.
55 changes: 55 additions & 0 deletions universal/hello/contracts/Hello.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";

import {RevertContext, RevertOptions} from "@zetachain/protocol-contracts/contracts/Revert.sol";
import "@zetachain/protocol-contracts/contracts/zevm/interfaces/UniversalContract.sol";
import "@zetachain/protocol-contracts/contracts/zevm/interfaces/IGatewayZEVM.sol";
import "@zetachain/protocol-contracts/contracts/zevm/interfaces/IZRC20.sol";

contract Hello is UniversalContract {
event HelloEvent(string, string);

event ContextDataRevert(RevertContext revertContext);

address constant gateway = 0x610178dA211FEF7D417bC0e6FeD39F05609AD788;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: let's call it gatewayAddress

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.


function onCrossChainCall(
zContext calldata context,
address zrc20,
uint256 amount,
bytes calldata message
) external override {
string memory decodedMessage;
if (message.length > 0) {
decodedMessage = abi.decode(message, (string));
}
emit HelloEvent("Hello from a universal app", decodedMessage);
}

function callFromZetaChain(
bytes memory receiver,
address zrc20,
bytes calldata message,
uint256 gasLimit,
RevertOptions memory revertOptions
) external {
IZRC20(zrc20).approve(gateway, 1_000_000_000);
IGatewayZEVM(gateway).call(
receiver,
zrc20,
message,
gasLimit,
revertOptions
);
}

function onRevert(RevertContext calldata revertContext) external override {
emit ContextDataRevert(revertContext);
}

receive() external payable {}

fallback() external payable {}
}
27 changes: 27 additions & 0 deletions universal/hello/contracts/RevertContract.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";

import {RevertContext} from "@zetachain/protocol-contracts/contracts/Revert.sol";
import "@zetachain/protocol-contracts/contracts/zevm/interfaces/UniversalContract.sol";

contract RevertContract {
event RevertEvent(string message);
event HelloEvent(string name);

event ContextDataRevert(RevertContext revertContext);

function onRevert(RevertContext calldata revertContext) external {
// emit ContextDataRevert(revertContext);
emit RevertEvent("Event from RevertContract!!!");
}

function hello(string memory name) external {
emit HelloEvent(name);
}

receive() external payable {}

fallback() external payable {}
}
11 changes: 11 additions & 0 deletions universal/hello/foundry.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
[profile.default]
src = 'contracts'
out = 'out'
viaIR = true
libs = ['node_modules', 'lib']
test = 'test'
cache_path = 'cache_forge'
verbosity = 3

[dependencies]
forge-std = { version = "1.9.2" }
19 changes: 19 additions & 0 deletions universal/hello/hardhat.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import "./tasks/interact";
import "./tasks/deploy";
import "./tasks/callFromZetaChain";
import "./tasks/solana/interact";
import "@zetachain/localnet/tasks";
import "@nomicfoundation/hardhat-toolbox";
import "@zetachain/toolkit/tasks";

import { getHardhatConfigNetworks } from "@zetachain/networks";
import { HardhatUserConfig } from "hardhat/config";

const config: HardhatUserConfig = {
networks: {
...getHardhatConfigNetworks(),
},
solidity: "0.8.26",
};

export default config;
62 changes: 62 additions & 0 deletions universal/hello/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
{
"name": "example-template",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"lint:fix": "npx eslint . --ext .js,.ts --fix",
"lint": "npx eslint . --ext .js,.ts",
"deploy": "npx hardhat compile --force && npx hardhat deploy --network localhost --name Hello && npx hardhat deploy --network localhost --name RevertContract"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@ethersproject/abi": "^5.4.7",
"@ethersproject/providers": "^5.4.7",
"@nomicfoundation/hardhat-chai-matchers": "^1.0.0",
"@nomicfoundation/hardhat-foundry": "^1.1.2",
"@nomicfoundation/hardhat-network-helpers": "^1.0.0",
"@nomicfoundation/hardhat-toolbox": "^2.0.0",
"@nomiclabs/hardhat-ethers": "^2.0.0",
"@nomiclabs/hardhat-etherscan": "^3.0.0",
"@typechain/ethers-v5": "^10.1.0",
"@typechain/hardhat": "^6.1.2",
"@types/chai": "^4.2.0",
"@types/mocha": ">=9.1.0",
"@types/node": ">=12.0.0",
"@typescript-eslint/eslint-plugin": "^5.59.9",
"@typescript-eslint/parser": "^5.59.9",
"@zetachain/localnet": "1.0.0-rc9",
"@zetachain/protocol-contracts": "10.0.0-rc9",
"@zetachain/toolkit": "^10.0.0",
"axios": "^1.3.6",
"chai": "^4.2.0",
"dotenv": "^16.0.3",
"envfile": "^6.18.0",
"eslint": "^8.42.0",
"eslint-config-prettier": "^8.8.0",
"eslint-import-resolver-typescript": "^3.5.5",
"eslint-plugin-import": "^2.27.5",
"eslint-plugin-prettier": "^4.2.1",
"eslint-plugin-simple-import-sort": "^10.0.0",
"eslint-plugin-sort-keys-fix": "^1.1.2",
"eslint-plugin-typescript-sort-keys": "^2.3.0",
"ethers": "^5.4.7",
"hardhat": "^2.17.2",
"hardhat-gas-reporter": "^1.0.8",
"prettier": "^2.8.8",
"solidity-coverage": "^0.8.0",
"ts-node": ">=8.0.0",
"typechain": "^8.1.0",
"typescript": ">=4.5.0"
},
"packageManager": "[email protected]+sha1.1959a18351b811cdeedbd484a8f86c3cc3bbaf72",
"dependencies": {
"@coral-xyz/anchor": "0.30.0",
"@solana-developers/helpers": "^2.4.0",
"@solana/spl-memo": "^0.2.5",
"@solana/web3.js": "^1.95.2"
}
}
78 changes: 78 additions & 0 deletions universal/hello/tasks/callFromZetaChain.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import { task, types } from "hardhat/config";
import type { HardhatRuntimeEnvironment } from "hardhat/types";

const main = async (args: any, hre: HardhatRuntimeEnvironment) => {
const [signer] = await hre.ethers.getSigners();

const contractArtifact = await hre.artifacts.readArtifact("Hello");
const contract = new hre.ethers.Contract(
args.contract,
contractArtifact.abi,
signer
);
Comment on lines +4 to +12
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider validating input parameters.

While the function retrieves the signer and contract artifact correctly, it lacks validation for args.contract to ensure it is a valid Ethereum address. Consider adding validation to prevent runtime errors.

import { isAddress } from "ethers/lib/utils";

// Validate contract address
if (!isAddress(args.contract)) {
  throw new Error("Invalid contract address");
}


const zrc20Artifact = await hre.artifacts.readArtifact("IZRC20");
const zrc20 = new hre.ethers.Contract(args.zrc20, zrc20Artifact.abi, signer);

const revertMessageBytes = hre.ethers.utils.toUtf8Bytes(args.revertMessage);

// Encode the function signature using ethers.utils.id and concatenate with encoded parameters
const functionSignature = hre.ethers.utils.id("hello(string)").slice(0, 10); // Get the first 4 bytes (function selector)
const encodedParameters = hre.ethers.utils.defaultAbiCoder.encode(
["string"],
[args.message]
);

// Concatenate the function signature and the encoded parameters
const message = hre.ethers.utils.hexlify(
hre.ethers.utils.concat([functionSignature, encodedParameters])
);

try {
const zrc20TransferTx = await zrc20.transfer(args.contract, 500_000_000, {
gasPrice: 10000000000,
gasLimit: 7000000,
});
await zrc20TransferTx.wait();

const tx = await contract.callFromZetaChain(
hre.ethers.utils.hexlify(args.receiver),
args.zrc20,
message,
args.gasLimit,
{
revertAddress: args.revertAddress,
callOnRevert: args.callOnRevert,
abortAddress: "0x0000000000000000000000000000000000000000", // not used
revertMessage: hre.ethers.utils.hexlify(revertMessageBytes),
},
{
gasPrice: 10000000000,
gasLimit: 7000000,
}
);

await tx.wait();
console.log("Successfully called the contract on ZetaChain!");
} catch (e) {
console.error("Error calling contract:", e);
}
};

task(
"call-from-zetachain",
"Calls the callFromZetaChain function on a universal app",
main
)
.addParam("message", "A message")
.addParam("contract", "The address of the universal app on ZetaChain")
.addOptionalParam(
"zrc20",
"The address of the ZRC20 token",
"0x9fd96203f7b22bCF72d9DCb40ff98302376cE09c"
)
.addParam("gasLimit", "The gas limit for the transaction", 7000000, types.int)
.addFlag("callOnRevert", "Whether to call on revert")
.addParam("revertAddress")
.addParam("revertMessage")
.addParam("receiver", "The address of the receiver contract on EVM");
Loading
Loading