Solidity经典合约案例----拍卖
1. 案例分析
2. 具体的代码
pragma solidity^0.6.1;
contract aution_demo{
address payable public seller;
address payable public buyer;
uint256 public highAmount;
address public admin;
string autionName;
bool isFinshed;
uint256 outTime;
mapping (address => uint256) pendingReturns;
event HighestBidIncreased(address _bidder,uint256 _amount);
event End_Auction(address _winner,uint256 _amount);
constructor(address payable _seller,string memory _name)public{
seller=_seller;
autionName=_name;
admin=msg.sender;
outTime=now+120;
isFinshed=false;
highAmount=0;
}
function aution(uint256 amount)public payable{
require(amount>highAmount,"amount must>highAmount");
require(amount==msg.value,"amount must==msg.value");
require(now<=outTime,"must not time out");
require(!isFinshed,"must not finshed");
pendingReturns[buyer]+=highAmount;
buyer=msg.sender;
highAmount=amount;
emit HighestBidIncreased(msg.sender,msg.value);
}
function withdraw() public returns (bool){
uint256 amount = pendingReturns[msg.sender];
if (amount > 0){
pendingReturns[msg.sender] = 0;
if (!msg.sender.send(amount)){
pendingReturns[msg.sender] = amount;
return false;
}
}
return true;
}
function endAuction()public payable{
require(msg.sender==admin,"only admin can do this");
require(now>outTime,"time is not ok");
require(!isFinshed,"must not finshed");
isFinshed=true;
emit End_Auction(buyer, highAmount);
seller.transfer(highAmount*90/100);
}
}
3.测试之前的账户地址准备
4. 管理员(平台方部署合约,并初始化)
5. 卖方调用智能合约
模拟3个卖家,调用aution()函数分别支付1000000wei,2000000wei,3000000wei
6. 管理员(平台方结束拍卖)
管理员通过调用endAuction()函数结束拍卖,并将抽取10%的利益,剩余的90%的钱发送给卖家。
7. 未拍卖成功的卖方取回金钱
拍卖结束后,卖方调用withdarw()函数取回金钱。 以下为整体的测试结果图(顺序为从左到右,从上到下)
|