本次範例試著寫出一份遠端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;
}
}
(待補)