发币时如何选择哪个账户是选中的账户?

How can I choose which account is the selected account when sending coins?

我正在使用 truffle console 部署在 Ganache 网络上的交互式智能合约。并使用以下代码将硬币发送到其他帐户:

truffle(development)> let instance = await MetaCoin.deployed()
truffle(development)> let accounts = await web3.eth.getAccounts()

instance.sendCoin(accounts[1], 500)

这样做之后,我看到交易发生在 account[0]account[1] 之间。我不明白的是为什么它选择 account[0] 作为来源。这是默认行为吗?我怎样才能 select 一个不同的帐户?

合约代码为:

// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.7.0;

import "./ConvertLib.sol";

// This is just a simple example of a coin-like contract.
// It is not standards compatible and cannot be expected to talk to other
// coin/token contracts. If you want to create a standards-compliant
// token, see: https://github.com/ConsenSys/Tokens. Cheers!

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

    event Transfer(address indexed _from, address indexed _to, uint256 _value);

    constructor() public {
        balances[tx.origin] = 10000;
    }

    function sendCoin(address receiver, uint amount) public returns(bool sufficient) {
        if (balances[msg.sender] < amount) return false;
        balances[msg.sender] -= amount;
        balances[receiver] += amount;
        emit Transfer(msg.sender, receiver, amount);
        return true;
    }

    function getBalanceInEth(address addr) public view returns(uint){
        return ConvertLib.convert(getBalance(addr),2);
    }

    function getBalance(address addr) public view returns(uint) {
        return balances[addr];
    }
}

是的,这是默认行为。默认情况下,交易由 accounts[0] 发送,因为 Sendcoin() 函数使用 msg.sender ( msg.sender:solidity 中的全局变量始终等于发送交易的账户)作为发送者和账户作为接收者传递参数因此你看到硬币从账户[0]中扣除并发送到账户[0]

要更改此使用下面的代码来传递选项来更改帐户发送交易 instance.sendCoin(accounts[1], 10, {from: accounts[2]})