简体   繁体   中英

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

Lottery.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

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)

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

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

Looks like you are not providing a correct path of compile.js . Check where your compile.js file is in your project directory. Get the correct path of the file and then paste it.

Based on this line of code in 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" means it is in same directory as test file:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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