简体   繁体   English

使用 Ganache-Cli、Mocha、Web3、Solc 0.8.6 编译器运行智能合约

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

Following the udemy course for learning and understanding smart contracts, I decided to create a Lottery contract using the latest solc compiler 0.8.6 as the original course contract was made using solc compiler 0.4.17在学习和理解智能合约的 udemy 课程之后,我决定使用最新的 solc 编译器 0.8.6 创建一个彩票合约,因为原始课程合约是使用 solc 编译器 0.4.17 制作的

Lottery.sol彩票.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;
    }


}

Compile.js file编译.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 (Using Mocha, Ganache-Cli, web3) Lottery.test.js(使用 Mocha、Ganache-Cli、web3)

I tried to run basic commands first so i could test it and then again test it with my test conditions.我尝试先运行基本命令,以便我可以对其进行测试,然后再使用我的测试条件对其进行测试。

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();

When i run npm run test, it gives me this error .当我运行 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

It is my first contract, I'd really appreciate if someone helps and explains me the problem.这是我的第一份合同,如果有人帮助并解释我的问题,我真的很感激。 Thank you :)谢谢 :)

You are importing compile.js in this line const {abi, bytecode} = require('./compile');您正在这一行中导入compile.js const {abi, bytecode} = require('./compile');

Looks like you are not providing a correct path of compile.js .看起来您没有提供compile.js的正确路径。 Check where your compile.js file is in your project directory.检查compile.js文件在项目目录中的位置。 Get the correct path of the file and then paste it.获取文件的正确路径,然后粘贴它。

Based on this line of code in Compile.js :基于 Compile.js 中的这行代码:

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

this is the file structure这是文件结构

 rootDir/contracts/Lottery.sol

I think compile.js in root directory.我认为 compile.js 在根目录中。 "./compile.js" means it is in same directory as test file: "./compile.js" 表示它与测试文件在同一目录中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM