# Solidity实现存钱罐合约 **Published by:** [kaiming](https://paragraph.com/@kaiming/) **Published on:** 2022-07-26 **URL:** https://paragraph.com/@kaiming/solidity ## Content 使用solidity编写合约实现类似存钱罐功能。 具体功能是: 可以通过任何人的地址向存钱罐合约发送以太坊主币。 任何人都可以查看存钱罐合约里的主币余额。 只有存钱罐的拥有者才能从存钱罐中取出主币,拥有者在取出主币后合约就自毁掉,像现实世界中的存钱罐一样被打碎,不能再被使用。 接下来我们看一下实现代码: // SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.9.0; contract PiggyBank{ event Deposit(uint amount); event Withdraw(uint amount); address public owner=msg.sender; receive() external payable{ emit Deposit(msg.value); } function getBalance() external view returns (uint ){ return address(this).balance; } function withdraw() external{ require(msg.sender==owner,"not owner"); emit Withdraw(address(this).balance); selfdestruct(payable(msg.sender)); } } ## Publication Information - [kaiming](https://paragraph.com/@kaiming/): Publication homepage - [All Posts](https://paragraph.com/@kaiming/): More posts from this publication - [RSS Feed](https://api.paragraph.com/blogs/rss/@kaiming): Subscribe to updates