问题
I try implement a simple bank account example (get balance, deposit, withdraw).
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;
}
}
I can get the balance of a simple account but I cannot use the deposit/withdraw functions as web3.eth.getAccounts() returns zero accounts.
$('#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);
})
})
I have tried several versions of web3 but nothing so far:
<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
来源:https://stackoverflow.com/questions/57755748/web3-eth-getaccounts-returns-empty