web3.eth.getAccounts()返回空

时间:2019-09-02 10:57:31

标签: blockchain web3

我尝试实现一个简单的银行帐户示例(获取余额,存款,取款)。

pragma solidity 0.5.1;
contract Bank
{

int bal;

constructor() public 
{
    bal = 1;
}
//get balance function
function getBalance () view public returns(int)
{
    return bal;
}
//withdraw money
function withdraw (int amt) public
{
    bal = bal - amt;
}
//deposit money
    function deposit (int amt) public
{
    bal = bal + amt; 
}

}

我可以获得一个简单帐户的余额,但是由于web3.eth.getAccounts()返回零个帐户,因此无法使用存款/取款功能。

$('#deposit').click(function () {
        var amount = 0;
        amount = parseInt($('#amount').val());

        web3.eth.getAccounts().then(function (accounts) {
            console.log("accounts: " + accounts.length);

            var acc = accounts[0];
            console.log("acc: " + acc);
            return contract.methods.deposit(amount).send({ from: acc });
        }).then(function (tx) {
            console.log("success deposit:" + tx);
        }).catch(function (tx) {
            console.log("fail deposit:" + tx);
        })
    })

我已经尝试了多个版本的web3,但到目前为止还没有:

<script src="https://cdn.jsdelivr.net/gh/ethereum/web3.js@1.2.0/dist/web3.min.js"></script>



bal ===501 localhost:8080:81:25
accounts: 0 localhost:8080:92:25
acc: undefined localhost:8080:95:25
fail deposit:Error: No "from" address specified in neither the given options, nor the default options. localhost:8080:100:25

0 个答案:

没有答案