/
ExchangeRates.sol
581 lines (488 loc) · 20.2 KB
/
ExchangeRates.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
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: ExchangeRates.sol
version: 1.0
author: Kevin Brown
date: 2018-09-12
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
A contract that any other contract in the Synthetix system can query
for the current market value of various assets, including
crypto assets as well as various fiat assets.
This contract assumes that rate updates will completely update
all rates to their current values. If a rate shock happens
on a single asset, the oracle will still push updated rates
for all other assets.
-----------------------------------------------------------------
*/
pragma solidity 0.4.25;
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "./SafeDecimalMath.sol";
import "./SelfDestructible.sol";
import "chainlink/solidity/contracts/Chainlinked.sol"; // technically this is all we need
/**
* @title The repository for exchange rates
*/
contract ExchangeRates is Chainlinked, SelfDestructible {
using SafeMath for uint;
using SafeDecimalMath for uint;
// Exchange rates stored by currency code, e.g. 'SNX', or 'sUSD'
mapping(bytes4 => uint) public rates;
// Update times stored by currency code, e.g. 'SNX', or 'sUSD'
mapping(bytes4 => uint) public lastRateUpdateTimes;
// The address of the SNX oracle which pushes rate updates to this contract
address public snxOracle;
// Do not allow the oracle to submit times any further forward into the future than this constant.
uint constant ORACLE_FUTURE_LIMIT = 10 minutes;
// How long will the contract assume the rate of any asset is correct
uint public rateStalePeriod = 3 hours;
// Each participating currency in the XDR basket is represented as a currency key with
// equal weighting.
// There are 5 participating currencies, so we'll declare that clearly.
bytes4[5] public xdrParticipants;
// -----------------
// Chainlink properties
struct Request {
uint256 timestamp;
bytes4 currencyKey;
}
bytes32 public oracleJobId;
uint256 constant private ORACLE_PAYMENT = 1 * LINK; // solium-disable-line zeppelin/no-arithmetic-operations
mapping(bytes32 => Request) private requests;
uint256 constant ORACLE_PRECISION = 1000000000000000000;
// ------------------
// For inverted prices, keep a mapping of their entry, limits and frozen status
struct InversePricing {
uint entryPoint;
uint upperLimit;
uint lowerLimit;
bool frozen;
}
mapping(bytes4 => InversePricing) public inversePricing;
bytes4[] public invertedKeys;
//
// ========== CONSTRUCTOR ==========
/**
* @dev Constructor
* @param _owner The owner of this contract.
* @param _snxOracle The address which is able to update rate information.
* @param _currencyKeys The initial currency keys to store (in order).
* @param _newRates The initial currency amounts for each currency (in order).
*/
constructor(
// SelfDestructible (Ownable)
address _owner,
// Oracle values - Allows for rate updates
address _snxOracle,
bytes4[] _currencyKeys,
uint[] _newRates,
// Chainlink requirementss
address _chainlinkToken,
address _chainlinkOracle,
bytes32 _chainlinkJobId
)
/* Owned is initialised in SelfDestructible */
SelfDestructible(_owner)
public
{
require(_currencyKeys.length == _newRates.length, "Currency key length and rate length must match.");
snxOracle = _snxOracle;
// The sUSD rate is always 1 and is never stale.
rates["sUSD"] = SafeDecimalMath.unit();
lastRateUpdateTimes["sUSD"] = now;
// These are the currencies that make up the XDR basket.
// These are hard coded because:
// - This way users can depend on the calculation and know it won't change for this deployment of the contract.
// - Adding new currencies would likely introduce some kind of weighting factor, which
// isn't worth preemptively adding when all of the currencies in the current basket are weighted at 1.
// - The expectation is if this logic needs to be updated, we'll simply deploy a new version of this contract
// then point the system at the new version.
xdrParticipants = [
bytes4("sUSD"),
bytes4("sAUD"),
bytes4("sCHF"),
bytes4("sEUR"),
bytes4("sGBP")
];
internalUpdateRates(_currencyKeys, _newRates, now);
// Setup Chainlink props
setLinkToken(_chainlinkToken);
setOracle(_chainlinkOracle);
oracleJobId = _chainlinkJobId;
}
/* ========== SETTERS ========== */
/**
* @notice Set the rates stored in this contract
* @param currencyKeys The currency keys you wish to update the rates for (in order)
* @param newRates The rates for each currency (in order)
* @param timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity).contract
* This is useful because transactions can take a while to confirm, so this way we know how old the oracle's datapoint was exactly even
* if it takes a long time for the transaction to confirm.
*/
function updateRates(bytes4[] currencyKeys, uint[] newRates, uint timeSent)
external
onlySNXOracle
returns(bool)
{
return internalUpdateRates(currencyKeys, newRates, timeSent);
}
/**
* @notice Internal function which sets the rates stored in this contract
* @param currencyKeys The currency keys you wish to update the rates for (in order)
* @param newRates The rates for each currency (in order)
* @param timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity).contract
* This is useful because transactions can take a while to confirm, so this way we know how old the oracle's datapoint was exactly even
* if it takes a long time for the transaction to confirm.
*/
function internalUpdateRates(bytes4[] currencyKeys, uint[] newRates, uint timeSent)
internal
returns(bool)
{
require(currencyKeys.length == newRates.length, "Currency key array length must match rates array length.");
require(timeSent < (now + ORACLE_FUTURE_LIMIT), "Time is too far into the future");
// Loop through each key and perform update.
for (uint i = 0; i < currencyKeys.length; i++) {
// Should not set any rate to zero ever, as no asset will ever be
// truely worthless and still valid. In this scenario, we should
// delete the rate and remove it from the system.
require(newRates[i] != 0, "Zero is not a valid rate, please call deleteRate instead.");
require(currencyKeys[i] != "sUSD", "Rate of sUSD cannot be updated, it's always UNIT.");
// We should only update the rate if it's at least the same age as the last rate we've got.
if (timeSent < lastRateUpdateTimes[currencyKeys[i]]) {
continue;
}
newRates[i] = rateOrInverted(currencyKeys[i], newRates[i]);
// Ok, go ahead with the update.
rates[currencyKeys[i]] = newRates[i];
lastRateUpdateTimes[currencyKeys[i]] = timeSent;
}
emit RatesUpdated(currencyKeys, newRates);
// Now update our XDR rate.
updateXDRRate(timeSent);
return true;
}
/**
* @notice Internal function to get the inverted rate, if any, and mark an inverted
* key as frozen if either limits are reached.
* @param currencyKey The price key to lookup
* @param rate The rate for the given price key
*/
function rateOrInverted(bytes4 currencyKey, uint rate) internal returns (uint) {
// if an inverse mapping exists, adjust the price accordingly
InversePricing storage inverse = inversePricing[currencyKey];
if (inverse.entryPoint <= 0) {
return rate;
}
// set the rate to the current rate initially (if it's frozen, this is what will be returned)
uint newInverseRate = rates[currencyKey];
// get the new inverted rate if not frozen
if (!inverse.frozen) {
uint doubleEntryPoint = inverse.entryPoint.mul(2);
if (doubleEntryPoint <= rate) {
// avoid negative numbers for unsigned ints, so set this to 0
// which by the requirement that lowerLimit be > 0 will
// cause this to freeze the price to the lowerLimit
newInverseRate = 0;
} else {
newInverseRate = doubleEntryPoint.sub(rate);
}
// now if new rate hits our limits, set it to the limit and freeze
if (newInverseRate >= inverse.upperLimit) {
newInverseRate = inverse.upperLimit;
} else if (newInverseRate <= inverse.lowerLimit) {
newInverseRate = inverse.lowerLimit;
}
if (newInverseRate == inverse.upperLimit || newInverseRate == inverse.lowerLimit) {
inverse.frozen = true;
emit InversePriceFrozen(currencyKey);
}
}
return newInverseRate;
}
/**
* @notice Update the Synthetix Drawing Rights exchange rate based on other rates already updated.
*/
function updateXDRRate(uint timeSent)
internal
{
uint total = 0;
for (uint i = 0; i < xdrParticipants.length; i++) {
total = rates[xdrParticipants[i]].add(total);
}
// Set the rate
rates["XDR"] = total;
// Record that we updated the XDR rate.
lastRateUpdateTimes["XDR"] = timeSent;
// Emit our updated event separate to the others to save
// moving data around between arrays.
bytes4[] memory eventCurrencyCode = new bytes4[](1);
eventCurrencyCode[0] = "XDR";
uint[] memory eventRate = new uint[](1);
eventRate[0] = rates["XDR"];
emit RatesUpdated(eventCurrencyCode, eventRate);
}
/**
* @notice Delete a rate stored in the contract
* @param currencyKey The currency key you wish to delete the rate for
*/
function deleteRate(bytes4 currencyKey)
external
onlySNXOracle
{
require(rates[currencyKey] > 0, "Rate is zero");
delete rates[currencyKey];
delete lastRateUpdateTimes[currencyKey];
emit RateDeleted(currencyKey);
}
/**
* @notice Set the Oracle that pushes the rate information to this contract
* @param _snxOracle The new oracle address
*/
function setSNXOracle(address _snxOracle)
external
onlyOwner
{
snxOracle = _snxOracle;
emit OracleUpdated(snxOracle);
}
/**
* @notice Set the stale period on the updated rate variables
* @param _time The new rateStalePeriod
*/
function setRateStalePeriod(uint _time)
external
onlyOwner
{
rateStalePeriod = _time;
emit RateStalePeriodUpdated(rateStalePeriod);
}
/**
* @notice Set an inverse price up for the currency key
* @param currencyKey The currency to update
* @param entryPoint The entry price point of the inverted price
* @param upperLimit The upper limit, at or above which the price will be frozen
* @param lowerLimit The lower limit, at or below which the price will be frozen
*/
function setInversePricing(bytes4 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit)
external onlyOwner
{
require(entryPoint > 0, "entryPoint must be above 0");
require(lowerLimit > 0, "lowerLimit must be above 0");
require(upperLimit > entryPoint, "upperLimit must be above the entryPoint");
require(upperLimit < entryPoint.mul(2), "upperLimit must be less than double entryPoint");
require(lowerLimit < entryPoint, "lowerLimit must be below the entryPoint");
if (inversePricing[currencyKey].entryPoint <= 0) {
// then we are adding a new inverse pricing, so add this
invertedKeys.push(currencyKey);
}
inversePricing[currencyKey].entryPoint = entryPoint;
inversePricing[currencyKey].upperLimit = upperLimit;
inversePricing[currencyKey].lowerLimit = lowerLimit;
inversePricing[currencyKey].frozen = false;
emit InversePriceConfigured(currencyKey, entryPoint, upperLimit, lowerLimit);
}
/**
* @notice Remove an inverse price for the currency key
* @param currencyKey The currency to remove inverse pricing for
*/
function removeInversePricing(bytes4 currencyKey) external onlyOwner {
inversePricing[currencyKey].entryPoint = 0;
inversePricing[currencyKey].upperLimit = 0;
inversePricing[currencyKey].lowerLimit = 0;
inversePricing[currencyKey].frozen = false;
// now remove inverted key from array
for (uint8 i = 0; i < invertedKeys.length; i++) {
if (invertedKeys[i] == currencyKey) {
delete invertedKeys[i];
// Copy the last key into the place of the one we just deleted
// If there's only one key, this is array[0] = array[0].
// If we're deleting the last one, it's also a NOOP in the same way.
invertedKeys[i] = invertedKeys[invertedKeys.length - 1];
// Decrease the size of the array by one.
invertedKeys.length--;
break;
}
}
emit InversePriceConfigured(currencyKey, 0, 0, 0);
}
/* ========== VIEWS ========== */
/**
* @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency
* @param sourceCurrencyKey The currency the amount is specified in
* @param sourceAmount The source amount, specified in UNIT base
* @param destinationCurrencyKey The destination currency
*/
function effectiveValue(bytes4 sourceCurrencyKey, uint sourceAmount, bytes4 destinationCurrencyKey)
public
view
rateNotStale(sourceCurrencyKey)
rateNotStale(destinationCurrencyKey)
returns (uint)
{
// If there's no change in the currency, then just return the amount they gave us
if (sourceCurrencyKey == destinationCurrencyKey) return sourceAmount;
// Calculate the effective value by going from source -> USD -> destination
return sourceAmount.multiplyDecimalRound(rateForCurrency(sourceCurrencyKey))
.divideDecimalRound(rateForCurrency(destinationCurrencyKey));
}
/**
* @notice Retrieve the rate for a specific currency
*/
function rateForCurrency(bytes4 currencyKey)
public
view
returns (uint)
{
return rates[currencyKey];
}
/**
* @notice Retrieve the rates for a list of currencies
*/
function ratesForCurrencies(bytes4[] currencyKeys)
public
view
returns (uint[])
{
uint[] memory _rates = new uint[](currencyKeys.length);
for (uint8 i = 0; i < currencyKeys.length; i++) {
_rates[i] = rates[currencyKeys[i]];
}
return _rates;
}
/**
* @notice Retrieve a list of last update times for specific currencies
*/
function lastRateUpdateTimeForCurrency(bytes4 currencyKey)
public
view
returns (uint)
{
return lastRateUpdateTimes[currencyKey];
}
/**
* @notice Retrieve the last update time for a specific currency
*/
function lastRateUpdateTimesForCurrencies(bytes4[] currencyKeys)
public
view
returns (uint[])
{
uint[] memory lastUpdateTimes = new uint[](currencyKeys.length);
for (uint8 i = 0; i < currencyKeys.length; i++) {
lastUpdateTimes[i] = lastRateUpdateTimes[currencyKeys[i]];
}
return lastUpdateTimes;
}
/**
* @notice Check if a specific currency's rate hasn't been updated for longer than the stale period.
*/
function rateIsStale(bytes4 currencyKey)
public
view
returns (bool)
{
// sUSD is a special case and is never stale.
if (currencyKey == "sUSD") return false;
return lastRateUpdateTimes[currencyKey].add(rateStalePeriod) < now;
}
/**
* @notice Check if any rate is frozen (cannot be exchanged into)
*/
function rateIsFrozen(bytes4 currencyKey)
external
view
returns (bool)
{
return inversePricing[currencyKey].frozen;
}
/**
* @notice Check if any of the currency rates passed in haven't been updated for longer than the stale period.
*/
function anyRateIsStale(bytes4[] currencyKeys)
external
view
returns (bool)
{
// Loop through each key and check whether the data point is stale.
uint256 i = 0;
while (i < currencyKeys.length) {
// sUSD is a special case and is never false
if (currencyKeys[i] != "sUSD" && lastRateUpdateTimes[currencyKeys[i]].add(rateStalePeriod) < now) {
return true;
}
i += 1;
}
return false;
}
// CHAINLINK ///
/**
* @notice Initiatiate a price request via chainlink. Provide both the
* bytes4 currencyKey (for SNX) and the string representation (for Chainlink)
*/
function requestCryptoPrice(bytes4 currencyKey, string asset)
public
onlyOwner
{
Chainlink.Request memory req = newRequest(oracleJobId, this, this.fulfill.selector);
req.add("sym", asset);
req.add("convert", "USD");
string[] memory path = new string[](5);
path[0] = "data";
path[1] = asset;
path[2] = "quote";
path[3] = "USD";
path[4] = "price";
req.addStringArray("copyPath", path);
req.addInt("times", int256(ORACLE_PRECISION));
requests[chainlinkRequest(req, ORACLE_PAYMENT)] = Request(now, currencyKey);
}
function fulfill(bytes32 _requestId, uint256 _price)
public
validateTimestamp(_requestId)
recordChainlinkFulfillment(_requestId)
{
bytes4 currencyKey = requests[_requestId].currencyKey;
uint timestamp = requests[_requestId].timestamp;
bytes4[] memory ccy = new bytes4[](1);
ccy[0] = currencyKey;
uint[] memory newRates = new uint[](1);
newRates[0] = _price;
internalUpdateRates(ccy, newRates, timestamp);
delete requests[_requestId];
}
function getChainlinkToken() public view returns (address) {
return chainlinkToken();
}
function getOracle() public view returns (address) {
return oracleAddress();
}
function withdrawLink() public onlyOwner {
LinkTokenInterface link = LinkTokenInterface(chainlinkToken());
require(link.transfer(msg.sender, link.balanceOf(address(this))), "Unable to transfer");
}
modifier validateTimestamp(bytes32 _requestId) {
require(requests[_requestId].timestamp > now - ORACLE_FUTURE_LIMIT, "Request has expired");
_;
}
////////////
/* ========== MODIFIERS ========== */
modifier rateNotStale(bytes4 currencyKey) {
require(!rateIsStale(currencyKey), "Rate stale or nonexistant currency");
_;
}
modifier onlySNXOracle
{
require(msg.sender == snxOracle, "Only the oracle can perform this action");
_;
}
/* ========== EVENTS ========== */
event OracleUpdated(address newOracle);
event RateStalePeriodUpdated(uint rateStalePeriod);
event RatesUpdated(bytes4[] currencyKeys, uint[] newRates);
event RateDeleted(bytes4 currencyKey);
event InversePriceConfigured(bytes4 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit);
event InversePriceFrozen(bytes4 currencyKey);
}