iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 12
0

導言

本次範例試著寫出一份遠端P2P Lending的smart contract,合約的邏輯設計是從Safe Purchase smart contract延伸發想出來,當放款、借款雙方已達成協議,放款人同意放款並將錢放進合約發送給借款人,借款人可以從合約拿錢

程式碼

pragma solidity^0.4.25;
contract P2P{
    address public owner;
    address public lender;
    uint256 public loan;
    enum State{
        Created,
        Lending,
        End
    }
    State public state;

    event PayInterested(uint8 indexed _timstamp,uint _value);
    event Take();
    event Payback();

    constructor(address _lender) public payable{
        owner = msg.sender;
        lender = _lender;
        loan = msg.value;
    }

    modifier inState(State _state){
        require(state == _state,"Wrong state");
        _;
    }
    modifier onlyLender{
        require(msg.sender == lender);
        _;
    }
    modifier onlyOwner{
        require(msg.sender == owner);
        _;
    }

    //查看合約餘額
    function watch() public view onlyOwner returns(uint256 balances){
        balances = address(this).balance;
    }
    //貸款人提款
    function take() public onlyLender inState(State.Created) returns(bool){
        msg.sender.transfer(loan);
        emit Take();
        state = State.Lending;
        return true;
    }

    //貸款人償付
    function repay() public payable  inState(State.Lending) returns(bool){
        require(msg.value == loan);
        emit Payback();
        state = State.End;
        return true;
    }
    //償付完畢,銷毀合約,並將錢回給owner
    function withdraw() public onlyOwner inState(State.End) returns(bool){
        selfdestruct(msg.sender);
        return true;
    }
}

解說

(待補)


上一篇
Day10-Vote
下一篇
Day12-ERC20
系列文
30天30個Smart contract 20
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言