pragma solidity ^0.8.0;
contract TuitionPayment {
address public school;
uint public tuitionFee;
mapping(address => uint) public studentBalances;
event TuitionReceived(address payer, uint amount);
constructor(uint _tuitionFee) {
school = msg.sender;
tuitionFee = _tuitionFee;
}
receive() external payable {
require(msg.sender != school, "School cannot pay tuition");
require(msg.value == tuitionFee, "Incorrect tuition fee amount");
studentBalances[msg.sender] += msg.value;
emit TuitionReceived(msg.sender, msg.value);
}
function withdraw(uint amount) public {
require(msg.sender == school, "Only school can withdraw");
require(amount <= address(this).balance, "Insufficient balance");
payable(school).transfer(amount);
}
}
- 當我們想要在 Solidity 合約中接收以太幣,例如收取學費,可以使用
receive
函式來實現這一功能。 TuitionPayment
合約用於收取學費。在合約創建時,設定了學校的地址和學費的金額。receive
函式被定義為外部函式,用於接收以太幣。- 當有人向合約地址轉帳時,如果轉帳金額等於學費金額,則該函式將被自動調用。
- 如果轉帳者不是學校,且轉帳金額正確,則學費將被記錄到相應的學生帳戶中。
- 當學費被成功接收時,將觸發一個事件
TuitionReceived
,用於通知外部觀察者。 - 合約還包含一個
withdraw
函式,用於將合約中的以太幣提取到學校地址。