solidity-编写一个简单的存款、查询余额案例

163 阅读1分钟

需要注意ERC20的approve方法来授权。

先有一个发行代币的合约,再写银行转账的合约。

一个合约要调用tranferForm方法来实现转移代币,需要发行代币合约的approve来授权后,才能转账。(实际项目中使用safeTranfer())

这样会产生两笔gas费用, 有三方线下签名的方式,可以节约gas费用(EIP2612的方法)。

同时注意,solidity里没有浮点数,因为数字转账会有浮点精度问题,

solidity推荐使用整数来模拟浮点数,即整数*10^18来模拟浮点数运算,这样可以提高精度。

前端的浮点数,需要*10^18,才是solidity里的数字。

// SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.8.2 <0.9.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
contract Bank {
    //地址到合约的映射
    mapping(address => uint256) balance;

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

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

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

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

remix 这个IDE,开两个网页,两个合约是互相找不到的,需要把两个合约开在一个网页里部署,这里卡了很久。