-
Notifications
You must be signed in to change notification settings - Fork 6
/
OptinoFactory.sol
1392 lines (1293 loc) · 64.3 KB
/
OptinoFactory.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.6.8;
// ----------------------------------------------------------------------------
// ____ _ _ ______ _
// / __ \ | | (_) | ____| | |
// | | | |_ __ | |_ _ _ __ ___tm | |__ __ _ ___| |_ ___ _ __ _ _
// | | | | '_ \| __| | '_ \ / _ \ | __/ _` |/ __| __/ _ \| '__| | | |
// | |__| | |_) | |_| | | | | (_) | | | | (_| | (__| || (_) | | | |_| |
// \____/| .__/ \__|_|_| |_|\___/ |_| \__,_|\___|\__\___/|_| \__, |
// | | __/ |
// |_| |___/
//
// Optino Factory v0.992-testnet-pre-release
//
// Status: Work in progress. To test, optimise and review
//
// A factory to conveniently deploy your own source code verified ERC20 vanilla
// european optinos and the associated collateral optinos
//
// OptinoToken deployment on Ropsten: 0x1a00323741D7E6Dc0461909a8c7900C0c5680B21
// OptinoFactory deployment on Ropsten: 0xe607dd1f70d79312575e3A350F1193EA9a89CB8e
//
// Web UI at https://bokkypoobah.github.io/OptinoExplorer,
// Later at https://optino.xyz, https://optino.eth and https://optino.eth.link
//
// https://github.com/bokkypoobah/Optino
//
// NOTE: If you deploy this contract, or derivatives of this contract, please
// forward 50% of the fees you earn from this code or derivatives of it to
// bokkypoobah.eth
//
// SPDX-License-Identifier: MIT
//
// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2020. The MIT Licence.
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
/// @notice BokkyPooBah's DateTime Library v1.01 - only the necessary snippets
//
// A gas-efficient Solidity date and time library
//
// https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary
//
// Tested date range 1970/01/01 to 2345/12/31
//
// Conventions:
// Unit | Range | Notes
// :-------- |:-------------:|:-----
// timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC
// year | 1970 ... 2345 |
// month | 1 ... 12 |
// day | 1 ... 31 |
// hour | 0 ... 23 |
// minute | 0 ... 59 |
// second | 0 ... 59 |
// dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday
//
//
// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence.
// ----------------------------------------------------------------------------
library BokkyPooBahsDateTimeLibrary {
uint constant SECONDS_PER_DAY = 24 * 60 * 60;
uint constant SECONDS_PER_HOUR = 60 * 60;
uint constant SECONDS_PER_MINUTE = 60;
int constant OFFSET19700101 = 2440588;
// ------------------------------------------------------------------------
// Calculate year/month/day from the number of days since 1970/01/01 using
// the date conversion algorithm from
// http://aa.usno.navy.mil/faq/docs/JD_Formula.php
// and adding the offset 2440588 so that 1970/01/01 is day 0
//
// int L = days + 68569 + offset
// int N = 4 * L / 146097
// L = L - (146097 * N + 3) / 4
// year = 4000 * (L + 1) / 1461001
// L = L - 1461 * year / 4 + 31
// month = 80 * L / 2447
// dd = L - 2447 * month / 80
// L = month / 11
// month = month + 2 - 12 * L
// year = 100 * (N - 49) + year + L
// ------------------------------------------------------------------------
function daysToDate(uint _days) internal pure returns (uint year, uint month, uint day) {
int __days = int(_days);
int L = __days + 68569 + OFFSET19700101;
int N = 4 * L / 146097;
L = L - (146097 * N + 3) / 4;
int _year = 4000 * (L + 1) / 1461001;
L = L - 1461 * _year / 4 + 31;
int _month = 80 * L / 2447;
int _day = L - 2447 * _month / 80;
L = _month / 11;
_month = _month + 2 - 12 * L;
_year = 100 * (N - 49) + _year + L;
year = uint(_year);
month = uint(_month);
day = uint(_day);
}
function timestampToDateTime(uint timestamp) internal pure returns (uint year, uint month, uint day, uint hour, uint minute, uint second) {
(year, month, day) = daysToDate(timestamp / SECONDS_PER_DAY);
uint secs = timestamp % SECONDS_PER_DAY;
hour = secs / SECONDS_PER_HOUR;
secs = secs % SECONDS_PER_HOUR;
minute = secs / SECONDS_PER_MINUTE;
second = secs % SECONDS_PER_MINUTE;
}
}
// End BokkyPooBah's DateTime Library v1.01 - only the necessary snippets
/// @notice https://github.com/optionality/clone-factory/blob/32782f82dfc5a00d103a7e61a17a5dedbd1e8e9d/contracts/CloneFactory.sol
/*
The MIT License (MIT)
Copyright (c) 2018 Murray Software, LLC.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
//solhint-disable max-line-length
//solhint-disable no-inline-assembly
contract CloneFactory {
function createClone(address target) internal returns (address result) {
bytes20 targetBytes = bytes20(target);
assembly {
let clone := mload(0x40)
mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(clone, 0x14), targetBytes)
mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
result := create(0, clone, 0x37)
}
}
function isClone(address target, address query) internal view returns (bool result) {
bytes20 targetBytes = bytes20(target);
assembly {
let clone := mload(0x40)
mstore(clone, 0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000)
mstore(add(clone, 0xa), targetBytes)
mstore(add(clone, 0x1e), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
let other := add(clone, 0x40)
extcodecopy(query, other, 0, 0x2d)
result := and(
eq(mload(clone), mload(other)),
eq(mload(add(clone, 0xd)), mload(add(other, 0xd)))
)
}
}
}
// End CloneFactory.sol
contract DataType {
enum FeedDataField { Type, Decimals, Locked }
enum FeedParametersField { Type0, Type1, Decimals0, Decimals1, Inverse0, Inverse1 }
enum SeriesDataField { CallPut, Expiry, Strike, Bound, Spot }
enum InputDataField { CallPut, Expiry, Strike, Bound, Tokens }
struct Feed {
uint timestamp;
uint index;
address feed;
string[2] text; // [name, note]
uint8[3] data; // FeedDataField: [type, decimals, locked]
}
struct Series {
uint timestamp;
uint index;
bytes32 key;
ERC20[2] pair; // [token0, token1]
address[2] feeds; // [feed0, feed1]
uint8[6] feedParameters; // FeedParametersField: [type0, type1, decimals0, decimals1, inverse0, inverse1]
uint[5] data; // SeriesDataField: [callPut, expiry, strike, bound, spot]
OptinoToken[2] optinos; // optino and cover
}
struct InputData {
ERC20[2] pair; // [token0, token1]
address[2] feeds; // [feed0, feed1]
uint8[6] feedParameters; // FeedParametersField: [type0, type1, decimals0, decimals1, inverse0, inverse1]
uint[5] data; // InputDataField: [callPut, expiry, strike, bound, tokens]
}
uint8 immutable FEEDPARAMETERS_DEFAULT = uint8(0xff);
}
/// @notice Name utils
contract NameUtils is DataType {
// TODO: Remove 'z' before deployment to reduce symbol space pollution
bytes constant OPTINOSYMBOL = "zOPT";
bytes constant COVERSYMBOL = "zCOV";
bytes constant VANILLACALLNAME = "Vanilla Call";
bytes constant VANILLAPUTNAME = "Vanilla Put";
bytes constant CAPPEDCALLNAME = "Capped Call";
bytes constant FLOOREDPUTNAME = "Floored Put";
bytes constant OPTINO = "Optino";
bytes constant COVERNAME = "Cover";
bytes constant CUSTOMFEED = "CustomFeed";
bytes constant INVERSESTART = "Inv(";
uint8 constant INVERSEEND = 41; // ")"
uint8 constant SPACE = 32;
uint8 constant MULTIPLY = 42;
uint8 constant DIVIDE = 246;
uint8 constant DASH = 45;
uint8 constant DOT = 46;
uint8 constant SLASH = 47;
uint8 constant ZERO = 48;
uint8 constant COLON = 58;
uint8 constant CHAR_T = 84;
uint8 constant CHAR_Z = 90;
uint constant MAXSYMBOLLENGTH = 8;
uint constant MAXFEEDLENGTH = 24;
function numToBytes(uint number, uint8 decimals) internal pure returns (bytes memory b, uint _length) {
uint i;
uint j;
uint result;
b = new bytes(40);
if (number == 0) {
b[j++] = byte(ZERO);
} else {
i = decimals + 18;
do {
uint num = number / 10 ** i;
result = result * 10 + num % 10;
if (result > 0) {
b[j++] = byte(uint8(num % 10 + ZERO));
if ((j > 1) && (number == num * 10 ** i) && (i <= decimals)) {
break;
}
} else {
if (i == decimals) {
b[j++] = byte(ZERO);
b[j++] = byte(DOT);
}
if (i < decimals) {
b[j++] = byte(ZERO);
}
}
if (decimals != 0 && decimals == i && result > 0 && i > 0) {
b[j++] = byte(DOT);
}
i--;
} while (i >= 0);
}
return (b, j);
}
function dateTimeToBytes(uint timestamp) internal pure returns (bytes memory b) {
(uint year, uint month, uint day, uint hour, uint min, uint sec) = BokkyPooBahsDateTimeLibrary.timestampToDateTime(timestamp);
b = new bytes(20);
uint i;
uint j;
uint num;
i = 4;
do {
i--;
num = year / 10 ** i;
b[j++] = byte(uint8(num % 10 + ZERO));
} while (i > 0);
b[j++] = byte(DASH);
i = 2;
do {
i--;
num = month / 10 ** i;
b[j++] = byte(uint8(num % 10 + ZERO));
} while (i > 0);
b[j++] = byte(DASH);
i = 2;
do {
i--;
num = day / 10 ** i;
b[j++] = byte(uint8(num % 10 + ZERO));
} while (i > 0);
b[j++] = byte(CHAR_T);
i = 2;
do {
i--;
num = hour / 10 ** i;
b[j++] = byte(uint8(num % 10 + ZERO));
} while (i > 0);
b[j++] = byte(COLON);
i = 2;
do {
i--;
num = min / 10 ** i;
b[j++] = byte(uint8(num % 10 + ZERO));
} while (i > 0);
b[j++] = byte(COLON);
i = 2;
do {
i--;
num = sec / 10 ** i;
b[j++] = byte(uint8(num % 10 + ZERO));
} while (i > 0);
b[j++] = byte(CHAR_Z);
}
function toSymbol(bool cover, uint id) internal pure returns (string memory s) {
bytes memory b = new bytes(20);
uint i;
uint j;
uint num;
if (cover) {
for (i = 0; i < COVERSYMBOL.length; i++) {
b[j++] = COVERSYMBOL[i];
}
} else {
for (i = 0; i < OPTINOSYMBOL.length; i++) {
b[j++] = OPTINOSYMBOL[i];
}
}
i = 7;
do {
i--;
num = id / 10 ** i;
b[j++] = byte(uint8(num % 10 + ZERO));
} while (i > 0);
s = string(b);
}
function pairSymbolToBytes(ERC20[2] memory pair) internal view returns (bytes memory b, uint _length) {
uint i;
uint j;
b = new bytes(40);
bytes memory b1 = bytes(pair[0].symbol());
for (i = 0; i < b1.length && i < MAXSYMBOLLENGTH; i++) {
b[j++] = b1[i];
}
b[j++] = byte(SLASH);
b1 = bytes(pair[1].symbol());
for (i = 0; i < b1.length && i < MAXSYMBOLLENGTH; i++) {
b[j++] = b1[i];
}
return (b, j);
}
function feedToBytes(OptinoFactory factory, address[2] memory feeds, uint8[6] memory feedParameters) internal view returns (bytes memory b, uint _length) {
uint i;
uint j;
b = new bytes(80);
bytes memory b1;
(bool isRegistered, string memory feedName, uint8 feedType, uint8 decimals) = factory.getFeedData(feeds[0]);
if (isRegistered &&
(feedParameters[uint(FeedParametersField.Type0)] == FEEDPARAMETERS_DEFAULT || feedParameters[uint(FeedParametersField.Type0)] == feedType) &&
(feedParameters[uint(FeedParametersField.Decimals0)] == FEEDPARAMETERS_DEFAULT || feedParameters[uint(FeedParametersField.Decimals0)] == decimals)) {
if (feedParameters[uint(FeedParametersField.Inverse0)] != 0) {
for (i = 0; i < INVERSESTART.length; i++) {
b[j++] = INVERSESTART[i];
}
}
b1 = bytes(feedName);
for (i = 0; i < b1.length && i < MAXFEEDLENGTH; i++) {
b[j++] = b1[i];
}
if (feedParameters[uint(FeedParametersField.Inverse0)] != 0) {
b[j++] = byte(INVERSEEND);
}
} else {
for (i = 0; i < CUSTOMFEED.length; i++) {
b[j++] = CUSTOMFEED[i];
}
}
if (feeds[1] != address(0)) {
(isRegistered, feedName, feedType, decimals) = factory.getFeedData(feeds[1]);
b[j++] = byte(MULTIPLY);
if (isRegistered &&
(feedParameters[uint(FeedParametersField.Type1)] == FEEDPARAMETERS_DEFAULT || feedParameters[uint(FeedParametersField.Type1)] == feedType) &&
(feedParameters[uint(FeedParametersField.Decimals1)] == FEEDPARAMETERS_DEFAULT || feedParameters[uint(FeedParametersField.Decimals1)] == decimals)) {
if (feedParameters[uint(FeedParametersField.Inverse1)] != 0) {
for (i = 0; i < INVERSESTART.length; i++) {
b[j++] = INVERSESTART[i];
}
} else {
}
b1 = bytes(feedName);
for (i = 0; i < b1.length && i < MAXFEEDLENGTH; i++) {
b[j++] = b1[i];
}
if (feedParameters[uint(FeedParametersField.Inverse1)] != 0) {
b[j++] = byte(INVERSEEND);
}
} else {
for (i = 0; i < CUSTOMFEED.length; i++) {
b[j++] = CUSTOMFEED[i];
}
}
}
return (b, j);
}
function toName(OptinoFactory factory, bytes32 seriesKey, bool cover) internal view returns (string memory s) {
(/*uint seriesIndex*/, ERC20[2] memory pair, address[2] memory feeds, uint8[6] memory feedParameters, uint[5] memory data, /*_optinos*/) = factory.getSeriesByKey(seriesKey);
uint8 feedDecimals0 = factory.getFeedDecimals0(seriesKey);
bytes memory b = new bytes(256);
uint i;
uint j;
if (data[uint(SeriesDataField.Bound)] == 0) {
if (data[uint(SeriesDataField.CallPut)] == 0) {
for (i = 0; i < VANILLACALLNAME.length; i++) {
b[j++] = VANILLACALLNAME[i];
}
} else {
for (i = 0; i < VANILLAPUTNAME.length; i++) {
b[j++] = VANILLAPUTNAME[i];
}
}
} else {
if (data[uint(SeriesDataField.CallPut)] == 0) {
for (i = 0; i < CAPPEDCALLNAME.length; i++) {
b[j++] = CAPPEDCALLNAME[i];
}
} else {
for (i = 0; i < FLOOREDPUTNAME.length; i++) {
b[j++] = FLOOREDPUTNAME[i];
}
}
}
b[j++] = byte(SPACE);
if (cover) {
for (i = 0; i < COVERNAME.length; i++) {
b[j++] = COVERNAME[i];
}
} else {
for (i = 0; i < OPTINO.length; i++) {
b[j++] = OPTINO[i];
}
}
b[j++] = byte(SPACE);
bytes memory b1;
uint l1;
(b1, l1) = pairSymbolToBytes(pair);
for (i = 0; i < b1.length && i < l1; i++) {
b[j++] = b1[i];
}
b[j++] = byte(SPACE);
b1 = dateTimeToBytes(data[uint(SeriesDataField.Expiry)]);
for (i = 0; i < b1.length; i++) {
b[j++] = b1[i];
}
b[j++] = byte(SPACE);
if (data[uint(SeriesDataField.CallPut)] != 0 && data[uint(SeriesDataField.Bound)] != 0) {
(b1, l1) = numToBytes(data[uint(SeriesDataField.Bound)], feedDecimals0);
for (i = 0; i < b1.length && i < l1; i++) {
b[j++] = b1[i];
}
b[j++] = byte(DASH);
}
(b1, l1) = numToBytes(data[uint(SeriesDataField.Strike)], feedDecimals0);
for (i = 0; i < b1.length && i < l1; i++) {
b[j++] = b1[i];
}
if (data[uint(SeriesDataField.CallPut)] == 0 && data[uint(SeriesDataField.Bound)] != 0) {
b[j++] = byte(DASH);
(b1, l1) = numToBytes(data[uint(SeriesDataField.Bound)], feedDecimals0);
for (i = 0; i < b1.length && i < l1; i++) {
b[j++] = b1[i];
}
}
b[j++] = byte(SPACE);
(b1, l1) = feedToBytes(factory, feeds, feedParameters);
for (i = 0; i < b1.length && i < l1; i++) {
b[j++] = b1[i];
}
return string(b);
}
}
/// @notice Safe maths
library SafeMath {
function add(uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a, "Add overflow");
}
function sub(uint a, uint b) internal pure returns (uint c) {
require(b <= a, "Sub underflow");
c = a - b;
}
function mul(uint a, uint b) internal pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b, "Mul overflow");
}
function div(uint a, uint b) internal pure returns (uint c) {
require(b > 0, "Divide by 0");
c = a / b;
}
}
/// @notice Ownership
contract Owned {
bool initialised;
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
modifier onlyOwner {
require(msg.sender == owner, "Not owner");
_;
}
function initOwned(address _owner) internal {
require(!initialised, "Already initialised");
owner = address(uint160(_owner));
initialised = true;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
/// @notice ERC20 https://eips.ethereum.org/EIPS/eip-20 with optional symbol, name and decimals
interface ERC20 {
function totalSupply() external view returns (uint);
function balanceOf(address tokenOwner) external view returns (uint balance);
function allowance(address tokenOwner, address spender) external view returns (uint remaining);
function transfer(address to, uint tokens) external returns (bool success);
function approve(address spender, uint tokens) external returns (bool success);
function transferFrom(address from, address to, uint tokens) external returns (bool success);
function symbol() external view returns (string memory);
function name() external view returns (string memory);
function decimals() external view returns (uint8);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
/// @notice Basic token = ERC20 + symbol + name + decimals + mint + ownership
contract BasicToken is ERC20, Owned {
using SafeMath for uint;
string _symbol;
string _name;
uint _decimals;
uint _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
function initToken(address tokenOwner, string memory symbol, string memory name, uint decimals) internal {
super.initOwned(tokenOwner);
_symbol = symbol;
_name = name;
_decimals = decimals;
}
function symbol() override external view returns (string memory) {
return _symbol;
}
function name() override external view returns (string memory) {
return _name;
}
function decimals() override external view returns (uint8) {
return uint8(_decimals);
}
function totalSupply() override external view returns (uint) {
return _totalSupply.sub(balances[address(0)]);
}
function balanceOf(address tokenOwner) override external view returns (uint balance) {
return balances[tokenOwner];
}
function transfer(address to, uint tokens) override external returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
function approve(address spender, uint tokens) override external returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens) override external returns (bool success) {
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(from, to, tokens);
return true;
}
function allowance(address tokenOwner, address spender) override external view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function mint(address tokenOwner, uint tokens) external onlyOwner returns (bool success) {
balances[tokenOwner] = balances[tokenOwner].add(tokens);
_totalSupply = _totalSupply.add(tokens);
emit Transfer(address(0), tokenOwner, tokens);
return true;
}
}
/// @notice Vanilla, capped call and floored put options formulae for 100% collateralisation
// ----------------------------------------------------------------------------
// vanillaCallPayoff = max(spot - strike, 0)
// cappedCallPayoff = max(min(spot, cap) - strike, 0)
// = max(spot - strike, 0) - max(spot - cap, 0)
// vanillaPutPayoff = max(strike - spot, 0)
// flooredPutPayoff = max(strike - max(spot, floor), 0)
// = max(strike - spot, 0) - max(floor - spot, 0)
// ----------------------------------------------------------------------------
contract OptinoFormulae is DataType {
using SafeMath for uint;
function shiftRightThenLeft(uint amount, uint8 right, uint8 left) internal pure returns (uint result) {
if (right == left) {
return amount;
} else if (right > left) {
return amount.mul(10 ** uint(right - left));
} else {
return amount.div(10 ** uint(left - right));
}
}
function computeCollateral(uint[5] memory _seriesData, uint tokens, uint8[4] memory decimalsData) internal pure returns (uint collateral) {
(uint callPut, uint strike, uint bound) = (_seriesData[uint(SeriesDataField.CallPut)], _seriesData[uint(SeriesDataField.Strike)], _seriesData[uint(SeriesDataField.Bound)]);
(uint8 decimals, uint8 decimals0, uint8 decimals1, uint8 rateDecimals) = (decimalsData[0], decimalsData[1], decimalsData[2], decimalsData[3]);
require(strike > 0, "strike must be > 0");
if (callPut == 0) {
require(bound == 0 || bound > strike, "Call bound must = 0 or > strike");
if (bound <= strike) {
return shiftRightThenLeft(tokens, decimals0, decimals);
} else {
return shiftRightThenLeft(bound.sub(strike).mul(tokens).div(bound), decimals0, decimals);
}
} else {
require(bound < strike, "Put bound must = 0 or < strike");
return shiftRightThenLeft(strike.sub(bound).mul(tokens), decimals1, decimals).div(10 ** uint(rateDecimals));
}
}
function computePayoff(uint[5] memory _seriesData, uint spot, uint tokens, uint8[4] memory decimalsData) internal pure returns (uint payoff) {
(uint callPut, uint strike, uint bound) = (_seriesData[uint(SeriesDataField.CallPut)], _seriesData[uint(SeriesDataField.Strike)], _seriesData[uint(SeriesDataField.Bound)]);
return _computePayoff(callPut, strike, bound, spot, tokens, decimalsData);
}
function _computePayoff(uint callPut, uint strike, uint bound, uint spot, uint tokens, uint8[4] memory decimalsData) internal pure returns (uint payoff) {
(uint8 decimals, uint8 decimals0, uint8 decimals1, uint8 rateDecimals) = (decimalsData[0], decimalsData[1], decimalsData[2], decimalsData[3]);
require(strike > 0, "strike must be > 0");
if (callPut == 0) {
require(bound == 0 || bound > strike, "Call bound must = 0 or > strike");
if (spot > 0 && spot > strike) {
if (bound > strike && spot > bound) {
return shiftRightThenLeft(bound.sub(strike).mul(tokens), decimals0, decimals).div(spot);
} else {
return shiftRightThenLeft(spot.sub(strike).mul(tokens), decimals0, decimals).div(spot);
}
}
} else {
require(bound < strike, "Put bound must = 0 or < strike");
if (spot < strike) {
if (bound == 0 || (bound > 0 && spot >= bound)) {
return shiftRightThenLeft(strike.sub(spot).mul(tokens), decimals1, decimals + rateDecimals);
} else {
return shiftRightThenLeft(strike.sub(bound).mul(tokens), decimals1, decimals + rateDecimals);
}
}
}
}
}
/// @notice OptinoToken = basic token + burn + payoff + close + settle
contract OptinoToken is BasicToken, OptinoFormulae, NameUtils {
enum BurnType { Close, Settle }
OptinoFactory public factory;
bytes32 public seriesKey;
bool public isCover;
OptinoToken public optinoPair;
ERC20 public collateralToken;
uint public closed;
uint public settled;
event Close(OptinoToken indexed optinoToken, OptinoToken indexed coverToken, address indexed tokenOwner, uint tokens, uint collateralRefund);
event Settle(OptinoToken indexed optinoOrCoverToken, address indexed tokenOwner, uint tokens, uint collateralPayoff);
// event LogInfo(bytes note, address addr, uint number);
function initOptinoToken(OptinoFactory _factory, bytes32 _seriesKey, OptinoToken _optinoPair, bool _isCover, uint _decimals) public {
(factory, seriesKey, optinoPair, isCover) = (_factory, _seriesKey, _optinoPair, _isCover);
(uint seriesIndex, ERC20[2] memory pair, /*feeds*/, /*feedParameters*/, uint[5] memory data, /*_optinos*/) = factory.getSeriesByKey(seriesKey);
collateralToken = data[uint(SeriesDataField.CallPut)] == 0 ? pair[0] : pair[1];
string memory _symbol = toSymbol(isCover, seriesIndex);
string memory _name = toName(_factory, _seriesKey, isCover);
super.initToken(address(factory), _symbol, _name, _decimals);
}
function burn(address tokenOwner, uint tokens, BurnType burnType) external returns (bool success) {
require(msg.sender == tokenOwner || msg.sender == address(optinoPair) || msg.sender == address(this), "Not authorised");
balances[tokenOwner] = balances[tokenOwner].sub(tokens);
_totalSupply = _totalSupply.sub(tokens);
if (burnType == BurnType.Close) {
closed = closed.add(tokens);
} else if (burnType == BurnType.Settle) {
settled = settled.add(tokens);
}
emit Transfer(tokenOwner, address(0), tokens);
return true;
}
function getSeriesData() public view returns (bytes32 _seriesKey, uint _seriesIndex, ERC20[2] memory pair, address[2] memory feeds, uint8[6] memory feedParameters, uint[5] memory data, OptinoToken[2] memory optinos) {
_seriesKey = seriesKey;
(_seriesIndex, pair, feeds, feedParameters, data, optinos) = factory.getSeriesByKey(seriesKey);
}
function getInfo() public view returns (ERC20 token0, ERC20 token1, ERC20 _collateralToken, uint8 collateralDecimals, uint callPut, uint expiry, uint strike, uint bound, bool _isCover, OptinoToken _optinoPair) {
(/*seriesIndex*/, ERC20[2] memory pair, /*feeds*/, /*_feedParameters*/, uint[5] memory data, /*_optinos*/) = factory.getSeriesByKey(seriesKey);
callPut = data[uint(SeriesDataField.CallPut)];
return (pair[0], pair[1], collateralToken, collateralToken.decimals(), data[uint(SeriesDataField.CallPut)], data[uint(SeriesDataField.Expiry)], data[uint(SeriesDataField.Strike)], data[uint(SeriesDataField.Bound)], isCover, optinoPair);
}
function getFeedInfo() public view returns (address feed0, address feed1, uint8 feedType0, uint8 feedType1, uint8 decimals0, uint8 decimals1, uint8 inverse0, uint8 inverse1, uint8 usedFeedDecimals0, uint8 usedFeedType0, uint currentSpot) {
(/*seriesIndex*/, /*pair*/, address[2] memory feeds, uint8[6] memory feedParameters, /*data*/, /*optinos*/) = factory.getSeriesByKey(seriesKey);
(usedFeedDecimals0, usedFeedType0, currentSpot, /*ok*/, /*error*/) = factory.calculateSpot(feeds, feedParameters);
return (feeds[0], feeds[1], feedParameters[0], feedParameters[1], feedParameters[2], feedParameters[3], feedParameters[4], feedParameters[5], usedFeedDecimals0, usedFeedType0, currentSpot);
}
function getPricingInfo() public view returns (uint currentSpot, uint currentPayoff, uint spot, uint payoff, uint collateral) {
uint tokens = 10 ** _decimals;
(uint[5] memory data, uint8[4] memory decimalsData) = factory.getCalcData(seriesKey);
collateral = computeCollateral(data, tokens, decimalsData);
(/*seriesIndex*/, /*pair*/, address[2] memory feeds, uint8[6] memory feedParameters, /*data*/, /*optinos*/) = factory.getSeriesByKey(seriesKey);
(/*_feedDecimals0*/, /*_feedType0*/, currentSpot, /*ok*/, /*error*/) = factory.calculateSpot(feeds, feedParameters);
currentPayoff = computePayoff(data, currentSpot, tokens, decimalsData);
currentPayoff = isCover ? collateral.sub(currentPayoff) : currentPayoff;
spot = factory.getSeriesSpot(seriesKey);
if (spot > 0) {
payoff = computePayoff(data, spot, tokens, decimalsData);
payoff = isCover ? collateral.sub(payoff) : payoff;
}
}
function spot() public view returns (uint _spot) {
_spot = factory.getSeriesSpot(seriesKey);
}
function currentSpot() public view returns (uint _currentSpot) {
address[2] memory feeds;
uint8[6] memory feedParameters;
(/*seriesIndex*/, /*pair*/, feeds, feedParameters, /*data*/, /*optinos*/) = factory.getSeriesByKey(seriesKey);
(/*_feedDecimals0*/, /*_feedType0*/, _currentSpot, /*ok*/, /*error*/) = factory.calculateSpot(feeds, feedParameters);
}
function setSpot() public {
factory.setSeriesSpot(seriesKey);
}
function currentSpotAndPayoff(uint tokens) public view returns (uint _spot, uint currentPayoff) {
(uint[5] memory _seriesData, uint8[4] memory decimalsData) = factory.getCalcData(seriesKey);
address[2] memory feeds;
uint8[6] memory feedParameters;
(/*seriesIndex*/, /*pair*/, feeds, feedParameters, /*data*/, /*optinos*/) = factory.getSeriesByKey(seriesKey);
(/*_feedDecimals0*/, /*_feedType0*/, _spot, /*ok*/, /*error*/) = factory.calculateSpot(feeds, feedParameters);
uint payoff = computePayoff(_seriesData, _spot, tokens, decimalsData);
uint collateral = computeCollateral(_seriesData, tokens, decimalsData);
currentPayoff = isCover ? collateral.sub(payoff) : payoff;
}
function spotAndPayoff(uint tokens) public view returns (uint _spot, uint payoff) {
_spot = factory.getSeriesSpot(seriesKey);
if (_spot > 0) {
(uint[5] memory _seriesData, uint8[4] memory decimalsData) = factory.getCalcData(seriesKey);
payoff = computePayoff(_seriesData, _spot, tokens, decimalsData);
uint collateral = computeCollateral(_seriesData, tokens, decimalsData);
payoff = isCover ? collateral.sub(payoff) : payoff;
}
}
// function payoffForSpot(uint tokens, uint _spot) public view returns (uint payoff) {
// (uint[5] memory _seriesData, uint8[4] memory decimalsData) = factory.getCalcData(seriesKey);
// uint collateral = computeCollateral(_seriesData, tokens, decimalsData);
// payoff = computePayoff(_seriesData, _spot, tokens, decimalsData);
// payoff = isCover ? collateral.sub(payoff) : payoff;
// }
function payoffForSpots(uint tokens, uint[] memory spots) public view returns (uint[] memory payoffs) {
payoffs = new uint[](spots.length);
(uint[5] memory _seriesData, uint8[4] memory decimalsData) = factory.getCalcData(seriesKey);
uint collateral = computeCollateral(_seriesData, tokens, decimalsData);
for (uint i = 0; i < spots.length; i++) {
uint payoff = computePayoff(_seriesData, spots[i], tokens, decimalsData);
payoffs[i] = isCover ? collateral.sub(payoff) : payoff;
}
}
function close(uint tokens) public {
closeFor(msg.sender, tokens);
}
function closeFor(address tokenOwner, uint tokens) public {
require(msg.sender == tokenOwner || msg.sender == address(optinoPair) || msg.sender == address(this), "Not authorised");
if (!isCover) {
optinoPair.closeFor(tokenOwner, tokens);
} else {
require(tokens <= optinoPair.balanceOf(tokenOwner), "Insufficient optino tokens");
require(tokens <= this.balanceOf(tokenOwner), "Insufficient cover tokens");
require(optinoPair.burn(tokenOwner, tokens, BurnType.Close), "Burn optino tokens failure");
require(this.burn(tokenOwner, tokens, BurnType.Close), "Burn cover tokens failure");
(uint[5] memory _seriesData, uint8[4] memory decimalsData) = factory.getCalcData(seriesKey);
uint collateralRefund = computeCollateral(_seriesData, tokens, decimalsData);
bool isEmpty = optinoPair.totalSupply() + this.totalSupply() == 0;
collateralRefund = isEmpty ? collateralToken.balanceOf(address(this)) : collateralRefund;
require(collateralToken.transfer(tokenOwner, collateralRefund), "Transfer failure");
emit Close(optinoPair, this, tokenOwner, tokens, collateralRefund);
}
}
function settle() public {
settleFor(msg.sender);
}
function settleFor(address tokenOwner) public {
require(msg.sender == tokenOwner || msg.sender == address(optinoPair) || msg.sender == address(this), "Not authorised");
if (!isCover) {
optinoPair.settleFor(tokenOwner);
} else {
uint optinoTokens = optinoPair.balanceOf(tokenOwner);
uint coverTokens = this.balanceOf(tokenOwner);
require (optinoTokens > 0 || coverTokens > 0, "No optino or cover tokens");
uint _spot = factory.getSeriesSpot(seriesKey);
if (_spot == 0) {
setSpot();
_spot = factory.getSeriesSpot(seriesKey);
}
require(_spot > 0);
uint payoff;
uint collateral;
(uint[5] memory _seriesData, uint8[4] memory decimalsData) = factory.getCalcData(seriesKey);
if (optinoTokens > 0) {
require(optinoPair.burn(tokenOwner, optinoTokens, BurnType.Settle), "Burn optino tokens failure");
}
bool isEmpty1 = optinoPair.totalSupply() + this.totalSupply() == 0;
if (coverTokens > 0) {
require(this.burn(tokenOwner, coverTokens, BurnType.Settle), "Burn cover tokens failure");
}
bool isEmpty2 = optinoPair.totalSupply() + this.totalSupply() == 0;
if (optinoTokens > 0) {
payoff = computePayoff(_seriesData, _spot, optinoTokens, decimalsData);
if (payoff > 0) {
payoff = isEmpty1 ? collateralToken.balanceOf(address(this)) : payoff;
require(collateralToken.transfer(tokenOwner, payoff), "Payoff transfer failure");
}
emit Settle(optinoPair, tokenOwner, optinoTokens, payoff);
}
if (coverTokens > 0) {
payoff = computePayoff(_seriesData, _spot, coverTokens, decimalsData);
collateral = computeCollateral(_seriesData, coverTokens, decimalsData);
uint coverPayoff = collateral.sub(payoff);
if (coverPayoff > 0) {
coverPayoff = isEmpty2 ? collateralToken.balanceOf(address(this)) : coverPayoff;
require(collateralToken.transfer(tokenOwner, coverPayoff), "Cover payoff transfer failure");
}
emit Settle(this, tokenOwner, coverTokens, coverPayoff);
}
}
}
function recoverTokens(ERC20 token, uint tokens) public onlyOwner {
require(token != collateralToken || this.totalSupply() == 0, "Cannot recover collateral tokens until totalSupply is 0");
if (token == ERC20(0)) {
payable(owner).transfer((tokens == 0 ? address(this).balance : tokens));
} else {
token.transfer(owner, tokens == 0 ? token.balanceOf(address(this)) : tokens);
}
}
}
/// @notice @chainlink/contracts/src/v0.4/interfaces/AggregatorInterface.sol
interface AggregatorInterface4 {
function latestAnswer() external view returns (int256);
function latestTimestamp() external view returns (uint256);
function latestRound() external view returns (uint256);
function getAnswer(uint256 roundId) external view returns (int256);
function getTimestamp(uint256 roundId) external view returns (uint256);
event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 timestamp);
event NewRound(uint256 indexed roundId, address indexed startedBy);
}
/// @notice Chainlink AggregatorInterface @chainlink/contracts/src/v0.6/dev/AggregatorInterface.sol
interface AggregatorInterface6 {
function latestAnswer() external view returns (int256);
function latestTimestamp() external view returns (uint256);
function latestRound() external view returns (uint256);
function getAnswer(uint256 roundId) external view returns (int256);
function getTimestamp(uint256 roundId) external view returns (uint256);
function decimals() external view returns (uint8);
event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 timestamp);
event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt);
}
/// @notice MakerDAO Oracles v2
interface MakerFeed {
function peek() external view returns (bytes32 _value, bool _hasValue);
}
/// @notice Compound V1PriceOracle @ 0xddc46a3b076aec7ab3fc37420a8edd2959764ec4
// interface V1PriceOracleInterface {
// function assetPrices(address asset) external view returns (uint);
// }
/// @notice AdaptorFeed
interface AdaptorFeed {
function spot() external view returns (uint value, bool hasValue);
}
/// @notice Get feed
contract FeedHandler {
enum FeedType {
CHAINLINK4,
CHAINLINK6,
MAKER,
ADAPTOR
// COMPOUND,
}
uint8 immutable NODATA = uint8(0xff);
uint immutable FEEDTYPECOUNT = 4;
function getRateFromFeed(address feed, FeedType feedType) public view returns (uint rate, bool hasData, uint8 decimals, uint timestamp) {
if (feedType == FeedType.CHAINLINK4) {
int iRate = AggregatorInterface4(feed).latestAnswer();
hasData = iRate > 0;
rate = hasData ? uint(iRate) : 0;
decimals = NODATA;
timestamp = AggregatorInterface4(feed).latestTimestamp();
} else if (feedType == FeedType.CHAINLINK6) {
int iRate = AggregatorInterface6(feed).latestAnswer();
hasData = iRate > 0;
rate = hasData ? uint(iRate) : 0;
decimals = AggregatorInterface6(feed).decimals();
timestamp = AggregatorInterface6(feed).latestTimestamp();
} else if (feedType == FeedType.MAKER) {
bytes32 bRate;
(bRate, hasData) = MakerFeed(feed).peek();
rate = uint(bRate);
if (!hasData) {
rate = 0;
}
decimals = NODATA;
timestamp = NODATA;
} else if (feedType == FeedType.ADAPTOR) {
(rate, hasData) = AdaptorFeed(feed).spot();
if (!hasData) {
rate = 0;
}
decimals = NODATA;
timestamp = NODATA;
// } else if (feedType == FeedType.COMPOUND) {
// // TODO - Remove COMPOUND, or add a parameter to save asset
// uint uRate = V1PriceOracleInterface(feed).assetPrices(address(0));
// rate = uint(uRate);
// hasData = rate > 0;
// decimals = NODATA;
// timestamp = block.timestamp;
} else {
revert("Invalid feedType");
}
}
}
/// @title Optino Factory - Deploy optino and cover token contracts
/// @author BokkyPooBah, Bok Consulting Pty Ltd - <https://github.com/bokkypoobah>
/// @notice Check `message` for deprecation status
contract OptinoFactory is Owned, CloneFactory, OptinoFormulae, FeedHandler {