Skip to content

Commit

Permalink
chore: sanity check orders (#124)
Browse files Browse the repository at this point in the history
# Description

Reduces pressure on the API by doing some sanity checks on orders from
contracts.

# Changes

- [x] Filters out invalid orders that will be rejected by the API

## How to test

1. Run on staging
2. Observe no API errors for orders that are filtered

## Related Issues

Fixes #122
  • Loading branch information
mfw78 authored Dec 15, 2023
1 parent 6107453 commit ad7b1d6
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/domain/checkForAndPlaceOrder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ import {
measureTime,
} from "../utils/metrics";
import { FilterAction } from "../utils/filterPolicy";
import { validateOrder } from "../utils/filterOrder";

const GPV2SETTLEMENT = "0x9008D19f58AAbD9eD0D60971565AA8510560ab41";

Expand Down Expand Up @@ -345,6 +346,10 @@ async function _processConditionalOrder(
validTo: Number(order.validTo),
};

// We now have the order, so we can validate it. This will throw if the order is invalid
// and we will catch it below.
validateOrder(orderToSubmit);

// calculate the orderUid
const orderUid = _getOrderUid(chainId, orderToSubmit, owner);

Expand Down
37 changes: 37 additions & 0 deletions src/utils/filterOrder.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { Order } from "@cowprotocol/contracts";
import { BigNumber, ethers } from "ethers";

/**
* Process an order to determine if it is valid
* @param order The GPv2.Order data struct to validate
* @throws Error if the order is invalid
*/
export function validateOrder(order: Order) {
// amounts must be non-zero
if (BigNumber.from(order.sellAmount).isZero()) {
throw new Error("Order has zero sell amount");
}

if (BigNumber.from(order.buyAmount).isZero()) {
throw new Error("Order has zero buy amount");
}

// token addresses must not be the ZeroAddress
if (order.sellToken === ethers.constants.AddressZero) {
throw new Error("Order has zero sell token address");
}

if (order.buyToken === ethers.constants.AddressZero) {
throw new Error("Order has zero buy token address");
}

// tokens must not be the same
if (order.sellToken === order.buyToken) {
throw new Error("Order has identical sell and buy token addresses");
}

// Check to make sure that the order has at least 120s of validity
if (Math.floor(Date.now() / 1000) + 60 > Number(order.validTo)) {
throw new Error("Order expires too soon");
}
}

0 comments on commit ad7b1d6

Please sign in to comment.