Skip to content

Commit de5abf8

Browse files
authored
Migrate settlement part 2 (#3834)
# Description Follow up to #3830 completely migrating the settlement contract to alloy
1 parent 66b4aa0 commit de5abf8

File tree

20 files changed

+277
-399
lines changed

20 files changed

+277
-399
lines changed

crates/autopilot/src/boundary/events/settlement.rs

Lines changed: 31 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,36 @@
11
use {
22
crate::{database::Postgres, domain::settlement},
3+
alloy::{
4+
primitives::Address,
5+
rpc::types::{Filter, Log},
6+
},
37
anyhow::Result,
4-
ethrpc::block_stream::RangeInclusive,
5-
shared::{event_handling::EventStoring, impl_event_retrieving},
8+
contracts::alloy::GPv2Settlement::GPv2Settlement::GPv2SettlementEvents,
9+
ethrpc::{AlloyProvider, block_stream::RangeInclusive},
10+
shared::event_handling::{AlloyEventRetrieving, EventStoring},
611
};
712

8-
impl_event_retrieving! {
9-
pub GPv2SettlementContract for contracts::gpv2_settlement
13+
pub struct GPv2SettlementContract {
14+
provider: AlloyProvider,
15+
address: Address,
16+
}
17+
18+
impl GPv2SettlementContract {
19+
pub fn new(provider: AlloyProvider, address: Address) -> Self {
20+
Self { provider, address }
21+
}
22+
}
23+
24+
impl AlloyEventRetrieving for GPv2SettlementContract {
25+
type Event = GPv2SettlementEvents;
26+
27+
fn filter(&self) -> alloy::rpc::types::Filter {
28+
Filter::new().address(self.address)
29+
}
30+
31+
fn provider(&self) -> &contracts::alloy::Provider {
32+
&self.provider
33+
}
1034
}
1135

1236
pub struct Indexer {
@@ -29,7 +53,7 @@ impl Indexer {
2953
pub(crate) const INDEX_NAME: &str = "settlements";
3054

3155
#[async_trait::async_trait]
32-
impl EventStoring<ethcontract::Event<contracts::gpv2_settlement::Event>> for Indexer {
56+
impl EventStoring<(GPv2SettlementEvents, Log)> for Indexer {
3357
async fn last_event_block(&self) -> Result<u64> {
3458
super::read_last_block_from_db(&self.db.pool, INDEX_NAME)
3559
.await
@@ -42,7 +66,7 @@ impl EventStoring<ethcontract::Event<contracts::gpv2_settlement::Event>> for Ind
4266

4367
async fn replace_events(
4468
&mut self,
45-
events: Vec<ethcontract::Event<contracts::gpv2_settlement::Event>>,
69+
events: Vec<(GPv2SettlementEvents, Log)>,
4670
range: RangeInclusive<u64>,
4771
) -> Result<()> {
4872
let mut transaction = self.db.pool.begin().await?;
@@ -55,10 +79,7 @@ impl EventStoring<ethcontract::Event<contracts::gpv2_settlement::Event>> for Ind
5579
Ok(())
5680
}
5781

58-
async fn append_events(
59-
&mut self,
60-
events: Vec<ethcontract::Event<contracts::gpv2_settlement::Event>>,
61-
) -> Result<()> {
82+
async fn append_events(&mut self, events: Vec<(GPv2SettlementEvents, Log)>) -> Result<()> {
6283
let mut transaction = self.db.pool.begin().await?;
6384
crate::database::events::append_events(&mut transaction, events).await?;
6485
transaction.commit().await?;
Lines changed: 80 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -1,51 +1,86 @@
11
use {
22
alloy::rpc::types::Log,
3-
anyhow::{Context, Result, anyhow},
4-
contracts::gpv2_settlement::{
5-
Event as ContractEvent,
6-
event_data::{
7-
OrderInvalidated as ContractInvalidation,
8-
PreSignature as ContractPreSignature,
9-
Settlement as ContractSettlement,
10-
Trade as ContractTrade,
11-
},
12-
},
3+
anyhow::{Context, Result},
4+
contracts::alloy::GPv2Settlement::GPv2Settlement::{self, GPv2SettlementEvents},
135
database::{
146
OrderUid,
157
PgTransaction,
8+
TransactionHash,
169
byte_array::ByteArray,
1710
events::{Event, EventIndex, Invalidation, PreSignature, Settlement, Trade},
1811
},
19-
ethcontract::{Event as EthContractEvent, EventMetadata},
12+
ethcontract::EventMetadata,
13+
ethrpc::alloy::conversions::IntoLegacy,
2014
number::conversions::u256_to_big_decimal,
2115
std::convert::TryInto,
2216
};
2317

2418
pub fn contract_to_db_events(
25-
contract_events: Vec<EthContractEvent<ContractEvent>>,
19+
contract_events: Vec<(GPv2SettlementEvents, Log)>,
2620
) -> Result<Vec<(EventIndex, Event)>> {
2721
contract_events
2822
.into_iter()
29-
.filter_map(|EthContractEvent { data, meta }| {
30-
let meta = match meta {
31-
Some(meta) => meta,
32-
None => return Some(Err(anyhow!("event without metadata"))),
33-
};
34-
match data {
35-
ContractEvent::Trade(event) => Some(convert_trade(&event, &meta)),
36-
ContractEvent::Settlement(event) => Some(Ok(convert_settlement(&event, &meta))),
37-
ContractEvent::OrderInvalidated(event) => Some(convert_invalidation(&event, &meta)),
38-
ContractEvent::PreSignature(event) => Some(convert_presignature(&event, &meta)),
23+
.filter_map(|(event, log)| {
24+
let log = ValidatedLog::try_from(log).ok()?;
25+
match event {
26+
GPv2SettlementEvents::Trade(event) => Some(convert_trade(&event, log)),
27+
GPv2SettlementEvents::Settlement(event) => {
28+
Some(Ok(convert_settlement(&event, log)))
29+
}
30+
GPv2SettlementEvents::OrderInvalidated(event) => {
31+
Some(convert_invalidation(&event, log))
32+
}
33+
GPv2SettlementEvents::PreSignature(event) => {
34+
Some(convert_presignature(&event, log))
35+
}
3936
// TODO: handle new events
40-
ContractEvent::Interaction(_) => None,
37+
GPv2SettlementEvents::Interaction(_) => None,
4138
}
4239
})
4340
.collect::<Result<Vec<_>>>()
4441
}
4542

43+
struct ValidatedLog {
44+
block: i64,
45+
tx_hash: TransactionHash,
46+
log_index: i64,
47+
}
48+
49+
impl TryFrom<Log> for ValidatedLog {
50+
type Error = anyhow::Error;
51+
52+
fn try_from(log: Log) -> std::result::Result<Self, Self::Error> {
53+
Ok(Self {
54+
block: log
55+
.block_number
56+
.context("missing block_number")?
57+
.try_into()
58+
.context("could not convert block number to i64")?,
59+
tx_hash: log
60+
.transaction_hash
61+
.map(|hash| ByteArray(hash.0))
62+
.context("missing transaction_hash")?,
63+
log_index: log
64+
.log_index
65+
.context("missing log_index")?
66+
.try_into()
67+
.context("could not convert log index to i64")?,
68+
})
69+
}
70+
}
71+
72+
impl From<ValidatedLog> for EventIndex {
73+
fn from(value: ValidatedLog) -> Self {
74+
Self {
75+
block_number: value.block,
76+
log_index: value.log_index,
77+
}
78+
}
79+
}
80+
4681
pub async fn append_events(
4782
transaction: &mut PgTransaction<'_>,
48-
events: Vec<EthContractEvent<ContractEvent>>,
83+
events: Vec<(GPv2SettlementEvents, Log)>,
4984
) -> Result<()> {
5085
let _timer = super::Metrics::get()
5186
.database_queries
@@ -61,7 +96,7 @@ pub async fn append_events(
6196

6297
pub async fn replace_events(
6398
transaction: &mut PgTransaction<'_>,
64-
events: Vec<EthContractEvent<ContractEvent>>,
99+
events: Vec<(GPv2SettlementEvents, Log)>,
65100
from_block: u64,
66101
) -> Result<()> {
67102
let _timer = super::Metrics::get()
@@ -100,52 +135,45 @@ pub fn bytes_to_order_uid(bytes: &[u8]) -> Result<OrderUid> {
100135
.map(ByteArray)
101136
}
102137

103-
fn convert_trade(trade: &ContractTrade, meta: &EventMetadata) -> Result<(EventIndex, Event)> {
138+
fn convert_trade(trade: &GPv2Settlement::Trade, log: ValidatedLog) -> Result<(EventIndex, Event)> {
104139
let event = Trade {
105-
order_uid: bytes_to_order_uid(&trade.order_uid.0)?,
106-
sell_amount_including_fee: u256_to_big_decimal(&trade.sell_amount),
107-
buy_amount: u256_to_big_decimal(&trade.buy_amount),
108-
fee_amount: u256_to_big_decimal(&trade.fee_amount),
140+
order_uid: bytes_to_order_uid(&trade.orderUid.0)?,
141+
sell_amount_including_fee: u256_to_big_decimal(&trade.sellAmount.into_legacy()),
142+
buy_amount: u256_to_big_decimal(&trade.buyAmount.into_legacy()),
143+
fee_amount: u256_to_big_decimal(&trade.feeAmount.into_legacy()),
109144
};
110-
Ok((meta_to_event_index(meta), Event::Trade(event)))
145+
Ok((log.into(), Event::Trade(event)))
111146
}
112147

113148
fn convert_settlement(
114-
settlement: &ContractSettlement,
115-
meta: &EventMetadata,
149+
settlement: &GPv2Settlement::Settlement,
150+
log: ValidatedLog,
116151
) -> (EventIndex, Event) {
117152
let event = Settlement {
118-
solver: ByteArray(settlement.solver.0),
119-
transaction_hash: ByteArray(meta.transaction_hash.0),
153+
solver: ByteArray(settlement.solver.into()),
154+
transaction_hash: log.tx_hash,
120155
};
121-
(meta_to_event_index(meta), Event::Settlement(event))
156+
(log.into(), Event::Settlement(event))
122157
}
123158

124159
fn convert_invalidation(
125-
invalidation: &ContractInvalidation,
126-
meta: &EventMetadata,
160+
invalidation: &GPv2Settlement::OrderInvalidated,
161+
log: ValidatedLog,
127162
) -> Result<(EventIndex, Event)> {
128163
let event = Invalidation {
129-
order_uid: bytes_to_order_uid(&invalidation.order_uid.0)?,
164+
order_uid: bytes_to_order_uid(invalidation.orderUid.as_ref())?,
130165
};
131-
Ok((meta_to_event_index(meta), Event::Invalidation(event)))
166+
Ok((log.into(), Event::Invalidation(event)))
132167
}
133168

134169
fn convert_presignature(
135-
presignature: &ContractPreSignature,
136-
meta: &EventMetadata,
170+
presignature: &GPv2Settlement::PreSignature,
171+
log: ValidatedLog,
137172
) -> Result<(EventIndex, Event)> {
138173
let event = PreSignature {
139-
owner: ByteArray(presignature.owner.0),
140-
order_uid: ByteArray(
141-
presignature
142-
.order_uid
143-
.0
144-
.as_slice()
145-
.try_into()
146-
.context("trade event order_uid has wrong number of bytes")?,
147-
),
174+
owner: ByteArray(presignature.owner.into()),
175+
order_uid: bytes_to_order_uid(presignature.orderUid.as_ref())?,
148176
signed: presignature.signed,
149177
};
150-
Ok((meta_to_event_index(meta), Event::PreSignature(event)))
178+
Ok((log.into(), Event::PreSignature(event)))
151179
}

crates/autopilot/src/database/onchain_order_events/ethflow_events.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,12 @@ use {
33
crate::database::events::log_to_event_index,
44
alloy::rpc::types::Log,
55
anyhow::{Context, Result, anyhow},
6-
contracts::{
7-
GPv2Settlement,
8-
alloy::CoWSwapOnchainOrders::CoWSwapOnchainOrders::{
6+
contracts::alloy::{
7+
CoWSwapOnchainOrders::CoWSwapOnchainOrders::{
98
CoWSwapOnchainOrdersEvents as ContractEvent,
109
OrderPlacement as ContractOrderPlacement,
1110
},
12-
deployment_block,
11+
GPv2Settlement,
1312
},
1413
database::{
1514
PgTransaction,
@@ -150,7 +149,8 @@ async fn settlement_deployment_block_number_hash(
150149
web3: &Web3,
151150
chain_id: u64,
152151
) -> Result<BlockNumberHash> {
153-
let block_number = deployment_block(GPv2Settlement::raw_contract(), chain_id)?;
152+
let block_number =
153+
GPv2Settlement::deployment_block(&chain_id).context("no deployment block configured")?;
154154
block_number_to_block_number_hash(web3, U64::from(block_number).into())
155155
.await
156156
.context("Deployment block not found")

0 commit comments

Comments
 (0)