@ensuro/core 1.2.7 → 2.0.0-beta10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/README.md +63 -27
  2. package/build/contracts/AccessManager.sol/AccessManager.json +559 -0
  3. package/build/contracts/ERC4626AssetManager.sol/ERC4626AssetManager.json +219 -0
  4. package/build/contracts/EToken.sol/EToken.json +217 -190
  5. package/build/contracts/LPManualWhitelist.sol/LPManualWhitelist.json +17 -4
  6. package/build/contracts/{extras/IPriceRiskModule.sol/IPriceRiskModule.json → LiquidityThresholdAssetManager.sol/LiquidityThresholdAssetManager.json} +81 -131
  7. package/build/contracts/Policy.sol/Policy.json +2 -2
  8. package/build/contracts/PolicyPool.sol/PolicyPool.json +425 -295
  9. package/build/contracts/PolicyPoolComponent.sol/PolicyPoolComponent.json +15 -2
  10. package/build/contracts/PremiumsAccount.sol/PremiumsAccount.json +868 -0
  11. package/build/contracts/{BaseAssetManager.sol/BaseAssetManager.json → Reserve.sol/Reserve.json} +37 -166
  12. package/build/contracts/RiskModule.sol/RiskModule.json +85 -312
  13. package/build/contracts/SignedQuoteRiskModule.sol/SignedQuoteRiskModule.json +960 -0
  14. package/build/contracts/{DataTypes.sol/DataTypes.json → TimeScaled.sol/TimeScaled.json} +4 -4
  15. package/build/contracts/TrustfulRiskModule.sol/TrustfulRiskModule.json +134 -336
  16. package/build/contracts/dependencies/ERC1967Proxy.sol/ERC1967Proxy.json +64 -0
  17. package/build/{interfaces/IExchange.sol/IExchange.json → contracts/dependencies/IERC20Metadata.sol/IERC20Metadata.json} +83 -79
  18. package/build/contracts/{WadRayMath.sol → dependencies/WadRayMath.sol}/WadRayMath.json +3 -3
  19. package/build/{interfaces/IPolicyPoolConfig.sol/IPolicyPoolConfig.json → contracts/interfaces/IAccessManager.sol/IAccessManager.json} +79 -77
  20. package/build/contracts/interfaces/IAssetManager.sol/IAssetManager.json +109 -0
  21. package/build/{interfaces → contracts/interfaces}/IEToken.sol/IEToken.json +39 -91
  22. package/build/{interfaces → contracts/interfaces}/ILPWhitelist.sol/ILPWhitelist.json +1 -1
  23. package/build/{interfaces → contracts/interfaces}/IPolicyHolder.sol/IPolicyHolder.json +1 -1
  24. package/build/{interfaces → contracts/interfaces}/IPolicyPool.sol/IPolicyPool.json +137 -100
  25. package/build/{interfaces → contracts/interfaces}/IPolicyPoolComponent.sol/IPolicyPoolComponent.json +1 -1
  26. package/build/contracts/interfaces/IPremiumsAccount.sol/IPremiumsAccount.json +315 -0
  27. package/build/{interfaces → contracts/interfaces}/IRiskModule.sol/IRiskModule.json +58 -34
  28. package/build/contracts/mocks/FixedRateVault.sol/FixedRateVault.json +736 -0
  29. package/build/contracts/mocks/ForwardProxy.sol/ForwardProxy.json +43 -0
  30. package/build/{interfaces/IInsolvencyHook.sol/IInsolvencyHook.json → contracts/mocks/IMintableERC20.sol/IMintableERC20.json} +13 -8
  31. package/build/contracts/mocks/PolicyHolderMock.sol/PolicyHolderMock.json +228 -0
  32. package/build/contracts/mocks/PolicyPoolComponentMock.sol/PolicyPoolComponentMock.json +35 -0
  33. package/build/contracts/mocks/PolicyPoolMock.sol/PolicyPoolMock.json +702 -0
  34. package/build/contracts/mocks/PolicyPoolMock.sol/PolicyPoolMockForward.json +92 -0
  35. package/build/contracts/mocks/RiskModuleMock.sol/RiskModuleMock.json +764 -0
  36. package/build/contracts/mocks/TestCurrency.sol/TestCurrency.json +343 -0
  37. package/build/contracts/mocks/TestNFT.sol/TestNFT.json +388 -0
  38. package/contracts/AccessManager.sol +103 -0
  39. package/contracts/ERC4626AssetManager.sol +52 -0
  40. package/contracts/EToken.sol +254 -299
  41. package/contracts/LPManualWhitelist.sol +4 -4
  42. package/contracts/LiquidityThresholdAssetManager.sol +160 -0
  43. package/contracts/Policy.sol +49 -45
  44. package/contracts/PolicyPool.sol +379 -514
  45. package/contracts/PolicyPoolComponent.sol +41 -41
  46. package/contracts/PremiumsAccount.sol +480 -0
  47. package/contracts/Reserve.sol +213 -0
  48. package/contracts/RiskModule.sol +233 -174
  49. package/contracts/SignedQuoteRiskModule.sol +241 -0
  50. package/contracts/TimeScaled.sol +138 -0
  51. package/contracts/TrustfulRiskModule.sol +85 -23
  52. package/contracts/dependencies/ERC1967Proxy.sol +19 -0
  53. package/contracts/dependencies/IERC20Metadata.sol +19 -0
  54. package/contracts/dependencies/WadRayMath.sol +126 -0
  55. package/contracts/interfaces/IAccessManager.sol +148 -0
  56. package/contracts/interfaces/IAssetManager.sol +84 -0
  57. package/contracts/interfaces/IEToken.sol +195 -0
  58. package/contracts/interfaces/ILPWhitelist.sol +40 -0
  59. package/{interfaces → contracts/interfaces}/IPolicyHolder.sol +0 -0
  60. package/contracts/interfaces/IPolicyPool.sol +145 -0
  61. package/{interfaces → contracts/interfaces}/IPolicyPoolComponent.sol +3 -0
  62. package/contracts/interfaces/IPremiumsAccount.sol +76 -0
  63. package/contracts/interfaces/IRiskModule.sol +123 -0
  64. package/contracts/mocks/FixedRateVault.sol +85 -0
  65. package/contracts/mocks/ForwardProxy.sol +66 -0
  66. package/contracts/mocks/IMintableERC20.sol +13 -0
  67. package/contracts/mocks/PolicyHolderMock.sol +89 -0
  68. package/contracts/mocks/PolicyPoolComponentMock.sol +17 -0
  69. package/contracts/mocks/PolicyPoolMock.sol +148 -0
  70. package/contracts/mocks/RiskModuleMock.sol +75 -0
  71. package/contracts/mocks/TestCurrency.sol +35 -0
  72. package/contracts/mocks/TestNFT.sol +23 -0
  73. package/js/test-utils.js +356 -0
  74. package/package.json +2 -2
  75. package/build/contracts/AaveAssetManager.sol/AaveAssetManager.json +0 -742
  76. package/build/contracts/Exchange.sol/Exchange.json +0 -591
  77. package/build/contracts/FlightDelayRiskModule.sol/FlightDelayRiskModule.json +0 -1112
  78. package/build/contracts/PolicyNFT.sol/PolicyNFT.json +0 -570
  79. package/build/contracts/PolicyPoolConfig.sol/PolicyPoolConfig.json +0 -686
  80. package/build/contracts/dependencies/ChainlinkClientUpgradeable.sol/ChainlinkClientUpgradeable.json +0 -50
  81. package/build/contracts/extras/PriceRiskModule.sol/PriceRiskModule.json +0 -1055
  82. package/build/contracts/upgraded/IPolicyNFTv1.sol/IPolicyNFTv1.json +0 -322
  83. package/build/contracts/upgraded/PolicyNFTv1.sol/PolicyNFTv1.json +0 -571
  84. package/build/contracts/upgraded/PolicyNFTv1.sol/PolicyNFTv1_Upgrade.json +0 -602
  85. package/build/interfaces/IAssetManager.sol/IAssetManager.json +0 -31
  86. package/build/interfaces/IExchange.sol/IPriceOracle.json +0 -30
  87. package/build/interfaces/IPolicyNFT.sol/IPolicyNFT.json +0 -321
  88. package/contracts/AaveAssetManager.sol +0 -298
  89. package/contracts/BaseAssetManager.sol +0 -301
  90. package/contracts/DataTypes.sol +0 -287
  91. package/contracts/Exchange.sol +0 -189
  92. package/contracts/FlightDelayRiskModule.sol +0 -208
  93. package/contracts/PolicyNFT.sol +0 -96
  94. package/contracts/PolicyPoolConfig.sol +0 -247
  95. package/contracts/WadRayMath.sol +0 -135
  96. package/contracts/dependencies/ChainlinkClientUpgradeable.sol +0 -371
  97. package/contracts/extras/IPriceRiskModule.sol +0 -41
  98. package/contracts/extras/PriceRiskModule.sol +0 -243
  99. package/contracts/upgraded/IPolicyNFTv1.sol +0 -15
  100. package/contracts/upgraded/PolicyNFTv1.sol +0 -126
  101. package/interfaces/IAssetManager.sol +0 -23
  102. package/interfaces/IEToken.sol +0 -48
  103. package/interfaces/IExchange.sol +0 -59
  104. package/interfaces/IInsolvencyHook.sol +0 -27
  105. package/interfaces/ILPWhitelist.sol +0 -23
  106. package/interfaces/IPolicyNFT.sol +0 -15
  107. package/interfaces/IPolicyPool.sol +0 -44
  108. package/interfaces/IPolicyPoolConfig.sol +0 -87
  109. package/interfaces/IRiskModule.sol +0 -29
@@ -1,371 +0,0 @@
1
- // SPDX-License-Identifier: MIT
2
- pragma solidity ^0.8.0;
3
-
4
- import {Chainlink} from "@chainlink/contracts/src/v0.8/Chainlink.sol";
5
- import {ENSInterface} from "@chainlink/contracts/src/v0.8/interfaces/ENSInterface.sol";
6
- import {LinkTokenInterface} from "@chainlink/contracts/src/v0.8/interfaces/LinkTokenInterface.sol";
7
- import {OperatorInterface} from "@chainlink/contracts/src/v0.8/interfaces/OperatorInterface.sol";
8
- import {PointerInterface} from "@chainlink/contracts/src/v0.8/interfaces/PointerInterface.sol";
9
- import {ENSResolver as ENSResolver_Chainlink} from "@chainlink/contracts/src/v0.8/vendor/ENSResolver.sol";
10
- import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
11
-
12
- /**
13
- * @title The ChainlinkClient contract in upgradeable version
14
- * @dev Changes to make it compatible with OZ UUPS proxies
15
- * @notice Contract writers can inherit this contract in order to create requests for the
16
- * Chainlink network
17
- */
18
- contract ChainlinkClientUpgradeable is Initializable {
19
- using Chainlink for Chainlink.Request;
20
-
21
- uint256 constant internal LINK_DIVISIBILITY = 10**18;
22
- uint256 constant private AMOUNT_OVERRIDE = 0;
23
- address constant private SENDER_OVERRIDE = address(0);
24
- uint256 constant private ORACLE_ARGS_VERSION = 1;
25
- uint256 constant private OPERATOR_ARGS_VERSION = 2;
26
- bytes32 constant private ENS_TOKEN_SUBNAME = keccak256("link");
27
- bytes32 constant private ENS_ORACLE_SUBNAME = keccak256("oracle");
28
- address constant private LINK_TOKEN_POINTER = 0xC89bD4E1632D3A43CB03AAAd5262cbe4038Bc571;
29
-
30
- ENSInterface private ens;
31
- bytes32 private ensNode;
32
- LinkTokenInterface private link;
33
- OperatorInterface private oracle;
34
- uint256 private requestCount;
35
- mapping(bytes32 => address) private pendingRequests;
36
-
37
- event ChainlinkRequested(
38
- bytes32 indexed id
39
- );
40
- event ChainlinkFulfilled(
41
- bytes32 indexed id
42
- );
43
- event ChainlinkCancelled(
44
- bytes32 indexed id
45
- );
46
-
47
- function __ChainlinkClient_init() internal initializer {
48
- requestCount = 1;
49
- }
50
-
51
- /**
52
- * @notice Creates a request that can hold additional parameters
53
- * @param specId The Job Specification ID that the request will be created for
54
- * @param callbackAddress The callback address that the response will be sent to
55
- * @param callbackFunctionSignature The callback function signature to use for the callback address
56
- * @return A Chainlink Request struct in memory
57
- */
58
- function buildChainlinkRequest(
59
- bytes32 specId,
60
- address callbackAddress,
61
- bytes4 callbackFunctionSignature
62
- )
63
- internal
64
- pure
65
- returns (
66
- Chainlink.Request memory
67
- )
68
- {
69
- Chainlink.Request memory req;
70
- return req.initialize(specId, callbackAddress, callbackFunctionSignature);
71
- }
72
-
73
- /**
74
- * @notice Creates a Chainlink request to the stored oracle address
75
- * @dev Calls `chainlinkRequestTo` with the stored oracle address
76
- * @param req The initialized Chainlink Request
77
- * @param payment The amount of LINK to send for the request
78
- * @return requestId The request ID
79
- */
80
- function sendChainlinkRequest(
81
- Chainlink.Request memory req,
82
- uint256 payment
83
- )
84
- internal
85
- returns (
86
- bytes32
87
- )
88
- {
89
- return sendChainlinkRequestTo(address(oracle), req, payment);
90
- }
91
-
92
- /**
93
- * @notice Creates a Chainlink request to the specified oracle address
94
- * @dev Generates and stores a request ID, increments the local nonce, and uses `transferAndCall` to
95
- * send LINK which creates a request on the target oracle contract.
96
- * Emits ChainlinkRequested event.
97
- * @param oracleAddress The address of the oracle for the request
98
- * @param req The initialized Chainlink Request
99
- * @param payment The amount of LINK to send for the request
100
- * @return requestId The request ID
101
- */
102
- function sendChainlinkRequestTo(
103
- address oracleAddress,
104
- Chainlink.Request memory req,
105
- uint256 payment
106
- )
107
- internal
108
- returns (
109
- bytes32 requestId
110
- )
111
- {
112
- return rawRequest(oracleAddress, req, payment, ORACLE_ARGS_VERSION, oracle.oracleRequest.selector);
113
- }
114
-
115
- /**
116
- * @notice Creates a Chainlink request to the stored oracle address
117
- * @dev This function supports multi-word response
118
- * @dev Calls `requestOracleDataFrom` with the stored oracle address
119
- * @param req The initialized Chainlink Request
120
- * @param payment The amount of LINK to send for the request
121
- * @return requestId The request ID
122
- */
123
- function requestOracleData(
124
- Chainlink.Request memory req,
125
- uint256 payment
126
- )
127
- internal
128
- returns (
129
- bytes32
130
- )
131
- {
132
- return requestOracleDataFrom(address(oracle), req, payment);
133
- }
134
-
135
- /**
136
- * @notice Creates a Chainlink request to the specified oracle address
137
- * @dev This function supports multi-word response
138
- * @dev Generates and stores a request ID, increments the local nonce, and uses `transferAndCall` to
139
- * send LINK which creates a request on the target oracle contract.
140
- * Emits ChainlinkRequested event.
141
- * @param oracleAddress The address of the oracle for the request
142
- * @param req The initialized Chainlink Request
143
- * @param payment The amount of LINK to send for the request
144
- * @return requestId The request ID
145
- */
146
- function requestOracleDataFrom(
147
- address oracleAddress,
148
- Chainlink.Request memory req,
149
- uint256 payment
150
- )
151
- internal
152
- returns (
153
- bytes32 requestId
154
- )
155
- {
156
- return rawRequest(oracleAddress, req, payment, OPERATOR_ARGS_VERSION, oracle.requestOracleData.selector);
157
- }
158
-
159
- /**
160
- * @notice Make a request to an oracle
161
- * @param oracleAddress The address of the oracle for the request
162
- * @param req The initialized Chainlink Request
163
- * @param payment The amount of LINK to send for the request
164
- * @param argsVersion The version of data support (single word, multi word)
165
- * @return requestId The request ID
166
- */
167
- function rawRequest(
168
- address oracleAddress,
169
- Chainlink.Request memory req,
170
- uint256 payment,
171
- uint256 argsVersion,
172
- bytes4 funcSelector
173
- )
174
- private
175
- returns (
176
- bytes32 requestId
177
- )
178
- {
179
- requestId = keccak256(abi.encodePacked(this, requestCount));
180
- req.nonce = requestCount;
181
- pendingRequests[requestId] = oracleAddress;
182
- emit ChainlinkRequested(requestId);
183
- bytes memory encodedData = abi.encodeWithSelector(
184
- funcSelector,
185
- SENDER_OVERRIDE, // Sender value - overridden by onTokenTransfer by the requesting contract's address
186
- AMOUNT_OVERRIDE, // Amount value - overridden by onTokenTransfer by the actual amount of LINK sent
187
- req.id,
188
- req.callbackAddress,
189
- req.callbackFunctionId,
190
- req.nonce,
191
- argsVersion,
192
- req.buf.buf);
193
- require(link.transferAndCall(oracleAddress, payment, encodedData), "unable to transferAndCall to oracle");
194
- requestCount += 1;
195
- }
196
-
197
- /**
198
- * @notice Allows a request to be cancelled if it has not been fulfilled
199
- * @dev Requires keeping track of the expiration value emitted from the oracle contract.
200
- * Deletes the request from the `pendingRequests` mapping.
201
- * Emits ChainlinkCancelled event.
202
- * @param requestId The request ID
203
- * @param payment The amount of LINK sent for the request
204
- * @param callbackFunc The callback function specified for the request
205
- * @param expiration The time of the expiration for the request
206
- */
207
- function cancelChainlinkRequest(
208
- bytes32 requestId,
209
- uint256 payment,
210
- bytes4 callbackFunc,
211
- uint256 expiration
212
- )
213
- internal
214
- {
215
- OperatorInterface requested = OperatorInterface(pendingRequests[requestId]);
216
- delete pendingRequests[requestId];
217
- emit ChainlinkCancelled(requestId);
218
- requested.cancelOracleRequest(requestId, payment, callbackFunc, expiration);
219
- }
220
-
221
- /**
222
- * @notice Sets the stored oracle address
223
- * @param oracleAddress The address of the oracle contract
224
- */
225
- function setChainlinkOracle(
226
- address oracleAddress
227
- )
228
- internal
229
- {
230
- oracle = OperatorInterface(oracleAddress);
231
- }
232
-
233
- /**
234
- * @notice Sets the LINK token address
235
- * @param linkAddress The address of the LINK token contract
236
- */
237
- function setChainlinkToken(
238
- address linkAddress
239
- )
240
- internal
241
- {
242
- link = LinkTokenInterface(linkAddress);
243
- }
244
-
245
- /**
246
- * @notice Sets the Chainlink token address for the public
247
- * network as given by the Pointer contract
248
- */
249
- function setPublicChainlinkToken()
250
- internal
251
- {
252
- setChainlinkToken(PointerInterface(LINK_TOKEN_POINTER).getAddress());
253
- }
254
-
255
- /**
256
- * @notice Retrieves the stored address of the LINK token
257
- * @return The address of the LINK token
258
- */
259
- function chainlinkTokenAddress()
260
- internal
261
- view
262
- returns (
263
- address
264
- )
265
- {
266
- return address(link);
267
- }
268
-
269
- /**
270
- * @notice Retrieves the stored address of the oracle contract
271
- * @return The address of the oracle contract
272
- */
273
- function chainlinkOracleAddress()
274
- internal
275
- view
276
- returns (
277
- address
278
- )
279
- {
280
- return address(oracle);
281
- }
282
-
283
- /**
284
- * @notice Allows for a request which was created on another contract to be fulfilled
285
- * on this contract
286
- * @param oracleAddress The address of the oracle contract that will fulfill the request
287
- * @param requestId The request ID used for the response
288
- */
289
- function addChainlinkExternalRequest(
290
- address oracleAddress,
291
- bytes32 requestId
292
- )
293
- internal
294
- notPendingRequest(requestId)
295
- {
296
- pendingRequests[requestId] = oracleAddress;
297
- }
298
-
299
- /**
300
- * @notice Sets the stored oracle and LINK token contracts with the addresses resolved by ENS
301
- * @dev Accounts for subnodes having different resolvers
302
- * @param ensAddress The address of the ENS contract
303
- * @param node The ENS node hash
304
- */
305
- function useChainlinkWithENS(
306
- address ensAddress,
307
- bytes32 node
308
- )
309
- internal
310
- {
311
- ens = ENSInterface(ensAddress);
312
- ensNode = node;
313
- bytes32 linkSubnode = keccak256(abi.encodePacked(ensNode, ENS_TOKEN_SUBNAME));
314
- ENSResolver_Chainlink resolver = ENSResolver_Chainlink(ens.resolver(linkSubnode));
315
- setChainlinkToken(resolver.addr(linkSubnode));
316
- updateChainlinkOracleWithENS();
317
- }
318
-
319
- /**
320
- * @notice Sets the stored oracle contract with the address resolved by ENS
321
- * @dev This may be called on its own as long as `useChainlinkWithENS` has been called previously
322
- */
323
- function updateChainlinkOracleWithENS()
324
- internal
325
- {
326
- bytes32 oracleSubnode = keccak256(abi.encodePacked(ensNode, ENS_ORACLE_SUBNAME));
327
- ENSResolver_Chainlink resolver = ENSResolver_Chainlink(ens.resolver(oracleSubnode));
328
- setChainlinkOracle(resolver.addr(oracleSubnode));
329
- }
330
-
331
- /**
332
- * @notice Ensures that the fulfillment is valid for this contract
333
- * @dev Use if the contract developer prefers methods instead of modifiers for validation
334
- * @param requestId The request ID for fulfillment
335
- */
336
- function validateChainlinkCallback(
337
- bytes32 requestId
338
- )
339
- internal
340
- recordChainlinkFulfillment(requestId)
341
- // solhint-disable-next-line no-empty-blocks
342
- {}
343
-
344
- /**
345
- * @dev Reverts if the sender is not the oracle of the request.
346
- * Emits ChainlinkFulfilled event.
347
- * @param requestId The request ID for fulfillment
348
- */
349
- modifier recordChainlinkFulfillment(
350
- bytes32 requestId
351
- )
352
- {
353
- require(msg.sender == pendingRequests[requestId],
354
- "Source must be the oracle of the request");
355
- delete pendingRequests[requestId];
356
- emit ChainlinkFulfilled(requestId);
357
- _;
358
- }
359
-
360
- /**
361
- * @dev Reverts if the request is already pending
362
- * @param requestId The request ID for fulfillment
363
- */
364
- modifier notPendingRequest(
365
- bytes32 requestId
366
- )
367
- {
368
- require(pendingRequests[requestId] == address(0), "Request is already pending");
369
- _;
370
- }
371
- }
@@ -1,41 +0,0 @@
1
- // SPDX-License-Identifier: Apache-2.0
2
- pragma solidity ^0.8.0;
3
-
4
- import {IRiskModule} from "../../interfaces/IRiskModule.sol";
5
- import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
6
-
7
- /**
8
- * @title IPriceRiskModule interface
9
- * @dev Interface for price risk module
10
- * @author Ensuro
11
- */
12
- interface IPriceRiskModule is IRiskModule {
13
- /**
14
- * @dev Returns the premium and lossProb of the policy
15
- * @param triggerPrice Price of the asset_ that will trigger the policy (expressed in _currency)
16
- * @param lower If true -> triggers if the price is lower, If false -> triggers if the price is higher
17
- * @param payout Expressed in policyPool.currency()
18
- * @param expiration Expiration of the policy
19
- * @return premium Premium that needs to be paid
20
- * @return lossProb Probability of paying the maximum payout
21
- */
22
- function pricePolicy(
23
- uint256 triggerPrice,
24
- bool lower,
25
- uint256 payout,
26
- uint40 expiration
27
- ) external view returns (uint256 premium, uint256 lossProb);
28
-
29
- function newPolicy(
30
- uint256 triggerPrice,
31
- bool lower,
32
- uint256 payout,
33
- uint40 expiration
34
- ) external returns (uint256);
35
-
36
- function triggerPolicy(uint256 policyId) external;
37
-
38
- function referenceCurrency() external view returns (IERC20Metadata);
39
-
40
- function asset() external view returns (IERC20Metadata);
41
- }
@@ -1,243 +0,0 @@
1
- // SPDX-License-Identifier: Apache-2.0
2
- pragma solidity ^0.8.0;
3
-
4
- import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
5
- import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
6
- import {IPolicyPool} from "../../interfaces/IPolicyPool.sol";
7
- import {IPolicyPoolConfig} from "../../interfaces/IPolicyPoolConfig.sol";
8
- import {RiskModule} from "../RiskModule.sol";
9
- import {Policy} from "../Policy.sol";
10
- import {WadRayMath} from "../WadRayMath.sol";
11
- import {IPriceRiskModule} from "./IPriceRiskModule.sol";
12
-
13
- /**
14
- * @title PriceRiskModule
15
- * @dev Risk Module that triggers the payout if the price of an asset is lower or higher than trigger price
16
- * @custom:security-contact security@ensuro.co
17
- * @author Ensuro
18
- */
19
- contract PriceRiskModule is RiskModule, IPriceRiskModule {
20
- using SafeERC20 for IERC20Metadata;
21
- using WadRayMath for uint256;
22
-
23
- bytes32 public constant CUSTOMER_ROLE = keccak256("CUSTOMER_ROLE");
24
- bytes32 public constant PRICER_ROLE = keccak256("PRICER_ROLE");
25
-
26
- uint8 public constant PRICE_SLOTS = 30;
27
-
28
- /// @custom:oz-upgrades-unsafe-allow state-variable-immutable
29
- IERC20Metadata internal immutable _asset;
30
- /// @custom:oz-upgrades-unsafe-allow state-variable-immutable
31
- IERC20Metadata internal immutable _referenceCurrency;
32
- /// @custom:oz-upgrades-unsafe-allow state-variable-immutable
33
- uint256 internal immutable _slotSize;
34
-
35
- struct PolicyData {
36
- Policy.PolicyData ensuroPolicy;
37
- uint256 triggerPrice;
38
- bool lower; // If true -> triggers if the price is lower, If false -> triggers if the price is higher
39
- }
40
-
41
- mapping(uint256 => PolicyData) internal _policies;
42
-
43
- // Duration (in hours) of the protection * (1 if lower else -1) => cummulative density function
44
- // [0] = prob of ([0, infinite%)
45
- // [1] = prob of ([1, infinite%)
46
- // ...
47
- // [PRICE_SLOTS - 1] = prob of ([PRICE_SLOTS - 1, -infinite%)
48
- mapping(int40 => uint256[PRICE_SLOTS]) internal _cdf;
49
-
50
- uint96 internal _internalId;
51
-
52
- event NewPricePolicy(
53
- address indexed customer,
54
- uint256 policyId,
55
- uint256 triggerPrice,
56
- bool lower
57
- );
58
-
59
- /**
60
- * @dev Constructs the LiquidationProtectionRiskModule
61
- * @param policyPool_ The policyPool
62
- * @param asset_ Address of the asset which price want to protect
63
- * @param referenceCurrency_ Address of the comparison asset (price will be price(asset)/price(currency))
64
- * @param slotSize_ Size of each percentage slot in the pdf function (in wad)
65
- */
66
- /// @custom:oz-upgrades-unsafe-allow constructor
67
- constructor(
68
- IPolicyPool policyPool_,
69
- IERC20Metadata asset_,
70
- IERC20Metadata referenceCurrency_,
71
- uint256 slotSize_
72
- ) RiskModule(policyPool_) {
73
- _asset = asset_;
74
- _referenceCurrency = referenceCurrency_;
75
- _slotSize = slotSize_;
76
- }
77
-
78
- /**
79
- * @dev Initializes the RiskModule
80
- * @param name_ Name of the Risk Module
81
- * @param scrPercentage_ Solvency Capital Requirement percentage, to calculate
82
- * capital requirement as % of (payout - premium) (in ray)
83
- * @param ensuroFee_ % of premium that will go for Ensuro treasury (in ray)
84
- * @param scrInterestRate_ cost of capital (in ray)
85
- * @param maxScrPerPolicy_ Max SCR to be allocated to this module (in wad)
86
- * @param scrLimit_ Max SCR to be allocated to this module (in wad)
87
- * @param wallet_ Address of the RiskModule provider
88
- */
89
- function initialize(
90
- string memory name_,
91
- uint256 scrPercentage_,
92
- uint256 ensuroFee_,
93
- uint256 scrInterestRate_,
94
- uint256 maxScrPerPolicy_,
95
- uint256 scrLimit_,
96
- address wallet_
97
- ) public initializer {
98
- __RiskModule_init(
99
- name_,
100
- scrPercentage_,
101
- ensuroFee_,
102
- scrInterestRate_,
103
- maxScrPerPolicy_,
104
- scrLimit_,
105
- wallet_
106
- );
107
- _internalId = 1;
108
- }
109
-
110
- function _getCurrentPrice() internal view returns (uint256) {
111
- uint256 ret = policyPool().config().exchange().convert(
112
- address(_asset),
113
- address(_referenceCurrency),
114
- 10**_asset.decimals()
115
- );
116
- require(ret != 0, "Price not available");
117
- return ret;
118
- }
119
-
120
- /**
121
- * @dev Returns the premium and lossProb of the policy
122
- * @param triggerPrice Price of the asset_ that will trigger the policy (expressed in _referenceCurrency)
123
- * @param lower If true -> triggers if the price is lower, If false -> triggers if the price is higher
124
- * @param payout Expressed in policyPool.currency()
125
- * @param expiration Expiration of the policy
126
- * @return premium Premium that needs to be paid
127
- * @return lossProb Probability of paying the maximum payout
128
- */
129
- function pricePolicy(
130
- uint256 triggerPrice,
131
- bool lower,
132
- uint256 payout,
133
- uint40 expiration
134
- ) public view override returns (uint256 premium, uint256 lossProb) {
135
- uint256 currentPrice = _getCurrentPrice();
136
- require(
137
- (lower && currentPrice > triggerPrice) || (!lower && currentPrice < triggerPrice),
138
- "Price already at trigger value"
139
- );
140
- lossProb = _computeLossProb(currentPrice, triggerPrice, expiration - uint40(block.timestamp));
141
- if (lossProb == 0) return (0, 0);
142
- premium = getMinimumPremium(payout, lossProb, expiration); // TODO: extra fee for RiskModule?
143
- return (premium, lossProb);
144
- }
145
-
146
- function _computeLossProb(
147
- uint256 currentPrice,
148
- uint256 triggerPrice,
149
- uint40 duration
150
- ) internal view returns (uint256) {
151
- uint256[PRICE_SLOTS] storage pdf = _cdf[
152
- int40((duration + 1800) / 3600) * (currentPrice > triggerPrice ? int40(1) : int40(-1))
153
- ];
154
- uint256 priceJump;
155
- uint256 decimalConv = 10**(18 - _referenceCurrency.decimals());
156
- // Calculate the jump percentage as integer with simetric rounding
157
- if (currentPrice > triggerPrice) {
158
- priceJump =
159
- WadRayMath.wad() -
160
- (triggerPrice * decimalConv).wadDiv(currentPrice * decimalConv);
161
- } else {
162
- priceJump =
163
- (triggerPrice * decimalConv).wadDiv(currentPrice * decimalConv) -
164
- WadRayMath.wad();
165
- }
166
-
167
- uint8 downPerc = uint8((priceJump + _slotSize / 2) / _slotSize);
168
-
169
- if (downPerc >= PRICE_SLOTS) {
170
- return pdf[PRICE_SLOTS - 1];
171
- } else {
172
- return pdf[downPerc];
173
- }
174
- }
175
-
176
- function newPolicy(
177
- uint256 triggerPrice,
178
- bool lower,
179
- uint256 payout,
180
- uint40 expiration
181
- ) external override returns (uint256) {
182
- (uint256 premium, uint256 lossProb) = pricePolicy(triggerPrice, lower, payout, expiration);
183
- require(premium > 0, "Either duration or percentage jump not supported");
184
-
185
- uint256 policyId = (uint256(uint160(address(this))) << 96) + _internalId;
186
- PolicyData storage priceRiskPolicy = _policies[policyId];
187
- address customer = _msgSender();
188
- priceRiskPolicy.ensuroPolicy = _newPolicy(
189
- payout,
190
- premium,
191
- lossProb,
192
- expiration,
193
- customer,
194
- _internalId
195
- );
196
- _internalId += 1;
197
- priceRiskPolicy.triggerPrice = triggerPrice;
198
- priceRiskPolicy.lower = lower;
199
- emit NewPricePolicy(customer, policyId, triggerPrice, lower);
200
- return policyId;
201
- }
202
-
203
- function triggerPolicy(uint256 policyId) external override whenNotPaused {
204
- PolicyData storage policy = _policies[policyId];
205
- uint256 currentPrice = _getCurrentPrice();
206
- require(
207
- !policy.lower || currentPrice <= policy.triggerPrice,
208
- "Condition not met CurrentPrice > triggerPrice"
209
- );
210
- require(
211
- policy.lower || currentPrice >= policy.triggerPrice,
212
- "Condition not met CurrentPrice < triggerPrice"
213
- );
214
-
215
- _policyPool.resolvePolicy(policy.ensuroPolicy, policy.ensuroPolicy.payout);
216
- }
217
-
218
- /**
219
- * @dev Sets the probability distribution for a given duration
220
- * @param duration Duration of the policy in hours (simetric rounding) positive if probability of lower price
221
- * negative if probability of higher price
222
- * @param cdf Array where cdf[i] = prob of price lower/higher than i% of current price
223
- */
224
- function setCDF(int40 duration, uint256[PRICE_SLOTS] calldata cdf)
225
- external
226
- onlyRole(PRICER_ROLE)
227
- whenNotPaused
228
- {
229
- _cdf[duration] = cdf;
230
- }
231
-
232
- function getCDF(int40 duration) external view returns (uint256[PRICE_SLOTS] memory) {
233
- return _cdf[duration];
234
- }
235
-
236
- function referenceCurrency() external view override returns (IERC20Metadata) {
237
- return _referenceCurrency;
238
- }
239
-
240
- function asset() external view override returns (IERC20Metadata) {
241
- return _asset;
242
- }
243
- }
@@ -1,15 +0,0 @@
1
- // SPDX-License-Identifier: Apache-2.0
2
- pragma solidity ^0.8.0;
3
-
4
- import {IERC721Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol";
5
-
6
- /**
7
- * @title IPolicyNFT interface
8
- * @dev Interface for mintable NFT token that returns tokenId
9
- * @author Ensuro
10
- */
11
- interface IPolicyNFTv1 is IERC721Upgradeable {
12
- function safeMint(address to) external returns (uint256);
13
-
14
- function connect() external;
15
- }