-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoptipair.sol
More file actions
396 lines (343 loc) · 17.7 KB
/
Copy pathoptipair.sol
File metadata and controls
396 lines (343 loc) · 17.7 KB
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
// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;
import {IERC20} from "./interfaces/IERC20.sol";
import {AggregatorV3Interface} from
"../lib/chainlink-brownie-contracts/contracts/src/v0.8/shared/interfaces/AggregatorV3Interface.sol";
/**
* @title OptionAMM
* @notice This contract implements an Automated Market Maker (AMM) for options trading.
* @author Yug Agarwal
* @dev This contract allows users to provide liquidity for options trading and earn profit.
*
* . . .#
* +#####+---+###+#############+- -+###.
* +###+++####+##-+++++##+++##++####+-. -+###+++
* +#########.-#+--+####++###- -########+---+++#####+++
* +#######+#+++--+####+-..-+-.###+++########+-++###++.
* +######. +#-#####+-.-------+############+++####-
* +####++... ########-++- +##########++++++.
* -#######-+. .########+++ -++######+++-
* #++########--+-+####++++-- . .. .-#++--+##+####.
* -+++++++++#####---###---.----###+-+########..-+#++##-
* ++###+++++#####-..---.. .+##++++#++#++-+--. .-++++#
* .###+. .+#+-+###+ .. +##+##+#++----...---. .-+--+.
* ###+---------+####+ -####+-....... ...--++. .---.
* -#++++-----#######+- .-+###+.... ..... .-+##-. .
* ##+++###++######++-. .--+---++---........ ...---. .
* -####+-+#++###++-. .--.--...-----.......--..... .
* +######+++###+--..---..... ...---------------.. .. . .
* .-#########+#+++--++--------......----++--.--. .--+---.
* -+++########++--++++----------------------.--+++--+++--
* .######-.-++++###+----------------------..---++--++-+++---..
* -##########-------+-----------------------+-++-++----..----+----+#####++--..
* -#############+.. ..--..----------.....-+++++++++++++++++##################+.
* --+++++#########+- . .... ....... -+++++++++++++++++++############-.----+##-
* -----....-+#######+- .. -+++++++++++++++++++++##+######+. +++.
* --------.....---+#####+--......----.+++++++++++++++++++++##+-+++##+. -++-
* -------... .--++++++---.....-----.+++++++++++++++++++++++. -+++##- .---
* #################+--.....-------. .+++++++++++++++++++++- -+-. .---
* +#########++++-.. .......-+--..--++-++++++++++++++++++++- .-... ....----
* -#####++---.. .-- -+++-. ..+++++++++++++++++++-- .-+-......-+---
* +####+---... -+#- . --++++-. .+++++++++++++++++++--- -- -+--
* ++++++++++--....-++.--++--.--+++++-.+++++++++++++++++++---. ....... ----
* .--++#########++-.--.+++++--++++###+-++++++++++++++++++++---- .-++- ----
* .-+#############+-.++#+-+-++#######-++++++++++++++++++++---- -++++- ..---
* .---+############+.+###++--++#####++-+++++++++++++++++++++-------++++-........-+-
* --+-+##########-+######+++++-++++++-++++++++++++++++++++++-----.----.......---+-
* .--+---#######..+#######+++++++--+++-+++++++++++++++++++++++-----------------+++-
* .++--..-+##-.-########+++++---++ .+-.+++++++++++++++++++++++++++++++++++---+++++-
* -+++. ..-..-+#########++-++--..--....+++++++++++++++++++++++++++++++++++++++++++-
* -++-......-+++############++++----- .+++++++++++++++++++++++++++++++++++++++++++-
* +##-.....---+#######+####+####+--++-.+++++++++++++++++++++++++++++++++++++++++++-
* .#+++-...-++######++-+-----..----++##-+++++++++++++++++++++++++++++++++++++++++++-
* .+++--------+##----+------+-..----+++-+++++++++++++++++++++++++++++++++++++++++++-
* ----.-----+++-+-...------++-----...--+++++++++++++++++++++++++++++++++++++++++++-
* .-..-.--.----..--.... ....++--. ....-+++++++++++++++++++++++++++++++++++++++++++-
* -----------.---..--.. ..+. . ... .+++++++++++++++++++++++++++++++++++++++++++-
* .+#+#+---####+-. .....--... . .+++++++++++++++++++++++++++++++++++++++++++-
* -+++++#++++++++. ..-...--.. .. .+++++++++++++++++++++++++++++++++++++++++++-
* ++++++-------++-- . ....--.. . . .. .+++++++++++++++++++++++++-+----------...
* -++++--++++.------......-- ... .. . .---------------...
* -++-+####+++---..-.........
* .....
*/
contract OptionAMM {
error Optipair__ZeroAmount();
struct Option {
uint256 strikePrice;
uint256 lotSize; // x
uint256 premium; // y
uint256 expiry;
bool isCall;
address creator;
bool purchased;
}
Option[] private options;
IERC20 private immutable i_usdc; // USDC token contract interface
AggregatorV3Interface private immutable i_priceFeed; // Chainlink price feed interface
uint256 private constant DECIMAL_PRECISION = 18;
uint256 private immutable i_usdcDecimals;
// Mapping from option ID to user address to active status
mapping(uint256 => mapping(address => bool)) private optionOwnership;
// Liquidity tracking
uint256 private totalLiquidity;
uint256 private totalPremiumLiquidity;
mapping(address => uint256) private liquidityContributions;
uint16 private immutable i_minPremiumPercentage; // Minimum premium percentage for options
mapping(address => uint256[]) private userOptions; // Mapping from user address to option IDs they own
event OptionCreated(
uint256 indexed optionId, uint256 strikePrice, uint256 lotSize, uint256 premium, uint256 expiry, bool isCall
);
event OptionPurchased(uint256 indexed optionId, address buyer, uint256 lotAmount, uint256 cost);
event LiquidityAdded(address indexed provider, uint256 amount);
event LiquidityRemoved(address indexed provider, uint256 amount);
event OptionSettled(uint256 indexed optionId, address indexed holder, uint256 payout, bool inTheMoney);
/**
* @param _usdcAddress USDC token contract address
* @param _priceFeedAddress The ETH/USD(for now) chainlink price feed contract address
*/
constructor(address _usdcAddress, address _priceFeedAddress, uint16 _minPremiumPercentage) {
require(_minPremiumPercentage > 0 && _minPremiumPercentage <= 10000, "Invalid min premium percentage");
require(_usdcAddress != address(0), "USDC address cannot be zero");
require(_priceFeedAddress != address(0), "Price feed address cannot be zero");
i_usdc = IERC20(_usdcAddress);
// ftso = FtsoV2Interface(_ftsoAddress);
i_priceFeed = AggregatorV3Interface(_priceFeedAddress);
i_usdcDecimals = IERC20(_usdcAddress).decimals();
i_minPremiumPercentage = _minPremiumPercentage;
}
/**
* @param _strikePrice strike price of the option in USD (18 decimals)
* @param _lotSize lot size of the option (number of tokens in the option, in 18 decimals)
* @param _premium premium price of the option (in USDC, 18 decimals)
* @param _expiry expiry timestamp of the option (in seconds)
* @param _isCall boolean indicating if the option is a call option (true) or a put option (false)
*/
function createOption(uint256 _strikePrice, uint256 _lotSize, uint256 _premium, uint256 _expiry, bool _isCall)
public
{
uint256 latestPrice = getLatestPrice();
require(_isCall ? _strikePrice > latestPrice : _strikePrice < latestPrice, "Strike price not valid");
require(_strikePrice > 0, "Strike price must be greater than 0");
require(_lotSize > 0, "Lot size must be greater than 0");
require(_premium >= _strikePrice * i_minPremiumPercentage / 10000, "Premium too low");
require(_expiry > block.timestamp, "Expiry must be in the future");
options.push(
Option({
strikePrice: _strikePrice,
lotSize: _lotSize,
premium: _premium,
expiry: _expiry,
isCall: _isCall,
creator: msg.sender,
purchased: false
})
);
uint256 optionId = options.length - 1;
emit OptionCreated(optionId, _strikePrice, _lotSize, _premium, _expiry, _isCall);
}
/**
*
* @param _optionId ID of the option to purchase
*/
function purchaseOption(uint256 _optionId) public {
require(_optionId < options.length, "Option does not exist");
Option memory option = options[_optionId];
require(block.timestamp < option.expiry, "Option has expired");
// uint256 currentPremium = option.lotSize > 0 ? option.k / option.lotSize : 0;
uint256 extraPenalty = getExtraPenalty(_optionId);
uint256 cost = (option.premium + extraPenalty) * option.lotSize / 10 ** DECIMAL_PRECISION; // Adjust for decimals
require(
i_usdc.transferFrom(msg.sender, address(this), cost / 10 ** (DECIMAL_PRECISION - i_usdcDecimals)),
"Failed to transfer USDC"
);
// option.lotSize -= _lotAmount; // Decrease lot size available
// option.premium = option.lotSize > 0 ? option.k / option.lotSize : 0; // Update premium for next buyer
optionOwnership[_optionId][msg.sender] = true; // Record the purchase
totalLiquidity += cost; // Update total liquidity
options[_optionId].purchased = true; // Mark option as purchased
//options[_optionId].lotSize = 0;
totalPremiumLiquidity += cost; // Update total premium liquidity
userOptions[msg.sender].push(_optionId); // Add option ID to user's list
emit OptionPurchased(_optionId, msg.sender, option.lotSize, cost);
}
/**
*
* @param _amount Amount of USDC to add as liquidity (in 18 decimals)
*/
function addLiquidity(uint256 _amount) public {
if (_amount == 0) revert Optipair__ZeroAmount();
require(
i_usdc.transferFrom(msg.sender, address(this), _amount / 10 ** (DECIMAL_PRECISION - i_usdcDecimals)),
"Failed to transfer USDC"
);
liquidityContributions[msg.sender] += _amount;
totalLiquidity += _amount;
emit LiquidityAdded(msg.sender, _amount);
}
/**
*
* @param _amount Amount of USDC to remove as liquidity (in 18 decimals)
*/
function removeLiquidity(uint256 _amount) public {
if (_amount == 0) revert Optipair__ZeroAmount();
require(liquidityContributions[msg.sender] >= _amount, "Insufficient liquidity");
require(i_usdc.transfer(msg.sender, _amount / 10 ** (DECIMAL_PRECISION - i_usdcDecimals)), "Transfer failed");
liquidityContributions[msg.sender] -= _amount;
totalLiquidity -= _amount;
emit LiquidityRemoved(msg.sender, _amount);
}
/**
* @notice Settle an option after its expiry
* @param optionId ID of the option to settle
*/
function settleOption(uint256 optionId) public {
require(optionId < options.length, "Option does not exist");
Option memory option = options[optionId];
require(block.timestamp >= option.expiry, "Option has not yet expired");
require(optionOwnership[optionId][msg.sender], "You do not own this option");
uint256 latestPrice = getLatestPrice();
uint256 payout;
bool inTheMoney;
/*
latest price = 1808.051 * 1e18 = 1808051 * 1e15
strike price = 500 * 1e18 = 500000 * 1e15
lot count = 1e18 = 1000 * 1e15
price difference = 1808051 - 500000 = 13,08,051 * 1e15
payout = 1308051000 * 1e12 * 1e18 / 1e30 = 1308051000 * 1e0 = 1308051000
*/
if (option.isCall) {
if (latestPrice > option.strikePrice) {
inTheMoney = true;
uint256 priceDifference = latestPrice - option.strikePrice;
payout = priceDifference * option.lotSize / 10 ** DECIMAL_PRECISION;
// Ensure there is enough liquidity to pay out
require(totalLiquidity >= payout, "Insufficient liquidity for payout");
require(
i_usdc.transfer(msg.sender, payout / 10 ** (DECIMAL_PRECISION - i_usdcDecimals)), "Payout failed"
);
totalLiquidity -= payout; // Update liquidity
}
} else {
// Put option
if (latestPrice < option.strikePrice) {
inTheMoney = true;
uint256 priceDifference = option.strikePrice - latestPrice;
payout = priceDifference * option.lotSize / 10 ** DECIMAL_PRECISION;
// Ensure there is enough liquidity to pay out
require(totalLiquidity >= payout, "Insufficient liquidity for payout");
require(
i_usdc.transfer(msg.sender, payout / 10 ** (DECIMAL_PRECISION - i_usdcDecimals)), "Payout failed"
);
totalLiquidity -= payout; // Update liquidity
}
}
// if (
// (option.isCall && latestPrice > int256(option.strikePrice))
// || (option.isCall == false && latestPrice < int256(option.strikePrice))
// ) {
// inTheMoney = true;
// uint256 priceDifference = uint256(abs(latestPrice - int256(option.strikePrice)));
// payout = priceDifference * lotCount;
// // Ensure there is enough liquidity to pay out
// require(totalLiquidity >= payout, "Insufficient liquidity for payout");
// require(usdc.transfer(msg.sender, payout), "Payout failed");
// totalLiquidity -= payout; // Update liquidity
// }
// Burn the settled options
optionOwnership[optionId][msg.sender] = false;
for (uint256 i = 0; i < userOptions[msg.sender].length; i++) {
if (userOptions[msg.sender][i] == optionId) {
userOptions[msg.sender][i] = userOptions[msg.sender][userOptions[msg.sender].length - 1];
userOptions[msg.sender].pop();
break;
}
}
emit OptionSettled(optionId, msg.sender, payout, inTheMoney);
}
/**
* @notice Get the latest price of ETH in USD from Chainlink
* @return Latest price in 18 decimals
*/
function getLatestPrice() public view returns (uint256) {
(, int256 price,,,) = i_priceFeed.latestRoundData();
uint8 decimals = i_priceFeed.decimals();
return abs(price * int256(10 ** (18 - decimals))); // Convert to 18 decimals
// bytes21[] memory feedIds = new bytes21[](1);
// feedIds[0] = ETH_USD_FEED_ID;
// (uint256[] memory values,,) = ftso.getFeedsById(feedIds);
// return int256(values[0]);
}
/**
* @notice Legacy payable function for backward compatibility (deprecated)
* @dev Use getLatestPrice() instead - this function is gas inefficient
* @return Latest price in 18 decimals
*/
function getLatestPricePayable() public payable returns (uint256) {
return getLatestPrice();
}
/**
*
* @param optionId ID of the option to get extra penalty for
* @return Extra penalty amount in 18 decimals
*/
function getExtraPenalty(uint256 optionId) public view returns (uint256) {
require(optionId < options.length, "Option does not exist");
Option memory option = options[optionId];
uint256 latestPrice = getLatestPrice();
uint256 extraPenalty = 0;
if (option.isCall) {
if (latestPrice > option.strikePrice) {
extraPenalty = latestPrice - option.strikePrice;
}
} else {
if (latestPrice < option.strikePrice) {
extraPenalty = option.strikePrice - latestPrice;
}
}
return extraPenalty;
}
/* Getter and Helper Functions */
function abs(int256 x) private pure returns (uint256) {
return x >= 0 ? uint256(x) : uint256(-x);
}
// Additional helper methods can be added here
function getOptionsLength() public view returns (uint256) {
return options.length;
}
function getUsersOptions(address user) public view returns (uint256[] memory) {
return userOptions[user];
}
function getOptionsList() public view returns (Option[] memory) {
return options;
}
function getMinPremiumPercentage() public view returns (uint16) {
return i_minPremiumPercentage;
}
function getUsdcAddress() public view returns (address) {
return address(i_usdc);
}
function getPriceFeedAddress() public view returns (address) {
return address(i_priceFeed);
}
function getIsOwnerOfTheOption(uint256 optionId, address user) public view returns (bool) {
return optionOwnership[optionId][user];
}
function getLiquidityContributionByAUser(address user) public view returns (uint256) {
return liquidityContributions[user];
}
function getTotalLiquidity() public view returns (uint256) {
return totalLiquidity;
}
function getOptionById(uint256 optionId) public view returns (Option memory) {
require(optionId < options.length, "Option does not exist");
return options[optionId];
}
function getOptionDetails(uint256 optionId) public view returns (Option memory) {
require(optionId < options.length, "Option does not exist");
return options[optionId];
}
function getTotalPremiumLiquidity() public view returns (uint256) {
return totalPremiumLiquidity;
}
}