无法弄清楚为什么在处理事务时出现VM异常:还原错误

时间:2020-04-12 03:43:03

标签: javascript blockchain web3 ganache

我是区块链编程的初学者,我无法理解为什么尝试使用Web3和Ganache进行整合功能时出现错误。

const PetList = require('./build/contracts/PetList.json')
const fs = require('fs')
const Web3 = require('web3')

const abi = fs.readFileSync("build/contracts/PetList.json").toString().trim();


// Ganache Blockchain
const web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:7545"));

web3.eth.net.isListening()
    .then(() => console.log('Web3 is connected'))
    .catch(e => console.log('Wow. Something went wrong'));

var setUpContract = async function( ){
    await web3.eth.net.getId().then((networkId) => {
        const networkData = PetList.networks[networkId]
        console.log("Setting up contract...")
        if(networkData){
            return petList = new web3.eth.Contract(PetList.abi, networkData.address)
        }
    })
    acc = await web3.eth.getAccounts()
    currentAccount = acc[0]
    console.log("Account: ", acc[0])
}

async function start(){
    await setUpContract()
    await addPet()
}

var addPet = async function(){
    console.log(await getPetCount())
    return results = await petList.methods.addPet('Zippo', 'Dog').send({from: currectAccount})
}

start()
pragma solidity ^0.5.0;

contract PetList{
    uint public petCount = 0;
    mapping (uint => Pet) public pets;

    struct Pet{
        uint id;
        string name;
        string tag;
    }

    event PetAdded(
        uint id,
        string name,
        string tag
    );

    function addPet(string memory _name, string memory _tag) public {
        require(bytes(_name).length > 0, "INVALID TAG");
        require(bytes(_tag).length > 0, "INVALID NAME");
        petCount++;
        pets[petCount] = Pet(petCount, _name, _tag);
        emit PetAdded(petCount, _name, _tag);
    }
}

我还使用了.send()而不带任何参数,这给了我一个错误,说既未在给定选项中也未在默认选项中指定“发件人”地址。

1 个答案:

答案 0 :(得分:0)

要使函数接收以太币,您必须具有fallback function或添加payable modifier

因此您可以将代码更改为以下

function addPet(string memory _name, string memory _tag) public payable