-
Notifications
You must be signed in to change notification settings - Fork 65
/
twap-order.mapper.ts
261 lines (230 loc) · 8.34 KB
/
twap-order.mapper.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
import { Inject, Injectable, Module } from '@nestjs/common';
import { TokenInfo } from '@/routes/transactions/entities/swaps/token-info.entity';
import {
SwapOrderHelper,
SwapOrderHelperModule,
} from '@/routes/transactions/helpers/swap-order.helper';
import { ComposableCowDecoder } from '@/domain/swaps/contracts/decoders/composable-cow-decoder.helper';
import {
TwapOrderInfo,
TwapOrderTransactionInfo,
} from '@/routes/transactions/entities/swaps/twap-order-info.entity';
import {
TwapOrderHelper,
TwapOrderHelperModule,
} from '@/routes/transactions/helpers/twap-order.helper';
import {
KnownOrder,
OrderKind,
OrderStatus,
} from '@/domain/swaps/entities/order.entity';
import { ISwapsRepository } from '@/domain/swaps/swaps.repository';
import { SwapsRepositoryModule } from '@/domain/swaps/swaps-repository.module';
import { SwapOrderMapperModule } from '@/routes/transactions/mappers/common/swap-order.mapper';
import { GPv2OrderHelper } from '@/routes/transactions/helpers/gp-v2-order.helper';
import { IConfigurationService } from '@/config/configuration.service.interface';
import { ILoggingService, LoggingService } from '@/logging/logging.interface';
import {
SwapAppsHelper,
SwapAppsHelperModule,
} from '@/routes/transactions/helpers/swap-apps.helper';
@Injectable()
export class TwapOrderMapper {
private maxNumberOfParts: number;
constructor(
@Inject(IConfigurationService)
private readonly configurationService: IConfigurationService,
@Inject(LoggingService) private readonly loggingService: ILoggingService,
private readonly swapOrderHelper: SwapOrderHelper,
@Inject(ISwapsRepository)
private readonly swapsRepository: ISwapsRepository,
private readonly composableCowDecoder: ComposableCowDecoder,
private readonly gpv2OrderHelper: GPv2OrderHelper,
private readonly twapOrderHelper: TwapOrderHelper,
private readonly swapAppsHelper: SwapAppsHelper,
) {
this.maxNumberOfParts = this.configurationService.getOrThrow(
'swaps.maxNumberOfParts',
);
}
/**
* Maps a TWAP order from a given transaction
*
* @param chainId - chain the order is on
* @param safeAddress - "owner" of the order
* @param transaction - transaction data and execution date
* @returns mapped {@link TwapOrderTransactionInfo}
*/
async mapTwapOrder(
chainId: string,
safeAddress: `0x${string}`,
transaction: { data: `0x${string}`; executionDate: Date | null },
): Promise<TwapOrderTransactionInfo> {
// Decode `staticInput` of `createWithContextCall`
const twapStruct = this.composableCowDecoder.decodeTwapStruct(
transaction.data,
);
const twapOrderData =
this.twapOrderHelper.twapStructToPartialOrderInfo(twapStruct);
// Generate parts of the TWAP order
const twapParts = this.twapOrderHelper.generateTwapOrderParts({
twapStruct,
executionDate: transaction.executionDate ?? new Date(),
chainId,
});
const fullAppData = await this.swapsRepository.getFullAppData(
chainId,
twapStruct.appData,
);
if (!this.swapAppsHelper.isAppAllowed(fullAppData)) {
throw new Error(`Unsupported App: ${fullAppData.fullAppData?.appCode}`);
}
// There can be up to uint256 parts in a TWAP order so we limit this
// to avoid requesting too many orders
const hasAbundantParts = twapParts.length > this.maxNumberOfParts;
// Fetch all order parts if the transaction has been executed, otherwise none
const partsToFetch = transaction.executionDate
? hasAbundantParts
? // We use the last part (and only one) to get the status of the entire
// order and we only need one to get the token info
twapParts.slice(-1)
: twapParts
: [];
const orders: Array<KnownOrder> = [];
for (const part of partsToFetch) {
const partFullAppData = await this.swapsRepository.getFullAppData(
chainId,
part.appData,
);
if (!this.swapAppsHelper.isAppAllowed(partFullAppData)) {
throw new Error(
`Unsupported App: ${partFullAppData.fullAppData?.appCode}`,
);
}
const orderUid = this.gpv2OrderHelper.computeOrderUid({
chainId,
owner: safeAddress,
order: part,
});
const order = await this.swapsRepository
.getOrder(chainId, orderUid)
.catch(() => {
this.loggingService.warn(
`Error getting orderUid ${orderUid} from SwapsRepository`,
);
});
if (!order || order.kind == OrderKind.Unknown) {
continue;
}
if (!this.swapAppsHelper.isAppAllowed(order)) {
throw new Error(`Unsupported App: ${order.fullAppData?.appCode}`);
}
orders.push(order as KnownOrder);
}
const executedSellAmount: TwapOrderInfo['executedSellAmount'] =
hasAbundantParts ? null : this.getExecutedSellAmount(orders).toString();
const executedBuyAmount: TwapOrderInfo['executedBuyAmount'] =
hasAbundantParts ? null : this.getExecutedBuyAmount(orders).toString();
const executedSurplusFee: TwapOrderInfo['executedSurplusFee'] =
hasAbundantParts ? null : this.getExecutedSurplusFee(orders).toString();
const [sellToken, buyToken] = await Promise.all([
this.swapOrderHelper.getToken({
chainId,
address: twapStruct.sellToken,
}),
this.swapOrderHelper.getToken({
chainId,
address: twapStruct.buyToken,
}),
]);
return new TwapOrderTransactionInfo({
status: this.getOrderStatus(orders),
kind: twapOrderData.kind,
class: twapOrderData.class,
validUntil: Math.max(...twapParts.map((order) => order.validTo)),
sellAmount: twapOrderData.sellAmount,
buyAmount: twapOrderData.buyAmount,
executedSellAmount,
executedBuyAmount,
executedSurplusFee,
sellToken: new TokenInfo({
address: sellToken.address,
decimals: sellToken.decimals,
logoUri: sellToken.logoUri,
name: sellToken.name,
symbol: sellToken.symbol,
trusted: sellToken.trusted,
}),
buyToken: new TokenInfo({
address: buyToken.address,
decimals: buyToken.decimals,
logoUri: buyToken.logoUri,
name: buyToken.name,
symbol: buyToken.symbol,
trusted: buyToken.trusted,
}),
receiver: twapStruct.receiver,
owner: safeAddress,
fullAppData: fullAppData.fullAppData,
numberOfParts: twapOrderData.numberOfParts,
partSellAmount: twapStruct.partSellAmount.toString(),
minPartLimit: twapStruct.minPartLimit.toString(),
timeBetweenParts: twapOrderData.timeBetweenParts,
durationOfPart: twapOrderData.durationOfPart,
startTime: twapOrderData.startTime,
});
}
private getOrderStatus(
orders: Array<Awaited<ReturnType<typeof this.swapOrderHelper.getOrder>>>,
): OrderStatus {
if (orders.length === 0) {
return OrderStatus.PreSignaturePending;
}
// If an order is fulfilled, cancelled or expired, the part is "complete"
const completeStatuses = [
OrderStatus.Fulfilled,
OrderStatus.Cancelled,
OrderStatus.Expired,
];
for (let i = 0; i < orders.length; i++) {
const order = orders[i];
// Return the status of the last part
if (i === orders.length - 1) {
return order.status;
}
// If the part is complete, continue to the next part
if (completeStatuses.includes(order.status)) {
continue;
}
return order.status;
}
return OrderStatus.Unknown;
}
private getExecutedSellAmount(orders: Array<KnownOrder>): bigint {
return orders.reduce((acc, order) => {
return acc + BigInt(order.executedSellAmount);
}, BigInt(0));
}
private getExecutedBuyAmount(orders: Array<KnownOrder>): bigint {
return orders.reduce((acc, order) => {
return acc + BigInt(order.executedBuyAmount);
}, BigInt(0));
}
private getExecutedSurplusFee(orders: Array<KnownOrder>): bigint {
return orders.reduce((acc, order) => {
return acc + BigInt(order.executedSurplusFee ?? BigInt(0));
}, BigInt(0));
}
}
@Module({
imports: [
SwapOrderHelperModule,
SwapsRepositoryModule,
SwapOrderMapperModule,
TwapOrderHelperModule,
SwapAppsHelperModule,
],
providers: [ComposableCowDecoder, GPv2OrderHelper, TwapOrderMapper],
exports: [TwapOrderMapper],
})
export class TwapOrderMapperModule {}