This repository has been archived by the owner on Dec 31, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathD3Trading.sol
252 lines (209 loc) · 9.93 KB
/
D3Trading.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
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.16;
import "../lib/PMMRangeOrder.sol";
import "../lib/Errors.sol";
import {IDODOSwapCallback} from "../intf/IDODOSwapCallback.sol";
import {ID3Maker} from "../intf/ID3Maker.sol";
import {ID3Vault} from "../intf/ID3Vault.sol";
import {D3Funding} from "./D3Funding.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
contract D3Trading is D3Funding {
using SafeERC20 for IERC20;
modifier onlyMaker() {
require(msg.sender == state._MAKER_, "not maker");
_;
}
// =============== Read ===============
/// @notice for external users to read tokenMMInfo
function getTokenMMPriceInfoForRead(
address token
)
external
view
returns (uint256 askDownPrice, uint256 askUpPrice, uint256 bidDownPrice, uint256 bidUpPrice, uint256 swapFee)
{
(Types.TokenMMInfo memory tokenMMInfo, ) =
ID3Maker(state._MAKER_).getTokenMMInfoForPool(token);
askDownPrice = tokenMMInfo.askDownPrice;
askUpPrice = tokenMMInfo.askUpPrice;
bidDownPrice = tokenMMInfo.bidDownPrice;
bidUpPrice = tokenMMInfo.bidUpPrice;
swapFee = tokenMMInfo.swapFeeRate;
}
function getTokenMMOtherInfoForRead(
address token
)
external
view
returns (
uint256 askAmount,
uint256 bidAmount,
uint256 kAsk,
uint256 kBid,
uint256 cumulativeAsk,
uint256 cumulativeBid
)
{
(Types.TokenMMInfo memory tokenMMInfo, uint256 tokenIndex) =
ID3Maker(state._MAKER_).getTokenMMInfoForPool(token);
cumulativeAsk = allFlag >> (tokenIndex) & 1 == 0 ? 0 : tokenCumMap[token].cumulativeAsk;
cumulativeBid = allFlag >> (tokenIndex) & 1 == 0 ? 0 : tokenCumMap[token].cumulativeBid;
bidAmount = tokenMMInfo.bidAmount;
askAmount = tokenMMInfo.askAmount;
kAsk = tokenMMInfo.kAsk;
kBid = tokenMMInfo.kBid;
}
// ============ Swap =============
/// @notice get swap status for internal swap
function getRangeOrderState(
address fromToken,
address toToken
) public view returns (Types.RangeOrderState memory roState) {
roState.oracle = state._ORACLE_;
uint256 fromTokenIndex;
uint256 toTokenIndex;
(roState.fromTokenMMInfo, fromTokenIndex) = ID3Maker(state._MAKER_).getTokenMMInfoForPool(fromToken);
(roState.toTokenMMInfo, toTokenIndex) = ID3Maker(state._MAKER_).getTokenMMInfoForPool(toToken);
// deal with update flag
roState.fromTokenMMInfo.cumulativeAsk =
allFlag >> (fromTokenIndex) & 1 == 0 ? 0 : tokenCumMap[fromToken].cumulativeAsk;
roState.fromTokenMMInfo.cumulativeBid =
allFlag >> (fromTokenIndex) & 1 == 0 ? 0 : tokenCumMap[fromToken].cumulativeBid;
roState.toTokenMMInfo.cumulativeAsk =
allFlag >> (toTokenIndex) & 1 == 0 ? 0 : tokenCumMap[toToken].cumulativeAsk;
roState.toTokenMMInfo.cumulativeBid =
allFlag >> (toTokenIndex) & 1 == 0 ? 0 : tokenCumMap[toToken].cumulativeAsk;
}
/// @notice user sell a certain amount of fromToken, get toToken
function sellToken(
address to,
address fromToken,
address toToken,
uint256 fromAmount,
uint256 minReceiveAmount,
bytes calldata data
) external poolOngoing nonReentrant returns (uint256) {
require(ID3Maker(state._MAKER_).checkHeartbeat(), Errors.HEARTBEAT_CHECK_FAIL);
_updateCumulative(fromToken);
_updateCumulative(toToken);
(uint256 payFromAmount, uint256 receiveToAmount, uint256 vusdAmount, uint256 swapFee, uint256 mtFee) =
querySellTokens(fromToken, toToken, fromAmount);
require(receiveToAmount >= minReceiveAmount, Errors.MINRES_NOT_ENOUGH);
_transferOut(to, toToken, receiveToAmount);
// external call & swap callback
IDODOSwapCallback(msg.sender).d3MMSwapCallBack(fromToken, fromAmount, data);
// transfer mtFee to maintainer
_transferOut(state._MAINTAINER_, toToken, mtFee);
require(
IERC20(fromToken).balanceOf(address(this)) - state.balances[fromToken] >= fromAmount,
Errors.FROMAMOUNT_NOT_ENOUGH
);
// record swap
_recordSwap(fromToken, toToken, vusdAmount, receiveToAmount + swapFee);
require(checkSafe(), Errors.BELOW_IM_RATIO);
emit Swap(to, fromToken, toToken, payFromAmount, receiveToAmount, swapFee, mtFee, 0);
return receiveToAmount;
}
/// @notice user ask for a certain amount of toToken, fromToken's amount will be determined by toToken's amount
function buyToken(
address to,
address fromToken,
address toToken,
uint256 quoteAmount,
uint256 maxPayAmount,
bytes calldata data
) external poolOngoing nonReentrant returns (uint256) {
require(ID3Maker(state._MAKER_).checkHeartbeat(), Errors.HEARTBEAT_CHECK_FAIL);
_updateCumulative(fromToken);
_updateCumulative(toToken);
// query amount and transfer out
(uint256 payFromAmount, uint256 receiveToAmount, uint256 vusdAmount, uint256 swapFee, uint256 mtFee) =
queryBuyTokens(fromToken, toToken, quoteAmount);
require(payFromAmount <= maxPayAmount, Errors.MAXPAY_NOT_ENOUGH);
_transferOut(to, toToken, receiveToAmount);
// external call & swap callback
IDODOSwapCallback(msg.sender).d3MMSwapCallBack(fromToken, payFromAmount, data);
// transfer mtFee to maintainer
_transferOut(state._MAINTAINER_, toToken, mtFee);
require(
IERC20(fromToken).balanceOf(address(this)) - state.balances[fromToken] >= payFromAmount,
Errors.FROMAMOUNT_NOT_ENOUGH
);
// record swap
_recordSwap(fromToken, toToken, vusdAmount, receiveToAmount + swapFee);
require(checkSafe(), Errors.BELOW_IM_RATIO);
emit Swap(to, fromToken, toToken, payFromAmount, receiveToAmount, swapFee, mtFee, 1);
return payFromAmount;
}
/// @notice user could query sellToken result deducted swapFee, assign fromAmount
/// @return payFromAmount fromToken's amount = fromAmount
/// @return receiveToAmount toToken's amount
/// @return vusdAmount fromToken bid vusd
/// @return swapFee dodo takes the fee
function querySellTokens(
address fromToken,
address toToken,
uint256 fromAmount
) public view returns (uint256 payFromAmount, uint256 receiveToAmount, uint256 vusdAmount, uint256 swapFee, uint256 mtFee) {
require(fromAmount > 1000, Errors.AMOUNT_TOO_SMALL);
Types.RangeOrderState memory D3State = getRangeOrderState(fromToken, toToken);
(payFromAmount, receiveToAmount, vusdAmount) =
PMMRangeOrder.querySellTokens(D3State, fromToken, toToken, fromAmount);
receiveToAmount = receiveToAmount > state.balances[toToken] ? state.balances[toToken] : receiveToAmount;
uint256 swapFeeRate = D3State.fromTokenMMInfo.swapFeeRate + D3State.toTokenMMInfo.swapFeeRate;
swapFee = DecimalMath.mulFloor(receiveToAmount, swapFeeRate);
uint256 mtFeeRate = D3State.fromTokenMMInfo.mtFeeRate + D3State.toTokenMMInfo.mtFeeRate;
mtFee = DecimalMath.mulFloor(receiveToAmount, mtFeeRate);
return (payFromAmount, receiveToAmount - swapFee, vusdAmount, swapFee, mtFee);
}
/// @notice user could query sellToken result deducted swapFee, assign toAmount
/// @return payFromAmount fromToken's amount
/// @return receiveToAmount toToken's amount = toAmount
/// @return vusdAmount fromToken bid vusd
/// @return swapFee dodo takes the fee
function queryBuyTokens(
address fromToken,
address toToken,
uint256 toAmount
) public view returns (uint256 payFromAmount, uint256 receiveToAmount, uint256 vusdAmount, uint256 swapFee, uint256 mtFee) {
require(toAmount > 1000, Errors.AMOUNT_TOO_SMALL);
Types.RangeOrderState memory D3State = getRangeOrderState(fromToken, toToken);
// query amount and transfer out
{
uint256 swapFeeRate = D3State.fromTokenMMInfo.swapFeeRate + D3State.toTokenMMInfo.swapFeeRate;
swapFee = DecimalMath.mulFloor(toAmount, swapFeeRate);
uint256 mtFeeRate = D3State.fromTokenMMInfo.mtFeeRate + D3State.toTokenMMInfo.mtFeeRate;
mtFee = DecimalMath.mulFloor(toAmount, mtFeeRate);
toAmount += swapFee;
}
require(toAmount <= state.balances[toToken], Errors.BALANCE_NOT_ENOUGH);
uint256 receiveToAmountWithFee;
(payFromAmount, receiveToAmountWithFee , vusdAmount) =
PMMRangeOrder.queryBuyTokens(D3State, fromToken, toToken, toAmount);
return (payFromAmount, receiveToAmountWithFee - swapFee, vusdAmount, swapFee, mtFee);
}
// ================ internal ==========================
function _recordSwap(address fromToken, address toToken, uint256 fromAmount, uint256 toAmount) internal {
tokenCumMap[fromToken].cumulativeBid += fromAmount;
tokenCumMap[toToken].cumulativeAsk += toAmount;
_updateReserve(fromToken);
_updateReserve(toToken);
}
function _updateCumulative(address token) internal {
uint256 tokenIndex = ID3Maker(state._MAKER_).getOneTokenOriginIndex(token);
uint256 tokenFlag = (allFlag >> tokenIndex) & 1;
if (tokenFlag == 0) {
tokenCumMap[token].cumulativeAsk = 0;
tokenCumMap[token].cumulativeBid = 0;
allFlag |= (1 << tokenIndex);
}
}
function _transferOut(address to, address token, uint256 amount) internal {
IERC20(token).safeTransfer(to, amount);
}
// ================ call by maker ==========================
function setNewAllFlag(uint256 newFlag) external onlyMaker {
allFlag = newFlag;
}
}