-
Notifications
You must be signed in to change notification settings - Fork 13
/
auctions.ts
270 lines (249 loc) · 10.4 KB
/
auctions.ts
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
import type { Auction, AuctionInitialInfo, AuctionTransaction, Notifier, TakeEvent } from './types';
import BigNumber from './bignumber';
import fetchAuctionsByCollateralType, {
fetchAuctionByCollateralTypeAndAuctionIndex,
fetchAuctionStatus,
fetchMinimumBidDai,
} from './fetch';
import { getCalleeData, getMarketPrice } from './calleeFunctions';
import { fetchCalcParametersByCollateralType } from './params';
import executeTransaction from './execute';
import { RAY_NUMBER_OF_DIGITS, WAD_NUMBER_OF_DIGITS, NULL_BYTES } from './constants/UNITS';
import { getCalleeAddressByCollateralType } from './constants/CALLEES';
import {
calculateAuctionDropTime,
calculateAuctionPrice,
calculateTransactionGrossProfit,
calculateTransactionGrossProfitDate,
calculateTransactionCollateralOutcome,
} from './price';
import { getSupportedCollateralTypes } from './addresses';
import getContract, { getClipperNameByCollateralType } from './contracts';
import convertNumberTo32Bytes from './helpers/convertNumberTo32Bytes';
import { enrichAuctionWithTransactionFees, getApproximateTransactionFees } from './fees';
import parseAuctionId from './helpers/parseAuctionId';
import { EventFilter } from 'ethers';
import getNetworkDate, { fetchDateByBlockNumber } from './date';
const enrichAuctionWithActualNumbers = async function (
network: string,
auction: AuctionInitialInfo
): Promise<Auction> {
const defaultAcution = {
...auction,
minimumBidDai: new BigNumber(0),
unitPrice: new BigNumber(0),
approximateUnitPrice: new BigNumber(0),
totalPrice: new BigNumber(0),
collateralToCoverDebt: new BigNumber(NaN),
};
if (!auction.isActive || auction.isFinished) {
return defaultAcution;
}
const auctionStatus = await fetchAuctionStatus(network, auction.collateralType, auction.index);
const minimumBidDai = await fetchMinimumBidDai(network, auction.collateralType);
return {
...defaultAcution,
...auctionStatus,
minimumBidDai,
approximateUnitPrice: auctionStatus.unitPrice,
};
};
const calculateCollateralToCoverDebt = async function (network: string, auction: Auction): Promise<BigNumber> {
const collateralToCoverDebt = calculateTransactionCollateralOutcome(
auction.debtDAI,
auction.approximateUnitPrice,
auction
);
if (!collateralToCoverDebt.isNaN()) {
return collateralToCoverDebt;
}
const marketPriceForAllCollateral = await getMarketPrice(
network,
auction.collateralSymbol,
auction.collateralAmount
);
return auction.debtDAI.dividedBy(marketPriceForAllCollateral);
};
const enrichAuctionWithMarketValues = async function (auction: Auction, network: string): Promise<Auction> {
if (!auction.isActive || !auction.approximateUnitPrice || auction.isFinished) {
return auction;
}
try {
const collateralToCoverDebt = await calculateCollateralToCoverDebt(network, auction);
const marketUnitPrice = await getMarketPrice(network, auction.collateralSymbol, collateralToCoverDebt);
const marketUnitPriceToUnitPriceRatio = auction.approximateUnitPrice
.minus(marketUnitPrice)
.dividedBy(marketUnitPrice);
const auctionWithMarketValues = {
...auction,
collateralToCoverDebt,
marketUnitPrice,
marketUnitPriceToUnitPriceRatio,
};
const transactionGrossProfit = calculateTransactionGrossProfit(auctionWithMarketValues);
return {
...auctionWithMarketValues,
transactionGrossProfit,
};
} catch (error) {
// since it's expected that some collaterals are not tradable on some networks
// we should just ignore this error
return auction;
}
};
export const enrichAuctionWithPriceDrop = async function (auction: Auction): Promise<Auction> {
if (!auction.isActive || auction.isFinished) {
return auction;
}
try {
const params = await fetchCalcParametersByCollateralType(auction.network, auction.collateralType);
const auctionWithParams = {
...auction,
secondsBetweenPriceDrops: params.secondsBetweenPriceDrops,
priceDropRatio: params.priceDropRatio,
};
const currentDate = await getNetworkDate(auction.network);
const secondsTillNextPriceDrop = calculateAuctionDropTime(auctionWithParams, currentDate);
const approximateUnitPrice = calculateAuctionPrice(auctionWithParams, currentDate);
const totalPrice = auction.collateralAmount.multipliedBy(approximateUnitPrice);
const transactionGrossProfitDate = calculateTransactionGrossProfitDate(auctionWithParams, currentDate);
return {
...auctionWithParams,
secondsTillNextPriceDrop,
approximateUnitPrice,
totalPrice,
transactionGrossProfitDate,
};
} catch (error) {
return {
...auction,
totalPrice: auction.collateralAmount.multipliedBy(auction.unitPrice),
};
}
};
export const enrichAuctionWithPriceDropAndMarketValue = async function (
auction: Auction,
network: string
): Promise<Auction> {
const enrichedAuctionWithNewPriceDrop = await enrichAuctionWithPriceDrop(auction);
return await enrichAuctionWithMarketValues(enrichedAuctionWithNewPriceDrop, network);
};
export const fetchSingleAuctionById = async function (
network: string,
auctionId: string
): Promise<AuctionTransaction> {
const { collateralType, index } = parseAuctionId(auctionId);
const auction = await fetchAuctionByCollateralTypeAndAuctionIndex(network, collateralType, index);
return enrichAuction(network, auction);
};
export const fetchAllInitialAuctions = async function (
network: string,
collateralTypes?: string[]
): Promise<AuctionInitialInfo[]> {
if (!collateralTypes) {
collateralTypes = await getSupportedCollateralTypes(network);
}
const auctionGroupsPromises = collateralTypes.map((collateralType: string) => {
return fetchAuctionsByCollateralType(network, collateralType);
});
const auctionGroups = await Promise.all(auctionGroupsPromises);
return auctionGroups.flat();
};
export const fetchAllAuctions = async function (network: string): Promise<AuctionTransaction[]> {
const auctions = await fetchAllInitialAuctions(network);
return await Promise.all(auctions.map(a => enrichAuction(network, a)));
};
export const enrichAuction = async function (
network: string,
auction: AuctionInitialInfo
): Promise<AuctionTransaction> {
// enrich them with statuses
const auctionWithStatus = await enrichAuctionWithActualNumbers(network, auction);
// enrich them with price drop
const auctionWithPriceDrop = await enrichAuctionWithPriceDrop(auctionWithStatus);
// enrich them with market values
const auctionWithMarketValue = await enrichAuctionWithMarketValues(auctionWithPriceDrop, network);
// enrich with profit and fee calculation
const fees = await getApproximateTransactionFees(network);
const auctionWithFees = await enrichAuctionWithTransactionFees(auctionWithMarketValue, fees, network);
if (auction.debtDAI.isEqualTo(0)) {
return {
...auctionWithFees,
isFinished: true,
isActive: false,
};
}
return auctionWithFees;
};
const enrichTakeEventWithDate = async function (network: string, takeEvent: TakeEvent): Promise<TakeEvent> {
const date = await fetchDateByBlockNumber(network, takeEvent.blockNumber);
return {
...takeEvent,
transactionDate: date,
};
};
export const fetchTakeEvents = async function (network: string, auctionId: string): Promise<Array<TakeEvent>> {
const { collateralType, index } = parseAuctionId(auctionId);
const encodedAuctionIndex = convertNumberTo32Bytes(index);
const contractName = getClipperNameByCollateralType(collateralType);
const contract = await getContract(network, contractName);
const eventFilters: EventFilter = contract.filters.Take(encodedAuctionIndex);
const events = await contract.queryFilter(eventFilters);
return await Promise.all(
events.map(event =>
enrichTakeEventWithDate(network, {
transactionHash: event.transactionHash,
blockNumber: event.blockNumber,
})
)
);
};
export const restartAuction = async function (
network: string,
auction: Auction,
profitAddress: string,
notifier?: Notifier
): Promise<string> {
const contractName = getClipperNameByCollateralType(auction.collateralType);
return executeTransaction(network, contractName, 'redo', [auction.index, profitAddress], {
notifier,
confirmTransaction: false,
});
};
export const bidWithDai = async function (
network: string,
auction: AuctionTransaction,
bidAmountDai: BigNumber,
profitAddress: string,
notifier?: Notifier
): Promise<string> {
const contractName = getClipperNameByCollateralType(auction.collateralType);
const updatedAuction = await enrichAuctionWithActualNumbers(network, auction);
const collateralAmount = calculateTransactionCollateralOutcome(bidAmountDai, updatedAuction.unitPrice, auction);
const contractParameters = [
convertNumberTo32Bytes(auction.index),
collateralAmount.shiftedBy(WAD_NUMBER_OF_DIGITS).toFixed(0),
updatedAuction.unitPrice.shiftedBy(RAY_NUMBER_OF_DIGITS).toFixed(0),
profitAddress,
NULL_BYTES,
];
return executeTransaction(network, contractName, 'take', contractParameters, { notifier });
};
export const bidWithCallee = async function (
network: string,
auction: Auction,
profitAddress: string,
notifier?: Notifier
): Promise<string> {
const calleeAddress = getCalleeAddressByCollateralType(network, auction.collateralType);
const calleeData = await getCalleeData(network, auction.collateralType, profitAddress);
const contractName = getClipperNameByCollateralType(auction.collateralType);
const contractParameters = [
convertNumberTo32Bytes(auction.index),
auction.collateralAmount.shiftedBy(WAD_NUMBER_OF_DIGITS).toFixed(0),
auction.unitPrice.shiftedBy(RAY_NUMBER_OF_DIGITS).toFixed(0),
calleeAddress,
calleeData,
];
return executeTransaction(network, contractName, 'take', contractParameters, { notifier });
};