接下來幾天會來模擬一下,實際合約的案例,來更深入了解一下 solidity 語法
首先我們先設定一個 case
我們來實作發紅包的功能,那發紅包需要時做哪些功能呢?
那我們就看看下面的範例
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
contract redpacket {
//定義此合約發紅包的人
address payable public rich;
//定義要發幾個紅包
uint public number;
constructor(uint _number) payable {
rich = payable(msg.sender);
number = _number;
}
//取得發紅包的人身上餘額
function getBalance() public view returns (uint){
return address(this).balance;
}
//搶紅包
function stakeMoney() public payable returns(bool){
//紅包數須大於0
require(number>0);
//取得餘額需要大於0
require(getBalance()>0);
number --;
//此方法是 random 100內的數字
uint random = uint(keccak256(abi.encode(block.timestamp,msg.sender,"rich")))%100;
uint balance = getBalance();
address payable someone = payable(msg.sender);
//把錢給搶到紅包的人
someone.transfer(balance * random/100);
return true;
}
//合約銷毀
function kill() public{
require(msg.sender == rich);
透過此function 可以拿來銷毀合約
selfdestruct(rich);
}
}