-
Notifications
You must be signed in to change notification settings - Fork 162
Expand file tree
/
Copy pathsolution.rs
More file actions
384 lines (370 loc) · 19.5 KB
/
solution.rs
File metadata and controls
384 lines (370 loc) · 19.5 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
use {
crate::{
domain::{
self,
competition::{self},
liquidity,
},
infra::Solver,
},
alloy::primitives::Bytes,
app_data::AppDataHash,
eth_domain_types as eth,
itertools::Itertools,
model::{
DomainSeparator,
order::{BuyTokenDestination, OrderData, OrderKind, SellTokenSource},
},
simulator::encoding::WrapperCall,
std::{collections::HashMap, str::FromStr},
};
#[derive(derive_more::From)]
pub struct Solutions(Vec<solvers_dto::solution::Solution>);
impl Solutions {
const MAX_BASE_POINT: u32 = 10000;
pub fn into_domain(
self,
auction: &competition::Auction,
liquidity: &[liquidity::Liquidity],
weth: eth::WrappedNativeToken,
solver: Solver,
flashloan_hints: &HashMap<competition::order::Uid, domain::flashloan::Flashloan>,
) -> Result<Vec<competition::Solution>, super::Error> {
let haircut_bps = solver.haircut_bps();
self.0
.into_iter()
.map(|solution| {
competition::Solution::new(
competition::solution::Id::new(solution.id),
solution
.trades
.iter()
.map(|trade| match trade {
solvers_dto::solution::Trade::Fulfillment(fulfillment) => {
let order = auction
.orders()
.iter()
.find(|order| order.uid == fulfillment.order.0)
// TODO this error should reference the UID
.ok_or(super::Error(
"invalid order UID specified in fulfillment".to_owned(),
))?
.clone();
// Calculate haircut fee for conservative bidding.
// This reduces reported surplus without affecting executed amounts.
let haircut_fee = if haircut_bps > 0 {
eth::U256::from(fulfillment.executed_amount)
.checked_mul(eth::U256::from(haircut_bps))
.and_then(|v| {
v.checked_div(eth::U256::from(Self::MAX_BASE_POINT))
})
.unwrap_or_default()
} else {
Default::default()
};
competition::solution::trade::Fulfillment::new(
order,
fulfillment.executed_amount.into(),
match fulfillment.fee {
Some(fee) => competition::solution::trade::Fee::Dynamic(
competition::order::SellAmount(fee),
),
None => competition::solution::trade::Fee::Static,
},
haircut_fee,
)
.map(competition::solution::Trade::Fulfillment)
.map_err(|err| super::Error(format!("invalid fulfillment: {err}")))
}
solvers_dto::solution::Trade::Jit(jit) => {
let jit_order: JitOrder = jit.order.clone().into();
Ok(competition::solution::Trade::Jit(
competition::solution::trade::Jit::new(
competition::order::Jit {
uid: jit_order.uid(
solver.eth.contracts().settlement_domain_separator(),
)?,
sell: eth::Asset {
amount: jit_order.0.sell_amount.into(),
token: jit_order.0.sell_token.into(),
},
buy: eth::Asset {
amount: jit_order.0.buy_amount.into(),
token: jit_order.0.buy_token.into(),
},
receiver: jit_order.0.receiver,
partially_fillable: jit_order.0.partially_fillable,
valid_to: jit_order.0.valid_to.into(),
app_data: jit_order.0.app_data.into(),
side: match jit_order.0.kind {
solvers_dto::solution::Kind::Sell => {
competition::order::Side::Sell
}
solvers_dto::solution::Kind::Buy => {
competition::order::Side::Buy
}
},
sell_token_balance: match jit_order.0.sell_token_balance {
solvers_dto::solution::SellTokenBalance::Erc20 => {
competition::order::SellTokenBalance::Erc20
}
solvers_dto::solution::SellTokenBalance::Internal => {
competition::order::SellTokenBalance::Internal
}
solvers_dto::solution::SellTokenBalance::External => {
competition::order::SellTokenBalance::External
}
},
buy_token_balance: match jit_order.0.buy_token_balance {
solvers_dto::solution::BuyTokenBalance::Erc20 => {
competition::order::BuyTokenBalance::Erc20
}
solvers_dto::solution::BuyTokenBalance::Internal => {
competition::order::BuyTokenBalance::Internal
}
},
signature: jit_order.signature(
solver.eth.contracts().settlement_domain_separator(),
)?,
},
jit.executed_amount.into(),
jit.fee.unwrap_or_default().into(),
)
.map_err(|err| super::Error(format!("invalid JIT trade: {err}")))?,
))
}
})
.try_collect()?,
solution
.prices
.into_iter()
.map(|(address, price)| (address.into(), price))
.collect(),
solution
.pre_interactions
.into_iter()
.map(|interaction| domain::Interaction {
target: interaction.target,
value: interaction.value.into(),
call_data: Bytes::from(interaction.calldata),
})
.collect(),
solution
.interactions
.into_iter()
.map(|interaction| match interaction {
solvers_dto::solution::Interaction::Custom(interaction) => {
Ok(competition::solution::Interaction::Custom(
competition::solution::interaction::Custom {
target: interaction.target.into(),
value: interaction.value.into(),
call_data: interaction.calldata.into(),
allowances: interaction
.allowances
.into_iter()
.map(|allowance| {
eth::Allowance {
token: allowance.token.into(),
spender: allowance.spender,
amount: allowance.amount,
}
.into()
})
.collect(),
inputs: interaction
.inputs
.into_iter()
.map(|input| eth::Asset {
amount: input.amount.into(),
token: input.token.into(),
})
.collect(),
outputs: interaction
.outputs
.into_iter()
.map(|input| eth::Asset {
amount: input.amount.into(),
token: input.token.into(),
})
.collect(),
internalize: interaction.internalize,
},
))
}
solvers_dto::solution::Interaction::Liquidity(interaction) => {
let liquidity_id = usize::from_str(&interaction.id).map_err(|_| super::Error("invalid liquidity ID format".to_owned()))?;
let liquidity = liquidity
.iter()
.find(|liquidity| liquidity.id == liquidity_id)
.ok_or(super::Error(
"invalid liquidity ID specified in interaction".to_owned(),
))?
.to_owned();
Ok(competition::solution::Interaction::Liquidity(
competition::solution::interaction::Liquidity {
liquidity,
input: eth::Asset {
amount: interaction.input_amount.into(),
token: interaction.input_token.into(),
},
output: eth::Asset {
amount: interaction.output_amount.into(),
token: interaction.output_token.into(),
},
internalize: interaction.internalize,
},
))
}
})
.try_collect()?,
solution
.post_interactions
.into_iter()
.map(|interaction| domain::Interaction {
target: interaction.target,
value: interaction.value.into(),
call_data: interaction.calldata.into(),
})
.collect(),
solver.clone(),
weth,
solution.gas.map(eth::Gas::from),
solution
.gas_fee_override
.map(|o| {
Ok(competition::solution::GasFeeOverride {
max_fee_per_gas: o.max_fee_per_gas.try_into().map_err(|_| {
super::Error("max_fee_per_gas overflow".to_owned())
})?,
max_priority_fee_per_gas: o
.max_priority_fee_per_gas
.try_into()
.map_err(|_| {
super::Error(
"max_priority_fee_per_gas overflow".to_owned(),
)
})?,
})
})
.transpose()?,
solver.config().fee_handler,
auction.surplus_capturing_jit_order_owners(),
solution.flashloans
// convert the flashloan info provided by the solver
.map(|f| f.iter().map(|(order, loan)| (order.into(), loan.clone())).collect())
// or copy over the relevant flashloan hints from the solve request
.unwrap_or_else(|| solution.trades.iter()
.filter_map(|t| {
let solvers_dto::solution::Trade::Fulfillment(trade) = &t else {
// we don't have any flashloan data on JIT orders
return None;
};
let uid = competition::order::Uid::from(&trade.order);
Some((
uid,
flashloan_hints.get(&uid)?.into(),
))
}).collect()),
solution.wrappers.iter().cloned().map(|w| WrapperCall {
address: w.address,
data: w.data.into(),
}).collect(),
)
.map_err(|err| match err {
competition::solution::error::Solution::InvalidClearingPrices => {
super::Error("invalid clearing prices".to_owned())
}
competition::solution::error::Solution::ProtocolFee(err) => {
super::Error(format!("could not incorporate protocol fee: {err}"))
}
competition::solution::error::Solution::InvalidJitTrade(err) => {
super::Error(format!("invalid jit trade: {err}"))
}
})
})
.collect()
}
}
#[derive(derive_more::From)]
pub struct JitOrder(solvers_dto::solution::JitOrder);
impl JitOrder {
fn raw_order_data(&self) -> OrderData {
OrderData {
sell_token: self.0.sell_token,
buy_token: self.0.buy_token,
receiver: Some(self.0.receiver),
sell_amount: self.0.sell_amount,
buy_amount: self.0.buy_amount,
valid_to: self.0.valid_to,
app_data: AppDataHash(self.0.app_data),
fee_amount: alloy::primitives::U256::ZERO,
kind: match self.0.kind {
solvers_dto::solution::Kind::Sell => OrderKind::Sell,
solvers_dto::solution::Kind::Buy => OrderKind::Buy,
},
partially_fillable: self.0.partially_fillable,
sell_token_balance: match self.0.sell_token_balance {
solvers_dto::solution::SellTokenBalance::Erc20 => SellTokenSource::Erc20,
solvers_dto::solution::SellTokenBalance::Internal => SellTokenSource::Internal,
solvers_dto::solution::SellTokenBalance::External => SellTokenSource::External,
},
buy_token_balance: match self.0.buy_token_balance {
solvers_dto::solution::BuyTokenBalance::Erc20 => BuyTokenDestination::Erc20,
solvers_dto::solution::BuyTokenBalance::Internal => BuyTokenDestination::Internal,
},
}
}
fn signature(
&self,
domain_separator: ð::DomainSeparator,
) -> Result<competition::order::Signature, super::Error> {
let mut signature = competition::order::Signature {
scheme: match self.0.signing_scheme {
solvers_dto::solution::SigningScheme::Eip712 => {
competition::order::signature::Scheme::Eip712
}
solvers_dto::solution::SigningScheme::EthSign => {
competition::order::signature::Scheme::EthSign
}
solvers_dto::solution::SigningScheme::PreSign => {
competition::order::signature::Scheme::PreSign
}
solvers_dto::solution::SigningScheme::Eip1271 => {
competition::order::signature::Scheme::Eip1271
}
},
data: self.0.signature.clone().into(),
signer: Default::default(),
};
let signer = signature
.to_boundary_signature()
.and_then(|sig| {
sig.recover_owner(
self.0.signature.as_slice(),
&DomainSeparator(domain_separator.0),
&self.raw_order_data().hash_struct(),
)
})
.map_err(|e| super::Error(e.to_string()))?;
if matches!(
self.0.signing_scheme,
solvers_dto::solution::SigningScheme::Eip1271
) {
// For EIP-1271 signatures the encoding logic prepends the signer to the raw
// signature bytes. This leads to the owner being encoded twice in
// the final settlement calldata unless we remove that from the raw
// data.
signature.data = Bytes::copy_from_slice(&self.0.signature[20..]);
}
signature.signer = signer;
Ok(signature)
}
fn uid(&self, domain: ð::DomainSeparator) -> Result<competition::order::Uid, super::Error> {
let order_data = self.raw_order_data();
let signature = self.signature(domain)?;
Ok(order_data
.uid(&DomainSeparator(domain.0), signature.signer)
.0
.into())
}
}