Search code examples
blockchainethereumsoliditysmartcontracts

Does it make sense to manage balance manually inside smartcontract?


I am using Solidity to deploy smartcontract to a test Ethereum network launched by Ganache. I read some demo code of contract and one of them looks like:

// SPDX-License-Identifier: MIT
pragma solidity >=0.7.4;
pragma experimental ABIEncoderV2;

contract Ledger {
    struct TransferRequest {
        string title;
        uint256 amount;
        string bsb;
        string accountName;
        string accountNumber;
    }

    mapping(address => uint256) balances;

    address payable owner;

    event Transfered(bool _success, address _from, address _to, uint256 amount);

    constructor() payable {
        owner = payable(msg.sender);
        balances[tx.origin] = 10000;
    }

    function sendCoin(address payable receiver, uint256 amount)
        payable public
    {
        require(msg.sender == owner);
        if (balances[msg.sender] < amount) return;
        balances[msg.sender] -= amount;
        balances[receiver] += amount;
        emit Transfered(true, msg.sender, receiver, amount);
    }

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

}

As you can see above that the contract manages the balance by itself rather than using the balance from the blockchain. There is no real ether transfer inside sendCoin method. Does this mean there is no real transaction in the blockchain. Then what the point of building a contract like that. What would be the relationship between balance managed by blockchain and balance managed by contract?


Solution

  • the contract manages the balance by itself rather than using the balance from the blockchain

    Each state change (in this case change of balances storage property value) is recorded on the blockchain. So the contract is reading the balance from the blockchain.

    However, the way Ethereum network is designed, an address can only have few properties - its bytecode (non-zero bytecode means it's a smart contract), its balance, and few others. Since there's only one property for balance (and not a list of balances), it's used for the native ETH balance. Any token balances are stored in the contracts of the respective tokens.

    You can read more about the token balance storage design in the final version of ERC-20 and the linked documents. This is the first standard that introduced tokens on Ethereum.