簡體   English   中英

使用 Ganache-Cli、Mocha、Web3、Solc 0.8.6 編譯器運行智能合約

[英]Running smart contract using Ganache-Cli, Mocha, Web3, Solc 0.8.6 compiler

在學習和理解智能合約的 udemy 課程之后,我決定使用最新的 solc 編譯器 0.8.6 創建一個彩票合約,因為原始課程合約是使用 solc 編譯器 0.4.17 制作的

彩票.sol

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.6;

contract Lottery {
    address public manager;
    address[] public players;

    constructor() {
       manager=msg.sender;
    }

    function enter() public payable {
        require(msg.value > .01 ether);
        players.push(msg.sender);
    }

    function random() public view returns(uint) {
        return uint(keccak256 (abi.encodePacked(block.difficulty, block.timestamp, players)));

    }

    function pickWinner() public restricted {
        uint index = random () % players.length;

        payable(players[index]).transfer(address(this).balance);
        players = new address[](0);
    }

    modifier restricted() {
        require(msg.sender == manager);
        _;
    }

    function getPlayers() public view returns(address[] memory) {
        return players;
    }


}

編譯.js文件

const path = require('path');
const fs = require('fs');
const solc = require('solc');

const lotteryPath = path.resolve(__dirname, 'contracts', 'lottery.sol');
const source = fs.readFileSync(lotteryPath, 'UTF-8');

var input = {
    language: 'Solidity',
    sources: {
        'lottery.sol' : {
            content: source
        }
    },
    settings: {
        outputSelection: {
            '*': {
                '*': [ '*' ]
            }
        }
    }
};

var output = JSON.parse(solc.compile(JSON.stringify(input)));
exports.abi = output.contracts['lottery.sol']['Lottery'].abi;
exports.bytecode = output.contracts['lottery.sol']['Lottery'].evm.bytecode.object;

Lottery.test.js(使用 Mocha、Ganache-Cli、web3)

我嘗試先運行基本命令,以便我可以對其進行測試,然后再使用我的測試條件對其進行測試。

const assert = require('assert');
const ganache = require('ganache-cli');
const Web3 = require('web3');
const web3 = new Web3(ganache.provider());
const {abi, bytecode} = require('./compile');

const deploy = async () => {
  const accounts = await web3.eth.getAccounts();
  console.log('Attempting to deploy from account',accounts[0]);
  const result = await new web3.eth.Contract(abi)
    .deploy({data: '0x' + bytecode})
    .send({from: accounts[0]});

  console.log('contract deployed to', result);
}
deploy();

當我運行 npm run test 時,它給了我這個錯誤

$ npm run test

> lottery@1.0.0 test C:\cygwin64\home\KKL\lottery
> mocha


Error: Cannot find module './compile'
Require stack:
- C:\cygwin64\home\KKL\lottery\test\lottery.test.js
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:902:15)
    at Function.Module._load (internal/modules/cjs/loader.js:746:27)
    at Module.require (internal/modules/cjs/loader.js:974:19)
    at require (internal/modules/cjs/helpers.js:92:18)
    at Object.<anonymous> (C:\cygwin64\home\KKL\lottery\test\lottery.test.js:5:25)
    at Module._compile (internal/modules/cjs/loader.js:1085:14)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
    at Module.load (internal/modules/cjs/loader.js:950:32)
    at Function.Module._load (internal/modules/cjs/loader.js:790:14)
    at ModuleWrap.<anonymous> (internal/modules/esm/translators.js:199:29)
    at ModuleJob.run (internal/modules/esm/module_job.js:169:25)
    at Loader.import (internal/modules/esm/loader.js:177:24)
    at formattedImport (C:\cygwin64\home\KKL\lottery\node_modules\mocha\lib\esm-utils.js:7:14)
    at Object.exports.requireOrImport (C:\cygwin64\home\KKL\lottery\node_modules\mocha\lib\esm-utils.js:48:32)
    at Object.exports.loadFilesAsync (C:\cygwin64\home\KKL\lottery\node_modules\mocha\lib\esm-utils.js:88:20)
    at singleRun (C:\cygwin64\home\KKL\lottery\node_modules\mocha\lib\cli\run-helpers.js:125:3)
    at Object.exports.handler (C:\cygwin64\home\KKL\lottery\node_modules\mocha\lib\cli\run.js:366:5)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! lottery@1.0.0 test: `mocha`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the lottery@1.0.0 test script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\KKL\AppData\Roaming\npm-cache\_logs\2021-08-06T09_39_41_164Z-debug.log

這是我的第一份合同,如果有人幫助並解釋我的問題,我真的很感激。 謝謝 :)

您正在這一行中導入compile.js const {abi, bytecode} = require('./compile');

看起來您沒有提供compile.js的正確路徑。 檢查compile.js文件在項目目錄中的位置。 獲取文件的正確路徑,然后粘貼它。

基於 Compile.js 中的這行代碼:

    const lotteryPath = path.resolve(__dirname, 'contracts', 'lottery.sol');

這是文件結構

 rootDir/contracts/Lottery.sol

我認為 compile.js 在根目錄中。 "./compile.js" 表示它與測試文件在同一目錄中:

 var { abi, evm } = require("../compile.js");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM