Develop a simple smart contract

1. Environment construction

  1. Build Truffle Framework
    Introduction: This is a popular Ethereum development framework with built-in smart contract compilation, connection, deployment and other functions
  • The Truffle framework relies on Node and needs to be installed using npm. First, you need to install node. Npm will install it at the same time. Download it on the official website: Nodejs
    enter the command to view the current version

node -v

  • Then you can use npm to install the Truffle framework, use npm to install the Truffle framework, install the command:

np install -g truffle

Verify Truffle installation:

truffle --version

  1. Ganache
  • Here we also need to use Ganache, because deploying and testing smart contracts on Ethereum cost Ether, which is gas. And Ganache can create a blockchain network locally to test our program without consuming real gas.
  • Gannache download path: Ganache
  • How Ganache works: Create a Ganache virtual blockchain network for us, assign us 10 external accounts (nodes), and each account has 100 fake ethers.
  • Introduction to Ganache interface:
    Gannache main interface

ACCOUNTS: Account interface, showing all accounts and their balances automatically generated.
BLOCKS: Block interface, which shows each block mined on the local blockchain network, along with its gas cost and included transactions.
TRANSACTIONS: Transaction page, which lists all transactions that occurred on the local
blockchain. CONTRACTS: Contract page
EVENTS: Event page
LOGS: Log page

  • The search bar in the upper right corner can search for blocks or transactions on the local blockchain network.

  • Setting interface:
    Ganache setting interface
    SERVER: Server setting page, managing detailed information about network connection, such as network id, port, host name and automatic mining status.
    ACCOUNTS & KEYS: Account and key page, set to automatically generate accounts and their balances.
    CHAIN link page, you can set the gas limit and gas price.
    Advanced settings Log option settings, such as the ability to save log files and configure detailed output.

  1. Solidity code It is
    recommended to use vs code to write and install the solidity plug-in.

2. Development steps

  1. Initialize the project:
  • First create the project directory, then enter this directory
    first step
  • Initialize this project with truffle init
    initialized successfully

After the initialization is successful, we can click on the mydapp file, and we can see the following files:
After mydapp is initialized
Contracts directory: As the name suggests, it is a smart contract directory. Now there is a Migrations.sol file in it, whose function is to migrate/deploy/upgrade smart contracts. Migrations
directory: migration files, the js scripts inside are all to help us deploy the contract to the blockchain.
test directory: test code directory.
The truffle-config.js file can configure the network in it.
2. Add the package.json file, which is the configuration file used by npm to manage the package. The content:

{
  "name": "ethereum-demo",
  "version": "1.0.0",
  "description": "以太坊demo",
  "main": "truffle-config.js",
  "directories": {
    "test": "test"
  },
  "scripts": {
    "dev": "lite-server",
    "test": "echo \"Error: no test specified\" && sexit 1"
  },
  "author": "[email protected]",
  "license": "ISC",
  "devDependencies": {
    "@truffle/contract": "^4.0.33",
    "dotenv": "^8.1.0",
    "lite-server": "^2.5.4",
    "truffle-hdwallet-provider": "^1.0.17"
  }
}
  • Overview of package.json: Under the root directory of each project, there is generally a package.json file that defines the various modules required by the project and the configuration information of the project (such as name, version, license, etc.) , Npm install command, according to this configuration file, automatically download the required modules, that is, the running and development environment required by the project.
    For a detailed explanation of package.json, please refer to: packeage.json detailed fields
  1. Add smart contract source files
  • Create a new file MyContract.sol in the contracts directory and give the code:
// 声明solidity版本
pragma solidity ^0.5.0;

// 声明智能合约MyContract,合约的所有代码都包含在花括号中。
contract MyContract {

    // 声明一个名为value的状态变量
    string value;

    // 合约构造函数,每当将合约部署到网络时都会调用它。
    // 此函数具有public函数修饰符,以确保它对公共接口可用。
    // 在这个函数中,我们将公共变量value的值设置为“myValue”。
    constructor() public {
        value = "myValue";
    }

    // 本函数读取值状态变量的值。可见性设置为public,以便外部帐户可以访问它。
    // 它还包含view修饰符并指定一个字符串返回值。
    function get() public view returns(string memory ) {
        return value;
    }

    // 本函数设置值状态变量的值。可见性设置为public,以便外部帐户可以访问它。
    function set(string memory _value) public {
        value = _value;
    }
}

  • The function of this smart contract is to get values ​​and set values. This code is written in solidity. For solidity basic tutorials, please refer to my solidity article. There is no link here, there is on the homepage.
  1. Use truffle compile command to compile the project:
    Insert picture description here
  • After the compilation is complete, we can open the root directory of the project again, and we can find that there is an additional build directory.
    Compiled dapp
    This file is the ABI file of the smart contract, which stands for "abstract binary interface". It has the following two functions:
  • As an executable file that can be run on the Ethereum Virtual Machine (EVM)
  • Contains JSON representations of smart contract functions so that external clients can call these functions
  1. Update the configuration file
    Modify the network configuration to connect to the local blockchain network (Ganache)
  • Open the truffle-config.js file located in the root directory and modify the content as follows:
module.exports = {
  networks: {
    development: {
      host: "127.0.0.1", // ip地址
      port: 8545, // 端口
      network_id: "*" // Match any network id
    }
  },
  solc: {
    optimizer: {
      enabled: true,
      runs: 200
    }
  }
}

ip address, port number, etc., should match Ganache
Insert picture description here

  1. Create migration script
  • Create the script 2_deploy_contracts in the migrations directory. This script tells Truffle how to deploy smart contracts. It must be numbered. The function is to let Truffle know their execution order.
var MyContract = artifacts.require("./MyContract.sol");
// 用require将合约赋值给一个MyContract变量
module.exports = function(deployer) {
  deployer.deploy(MyContract); // 部署该合约
};
  1. Execute the migration command truffle migrate to
    Insert picture description here
    Insert picture description here
    deploy successfully and consume Ether

  2. Use truffle console (console) to access the smart contract. The
    The console started successfully
    console starts successfully

MyContract.deployed().then((instance) => { app = instance })

run
Enter the command and run successfully

Then try to call the get method, enter app.get() and the
Successful call
call is successful, indeed the value of myValue is displayed.

Let's try the set method again to see if this value can be changed. First enter app.set('new Value'), then enter app.get(), the result shows: the
Successfully modified
modification is successful.

Three, summary

Although it is just a simple smart contract to obtain the modified value, it is also a simple step to develop a smart contract. Through this step, by modifying the contract code, we can also write more complex smart contracts. This is just one step.

Guess you like

Origin blog.csdn.net/weixin_51194902/article/details/112306612