Joey Yi Zhao
Joey Yi Zhao

Reputation: 42596

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

I am using truffle console to interactive smart contract deployed on Ganache network. And use below code to send coin to other accounts:

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

instance.sendCoin(accounts[1], 500)

after doing that, I see the transaction happens from account[0] to account[1]. What I don't understand is why it chooses account[0] as the source. Is it a default behaviour? How can I select a different account?

The contract code is:

// 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];
    }
}

Upvotes: 0

Views: 617

Answers (1)

hassan ahmed
hassan ahmed

Reputation: 614

Yes it is default behaviour. By default transaction is sent by accounts[0] and since Sendcoin() function uses msg.sender ( msg.sender: A global variable in solidity that is always equal to the account that sent the transaction) as sender and account passed in parameter as receiver therefore you see the coins being deducted from account[0] and sent to account[0]

To change this use below code to pass optionals to change the account sending transaction instance.sendCoin(accounts[1], 10, {from: accounts[2]})

Upvotes: 1

Related Questions