当前位置:网站首页>Solid contract for remote purchase of goods
Solid contract for remote purchase of goods
2022-07-18 22:38:00 【LEVI_ one hundred and four】
Preface :
The previous public auction will be expanded into a secret auction . The advantage of secret bidding is that there will be no time pressure before the bidding ends . Secret bidding on a transparent computing platform sounds like a contradiction , But cryptography can realize it .
stay Bidding period , The bidder did not actually send her bid , Instead, just send a hash version of the bid . Because it is almost impossible to find two ( Long enough ) value , Its hash value is equal , Therefore, the bidder can submit the quotation in this way . After bidding , Bidders must disclose their bids : They send their bids unencrypted , The contract checks whether the hash value of the bid is the same as that provided during the bidding .
Another challenge is how to make auctions at the same time Bindings and secrets : The only way to stop the Bidder from not paying after she wins the auction is , Let her send the money with the bid . However, due to the transfer of funds in The etheric fang Ethereum Cannot be hidden , So anyone can see the transferred funds .
The following contract solves this problem by accepting any value greater than the maximum bid . Of course , Because this can only be checked at the disclosure stage , Some bids may be Invalid Of , also , This is intentional ( With high bid , It even provides a clear sign to identify invalid bids ): Bidders can confuse their competitors by setting several invalid bids, high or low .
analysis :
Buying goods remotely requires mutual trust between buyers and sellers , In the following example , Buyers and sellers must value the goods (1*value) Twice as many (2*value As a deposit ) Put it into the contract as escrow .
As there is no way to determine whether the goods have arrived at the buyer , Once that happens , The money will be locked in the contract , Until the buyer confirms receipt of the item .
After a successful transaction , What buyers get is value (1*value) And objects , And the seller gets three times the value (3*value, Deposit plus commodity value ). The idea behind this is , Both sides have motives to solve the problem , Otherwise their money will be locked forever .
This contract certainly does not solve the problem , But it outlines how to use state machine like structures in contracts .
The following code is in solidity Many comments are added to the official English documents to help deepen understanding .
pragma solidity ^0.8.4;
// Secure remote purchase ,Remix To write
contract Purchase{
uint public value;// The value of goods
address payable public seller;// Seller's address
address payable public buyer;// Buyer address
// Enumeration type , No semicolon , Used to mark the transaction status
enum State{Created,Locked,Release,Inactive}
State public state;// Define enumeration type variables
//modifier Similar to a general function for others function Repeated calls to , Reduce the amount of code
//_; Can be placed in modifier Structure {} Run the call from anywhere in modifier Of function Code
modifier condition(bool condition_){
require(condition_);
_;
}
//error Used to explain why the operation failed , Inherit , The parameter list can only define the data type or be empty
// Cannot overload , It cannot be used as a means of controlling flow , Both internal and external contracts can be defined .
// When calling, you must use revert modification ,revert For fallback error Give the data to the caller and rollback all changes in the current call .
error OnlyBuyer();// Only buyers can call
error OnlySeller();// Only the seller can call
error InvalidState();// The current transaction status is Invalid, Cannot call
error ValueNotEven();// The commodity price is not even , Transaction needs to be suspended
modifier onlyBuyer(){
if(msg.sender != buyer)
revert OnlyBuyer();
_;
}
modifier onlySeller(){
if(msg.sender != seller)
revert OnlySeller();
_;
}
modifier inState(State state_){
if(state != state_)
revert InvalidState();
_;
}
// call event You can record the changes of some contents in the contract in the log ( Recorded on the blockchain ), With keywords emit Decorated call
// event (event) And logs cannot be accessed inside the contract , Can be called by sub contract
event Aborted();// Identify the suspended transaction status
event PurchaseConfirmed();// Identify the transaction origination
event ItemReceived();// Identify transaction confirmation
event SellerRefunded();// Identify the seller's refund event
// Constructors , Called when deploying the contract , Call only once , The address of the contract called for the first time defaults to the seller and initializes the selling price
// Current version address It is divided into :address and payable address
//payable address Support .transfer and .send Method , Used for sending ether
//payable address Only for payable address Transfer accounts , And can't give address Transfer accounts
constructor() payable{
seller = payable(msg.sender);
value = msg.value/2;
if((2*value)!=msg.value)
revert ValueNotEven();//value Must be even
}
// Suspend the trading process , Refund the seller
function abort() external onlySeller inState(State.Created){
emit Aborted();
state = State.Inactive;
seller.transfer(address(this).balance);// The transaction invokes the... In the smart contract function, Accompanying transfer amount , So you need to refund the seller here
}
// Launch a deal ( The initiator of the transaction is set as the buyer ), Change the transaction status to Locked
function confirmPurchase() external
inState(State.Created) condition(msg.value == (2*value)) payable{
emit PurchaseConfirmed();
buyer = payable(msg.sender);// Cast will buyer Convert to payable address type
state = State.Locked;
}
// Confirm the deal , Transfer money to the buyer 1*value, Change the transaction status to Release
function confirmReceived() external onlyBuyer inState(State.Locked){
emit ItemReceived();
state = State.Release;
buyer.transfer(value);
}
// Transaction refund , Transfer money to the seller 3*value, Change the transaction status to Inactive
function refundSeller() external onlySeller inState(State.Release){
emit SellerRefunded();
state = State.Inactive;
seller.transfer(3*value);
}
}边栏推荐
- 7月7日易用性SIG技术分享活动精彩回顾
- 华为 机考js 素数之积
- 开发者分享 | MindSpore高阶API工具TinyMS初体验!
- Lingo operators and built-in functions
- Which securities company has a low handling fee for opening an account, and which stock is safe to open an account
- 创新中心首发!恭喜佳华物链云获MindSpore认证!
- The observation returned by the 'reset()' method is not contained with the
- uniapp基础知识
- Crazy God redis notes 01
- 解题-->在线OJ(十六)
猜你喜欢

new操作符具体做了什么,面试

Topic selection recommendation of the latest information security graduation project

Gym报错 The observation returned by the `reset()` method is not contained with the .......

uniapp基础知识

Practical application of machine learning: quickly brush five machine learning problems of Niuke

Sff1602-mhchxm ultrafast recovery diode sff1602

Graduation season -- common interview questions in database
![[UCOS III source code analysis] - mutually exclusive semaphores (mutually exclusive locks)](/img/82/4f15e59c9e1679b24b350cebfa7935.png)
[UCOS III source code analysis] - mutually exclusive semaphores (mutually exclusive locks)

Nike, the leader of sports, is "red and black" in the trend of consumption recovery

快速解决MySQL插入中文数据时报错或乱码问题
随机推荐
2 - Conan Binary package Dependence Management Scheme
Which kind of noise reduction Bluetooth headset is good? The most cost-effective active noise reduction Bluetooth headset
PHP memory overflow? How to solve it?
LCD 显示撕裂解决
毕业季--数据库常见面试题
技术干货 | 模型优化精度、速度我全都要!MindSpore模型精度调优实战(二)
Open source ten questions, a quick start guide for community newcomers
UCOS III learning notes - time slice rotation
pdf中的超链接,跳转之后,如何返回去? alt + ←
KDD 2017 | metapath2vec: scalable representation learning of heterogeneous graphs
Technical dry goods | I want all the accuracy and speed of model optimization! Mindspire model accuracy Optimization Practice (II)
js 手写sort
语音转换历史调研记录
A New Optimizer Using Particle Swarm Theory
Tencent is all around. It's silly to ask
开发者分享 | MindSpore高阶API工具TinyMS初体验!
解题-->在线OJ(十六)
MySQL transaction operation and locking mechanism
pA是什么?构建病毒的结构元件,polyA,一段重复的碱基序列
Opengauss database