如何通过web3 js调用智能合约功能?

时间:2019-04-10 21:19:29

标签: javascript solidity web3js

所以我对区块链开发非常陌生。

我已经在Ropsten测试网中部署了一个非常基本的智能合约。我正在开发一个前端,从这里,我想从合同地址中提取以太币/ wei到调用该函数的帐户(注入的Metamask)。当我进入etherscan合同并直接在其中使用撤回功能时,它非常完美。我只是不知道如何通过web3 js正确调用撤回功能。下面是当我尝试调用函数/方法时发生的错误消息。有人可以帮我指出正确的方向吗?谢谢!

引发错误。 https://imgur.com/a/RSVrJIF


Web3 = require('web3');

if (typeof web3 != 'undefined')
{
    web3 = new Web3(web3.currentProvider);
    console.log("existing web3: provider " + typeof web3);
    console.log(web3.currentProvider);
}
else{
    //To Do..
    web3 = new Web3(new Web3.providers.HttpProvider("https://ropsten.infura.io/"));
    console.log("new provider " + web3);
}

console.log(web3.isConnected());
console.log(web3.eth.accounts[0]);

abi = JSON.parse('[{"constant":false,"inputs":[{"name":"amount","type":"uint256"}],"name":"withdraw","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"getMyBalance","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"deposit","outputs":[],"payable":true,"stateMutability":"payable","type":"function"}]');
var bankContract = web3.eth.contract(abi);
contractInstance = bankContract.at('myaddressishere');
console.log (contractInstance);

function withdraw() {
    contractInstance.withdraw(300000000000000000, { from: web3.eth.accounts[0]})
}
pragma solidity ^0.5.0;

contract Bank{
    mapping(address=>uint) balances;

    function deposit() public payable{
        balances[msg.sender]+=msg.value;
    }
    function withdraw(uint amount) public{
        if(balances[msg.sender]>=amount){
            balances[msg.sender]-=amount;
            msg.sender.transfer(amount);
        }
    }
}

0 个答案:

没有答案
相关问题