# contcontract

By [ysbear](https://paragraph.com/@ysbear666) · 2023-05-24

---

1、打开gitpod

2、nvm install 16

3、新建文件夹

    mkdir ex
    cd ex
    

4、安装依赖

    yarn init -y
    
    yarn add -D typescript ts-node ethers@^5.7.2 zksync-web3 hardhat @matterlabs/hardhat-zksync-solc @matterlabs/hardhat-zksync-deploy
    
    yarn add -D @matterlabs/hardhat-zksync-verify @nomicfoundation/hardhat-verify
    

5、新建配置文件，命名为"hardhat.config.ts"。

6、填进去

默认测试网

    import "@matterlabs/hardhat-zksync-deploy";
    import "@matterlabs/hardhat-zksync-solc";
    import "@matterlabs/hardhat-zksync-verify";
    module.exports = {
      zksolc: {
        version: "1.3.13",
        compilerSource: "binary",
        settings: {},
      },
      defaultNetwork: "zkSyncTestnet",
    
      networks: {
        zkSyncTestnet: {
          url: "https://zksync2-testnet.zksync.dev",
          ethNetwork: "goerli",
          zksync: true,
        }, 
      },
      solidity: {
        version: "0.8.17",
      },
    };
    

默认主网

    import "@matterlabs/hardhat-zksync-deploy";
    import "@matterlabs/hardhat-zksync-solc";
    import "@matterlabs/hardhat-zksync-verify";
    module.exports = {
      zksolc: {
        version: "1.3.13",
        compilerSource: "binary",
        settings: {},
      },
      defaultNetwork: "zkMainnet",
    
      networks: {
        zkSyncTestnet: {
          url: "https://zksync2-testnet.zksync.dev",
          ethNetwork: "goerli",
          zksync: true,
        },
        zkMainnet: {
          url: "https://zksync2-mainnet.zksync.io",
          ethNetwork: "mainnet",
          zksync: true,
        }
      },
      solidity: {
        version: "0.8.17",
      },
    };
    

7、建两个文件夹 一个叫contracts，一个叫deploy

mkdir contracts deploy

8、在contracts文件夹下建立EHS.sol文件，代码如下（如果是部署erc20合约就贴你自己的erc20合约）：

    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.17;
    
    contract EHS {
    }
    

    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.17;
    
    contract WXY {
        string public name = "WXY";
        string public symbol = "WXY";
        uint8 public decimals = 18;
        uint256 public totalSupply = 0;
        uint256 public maxSupply = 100000000 * 10**uint256(decimals);
        uint256 public mintedTokens = 0;
        bool public mintingFinished = false;
    
        mapping(address => uint256) public balanceOf;
    
        event Transfer(address indexed from, address indexed to, uint256 value);
        event Mint(address indexed to, uint256 value);
        event MintFinished();
    
        modifier canMint() {
            require(!mintingFinished, "Minting has already finished");
            _;
        }
    
        constructor() {
            balanceOf[msg.sender] = totalSupply;
        }
    
        function transfer(address to, uint256 value) external returns (bool) {
            require(value >= 1 * 10**uint256(decimals), "Invalid transfer amount");
    
            balanceOf[msg.sender] -= value;
            balanceOf[to] += value;
    
            emit Transfer(msg.sender, to, value);
            return true;
        }
    
        function mint() external canMint() {
            require(totalSupply + 1 <= maxSupply, "Exceeds maximum supply");
    
            balanceOf[msg.sender] += 1;
            totalSupply += 1;
            mintedTokens += 1;
            mintingFinished = true;
    
            emit Mint(msg.sender, 1);
            emit MintFinished();
        }
    }
    

9、编译合约

    yarn hardhat compile
    

10、安装dotenv库

npm install dotenv

12、新建.env文件填入

    WALLET_PRIVATE_KEY=your_private_key_here
    NODE_ENV=test
    

12、在deploy文件夹下创建deploy.ts文件

    import { Wallet, utils } from "zksync-web3";
    import * as ethers from "ethers";
    import { HardhatRuntimeEnvironment } from "hardhat/types";
    import { Deployer } from "@matterlabs/hardhat-zksync-deploy";
    
    // load env file
    import dotenv from "dotenv";
    dotenv.config();
    
    // load wallet private key from env file
    const PRIVATE_KEY = process.env.WALLET_PRIVATE_KEY || "";
    
    if (!PRIVATE_KEY) throw "⛔️ Private key not detected! Add it to the .env file!";
    
    // An example of a deploy script that will deploy and call a simple contract.
    export default async function (hre: HardhatRuntimeEnvironment) {
      console.log(`Running deploy script for the WXY contract`);
    
      // Initialize the wallet.
      const wallet = new Wallet(PRIVATE_KEY);
    
      // Create deployer object and load the artifact of the contract you want to deploy.
      const deployer = new Deployer(hre, wallet);
      const artifact = await deployer.loadArtifact("WXY");
    
      // Estimate contract deployment fee
      const deploymentFee = await deployer.estimateDeployFee(artifact, [ ]);
    
      // ⚠️ OPTIONAL: You can skip this block if your account already has funds in L2
      // Deposit funds to L2
      // const depositHandle = await deployer.zkWallet.deposit({
      //   to: deployer.zkWallet.address,
      //   token: utils.ETH_ADDRESS,
      //   amount: deploymentFee.mul(2),
      // });
      // // Wait until the deposit is processed on zkSync
      // await depositHandle.wait();
    
      // Deploy this contract. The returned object will be of a `Contract` type, similarly to ones in `ethers`.
      // `greeting` is an argument for contract constructor.
      const parsedFee = ethers.utils.formatEther(deploymentFee.toString());
      console.log(`The deployment is estimated to cost ${parsedFee} ETH`);
    
      const deployedContract = await deployer.deploy(artifact, []);
    
      //obtain the Constructor Arguments
      console.log("Constructor args:" + deployedContract.interface.encodeDeploy([]));
    
      // Show the contract info.
      const contractAddress = deployedContract.address;
      console.log(`${artifact.contractName} was deployed to ${contractAddress}`);
    
      // verify contract for tesnet & mainnet
      if (process.env.NODE_ENV != "test") {
        // Contract MUST be fully qualified name (e.g. path/sourceName:contractName)
        const contractFullyQualifedName = "contracts/WXY.sol:WXY";
    
        // Verify contract programmatically
        const verificationId = await hre.run("verify:verify", {
          address: contractAddress,
          contract: contractFullyQualifedName,
          bytecode: artifact.bytecode,
        });
      } else {
        console.log(`Contract not verified, deployed locally.`);
      }
    }
    

13、部署合约

    yarn hardhat deploy-zksync
    

14、合约验证

借助 Remix 展开合约，获取单一文件格式的代码，右键选择 Flatten，然后填入代码行进行验证

15、构建前端dapp

[Subscribe](null)

---

*Originally published on [ysbear](https://paragraph.com/@ysbear666/contcontract)*
