Truffle - 2 利用Truffle编写、测试智能合约并将其部署到不同的测试网络

2 利用Truffle编写、测试智能合约并将其部署到不同的测试网络

2.1创建项目

建一个文件夹

mkdir truffle-project
truffle init //初始化

qinjianquan@MacBook-Pro-10 truffle-project % ls //查看文件
contracts		test
migrations		truffle-config.js  

contracts: 编写以及存放智能合约的文件夹

**migrations:**使用solidity编写智能合约的文件夹,编写文件解释truffle 如何部署智能合约,用的是node.js

test: 用来写测试文件,大多数使用的是node.js,也有一些使用的是Solidity

truffle-config.js: 配置文件用来定义智能合约部署的网络

2.2 编写合约

vim contracts/SimpleStorage.sol
pragma solidity ^0.8.4; //请注意solidity的版本问题,如果合约指定的版本和当前Solidity不兼容的话,这将会在编译的时候出错

contract SimpleStorage {
    uint data;

    function updateData(uint _data) external {
        data = _data;
    }

    function readData() external view returns(uint) {
        return data;
    }
}

2.3 编译合约

编译合约

truffle compile //编译
Compiling your contracts...
===========================
✓ Fetching solc version list from solc-bin. Attempt #1
✓ Downloading compiler. Attempt #1.
> Compiling ./contracts/Migrations.sol
> Compiling ./contracts/SimpleStorage.sol
> Compilation warnings encountered:

    Warning: SPDX license identifier not provided in source file. Before publishing, consider adding a comment containing "SPDX-License-Identifier: <SPDX-License>" to each source file. Use "SPDX-License-Identifier: UNLICENSED" for non-open-source code. Please see https://spdx.org for more information.
--> project:/contracts/SimpleStorage.sol


> Artifacts written to /Users/qinjianquan/truffle-project/build/contracts
> Compiled successfully using:
   - solc: 0.8.13+commit.abaa5c0e.Emscripten.clang

查看编译后的文件

qinjianquan@MacBook-Pro-10 truffle-project % ls //查看生成的json文件,主要是ABI信息等
build			contracts		migrations		test			truffle-config.js
qinjianquan@MacBook-Pro-10 truffle-project % ls build/contracts/
Migrations.json		SimpleStorage.json
qinjianquan@MacBook-Pro-10 truffle-project % ls
build			contracts		migrations		test			truffle-config.js
qinjianquan@MacBook-Pro-10 truffle-project % ls build/contracts/
Migrations.json		SimpleStorage.json
vim build/contracts/SimpleStorage.json //查看编译后的json文件以及一些其它编译合约的信息
"abi": [
    {
      "inputs": [
        {
          "internalType": "uint256",
          "name": "_data",
          "type": "uint256"
        }
      ],
      "name": "uodateData",
      "outputs": [],
      "stateMutability": "nonpayable",
      "type": "function"
    },
    {
      "inputs": [],
      "name": "readData",
      "outputs": [
        {
          "internalType": "uint256",
          "name": "",
          "type": "uint256"
        }
      ],
      "stateMutability": "view",
      "type": "function"
    }
  ],
--

2.3 测试合约

测试文件/合约都可以在vs code先编写,然后通过命令行工具部署和测试。这一步骤可以跳过,读者可以选择将合约部署到区块链之上后通过与合约交互从而测试合约的功能

vim test/SimpleStorage.js //编写测试文件
const SimpleStorage = artifacts.require('SimpleStorage');

contract('SimpleStorage', ()=> {
     it ('Should update data',sync () => {
          const storage = await SimpleStorage.new();
          await storage.updateData(10);
          const data = await storage.readData();
          assert(data.toString() === '10');
     });
});
qinjianquan@MacBook-Pro-10 truffle-project % truffle test 运行测试,此时的测试在本地的私有链Ganache上,非常简单方便
Using network 'test'.


Compiling your contracts...
===========================
> Everything is up to date, there is nothing to compile.


  Contract: SimpleStorage
    ✔ Should update data (2093ms)


  1 passing (2s)

2.4 部署合约

2.4.1 将合约部署到私有链ganache上

ganache可以独立安装,但是当安装了truffle时,也会自动安装ganache,编写、测试好的智能合约可以部署到私有链或

  • 2
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Truffle框架是一个用于以太坊智能合约开发的开发环境和工具集,Ganache则是一个用于本地测试以太坊智能合约的工具。下面是使用Truffle框架和Ganache网络进行智能合约部署的具体流程和代码。 1. 安装Truffle框架和Ganache网络 首先需要在本地安装Truffle框架和Ganache网络。可以使用npm命令进行安装: ``` npm install -g truffle npm install -g ganache-cli ``` 2. 创建Truffle项目 使用Truffle框架创建一个新的项目: ``` truffle init ``` 这将会在当前目录下创建一个名为`truffle-config.js`的配置文件和一个名为`contracts`的合约目录。 3. 编写智能合约代码 在`contracts`目录下创建一个名为`MyContract.sol`的智能合约文件,并编写合约代码。例如,创建一个简单的存储合约: ``` pragma solidity ^0.8.0; contract MyContract { uint256 private value; function setValue(uint256 newValue) public { value = newValue; } function getValue() public view returns (uint256) { return value; } } ``` 4. 配置Truffle项目 在`truffle-config.js`文件中配置Truffle项目。首先需要指定要使用的网络,这里使用Ganache网络: ``` module.exports = { networks: { development: { host: "localhost", port: 8545, network_id: "*" } } }; ``` 5. 编译智能合约 使用Truffle框架编译智能合约: ``` truffle compile ``` 6. 部署智能合约 使用Truffle框架部署智能合约: ``` truffle migrate ``` 这将会将智能合约部署Ganache网络上。 7. 与智能合约交互 现在可以使用Web3.js或其他以太坊客户端库与智能合约进行交互。以下是一个使用Web3.js与上一步中部署的存储合约进行交互的示例代码: ``` const Web3 = require('web3'); const web3 = new Web3('http://localhost:8545'); const myContract = new web3.eth.Contract([{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"uint256","name":"newValue","type":"uint256"}],"name":"setValue","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"getValue","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"}], '0x1234567890123456789012345678901234567890'); myContract.methods.setValue(42).send({from: '0x1234567890123456789012345678901234567890'}) .then(() => myContract.methods.getValue().call()) .then(value => console.log(value)); ``` 这段代码首先创建了一个Web3实例,并连接到Ganache网络。然后创建了一个`myContract`实例,它表示上一步中部署的存储合约。最后使用`myContract`实例调用`setValue`方法将值设置为42,并使用`getValue`方法获取当前值并输出到控制台。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值