使用-solidity-开发第一个-以太坊智能合约

目录

使用 solidity 开发第一个 以太坊智能合约

前言

使用 solidity 开发一个以太坊区块链的智能合约,并且使用Dapp 进行交互。

项目源代码

最终效果


环境搭建

Nodejs 和 Ganache 请自行安装,然后使用npm安装 Truffle 智能合同框架,web3js 
npm install -g truffle
npm install -g web3
  • Ganache v7.9.1 个人区块链测试环境
  • Solidity - 0.8.19 (solc-js) 以太坊区块链语言
  • Node v18.14.2
  • Truffle v5.11.5 (core: 5.11.5) 智能合约开发框架
  • Web3.js v1.10.0

智能合约内容

我们要实现在智能合约中存储和检索一个字符串值 setGreeting() 设置值, getGreeting() 获取值

Truffle 创建项目


mkdir sc-demo # 创建目录

truffle init # 项目初始化

初始化项目会生成3个文件夹和一个 配置文件

  • contracts 合同文件
  • migrations 部署文件
  • test 测试文件
  • truffle-config.js 配置文件

Truffle 编码

使用命令创建合同文件,也可以手动创建
# 命令创建
truffle create contract HelloWorld
文件生成的路径
contracts/HelloWorld.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;

contract HelloWorld {
  string public  greeting;

  constructor() {
    greeting = "Hello world!";
  }

  function setGreeting(string memory _greeting) public{
    greeting = _greeting;
  }

  function getGreeting() public view  returns (string memory ){
    return greeting;
  }

}

Truffle 打包

修改区块链地址 
truffle-config.js
// 地址是你个人区块链测试地址
development: {
    host: "127.0.0.1", // Localhost (default: none)
    port: 7545, // Standard Ethereum port (default: none)
    network_id: "*" // Any network (default: none)
}
# 打包命令
truffle compile

Truffle 部署

迁移文件的命名规则
Truffle要求迁移文件遵循一定的命名规则,通常是以数字开头,后跟一个描述性名称,如1_initial_migration.js、2_deploy_contracts.js等。数字用于确保迁移按正确的顺序执行。


编写部署文件 
migrations/2_deploy_contracts.js
const HelloWorld = artifacts.require("HelloWorld");

module.exports = function (deployer) {
  deployer.deploy(HelloWorld); 
};

修改编译器版本 0.8.19

  compilers: {
    solc: {
      version: "0.8.19" // Fetch exact version from solc-bin (default: truffle's version)
      // docker: true,        // Use "0.5.1" you've installed locally with docker (default: false)
      // settings: {          // See the solidity docs for advice about optimization and evmVersion
      //  optimizer: {
      //    enabled: false,
      //    runs: 200
      //  },
      //  evmVersion: "byzantium"
      // }
    }
  }
# 部署命令
truffle migrate

Truffle 测试

创建测试文件

路径 contracts/test/HelloWorld.test.js
const HelloWorld = artifacts.require("HelloWorld");

contract("HelloWorld", (accounts) => {
  it("should return the initial greeting", async () => {
    const instance = await HelloWorld.deployed();
    const greeting = await instance.getGreeting();
    assert.equal(
      greeting,
      "Hello, World!",
      "The initial greeting is not correct"
    );
  });

  it("should set a new greeting", async () => {
    const instance = await HelloWorld.deployed();
    await instance.setGreeting("Hello, Truffle!");
    const greeting = await instance.getGreeting();
    assert.equal(
      greeting,
      "Hello, Truffle!",
      "The new greeting is not set correctly"
    );
  });
});

运行测试命令

truffle test

Dapp

使用web3js 于智能合约交互,get()获取值,set()设置值
<!DOCTYPE html>
<html>

<head>
    <title>Simple Storage DApp</title>
</head>

<body>
    <h1>Simple Storage DApp</h1>
    <input type="text" id="storageValue">
    <button onclick="set()">Set Value</button>
    <button onclick="get()">Get Value</button>
    <p id="value"></p>

    <script src="https://cdn.jsdelivr.net/npm/web3@1.3.6/dist/web3.min.js"></script>
    <script>
        const web3 = new Web3(Web3.givenProvider || "http://127.0.0.1:7545");
        const contractAddress = '0x0cf35631BF8B3860c0D63Fc7eB03750566023F70'; // 使用你的合约地址替换这里

        // 使用你的 abi 替换这里
        const contractABI = [
            {
                "inputs": [],
                "name": "greeting",
                "outputs": [
                    {
                        "internalType": "string",
                        "name": "",
                        "type": "string"
                    }
                ],
                "stateMutability": "view",
                "type": "function",
                "constant": true
            },
            {
                "inputs": [
                    {
                        "internalType": "string",
                        "name": "_greeting",
                        "type": "string"
                    }
                ],
                "name": "setGreeting",
                "outputs": [],
                "stateMutability": "nonpayable",
                "type": "function"
            },
            {
                "inputs": [],
                "name": "getGreeting",
                "outputs": [
                    {
                        "internalType": "string",
                        "name": "",
                        "type": "string"
                    }
                ],
                "stateMutability": "view",
                "type": "function",
                "constant": true
            }
        ] // 使用你的合约ABI替换这里

        const contract = new web3.eth.Contract(contractABI, contractAddress);

        async function set() {
            const accounts = await web3.eth.getAccounts();
            const value = document.getElementById('storageValue').value;
            await contract.methods.setGreeting(value).send({ from: accounts[0] });
        }

        async function get() {
            const value = await contract.methods.getGreeting().call();
            document.getElementById('value').innerText = value;
        }
    </script>
</body>

</html>

命令总结

truffle init #初始化项目

truffle create contract XX #创建合同

truffle compile # 打包

truffle migrate # 部署命令

truffle console --network development # 部署完成后,你可以通过Truffle控制台与智能合约交互

truffle test # 测试

遇到的问题

注意Solidity 0.8.20

这是因为solidity 0.8.20引入了PUSH0(0x5f)操作码,该操作码仅在ETH主网上支持,而在任何其他链上都不支持。这就是为什么其他链找不到PUSH0(0x5f)操作码并抛出此错误的原因。考虑对其他链使用0.8.19。
posted @ 2024-03-01 18:32  半截肥皂  阅读(50)  评论(0编辑  收藏  举报