实现效果
-
房主发送拍卖房屋信息,并且设置拍卖过期时间
2. 其它非房主可以登录进行拍卖,选择自己的出价
参考
https://dev.to/yongchanghe/build-a-simple-dapp-using-truffle-ganache-ethersjs-and-react1-52bl
工具集合
-
安装node,版本是v16.16.0 -
npm install -g truffle, truffle可以让我们在本地开发合约,同时部署合约到链上。 -
安装ganache, ganache相当于是把以太网部署在本地,我们可以把合约发布到本地的以太网上。 -
metamask,钱包可以添加账户,查看我们的账户余额,
初始化项目
-
mkdir web3-ticket && truffle init
-
项目目录如下
-
修改truffle.config.js的development
4. 打开Ganache,新建workspace,选择项目的trffle.config.js
然后我们就可以看到很多账号了,而且里边还有余额
这样我们就可以通过truffle,连接到链上,同时部署合约到这里了
-
在web3-ticket/contracts下新建拍卖合约,Auction.sol,代码比较简单,关键地方都已经添加注释。
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
contract Auction {
// Properties
// 定义owner地址
address private owner;
uint256 public startTime;
uint256 public endTime;
// 映射
mapping(address => uint256) public bids;
// 结构体
struct House {
string houseType;
string houseColor;
string houseLocation;
}
// 最高出价,竞拍,最高价
struct HighestBid {
uint256 bidAmount;
address bidder;
}
House public newHouse;
HighestBid public highestBid;
// Insert modifiers here
// Modifiers
// 竞拍已经结束
modifier isOngoing() {
require(block.timestamp < endTime, 'This auction is closed.');
_;
}
// 竞拍还在进行
modifier notOngoing() {
require(block.timestamp >= endTime, 'This auction is still open.');
_;
}
// 是不是作者,如果不是没有权限
modifier isOwner() {
require(msg.sender == owner, 'Only owner can perform task.');
_;
}
// 不是作者
modifier notOwner() {
require(msg.sender != owner, 'Owner is not allowed to bid.');
_;
}
// Insert events here
// Events,允许前端调用事件
event LogBid(address indexed _highestBidder, uint256 _highestBid);
event LogWithdrawal(address indexed _withdrawer, uint256 amount);
// Insert constructor and function here
// Assign values to some properties during deployment
constructor () {
owner = msg.sender;
startTime = block.timestamp;
endTime = block.timestamp + 12 hours;
newHouse.houseColor = '#FFFFFF';
newHouse.houseLocation = 'Sask, SK';
newHouse.houseType = 'Townhouse';
}
// makeBid 开始竞价,房子必须是在拍卖中,并且不能房主自己出价
function makeBid() public payable isOngoing() notOwner() returns (bool) {
uint256 bidAmount = bids[msg.sender] + msg.value;
// 当前出价要高于前面的出价,不然报错
require(bidAmount > highestBid.bidAmount, 'Bid error: Make a higher Bid.');
highestBid.bidder = msg.sender;
highestBid.bidAmount = bidAmount;
bids[msg.sender] = bidAmount;
emit LogBid(msg.sender, bidAmount);
return true;
}
// 付款
function withdraw() public notOngoing() isOwner() returns (bool) {
uint256 amount = highestBid.bidAmount;
bids[highestBid.bidder] = 0;
highestBid.bidder = address(0);
highestBid.bidAmount = 0;
// 向房主付款
(bool success, ) = payable(owner).call{ value: amount }("");
require(success, 'Withdrawal failed.');
emit LogWithdrawal(msg.sender, amount);
return true;
}
// 获取最高出价
function fetchHighestBid() public view returns (HighestBid memory) {
HighestBid memory _highestBid = highestBid;
return _highestBid;
}
// 获得当前房主
function getOwner() public view returns (address) {
return owner;
}
}
-
执行compile
truffle compile