solidity-完善银行合约案例,取款、存款、转账、查询余额

143 阅读1分钟

学习内容:

  • modifer用法,就是提取一些校验参数作为公共的方法。
  • safeTranfer的方法已经实现,实际中尽量使用safeTranfer
// SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.8.2 <0.9.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

contract Bank {
    using SafeERC20 for IERC20; // 绑定 SafeERC20 到 IERC20

    //地址到合约的映射
    mapping(address => uint256) balance;

    //代币的地址
    IERC20 public immutable token;

    constructor(address _token) {
        token = IERC20(_token);
    }

    //校验参数小于余额
    modifier checkAmountLessBalance(uint256 count) {
        count = count * (10**18);
        require(count <= balance[msg.sender], "count must less than balance");
        _;
    }

    //存款
    function deposit(uint256 _count) public {
        _count = _count * (10**18);
        require(
            token.transferFrom(msg.sender, address(this), _count),
            "transferFromError"
        );
        balance[msg.sender] += _count;
    }

    //查询余额
    function searchBalance() public view returns (uint256 count) {
        count = balance[msg.sender] / (10**18);
    }

    //取款
    function withdraw(uint256 count) external checkAmountLessBalance(count){
        token.safeTransfer(msg.sender, count); // 安全转账
        balance[msg.sender] -= count;
    }

    //转账
    function transfer(address receiver, uint256 count) external checkAmountLessBalance(count){
        balance[receiver] += count;
        balance[msg.sender] -= count;
    }
}