This repository has been archived by the owner on Jan 25, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
FairSwap.sol
413 lines (351 loc) · 13.8 KB
/
FairSwap.sol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
// SPDX-License-Identifier: UNLICENSED
pragma solidity >=0.7.0 <0.8.0;
// import './SafeMath.sol';
interface CustomToken {
function transfer(address recipient, uint256 amount) external;
function getBalance() external returns (uint256);
}
struct PartyTerms {
// if a contract is defined (not "0") the terms have been set
// (https://stackoverflow.com/a/48220805/9184658)
// don't declare this address as a CustomToken contract,
// it cannot be verified anyway...
address sourceContract;
uint256 tokensToSwap;
}
// steps:
// A / B creates swap, stating other's address
// state terms
// other user confirms
// each transfer the required tokens and "lock"
// -- locking can only happen if the correct number of tokens is supplied
// before both lock, they can bail
// once both lock, no going back
// can now "complete", asking the contract to transfer tokens to them in the other contract
// create / confirm used as extra verification
contract FairSwap {
// using SafeMath for uint;
address public owner;
uint256 public collateralETH;
uint256 public swapStartTime;
address payable a;
address payable b;
event SwapStarted(address a, address b);
event TermsSet(address party, address tokenContract, uint256 amount);
event TermsAccepted(address party);
event DepositConfirmed(address party);
event Executed(address party);
event Cancelled(address party);
event SwapComplete();
// re-usable mapping for keeping state
mapping(address => bool) stageCompleted;
// store party terms. party A proposes terms to B,
// and what they are to receive is stored under their address
mapping(address => PartyTerms) partyTerms;
// https://docs.soliditylang.org/en/v0.8.0/common-patterns.html#state-machine
enum Stages {
ReadyToStart,
SwapStarted,
TermsSet,
TermsAccepted,
DepositConfirmed,
Executed
// cancelled, wait for refunds
// Cancelled
}
// This is the current stage.
Stages public stage = Stages.ReadyToStart;
// go to next stage and reset stage state
function nextStage() internal {
stage = Stages(uint256(stage) + 1);
}
function setStageCompleteAndProgress(address w) internal {
stageCompleted[w] = true;
address o = getOtherParty(w);
if (stageCompleted[o]) {
// both parties completed
stageCompleted[w] = false;
stageCompleted[o] = false;
// progress
nextStage();
}
}
modifier onlyParty() {
require(
msg.sender == a || msg.sender == b,
"Must be a swap party to do this"
);
_;
}
modifier onlyOwner() {
require(msg.sender == owner, "Only owner can do this");
_;
}
// https://docs.soliditylang.org/en/v0.8.0/common-patterns.html
modifier onlyAfter(uint256 _time) {
require(block.timestamp >= _time, "Function called too early");
_;
}
modifier atStage(Stages _stage) {
require(stage == _stage, "Function cannot be called at this time");
_;
}
modifier beforeStage(Stages _stage) {
require(stage < _stage, "Function cannot be called at this time");
_;
}
constructor() {
owner = msg.sender;
}
// ===============================================================
// swap setup (create, set terms)
// ===============================================================
/**
* a single user sets up a minimal swap by providing the address of the other party
*/
function step0_createSwap(
address payable otherParty,
uint256 _collateralETH
) public atStage(Stages.ReadyToStart) {
require(msg.sender != otherParty, "Party addresses cannot be equal");
// record the swap parties' addresses
a = msg.sender;
b = otherParty;
// collateral set by the user who creates the swap
collateralETH = _collateralETH;
// reset swap start time
swapStartTime = block.timestamp;
// only called by a single user
nextStage();
emit SwapStarted(msg.sender, otherParty);
}
/**
* each user should set their own swap terms for gas fairness
*/
function step1_setSwapTerms(address sourceContract, uint256 amount)
public
atStage(Stages.SwapStarted)
{
// cannot use "0" address
// https://stackoverflow.com/a/48220805/9184658
// require(
// sourceContract != address(0),
// "Source contract cannot be 0x0"
// );
// can only be set once, not modified afterwards
require(
partyTerms[msg.sender].sourceContract == address(0),
"Cannot change swap terms: cancel if necessary"
);
// record the terms set by this party
partyTerms[msg.sender] = PartyTerms(sourceContract, amount);
setStageCompleteAndProgress(msg.sender);
emit TermsSet(msg.sender, sourceContract, amount);
}
/**
* "view" allowing each party to review the terms of the swap prior to accepting
*/
function reviewTerms()
public
view
returns (
address party1,
address contract1,
uint256 party1_Tokens,
address party2,
address contract2,
uint256 party2_Tokens
)
{
PartyTerms memory ptA = partyTerms[a];
PartyTerms memory ptB = partyTerms[b];
return (
a,
ptA.sourceContract,
ptA.tokensToSwap,
b,
ptB.sourceContract,
ptB.tokensToSwap
);
}
/**
* each user should check, and then accept the terms.
* users must also provide the correct amount of collateral set at the beginning
*/
function step2_acceptTerms()
public
payable
onlyParty
atStage(Stages.TermsSet)
{
// store collateral
require(msg.value == collateralETH, "Must provide agreed collateral");
// terms have been accepted by the sender, this stage is confirmed by this user
setStageCompleteAndProgress(msg.sender);
emit TermsAccepted(msg.sender);
}
// ===============================================================
// deposit checking
// ===============================================================
// after accepting terms, both users should "transfer" to the contract
// store the number of tokens deposited?
/**
* "confirm" that you have transferred the required tokens to the contract
*/
function step3_confirmDeposit()
public
onlyParty
atStage(Stages.TermsAccepted)
{
// check balance on this user's contract
PartyTerms memory pt = partyTerms[msg.sender];
CustomToken sourceContract = CustomToken(pt.sourceContract);
uint256 balance = sourceContract.getBalance();
// since there is only ever one swap happening, we should
// only have exactly the required amount of tokens
// --> **assume that users only transfer either the exact number of tokens required, or none at all**
if (balance < pt.tokensToSwap) {
revert("Incorrect number of tokens provided");
} else if (balance > pt.tokensToSwap) {
// balance higher than expected, return the difference
sourceContract.transfer(msg.sender, balance - pt.tokensToSwap);
}
// should now be equal
// require(
// balance == pt.tokensToSwap,
// "Incorrect number of tokens provided"
// );
// // take this opportunity to return the tokens if amount not correct
// uint256 tokenBalance = sourceContract.getBalance();
// if (tokenBalance != pt.tokensToSwap) {
// sourceContract.transfer(msg.sender, tokenBalance - pt.tokensToSwap);
// revert("Incorrect number of tokens provided: refund issued");
// }
// then this deposit is confirmed
// if any more tokens are added after this, we are not responsible
setStageCompleteAndProgress(msg.sender);
emit DepositConfirmed(msg.sender);
}
// ===============================================================
// swap execution
// ===============================================================
function step4_requestFinalTransfer()
public
onlyParty
atStage(Stages.DepositConfirmed)
{
// the contract is in the possession of all tokens, so pass them to their new owners
// can only be called once
require(
!stageCompleted[msg.sender],
"Swapped tokens already transferred"
);
address o = getOtherParty(msg.sender);
PartyTerms memory targetTerms = partyTerms[o];
CustomToken sourceContract = CustomToken(targetTerms.sourceContract);
// prevent re-entrancy
setStageCompleteAndProgress(msg.sender);
// transfer tokens in the new contract
sourceContract.transfer(msg.sender, targetTerms.tokensToSwap);
// return collateral
payable(msg.sender).transfer(collateralETH);
emit Executed(msg.sender);
// reset other party's terms since this user is no longer owed anything
reset(o);
if (stage == Stages.Executed) {
// both parties have requested, swap complete
// a = address(0);
// b = address(0);
stage = Stages.ReadyToStart;
emit SwapComplete();
}
}
// ===============================================================
// swap cancelled / ends
// ===============================================================
/**
* if either party cancels the swap, they should both be allowed to claim what they had transferred
* can't give a penalty because we don't know why the user has cancelled.
* It could be that user A has completed their deposit, but B hasn't, or a user willingly cancels
* at the last minute because they do not agree to the terms.
* The user who cancels must wait at least one hour (or n hours), which would give a
* legitimate user enough time to transfer and confirm their deposit.
* Depends on deposits:
* - If A has deposited, but not B, A can cancel because B bailed.
* - If A has completed the stage, B cannot cancel. But A can cancel.
* - If neither A or B have deposited, either can cancel but both were bad for not depositing
* - If both have deposited (but one or both not confirmed), either can cancel and ???
*/
function cancel()
public
onlyParty
onlyAfter(swapStartTime + 6 hours)
beforeStage(Stages.DepositConfirmed)
{
// cannot cancel once both deposits have been confirmed
// if TermsAccepted stage is reached, there should be a penalty for not swapping
address o = getOtherParty(msg.sender);
// if you have accepted terms, then you may get collateral when the other cancels,
// but you must be in this stage, since the next stage is when deposits are confirmed
// and the swap can no longer be cancelled
if (stage == Stages.TermsAccepted) {
// collateral has been paid in,
// you can only cancel after agreeing terms if the other person has not already completed the step
require(
!stageCompleted[o],
"Other party has already completed this step, you cannot cancel"
);
// that is the case, so you'll receive your collateral
// https://ethereum.stackexchange.com/a/35412
// > If the only maths you need to do is adding sums of Ether obtained from msg.value to other
// > sums of Ether obtained from msg.value, it shouldn't be necessary to use SafeMath, since
// > the msg.value is bounded by the number of Ether in existence, which is well below the
// > range that can be represented by a uint256.
payable(msg.sender).transfer(collateralETH);
if (stageCompleted[msg.sender]) {
// additionally, if you've completed the stage, you'll be refunded
// your tokens and *all* the collateral
payable(msg.sender).transfer(collateralETH);
PartyTerms memory pt = partyTerms[msg.sender];
CustomToken(pt.sourceContract).transfer(
msg.sender,
pt.tokensToSwap
);
} else {
// if not, the other person gets their share of the collateral
payable(o).transfer(collateralETH);
}
}
reset(msg.sender);
reset(o);
// otherwise, just cancel, nothing lost
stage = Stages.ReadyToStart;
emit Cancelled(msg.sender);
}
// ===============================================================
// utility functions
// ===============================================================
function getOtherParty(address w) public view returns (address payable) {
address payable otherParty;
if (w == a) {
otherParty = b;
} else if (w == b) {
otherParty = a;
}
// returns address(0) if not a party?
return otherParty;
}
// can only call manual override 6 hours after "cancel" becomes avilable
function manualOverride()
public
onlyOwner
onlyAfter(swapStartTime + 12 hours)
beforeStage(Stages.Executed)
{
// owner returns collateral, tokens, etc
}
function reset(address o) internal {
// reset other party's terms since the party requesting reset is no longer owed anything
partyTerms[o] = PartyTerms(address(0), 0);
}
}