Skip to content

Commit

Permalink
Adjustments schema contracts (#26)
Browse files Browse the repository at this point in the history
* fix typo

* change validUntil to be timestamp

* bid status with id

* renamings

* addressed comments

---------

Co-authored-by: --systemdf <[email protected]>
  • Loading branch information
anihamde and --systemdf authored Mar 11, 2024
1 parent c89402f commit ccdb7a8
Show file tree
Hide file tree
Showing 8 changed files with 45 additions and 33 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,6 @@ To run a happy path test of the on-chain contracts plus the off-chain services,
b. `per_contract` to the value stored in MULTICALL
c. `adapter_contract` to the value stored in ADAPTER
6. Run `cargo run -- run --per-private-key ${OPERATOR_SK}` from `auction-server/`. This should start up the auction server.
7. Run `python3 -m per_sdk.protocols.token_vault_monitor --chain-id development --rpc-url ${ANVIL_RPC_URL} --vault-contract ${TOKEN_VAULT} --weth-contract ${WETH} --liquidation-server-url http://localhost:9000/liquidation/submit_opportunity --mock-pyth`. This should start up the monitor script that exposes liquidatable vaults to the liquidation monitor server.
7. Run `python3 -m per_sdk.protocols.token_vault_monitor --chain-id development --rpc-url ${ANVIL_RPC_URL} --vault-contract ${TOKEN_VAULT} --weth-contract ${WETH} --liquidation-server-url http://localhost:9000/v1/liquidation/opportunities --mock-pyth`. This should start up the monitor script that exposes liquidatable vaults to the liquidation monitor server.
8. Run `python3 -m per_sdk.searcher.simple_searcher --private-key ${SEARCHER_SK} --chain-id development --verbose --liquidation-server-url http://localhost:9000`.
9. Run `forge script script/Vault.s.sol --via-ir --fork-url ${ANVIL_RPC_URL} --private-key ${SK_TX_SENDER} -vvv --sig 'getVault(uint256)' 0 --broadcast` from `per_multicall/`. Confirm that the logged vault amounts are now 0--this indicates that the vault was properly liquidated.
6 changes: 4 additions & 2 deletions auction-server/src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use {
bid::BidResult,
liquidation::OpportunityParamsWithMetadata,
ws::{
APIResposne,
APIResponse,
ClientMessage,
ClientRequest,
ServerResultMessage,
Expand All @@ -21,6 +21,7 @@ use {
},
state::{
BidStatus,
BidStatusWithId,
OpportunityParams,
OpportunityParamsV1,
Store,
Expand Down Expand Up @@ -147,9 +148,10 @@ pub async fn start_api(run_options: RunOptions, store: Arc<Store>) -> Result<()>
),
components(
schemas(
APIResposne,
APIResponse,
Bid,
BidStatus,
BidStatusWithId,
BidResult,
OpportunityParamsV1,
OpportunityBid,
Expand Down
24 changes: 10 additions & 14 deletions auction-server/src/api/ws.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ use {
},
state::{
BidId,
BidStatus,
BidStatusWithId,
OpportunityId,
Store,
},
Expand Down Expand Up @@ -112,23 +112,19 @@ pub enum ServerUpdateResponse {
opportunity: OpportunityParamsWithMetadata,
},
#[serde(rename = "bid_status_update")]
BidStatusUpdate {
#[schema(value_type = String)]
id: BidId,
status: BidStatus,
},
BidStatusUpdate { status: BidStatusWithId },
}

#[derive(Serialize, Clone, ToSchema)]
#[serde(untagged)]
pub enum APIResposne {
pub enum APIResponse {
BidResult(BidResult),
}
#[derive(Serialize, Clone, ToSchema)]
#[serde(tag = "status", content = "result")]
pub enum ServerResultMessage {
#[serde(rename = "success")]
Success(Option<APIResposne>),
Success(Option<APIResponse>),
#[serde(rename = "error")]
Err(String),
}
Expand Down Expand Up @@ -161,7 +157,7 @@ async fn websocket_handler(stream: WebSocket, state: Arc<Store>) {
#[derive(Clone)]
pub enum UpdateEvent {
NewOpportunity(OpportunityParamsWithMetadata),
BidStatusUpdate { id: BidId, status: BidStatus },
BidStatusUpdate(BidStatusWithId),
}

pub type SubscriberId = usize;
Expand Down Expand Up @@ -260,13 +256,13 @@ impl Subscriber {
serde_json::to_string(&ServerUpdateResponse::NewOpportunity { opportunity })?;
self.sender.send(message.into()).await?;
}
UpdateEvent::BidStatusUpdate { id, status } => {
if !self.bid_ids.contains(&id) {
UpdateEvent::BidStatusUpdate(status) => {
if !self.bid_ids.contains(&status.id) {
// Irrelevant update
return Ok(());
}
let message =
serde_json::to_string(&ServerUpdateResponse::BidStatusUpdate { id, status })?;
serde_json::to_string(&ServerUpdateResponse::BidStatusUpdate { status })?;
self.sender.send(message.into()).await?;
}
}
Expand Down Expand Up @@ -347,7 +343,7 @@ impl Subscriber {
ServerResultResponse {
id: Some(id.clone()),
result: ServerResultMessage::Success(Some(
APIResposne::BidResult(bid_result.0),
APIResponse::BidResult(bid_result.0),
)),
}
}
Expand All @@ -373,7 +369,7 @@ impl Subscriber {
ServerResultResponse {
id: Some(id.clone()),
result: ServerResultMessage::Success(Some(
APIResposne::BidResult(bid_result.0),
APIResponse::BidResult(bid_result.0),
)),
}
}
Expand Down
10 changes: 7 additions & 3 deletions auction-server/src/auction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use {
},
state::{
BidStatus,
BidStatusWithId,
SimulatedBid,
Store,
},
Expand Down Expand Up @@ -254,11 +255,11 @@ pub async fn run_submission_loop(store: Arc<Store>) -> Result<()> {
tracing::debug!("Submitted transaction: {:?}", receipt);
let winner_ids:Vec<Uuid> = winner_bids.iter().map(|b| b.id).collect();
for bid in cloned_bids {
let status = match winner_ids.contains(&bid.id) {
let bid_status = match winner_ids.contains(&bid.id) {
true => BidStatus::Submitted(receipt.transaction_hash),
false => BidStatus::Lost
};
store.bid_status_store.set_and_broadcast(bid.id, status).await;
store.bid_status_store.set_and_broadcast(BidStatusWithId { id: bid.id, bid_status }).await;
}
chain_store.bids.write().await.remove(&permission_key);
}
Expand Down Expand Up @@ -349,7 +350,10 @@ pub async fn handle_bid(store: Arc<Store>, bid: Bid) -> result::Result<Uuid, Res
});
store
.bid_status_store
.set_and_broadcast(bid_id, BidStatus::Pending)
.set_and_broadcast(BidStatusWithId {
id: bid_id,
bid_status: BidStatus::Pending,
})
.await;
Ok(bid_id)
}
24 changes: 17 additions & 7 deletions auction-server/src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,10 @@ use {
broadcast,
RwLock,
},
utoipa::ToSchema,
utoipa::{
ToResponse,
ToSchema,
},
uuid::Uuid,
};

Expand Down Expand Up @@ -142,6 +145,13 @@ pub enum BidStatus {
Lost,
}

#[derive(Serialize, Clone, ToSchema, ToResponse)]
pub struct BidStatusWithId {
#[schema(value_type = String)]
pub id: BidId,
pub bid_status: BidStatus,
}

pub struct BidStatusStore {
pub bids_status: RwLock<HashMap<BidId, BidStatus>>,
pub event_sender: broadcast::Sender<UpdateEvent>,
Expand All @@ -152,12 +162,12 @@ impl BidStatusStore {
self.bids_status.read().await.get(id).cloned()
}

pub async fn set_and_broadcast(&self, id: BidId, status: BidStatus) {
self.bids_status.write().await.insert(id, status.clone());
match self
.event_sender
.send(UpdateEvent::BidStatusUpdate { id, status })
{
pub async fn set_and_broadcast(&self, update: BidStatusWithId) {
self.bids_status
.write()
.await
.insert(update.id, update.bid_status.clone());
match self.event_sender.send(UpdateEvent::BidStatusUpdate(update)) {
Ok(_) => (),
Err(e) => tracing::error!("Failed to send bid status update: {}", e),
};
Expand Down
2 changes: 1 addition & 1 deletion per_multicall/src/LiquidationAdapter.sol
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ contract LiquidationAdapter is SigVerify {
if (!validSignature) {
revert InvalidSearcherSignature();
}
if (block.number > params.validUntil) {
if (block.timestamp > params.validUntil) {
revert ExpiredSignature();
}
if (_signatureUsed[params.signatureLiquidator]) {
Expand Down
4 changes: 2 additions & 2 deletions per_multicall/src/SearcherVault.sol
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ contract SearcherVault is SigVerify {
*
* @param vaultID: ID of the vault to be liquidated
* @param bid: size of the bid to pay to PER operator
* @param validUntil: block number until which signatureSearcher is valid
* @param validUntil: timestamp at which signatureSearcher is no longer valid
* @param updateData: data to update price feed with
* @param signatureSearcher: signature of the vaultID and bid, signed by the searcher's EOA, to be verified if msg.sender is PER Multicall
*/
Expand All @@ -64,7 +64,7 @@ contract SearcherVault is SigVerify {
if (!validSignatureSearcher) {
revert InvalidSearcherSignature();
}
if (block.number > validUntil) {
if (block.timestamp > validUntil) {
revert ExpiredSignature();
}
if (_signatureUsed[signatureSearcher]) {
Expand Down
6 changes: 3 additions & 3 deletions per_multicall/test/PERIntegration.t.sol
Original file line number Diff line number Diff line change
Expand Up @@ -596,7 +596,7 @@ contract PERIntegrationTest is

bytes memory signatureSearcher;

uint256 validUntil = 1_000_000_000_000;
uint256 validUntil = UINT256_MAX;

AccountBalance memory balancesAPre = getBalances(
address(searcherA),
Expand Down Expand Up @@ -642,7 +642,7 @@ contract PERIntegrationTest is

bytes memory signatureSearcher;

uint256 validUntil = 1_000_000_000_000;
uint256 validUntil = UINT256_MAX;

vm.expectRevert(abi.encodeWithSelector(InvalidLiquidation.selector));
vm.prank(searcherAOwnerAddress, searcherAOwnerAddress);
Expand Down Expand Up @@ -1065,7 +1065,7 @@ contract PERIntegrationTest is

contracts[0] = address(liquidationAdapter);
bidInfos[0] = makeBidInfo(15, searcherAOwnerSk);
bidInfos[0].validUntil = block.number - 1; // use old block number for the validUntil field to create expired signature
bidInfos[0].validUntil = block.timestamp - 1; // use old timestamp for the validUntil field to create expired signature

(
bytes memory permission,
Expand Down

0 comments on commit ccdb7a8

Please sign in to comment.