forked from Synthetixio/synthetix
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathExchanger.sol
1055 lines (914 loc) · 39.1 KB
/
Exchanger.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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
pragma solidity ^0.5.16;
// Inheritance
import "./Owned.sol";
import "./MixinResolver.sol";
import "./MixinSystemSettings.sol";
import "./interfaces/IExchanger.sol";
// Libraries
import "./SafeDecimalMath.sol";
// Internal references
import "./interfaces/ISystemStatus.sol";
import "./interfaces/IERC20.sol";
import "./interfaces/IExchangeState.sol";
import "./interfaces/IExchangeRates.sol";
import "./interfaces/ICircuitBreaker.sol";
import "./interfaces/ISynthetix.sol";
import "./interfaces/IFeePool.sol";
import "./interfaces/IDelegateApprovals.sol";
import "./interfaces/IIssuer.sol";
import "./interfaces/ITradingRewards.sol";
import "./interfaces/IVirtualSynth.sol";
import "./Proxyable.sol";
// Used to have strongly-typed access to internal mutative functions in Synthetix
interface ISynthetixInternal {
function emitExchangeTracking(
bytes32 trackingCode,
bytes32 toCurrencyKey,
uint256 toAmount,
uint256 fee
) external;
function emitSynthExchange(
address account,
bytes32 fromCurrencyKey,
uint fromAmount,
bytes32 toCurrencyKey,
uint toAmount,
address toAddress
) external;
function emitAtomicSynthExchange(
address account,
bytes32 fromCurrencyKey,
uint fromAmount,
bytes32 toCurrencyKey,
uint toAmount,
address toAddress
) external;
function emitExchangeReclaim(
address account,
bytes32 currencyKey,
uint amount
) external;
function emitExchangeRebate(
address account,
bytes32 currencyKey,
uint amount
) external;
}
interface IExchangerInternalDebtCache {
function updateCachedSynthDebtsWithRates(bytes32[] calldata currencyKeys, uint[] calldata currencyRates) external;
function updateCachedSynthDebts(bytes32[] calldata currencyKeys) external;
}
// https://docs.synthetix.io/contracts/source/contracts/exchanger
contract Exchanger is Owned, MixinSystemSettings, IExchanger {
using SafeMath for uint;
using SafeDecimalMath for uint;
bytes32 public constant CONTRACT_NAME = "Exchanger";
bytes32 internal constant sUSD = "sUSD";
/* ========== ADDRESS RESOLVER CONFIGURATION ========== */
bytes32 private constant CONTRACT_SYSTEMSTATUS = "SystemStatus";
bytes32 private constant CONTRACT_EXCHANGESTATE = "ExchangeState";
bytes32 private constant CONTRACT_EXRATES = "ExchangeRates";
bytes32 private constant CONTRACT_SYNTHETIX = "Synthetix";
bytes32 private constant CONTRACT_FEEPOOL = "FeePool";
bytes32 private constant CONTRACT_TRADING_REWARDS = "TradingRewards";
bytes32 private constant CONTRACT_DELEGATEAPPROVALS = "DelegateApprovals";
bytes32 private constant CONTRACT_ISSUER = "Issuer";
bytes32 private constant CONTRACT_DEBTCACHE = "DebtCache";
bytes32 private constant CONTRACT_CIRCUIT_BREAKER = "CircuitBreaker";
constructor(address _owner, address _resolver) public Owned(_owner) MixinSystemSettings(_resolver) {}
/* ========== VIEWS ========== */
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {
bytes32[] memory existingAddresses = MixinSystemSettings.resolverAddressesRequired();
bytes32[] memory newAddresses = new bytes32[](10);
newAddresses[0] = CONTRACT_SYSTEMSTATUS;
newAddresses[1] = CONTRACT_EXCHANGESTATE;
newAddresses[2] = CONTRACT_EXRATES;
newAddresses[3] = CONTRACT_SYNTHETIX;
newAddresses[4] = CONTRACT_FEEPOOL;
newAddresses[5] = CONTRACT_TRADING_REWARDS;
newAddresses[6] = CONTRACT_DELEGATEAPPROVALS;
newAddresses[7] = CONTRACT_ISSUER;
newAddresses[8] = CONTRACT_DEBTCACHE;
newAddresses[9] = CONTRACT_CIRCUIT_BREAKER;
addresses = combineArrays(existingAddresses, newAddresses);
}
function systemStatus() internal view returns (ISystemStatus) {
return ISystemStatus(requireAndGetAddress(CONTRACT_SYSTEMSTATUS));
}
function exchangeState() internal view returns (IExchangeState) {
return IExchangeState(requireAndGetAddress(CONTRACT_EXCHANGESTATE));
}
function exchangeRates() internal view returns (IExchangeRates) {
return IExchangeRates(requireAndGetAddress(CONTRACT_EXRATES));
}
function circuitBreaker() internal view returns (ICircuitBreaker) {
return ICircuitBreaker(requireAndGetAddress(CONTRACT_CIRCUIT_BREAKER));
}
function synthetix() internal view returns (ISynthetix) {
return ISynthetix(requireAndGetAddress(CONTRACT_SYNTHETIX));
}
function feePool() internal view returns (IFeePool) {
return IFeePool(requireAndGetAddress(CONTRACT_FEEPOOL));
}
function tradingRewards() internal view returns (ITradingRewards) {
return ITradingRewards(requireAndGetAddress(CONTRACT_TRADING_REWARDS));
}
function delegateApprovals() internal view returns (IDelegateApprovals) {
return IDelegateApprovals(requireAndGetAddress(CONTRACT_DELEGATEAPPROVALS));
}
function issuer() internal view returns (IIssuer) {
return IIssuer(requireAndGetAddress(CONTRACT_ISSUER));
}
function debtCache() internal view returns (IExchangerInternalDebtCache) {
return IExchangerInternalDebtCache(requireAndGetAddress(CONTRACT_DEBTCACHE));
}
function maxSecsLeftInWaitingPeriod(address account, bytes32 currencyKey) public view returns (uint) {
return secsLeftInWaitingPeriodForExchange(exchangeState().getMaxTimestamp(account, currencyKey));
}
function waitingPeriodSecs() external view returns (uint) {
return getWaitingPeriodSecs();
}
function tradingRewardsEnabled() external view returns (bool) {
return getTradingRewardsEnabled();
}
function priceDeviationThresholdFactor() external view returns (uint) {
return getPriceDeviationThresholdFactor();
}
function lastExchangeRate(bytes32 currencyKey) external view returns (uint) {
return circuitBreaker().lastValue(address(exchangeRates().aggregators(currencyKey)));
}
function settlementOwing(address account, bytes32 currencyKey)
public
view
returns (
uint reclaimAmount,
uint rebateAmount,
uint numEntries
)
{
(reclaimAmount, rebateAmount, numEntries, ) = _settlementOwing(account, currencyKey);
}
// Internal function to aggregate each individual rebate and reclaim entry for a synth
function _settlementOwing(address account, bytes32 currencyKey)
internal
view
returns (
uint reclaimAmount,
uint rebateAmount,
uint numEntries,
IExchanger.ExchangeEntrySettlement[] memory
)
{
// Need to sum up all reclaim and rebate amounts for the user and the currency key
numEntries = exchangeState().getLengthOfEntries(account, currencyKey);
// For each unsettled exchange
IExchanger.ExchangeEntrySettlement[] memory settlements = new IExchanger.ExchangeEntrySettlement[](numEntries);
for (uint i = 0; i < numEntries; i++) {
uint reclaim;
uint rebate;
// fetch the entry from storage
IExchangeState.ExchangeEntry memory exchangeEntry = _getExchangeEntry(account, currencyKey, i);
// determine the last round ids for src and dest pairs when period ended or latest if not over
(uint srcRoundIdAtPeriodEnd, uint destRoundIdAtPeriodEnd) = getRoundIdsAtPeriodEnd(exchangeEntry);
// given these round ids, determine what effective value they should have received
(uint destinationAmount, , ) =
exchangeRates().effectiveValueAndRatesAtRound(
exchangeEntry.src,
exchangeEntry.amount,
exchangeEntry.dest,
srcRoundIdAtPeriodEnd,
destRoundIdAtPeriodEnd
);
// and deduct the fee from this amount using the exchangeFeeRate from storage
uint amountShouldHaveReceived = _deductFeesFromAmount(destinationAmount, exchangeEntry.exchangeFeeRate);
// SIP-65 settlements where the amount at end of waiting period is beyond the threshold, then
// settle with no reclaim or rebate
bool sip65condition =
circuitBreaker().isDeviationAboveThreshold(exchangeEntry.amountReceived, amountShouldHaveReceived);
if (!sip65condition) {
if (exchangeEntry.amountReceived > amountShouldHaveReceived) {
// if they received more than they should have, add to the reclaim tally
reclaim = exchangeEntry.amountReceived.sub(amountShouldHaveReceived);
reclaimAmount = reclaimAmount.add(reclaim);
} else if (amountShouldHaveReceived > exchangeEntry.amountReceived) {
// if less, add to the rebate tally
rebate = amountShouldHaveReceived.sub(exchangeEntry.amountReceived);
rebateAmount = rebateAmount.add(rebate);
}
}
settlements[i] = IExchanger.ExchangeEntrySettlement({
src: exchangeEntry.src,
amount: exchangeEntry.amount,
dest: exchangeEntry.dest,
reclaim: reclaim,
rebate: rebate,
srcRoundIdAtPeriodEnd: srcRoundIdAtPeriodEnd,
destRoundIdAtPeriodEnd: destRoundIdAtPeriodEnd,
timestamp: exchangeEntry.timestamp
});
}
return (reclaimAmount, rebateAmount, numEntries, settlements);
}
function _getExchangeEntry(
address account,
bytes32 currencyKey,
uint index
) internal view returns (IExchangeState.ExchangeEntry memory) {
(
bytes32 src,
uint amount,
bytes32 dest,
uint amountReceived,
uint exchangeFeeRate,
uint timestamp,
uint roundIdForSrc,
uint roundIdForDest
) = exchangeState().getEntryAt(account, currencyKey, index);
return
IExchangeState.ExchangeEntry({
src: src,
amount: amount,
dest: dest,
amountReceived: amountReceived,
exchangeFeeRate: exchangeFeeRate,
timestamp: timestamp,
roundIdForSrc: roundIdForSrc,
roundIdForDest: roundIdForDest
});
}
function hasWaitingPeriodOrSettlementOwing(address account, bytes32 currencyKey) external view returns (bool) {
if (maxSecsLeftInWaitingPeriod(account, currencyKey) != 0) {
return true;
}
(uint reclaimAmount, , , ) = _settlementOwing(account, currencyKey);
return reclaimAmount > 0;
}
/* ========== SETTERS ========== */
function calculateAmountAfterSettlement(
address from,
bytes32 currencyKey,
uint amount,
uint refunded
) public view returns (uint amountAfterSettlement) {
amountAfterSettlement = amount;
// balance of a synth will show an amount after settlement
uint balanceOfSourceAfterSettlement = IERC20(address(issuer().synths(currencyKey))).balanceOf(from);
// when there isn't enough supply (either due to reclamation settlement or because the number is too high)
if (amountAfterSettlement > balanceOfSourceAfterSettlement) {
// then the amount to exchange is reduced to their remaining supply
amountAfterSettlement = balanceOfSourceAfterSettlement;
}
if (refunded > 0) {
amountAfterSettlement = amountAfterSettlement.add(refunded);
}
}
function isSynthRateInvalid(bytes32 currencyKey) external view returns (bool) {
(, bool invalid) = exchangeRates().rateAndInvalid(currencyKey);
return invalid;
}
/* ========== MUTATIVE FUNCTIONS ========== */
function exchange(
address exchangeForAddress,
address from,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
address destinationAddress,
bool virtualSynth,
address rewardAddress,
bytes32 trackingCode
) external onlySynthetixorSynth returns (uint amountReceived, IVirtualSynth vSynth) {
uint fee;
if (from != exchangeForAddress) {
require(delegateApprovals().canExchangeFor(exchangeForAddress, from), "Not approved to act on behalf");
}
(amountReceived, fee, vSynth) = _exchange(
exchangeForAddress,
sourceCurrencyKey,
sourceAmount,
destinationCurrencyKey,
destinationAddress,
virtualSynth
);
_processTradingRewards(fee, rewardAddress);
if (trackingCode != bytes32(0)) {
_emitTrackingEvent(trackingCode, destinationCurrencyKey, amountReceived, fee);
}
}
function exchangeAtomically(
address,
bytes32,
uint,
bytes32,
address,
bytes32,
uint
) external returns (uint) {
_notImplemented();
}
function _emitTrackingEvent(
bytes32 trackingCode,
bytes32 toCurrencyKey,
uint256 toAmount,
uint256 fee
) internal {
ISynthetixInternal(address(synthetix())).emitExchangeTracking(trackingCode, toCurrencyKey, toAmount, fee);
}
function _processTradingRewards(uint fee, address rewardAddress) internal {
if (fee > 0 && rewardAddress != address(0) && getTradingRewardsEnabled()) {
tradingRewards().recordExchangeFeeForAccount(fee, rewardAddress);
}
}
function _updateSNXIssuedDebtOnExchange(bytes32[2] memory currencyKeys, uint[2] memory currencyRates) internal {
bool includesSUSD = currencyKeys[0] == sUSD || currencyKeys[1] == sUSD;
uint numKeys = includesSUSD ? 2 : 3;
bytes32[] memory keys = new bytes32[](numKeys);
keys[0] = currencyKeys[0];
keys[1] = currencyKeys[1];
uint[] memory rates = new uint[](numKeys);
rates[0] = currencyRates[0];
rates[1] = currencyRates[1];
if (!includesSUSD) {
keys[2] = sUSD; // And we'll also update sUSD to account for any fees if it wasn't one of the exchanged currencies
rates[2] = SafeDecimalMath.unit();
}
// Note that exchanges can't invalidate the debt cache, since if a rate is invalid,
// the exchange will have failed already.
debtCache().updateCachedSynthDebtsWithRates(keys, rates);
}
function _settleAndCalcSourceAmountRemaining(
uint sourceAmount,
address from,
bytes32 sourceCurrencyKey
) internal returns (uint sourceAmountAfterSettlement) {
(, uint refunded, uint numEntriesSettled) = _internalSettle(from, sourceCurrencyKey, false);
sourceAmountAfterSettlement = sourceAmount;
// when settlement was required
if (numEntriesSettled > 0) {
// ensure the sourceAmount takes this into account
sourceAmountAfterSettlement = calculateAmountAfterSettlement(from, sourceCurrencyKey, sourceAmount, refunded);
}
}
function _exchange(
address from,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
address destinationAddress,
bool virtualSynth
)
internal
returns (
uint amountReceived,
uint fee,
IVirtualSynth vSynth
)
{
if (!_ensureCanExchange(sourceCurrencyKey, destinationCurrencyKey, sourceAmount)) {
return (0, 0, IVirtualSynth(0));
}
// Using struct to resolve stack too deep error
IExchanger.ExchangeEntry memory entry;
entry.roundIdForSrc = exchangeRates().getCurrentRoundId(sourceCurrencyKey);
entry.roundIdForDest = exchangeRates().getCurrentRoundId(destinationCurrencyKey);
uint sourceAmountAfterSettlement = _settleAndCalcSourceAmountRemaining(sourceAmount, from, sourceCurrencyKey);
// If, after settlement the user has no balance left (highly unlikely), then return to prevent
// emitting events of 0 and don't revert so as to ensure the settlement queue is emptied
if (sourceAmountAfterSettlement == 0) {
return (0, 0, IVirtualSynth(0));
}
(entry.destinationAmount, entry.sourceRate, entry.destinationRate) = exchangeRates().effectiveValueAndRatesAtRound(
sourceCurrencyKey,
sourceAmountAfterSettlement,
destinationCurrencyKey,
entry.roundIdForSrc,
entry.roundIdForDest
);
// rates must also be good for the round we are doing
_ensureCanExchangeAtRound(sourceCurrencyKey, destinationCurrencyKey, entry.roundIdForSrc, entry.roundIdForDest);
bool tooVolatile;
(entry.exchangeFeeRate, tooVolatile) = _feeRateForExchangeAtRounds(
sourceCurrencyKey,
destinationCurrencyKey,
entry.roundIdForSrc,
entry.roundIdForDest
);
if (tooVolatile) {
// do not exchange if rates are too volatile, this to prevent charging
// dynamic fees that are over the max value
return (0, 0, IVirtualSynth(0));
}
amountReceived = _deductFeesFromAmount(entry.destinationAmount, entry.exchangeFeeRate);
// Note: `fee` is denominated in the destinationCurrencyKey.
fee = entry.destinationAmount.sub(amountReceived);
// Note: We don't need to check their balance as the _convert() below will do a safe subtraction which requires
// the subtraction to not overflow, which would happen if their balance is not sufficient.
vSynth = _convert(
sourceCurrencyKey,
from,
sourceAmountAfterSettlement,
destinationCurrencyKey,
amountReceived,
destinationAddress,
virtualSynth
);
// When using a virtual synth, it becomes the destinationAddress for event and settlement tracking
if (vSynth != IVirtualSynth(0)) {
destinationAddress = address(vSynth);
}
// Remit the fee if required
if (fee > 0) {
// Normalize fee to sUSD
// Note: `fee` is being reused to avoid stack too deep errors.
fee = exchangeRates().effectiveValue(destinationCurrencyKey, fee, sUSD);
// Remit the fee in sUSDs
issuer().synths(sUSD).issue(feePool().FEE_ADDRESS(), fee);
// Tell the fee pool about this
feePool().recordFeePaid(fee);
}
// Note: As of this point, `fee` is denominated in sUSD.
// Nothing changes as far as issuance data goes because the total value in the system hasn't changed.
// But we will update the debt snapshot in case exchange rates have fluctuated since the last exchange
// in these currencies
_updateSNXIssuedDebtOnExchange(
[sourceCurrencyKey, destinationCurrencyKey],
[entry.sourceRate, entry.destinationRate]
);
// Let the DApps know there was a Synth exchange
ISynthetixInternal(address(synthetix())).emitSynthExchange(
from,
sourceCurrencyKey,
sourceAmountAfterSettlement,
destinationCurrencyKey,
amountReceived,
destinationAddress
);
// iff the waiting period is gt 0
if (getWaitingPeriodSecs() > 0) {
// persist the exchange information for the dest key
appendExchange(
destinationAddress,
sourceCurrencyKey,
sourceAmountAfterSettlement,
destinationCurrencyKey,
amountReceived,
entry.exchangeFeeRate
);
}
}
function _convert(
bytes32 sourceCurrencyKey,
address from,
uint sourceAmountAfterSettlement,
bytes32 destinationCurrencyKey,
uint amountReceived,
address recipient,
bool virtualSynth
) internal returns (IVirtualSynth vSynth) {
// Burn the source amount
issuer().synths(sourceCurrencyKey).burn(from, sourceAmountAfterSettlement);
// Issue their new synths
ISynth dest = issuer().synths(destinationCurrencyKey);
if (virtualSynth) {
Proxyable synth = Proxyable(address(dest));
vSynth = _createVirtualSynth(IERC20(address(synth.proxy())), recipient, amountReceived, destinationCurrencyKey);
dest.issue(address(vSynth), amountReceived);
} else {
dest.issue(recipient, amountReceived);
}
}
function _createVirtualSynth(
IERC20,
address,
uint,
bytes32
) internal returns (IVirtualSynth) {
_notImplemented();
}
// Note: this function can intentionally be called by anyone on behalf of anyone else (the caller just pays the gas)
function settle(address from, bytes32 currencyKey)
external
returns (
uint reclaimed,
uint refunded,
uint numEntriesSettled
)
{
systemStatus().requireSynthActive(currencyKey);
return _internalSettle(from, currencyKey, true);
}
function suspendSynthWithInvalidRate(bytes32 currencyKey) external {
systemStatus().requireSystemActive();
// SIP-65: Decentralized Circuit Breaker
(, bool circuitBroken, ) = exchangeRates().rateWithSafetyChecks(currencyKey);
require(circuitBroken, "Synth price is valid");
}
/* ========== INTERNAL FUNCTIONS ========== */
// runs basic checks and calls `rateWithSafetyChecks` (which can trigger circuit breakers)
// returns if there are any problems found with the rate of the given currencyKey but not reverted
function _ensureCanExchange(
bytes32 sourceCurrencyKey,
bytes32 destinationCurrencyKey,
uint sourceAmount
) internal returns (bool) {
require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth");
require(sourceAmount > 0, "Zero amount");
(, bool srcBroken, bool srcStaleOrInvalid) =
sourceCurrencyKey != sUSD ? exchangeRates().rateWithSafetyChecks(sourceCurrencyKey) : (0, false, false);
(, bool dstBroken, bool dstStaleOrInvalid) =
destinationCurrencyKey != sUSD
? exchangeRates().rateWithSafetyChecks(destinationCurrencyKey)
: (0, false, false);
require(!srcStaleOrInvalid, "src rate stale or flagged");
require(!dstStaleOrInvalid, "dest rate stale or flagged");
return !srcBroken && !dstBroken;
}
// runs additional checks to verify a rate is valid at a specific round`
function _ensureCanExchangeAtRound(
bytes32 sourceCurrencyKey,
bytes32 destinationCurrencyKey,
uint roundIdForSrc,
uint roundIdForDest
) internal view {
require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth");
bytes32[] memory synthKeys = new bytes32[](2);
synthKeys[0] = sourceCurrencyKey;
synthKeys[1] = destinationCurrencyKey;
uint[] memory roundIds = new uint[](2);
roundIds[0] = roundIdForSrc;
roundIds[1] = roundIdForDest;
require(!exchangeRates().anyRateIsInvalidAtRound(synthKeys, roundIds), "src/dest rate stale or flagged");
}
function _internalSettle(
address from,
bytes32 currencyKey,
bool updateCache
)
internal
returns (
uint reclaimed,
uint refunded,
uint numEntriesSettled
)
{
require(maxSecsLeftInWaitingPeriod(from, currencyKey) == 0, "Cannot settle during waiting period");
(uint reclaimAmount, uint rebateAmount, uint entries, IExchanger.ExchangeEntrySettlement[] memory settlements) =
_settlementOwing(from, currencyKey);
if (reclaimAmount > rebateAmount) {
reclaimed = reclaimAmount.sub(rebateAmount);
reclaim(from, currencyKey, reclaimed);
} else if (rebateAmount > reclaimAmount) {
refunded = rebateAmount.sub(reclaimAmount);
refund(from, currencyKey, refunded);
}
// by checking a reclaim or refund we also check that the currency key is still a valid synth,
// as the deviation check will return 0 if the synth has been removed.
if (updateCache && (reclaimed > 0 || refunded > 0)) {
bytes32[] memory key = new bytes32[](1);
key[0] = currencyKey;
debtCache().updateCachedSynthDebts(key);
}
// emit settlement event for each settled exchange entry
for (uint i = 0; i < settlements.length; i++) {
emit ExchangeEntrySettled(
from,
settlements[i].src,
settlements[i].amount,
settlements[i].dest,
settlements[i].reclaim,
settlements[i].rebate,
settlements[i].srcRoundIdAtPeriodEnd,
settlements[i].destRoundIdAtPeriodEnd,
settlements[i].timestamp
);
}
numEntriesSettled = entries;
// Now remove all entries, even if no reclaim and no rebate
exchangeState().removeEntries(from, currencyKey);
}
function reclaim(
address from,
bytes32 currencyKey,
uint amount
) internal {
// burn amount from user
issuer().synths(currencyKey).burn(from, amount);
ISynthetixInternal(address(synthetix())).emitExchangeReclaim(from, currencyKey, amount);
}
function refund(
address from,
bytes32 currencyKey,
uint amount
) internal {
// issue amount to user
issuer().synths(currencyKey).issue(from, amount);
ISynthetixInternal(address(synthetix())).emitExchangeRebate(from, currencyKey, amount);
}
function secsLeftInWaitingPeriodForExchange(uint timestamp) internal view returns (uint) {
uint _waitingPeriodSecs = getWaitingPeriodSecs();
if (timestamp == 0 || now >= timestamp.add(_waitingPeriodSecs)) {
return 0;
}
return timestamp.add(_waitingPeriodSecs).sub(now);
}
/* ========== Exchange Related Fees ========== */
/// @notice public function to get the total fee rate for a given exchange
/// @param sourceCurrencyKey The source currency key
/// @param destinationCurrencyKey The destination currency key
/// @return The exchange fee rate, and whether the rates are too volatile
function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view returns (uint) {
(uint feeRate, bool tooVolatile) = _feeRateForExchange(sourceCurrencyKey, destinationCurrencyKey);
require(!tooVolatile, "too volatile");
return feeRate;
}
/// @notice public function to get the dynamic fee rate for a given exchange
/// @param sourceCurrencyKey The source currency key
/// @param destinationCurrencyKey The destination currency key
/// @return The exchange dynamic fee rate and if rates are too volatile
function dynamicFeeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey)
external
view
returns (uint feeRate, bool tooVolatile)
{
return _dynamicFeeRateForExchange(sourceCurrencyKey, destinationCurrencyKey);
}
/// @notice Calculate the exchange fee for a given source and destination currency key
/// @param sourceCurrencyKey The source currency key
/// @param destinationCurrencyKey The destination currency key
/// @return The exchange fee rate
/// @return The exchange dynamic fee rate and if rates are too volatile
function _feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey)
internal
view
returns (uint feeRate, bool tooVolatile)
{
// Get the exchange fee rate as per the source currencyKey and destination currencyKey
uint baseRate = getExchangeFeeRate(sourceCurrencyKey).add(getExchangeFeeRate(destinationCurrencyKey));
uint dynamicFee;
(dynamicFee, tooVolatile) = _dynamicFeeRateForExchange(sourceCurrencyKey, destinationCurrencyKey);
return (baseRate.add(dynamicFee), tooVolatile);
}
/// @notice Calculate the exchange fee for a given source and destination currency key
/// @param sourceCurrencyKey The source currency key
/// @param destinationCurrencyKey The destination currency key
/// @param roundIdForSrc The round id of the source currency.
/// @param roundIdForDest The round id of the target currency.
/// @return The exchange fee rate
/// @return The exchange dynamic fee rate
function _feeRateForExchangeAtRounds(
bytes32 sourceCurrencyKey,
bytes32 destinationCurrencyKey,
uint roundIdForSrc,
uint roundIdForDest
) internal view returns (uint feeRate, bool tooVolatile) {
// Get the exchange fee rate as per the source currencyKey and destination currencyKey
uint baseRate = getExchangeFeeRate(sourceCurrencyKey).add(getExchangeFeeRate(destinationCurrencyKey));
uint dynamicFee;
(dynamicFee, tooVolatile) = _dynamicFeeRateForExchangeAtRounds(
sourceCurrencyKey,
destinationCurrencyKey,
roundIdForSrc,
roundIdForDest
);
return (baseRate.add(dynamicFee), tooVolatile);
}
function _dynamicFeeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey)
internal
view
returns (uint dynamicFee, bool tooVolatile)
{
DynamicFeeConfig memory config = getExchangeDynamicFeeConfig();
(uint dynamicFeeDst, bool dstVolatile) = _dynamicFeeRateForCurrency(destinationCurrencyKey, config);
(uint dynamicFeeSrc, bool srcVolatile) = _dynamicFeeRateForCurrency(sourceCurrencyKey, config);
dynamicFee = dynamicFeeDst.add(dynamicFeeSrc);
// cap to maxFee
bool overMax = dynamicFee > config.maxFee;
dynamicFee = overMax ? config.maxFee : dynamicFee;
return (dynamicFee, overMax || dstVolatile || srcVolatile);
}
function _dynamicFeeRateForExchangeAtRounds(
bytes32 sourceCurrencyKey,
bytes32 destinationCurrencyKey,
uint roundIdForSrc,
uint roundIdForDest
) internal view returns (uint dynamicFee, bool tooVolatile) {
DynamicFeeConfig memory config = getExchangeDynamicFeeConfig();
(uint dynamicFeeDst, bool dstVolatile) =
_dynamicFeeRateForCurrencyRound(destinationCurrencyKey, roundIdForDest, config);
(uint dynamicFeeSrc, bool srcVolatile) = _dynamicFeeRateForCurrencyRound(sourceCurrencyKey, roundIdForSrc, config);
dynamicFee = dynamicFeeDst.add(dynamicFeeSrc);
// cap to maxFee
bool overMax = dynamicFee > config.maxFee;
dynamicFee = overMax ? config.maxFee : dynamicFee;
return (dynamicFee, overMax || dstVolatile || srcVolatile);
}
/// @notice Get dynamic dynamicFee for a given currency key (SIP-184)
/// @param currencyKey The given currency key
/// @param config dynamic fee calculation configuration params
/// @return The dynamic fee and if it exceeds max dynamic fee set in config
function _dynamicFeeRateForCurrency(bytes32 currencyKey, DynamicFeeConfig memory config)
internal
view
returns (uint dynamicFee, bool tooVolatile)
{
// no dynamic dynamicFee for sUSD or too few rounds
if (currencyKey == sUSD || config.rounds <= 1) {
return (0, false);
}
uint roundId = exchangeRates().getCurrentRoundId(currencyKey);
return _dynamicFeeRateForCurrencyRound(currencyKey, roundId, config);
}
/// @notice Get dynamicFee for a given currency key (SIP-184)
/// @param currencyKey The given currency key
/// @param roundId The round id
/// @param config dynamic fee calculation configuration params
/// @return The dynamic fee and if it exceeds max dynamic fee set in config
function _dynamicFeeRateForCurrencyRound(
bytes32 currencyKey,
uint roundId,
DynamicFeeConfig memory config
) internal view returns (uint dynamicFee, bool tooVolatile) {
// no dynamic dynamicFee for sUSD or too few rounds
if (currencyKey == sUSD || config.rounds <= 1) {
return (0, false);
}
uint[] memory prices;
(prices, ) = exchangeRates().ratesAndUpdatedTimeForCurrencyLastNRounds(currencyKey, config.rounds, roundId);
dynamicFee = _dynamicFeeCalculation(prices, config.threshold, config.weightDecay);
// cap to maxFee
bool overMax = dynamicFee > config.maxFee;
dynamicFee = overMax ? config.maxFee : dynamicFee;
return (dynamicFee, overMax);
}
/// @notice Calculate dynamic fee according to SIP-184
/// @param prices A list of prices from the current round to the previous rounds
/// @param threshold A threshold to clip the price deviation ratop
/// @param weightDecay A weight decay constant
/// @return uint dynamic fee rate as decimal
function _dynamicFeeCalculation(
uint[] memory prices,
uint threshold,
uint weightDecay
) internal pure returns (uint) {
// don't underflow
if (prices.length == 0) {
return 0;
}
uint dynamicFee = 0; // start with 0
// go backwards in price array
for (uint i = prices.length - 1; i > 0; i--) {
// apply decay from previous round (will be 0 for first round)
dynamicFee = dynamicFee.multiplyDecimal(weightDecay);
// calculate price deviation
uint deviation = _thresholdedAbsDeviationRatio(prices[i - 1], prices[i], threshold);
// add to total fee
dynamicFee = dynamicFee.add(deviation);
}
return dynamicFee;
}
/// absolute price deviation ratio used by dynamic fee calculation
/// deviationRatio = (abs(current - previous) / previous) - threshold
/// if negative, zero is returned
function _thresholdedAbsDeviationRatio(
uint price,
uint previousPrice,
uint threshold
) internal pure returns (uint) {
if (previousPrice == 0) {
return 0; // don't divide by zero
}
// abs difference between prices
uint absDelta = price > previousPrice ? price - previousPrice : previousPrice - price;
// relative to previous price
uint deviationRatio = absDelta.divideDecimal(previousPrice);
// only the positive difference from threshold
return deviationRatio > threshold ? deviationRatio - threshold : 0;
}
function getAmountsForExchange(
uint sourceAmount,
bytes32 sourceCurrencyKey,
bytes32 destinationCurrencyKey
)
external
view
returns (
uint amountReceived,
uint fee,
uint exchangeFeeRate
)
{
require(sourceCurrencyKey == sUSD || !exchangeRates().rateIsInvalid(sourceCurrencyKey), "src synth rate invalid");
require(
destinationCurrencyKey == sUSD || !exchangeRates().rateIsInvalid(destinationCurrencyKey),
"dest synth rate invalid"
);
// The checks are added for consistency with the checks performed in _exchange()
// The reverts (instead of no-op returns) are used order to prevent incorrect usage in calling contracts
// (The no-op in _exchange() is in order to trigger system suspension if needed)
// check synths active
systemStatus().requireSynthActive(sourceCurrencyKey);
systemStatus().requireSynthActive(destinationCurrencyKey);
bool tooVolatile;
(exchangeFeeRate, tooVolatile) = _feeRateForExchange(sourceCurrencyKey, destinationCurrencyKey);
// check rates volatility result
require(!tooVolatile, "exchange rates too volatile");
(uint destinationAmount, , ) =
exchangeRates().effectiveValueAndRates(sourceCurrencyKey, sourceAmount, destinationCurrencyKey);
amountReceived = _deductFeesFromAmount(destinationAmount, exchangeFeeRate);
fee = destinationAmount.sub(amountReceived);
}
function _deductFeesFromAmount(uint destinationAmount, uint exchangeFeeRate)
internal
pure
returns (uint amountReceived)
{
amountReceived = destinationAmount.multiplyDecimal(SafeDecimalMath.unit().sub(exchangeFeeRate));
}
function appendExchange(
address account,
bytes32 src,
uint amount,
bytes32 dest,
uint amountReceived,
uint exchangeFeeRate
) internal {
IExchangeRates exRates = exchangeRates();
uint roundIdForSrc = exRates.getCurrentRoundId(src);
uint roundIdForDest = exRates.getCurrentRoundId(dest);
exchangeState().appendExchangeEntry(
account,
src,
amount,
dest,
amountReceived,
exchangeFeeRate,
now,
roundIdForSrc,
roundIdForDest
);
emit ExchangeEntryAppended(
account,
src,
amount,
dest,
amountReceived,
exchangeFeeRate,
roundIdForSrc,
roundIdForDest
);
}
function getRoundIdsAtPeriodEnd(IExchangeState.ExchangeEntry memory exchangeEntry)
internal
view
returns (uint srcRoundIdAtPeriodEnd, uint destRoundIdAtPeriodEnd)
{
IExchangeRates exRates = exchangeRates();