Automatically verify contract code on Etherscan with the Truffle plugin

Translation from : Dengchain Translation Project _


Etherscan is the most popular browser on Ethereum. One of its functions is to verify the source code of smart contracts . It enables users to understand the functions of the contract through the source code before using the contract. This increases the user's trust in the contract and thus benefits the developer.

Submitting codes through the Etherscan website form is the primary method of validating codes, but it requires a lot of manual work . Contents such as compiler version and constructor parameters need to be entered, and the contract source code after expansion needs to be submitted. The code needs to exactly match the deployed code.

Some people use command line tools to unwind Truffle contracts and use the browser-based Remix IDE to deploy the unrolled source code. Then, copy the same expanded source code to Etherscan to validate the form submission. This is a very tedious process and should be automated.

This is why I created the  truffle-plugin-verify  plugin, which automatically verifies Truffle contracts via the Etherscan API. This plugin is an open source project with many different participants, including some of Ren 's developers. Use this plugin to verify contracts with a simple command:

truffle run verify ContractName

Dependency

In this article, we assume that you already have a deployable Truffle project. If not, you can refer to this Truffle tutorial , which also explains how to use Infura to set up the deployment of a Truffle project.

You can also check out the source code for this article on GitHub .

contract

Let's take the Casino contract as an example. In the contract, players can bet 1-10 ETH. To make sure the contract doesn't run out of money, players can only bet a fraction of the total contract amount.

The winning number is the result of modulo operation on the current block number. This operation is OK in testing, but be aware that it may be abused in production.

In this article, we will specifically split the contract further so that it is spread across multiple files. It is convenient to show the full functionality of the plugin.

contracts/Killable.sol

pragma solidity ^0.5.8;

contract Killable {
    address payable public owner;

    constructor() public {
        owner = msg.sender;
    }

    function kill() external {
        require(msg.sender == owner, "Only the owner can kill this contract");
        selfdestruct(owner);
    }
}

contracts/Casino.sol

pragma solidity ^0.5.8;

import "./Killable.sol"

contract Casino is Killable {
    event Play(address payable indexed player, uint256 betSize, uint8 betNumber, uint8 winningNumber);
    event Payout(address payable winner, uint256 payout);

    function fund() external payable {}

    function bet(uint8 number) external payable {
        require(msg.value <= getMaxBet(), "Bet amount can not exceed max bet size");
        require(msg.value >0, "A bet should be placed");

        uint8 winningNumber = generateWinningNumber();
        emit Play(msg.sender, msg.value, number, winningNumber);

        if (number == winningNumber) {
            payout(msg.sender, msg.value * 10);
        }
    }

    function getMaxBet() public view returns (uint256) {
        return address(this).balance / 100;
    }

    function generateWinningNumber() internal view returns (uint8) {
        return uint8(block.number % 10 + 1); // Don't do this in production
    }

    function payout(address payable winner, uint256 amount) internal {
        assert(amount > 0);
        assert(amount <= address(this).balance);

        winner.transfer(amount);
        emit Payout(winner, amount);
    }
}

Verify the contract

Now that we have the contract ready, we can show how simple it is to verify the contract using truffle-plugin-verify.

1. Install & enable truffle-plugin-verify

The Truffle plugin can be installed using npm or yarn:

npm install -D truffle-plugin-verify
yarn add -D truffle-plugin-verify

After installation, add the following to the truffle-config.jsor truffle.jsfile for Truffle to enable the plugin:

module.exports = {
  /* ... rest of truffle-config */

  plugins: [
    'truffle-plugin-verify'
  ]
}

2. Create an Etherscan API key and add it to Truffle

To create an Etherscan API key, you first need to create an account on the Etherscan website . After creating an account, a new API key can be added on the profile page as shown in the image above. After creating the new key, add it to the truffle-config.js or  truffle.jsfile api_keysunder:

module.exports = {
  /* ... rest of truffle-config */

  api_keys: {
    etherscan: 'MY_API_KEY'
  }
}

Currently, you can not submit the API key to the code base. It is recommended to use  dotenv.env to save the API key, then ignore the file  in the git repository  , and then read it in the truffle-config.js or  truffle.jsconfiguration file. The reading method is as follows:

var HDWalletProvider = require("truffle-hdwallet-provider");
require('dotenv').config();

module.exports = {
  networks: {
    rinkeby: {
      provider: function() {
        return new HDWalletProvider(`${process.env.MNEMONIC}`, `https://rinkeby.infura.io/v3/${process.env.INFURA_ID}`)
      },
      network_id: 4
    }
  },
  plugins: [
   'truffle-plugin-verify'
  ],
  api_keys: {
    etherscan: process.env.ETHERSCAN_API_KEY
  }
};

Your config file may differ from the above, but as long as the public network deployment is set up, and both are set up correctly plugins, api_keysyou should be fine.

3. Deploy and verify the contract

The use of truffle-plugin-verify is set, and the next step is to actually deploy and verify the smart contract.

deploy:

truffle migrate --network rinkeby

This will take some time, and once deployed, something similar to the following will appear:

Summary
=======
> Total deployments:   2
> Final cost:          0.0146786 ETH

Once the contract is deployed, we can use truffle-plugin-verify to Etherscan our Casino contract:

truffle run verify Casino --network rinkeby

Still takes some time, and eventually returns:

Pass - Verified: https://rinkeby.etherscan.io/address/0xAf6e21d371f1F3D2459D352242564451af9AA23F#contracts

Visit the above address to view the contract

 

in conclusion

In this article, we discussed how cumbersome it can be to validate code through the Etherscan online form, as there are several manual steps to perform each time a contract is deployed. In this article, we use truffle-plugin-verify to enable developers to verify any smart contract with just one simple command, which provides an easy, automated alternative to manual verification.

This translation is supported by the Chainlink community and  CellNetwork  .

Original address: Automatically verify Truffle smart contracts on Etherscan
Author: Rosco Kalis

[Translation] Automatically verify contract code on Etherscan with the Truffle plugin

Guess you like

Origin blog.csdn.net/u013288190/article/details/123865542