iT邦幫忙

2021 iThome 鐵人賽

DAY 19
0
Modern Web

區塊鏈&DAPP介紹系列 第 19

[區塊鏈&DAPP介紹 Day19] contract 案例1 - 搶紅包

接下來幾天會來模擬一下,實際合約的案例,來更深入了解一下 solidity 語法

首先我們先設定一個 case

情境

我們來實作發紅包的功能,那發紅包需要時做哪些功能呢?

  1. 發紅包
  2. 搶紅包
  3. 退還

那我們就看看下面的範例

// 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);
    }
}

上一篇
[區塊鏈&DAPP介紹 Day18] 智能合約中什麼是 Gas
下一篇
[區塊鏈&DAPP介紹 Day20] contract 案例2 - 拍賣
系列文
區塊鏈&DAPP介紹30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言