Solidity 练习:Ether 钱包

2022-12-29 Web3 Solidity

# 一、题目说明

创建一个可以从任何人那里接收 Ether 的合约。只有 owner 可以提现。

# 二、任务列表

    1. 为该合约开启接收 Ether。
    1. 编写函数 withdraw(uint _amount),发送 _amount Ether 给 owner,只有 owner 可以调用该函数。

# 三、解答代码

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

contract EtherWallet {
    address payable public owner;

    constructor() {
        owner = payable(msg.sender);
    }

    receive() external payable {}

    function withdraw(uint _amount) external {
        require(msg.sender == owner, "not owner");

        (bool sent, ) = owner.call{value: _amount}("");
        require(sent, "Failed to send Ether");
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

# 四、参考资料

Last Updated: 2023-01-28 4:31:25