在智能合约中手动管理余额是否有意义?

Does it make sense to manage balance manually inside smartcontract?

我正在使用 Solidity 将智能合约部署到 Ganache 启动的测试以太坊网络。我读了一些合同的演示代码,其中一个看起来像:

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

}

正如您在上面看到的那样,合约自行管理余额,而不是使用区块链中的余额。 sendCoin 方法中没有真正的以太币转移。这是否意味着区块链中没有真正的交易。那么建立这样的合同有什么意义呢? balance 由区块链管理和 balance 由合约管理之间的关系是什么?

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

每个状态变化(在这种情况下 balances 存储 属性 值的变化)都记录在区块链上。所以合约正在从区块链中读取余额。

然而,按照以太坊网络的设计方式,一个地址只能有几个属性——它的字节码(非零字节码意味着它是一个智能合约)、它的余额,以及其他一些。由于只有一个 属性 用于余额(而不是余额列表),因此它用于本机 ETH 余额。任何代币余额都存储在相应代币的合约中。

您可以在 ERC-20 的最终版本和链接文档中阅读有关代币余额存储设计的更多信息。这是第一个在以太坊上引入代币的标准。