Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Use tsc-friendly assert #867

Merged
merged 7 commits into from
Feb 13, 2025
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 33 additions & 29 deletions src/clients/BundleDataClient/BundleDataClient.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import assert from "assert";
import _ from "lodash";
import {
ProposedRootBundle,
Expand All @@ -24,7 +25,6 @@ import {
bnZero,
queryHistoricalDepositForFill,
assign,
assert,
fixedPointAdjustment,
isDefined,
toBN,
Expand Down Expand Up @@ -388,7 +388,7 @@ export class BundleDataClient {
const fill = await verifyFillRepayment(
_fill,
this.spokePoolClients[_fill.destinationChainId].spokePool.provider,
matchingDeposit!,
matchingDeposit,
this.clients.hubPoolClient
);
if (!isDefined(fill)) {
Expand All @@ -399,7 +399,7 @@ export class BundleDataClient {
this.clients.hubPoolClient,
blockRanges,
this.chainIdListForBundleEvaluationBlockNumbers,
matchingDeposit!.fromLiteChain // Use ! because we've already asserted that matchingDeposit is defined.
matchingDeposit.fromLiteChain
);
// Assume that lp fees are 0 for the sake of speed. In the future we could batch compute
// these or make hardcoded assumptions based on the origin-repayment chain direction. This might result
Expand Down Expand Up @@ -862,16 +862,20 @@ export class BundleDataClient {
slowFillRequest: undefined,
};
} else {
v3RelayHashes[relayDataHash].deposits!.push(deposit);
const { deposits } = v3RelayHashes[relayDataHash];
assert(isDefined(deposits) && deposits.length > 0, "Deposit should exist in relay hash dictionary.");
deposits.push(deposit);
}

// Account for duplicate deposits by concatenating the relayDataHash with the count of the number of times
// we have seen it so far.
const newBundleDepositHash = `${relayDataHash}@${v3RelayHashes[relayDataHash].deposits!.length - 1}`;
const { deposits } = v3RelayHashes[relayDataHash];
assert(isDefined(deposits) && deposits.length > 0, "Deposit should exist in relay hash dictionary.");
const newBundleDepositHash = `${relayDataHash}@${deposits.length - 1}`;
const decodedBundleDepositHash = decodeBundleDepositHash(newBundleDepositHash);
assert(
decodedBundleDepositHash.relayDataHash === relayDataHash &&
decodedBundleDepositHash.index === v3RelayHashes[relayDataHash].deposits!.length - 1,
decodedBundleDepositHash.index === deposits.length - 1,
"Not using correct bundle deposit hash key"
);
if (deposit.blockNumber >= originChainBlockRange[0]) {
Expand Down Expand Up @@ -933,16 +937,14 @@ export class BundleDataClient {
const relayDataHash = getRelayEventKey(fill);
if (v3RelayHashes[relayDataHash]) {
if (!v3RelayHashes[relayDataHash].fill) {
assert(
isDefined(v3RelayHashes[relayDataHash].deposits) && v3RelayHashes[relayDataHash].deposits!.length > 0,
"Deposit should exist in relay hash dictionary."
);
const { deposits } = v3RelayHashes[relayDataHash];
assert(isDefined(deposits) && deposits.length > 0, "Deposit should exist in relay hash dictionary.");
v3RelayHashes[relayDataHash].fill = fill;
if (fill.blockNumber >= destinationChainBlockRange[0]) {
const fillToRefund = await verifyFillRepayment(
fill,
destinationClient.spokePool.provider,
v3RelayHashes[relayDataHash].deposits![0],
deposits[0],
this.clients.hubPoolClient
);
if (!isDefined(fillToRefund)) {
Expand All @@ -953,7 +955,7 @@ export class BundleDataClient {
v3RelayHashes[relayDataHash].fill = fillToRefund;
validatedBundleV3Fills.push({
...fillToRefund,
quoteTimestamp: v3RelayHashes[relayDataHash].deposits![0].quoteTimestamp,
quoteTimestamp: deposits[0].quoteTimestamp,
});

// Now that we know this deposit has been filled on-chain, identify any duplicate deposits
Expand All @@ -964,7 +966,7 @@ export class BundleDataClient {
// fill is from a prior bundle. Paying out the filler keeps the behavior consistent for how
// we deal with duplicate deposits regardless if the deposit is matched with a pre-fill or
// a current bundle fill.
const duplicateDeposits = v3RelayHashes[relayDataHash].deposits!.slice(1);
const duplicateDeposits = deposits.slice(1);
duplicateDeposits.forEach((duplicateDeposit) => {
if (isSlowFill(fill)) {
updateExpiredDepositsV3(expiredDepositsToRefundV3, duplicateDeposit);
Expand All @@ -982,7 +984,7 @@ export class BundleDataClient {
// events.
if (
fill.relayExecutionInfo.fillType === FillType.ReplacedSlowFill &&
_canCreateSlowFillLeaf(v3RelayHashes[relayDataHash].deposits![0])
_canCreateSlowFillLeaf(deposits[0])
) {
fastFillsReplacingSlowFills.push(relayDataHash);
}
Expand Down Expand Up @@ -1091,17 +1093,15 @@ export class BundleDataClient {
if (v3RelayHashes[relayDataHash]) {
if (!v3RelayHashes[relayDataHash].slowFillRequest) {
v3RelayHashes[relayDataHash].slowFillRequest = slowFillRequest;
if (v3RelayHashes[relayDataHash].fill) {
const { deposits, fill } = v3RelayHashes[relayDataHash];
if (fill) {
// Exiting here assumes that slow fill requests must precede fills, so if there was a fill
// following this slow fill request, then we would have already seen it. We don't need to check
// for a fill older than this slow fill request.
return;
}
assert(
isDefined(v3RelayHashes[relayDataHash].deposits) && v3RelayHashes[relayDataHash].deposits!.length > 0,
"Deposit should exist in relay hash dictionary."
);
const matchedDeposit = v3RelayHashes[relayDataHash].deposits![0];
assert(isDefined(deposits) && deposits.length > 0, "Deposit should exist in relay hash dictionary.");
const matchedDeposit = deposits[0];

if (
slowFillRequest.blockNumber >= destinationChainBlockRange[0] &&
Expand Down Expand Up @@ -1207,7 +1207,7 @@ export class BundleDataClient {
const fillToRefund = await verifyFillRepayment(
fill,
destinationClient.spokePool.provider,
v3RelayHashes[relayDataHash].deposits![0],
deposits[0],
this.clients.hubPoolClient
);
if (!isDefined(fillToRefund)) {
Expand Down Expand Up @@ -1256,19 +1256,19 @@ export class BundleDataClient {
// then we wouldn't be in this branch of the code.
const prefill = await this.findMatchingFillEvent(deposit, destinationClient);
assert(isDefined(prefill), `findFillEvent# Cannot find prefill: ${relayDataHash}`);
assert(getRelayEventKey(prefill!) === relayDataHash, "Relay hashes should match.");
assert(getRelayEventKey(prefill) === relayDataHash, "Relay hashes should match.");
if (canRefundPrefills) {
const verifiedFill = await verifyFillRepayment(
prefill!,
prefill,
destinationClient.spokePool.provider,
deposit,
this.clients.hubPoolClient
);
if (!isDefined(verifiedFill)) {
bundleUnrepayableFillsV3.push(prefill!);
bundleUnrepayableFillsV3.push(prefill);
} else if (!isSlowFill(verifiedFill)) {
validatedBundleV3Fills.push({
...verifiedFill!,
...verifiedFill,
quoteTimestamp: deposit.quoteTimestamp,
});
} else {
Expand Down Expand Up @@ -1383,14 +1383,16 @@ export class BundleDataClient {
validatedBundleV3Fills.length > 0
? this.clients.hubPoolClient.batchComputeRealizedLpFeePct(
validatedBundleV3Fills.map((fill) => {
const matchedDeposit = v3RelayHashes[getRelayEventKey(fill)].deposits![0];
const { deposits } = v3RelayHashes[getRelayEventKey(fill)];
assert(isDefined(deposits) && deposits.length > 0, "Deposit should exist in relay hash dictionary.");
const matchedDeposit = deposits[0];
assert(isDefined(matchedDeposit), "Deposit should exist in relay hash dictionary.");
const { chainToSendRefundTo: paymentChainId } = getRefundInformationFromFill(
fill,
this.clients.hubPoolClient,
blockRangesForChains,
chainIds,
matchedDeposit!.fromLiteChain
matchedDeposit.fromLiteChain
);
return {
...fill,
Expand Down Expand Up @@ -1427,14 +1429,16 @@ export class BundleDataClient {
});
v3FillLpFees.forEach(({ realizedLpFeePct }, idx) => {
const fill = validatedBundleV3Fills[idx];
const associatedDeposit = v3RelayHashes[getRelayEventKey(fill)].deposits![0];
const { deposits } = v3RelayHashes[getRelayEventKey(fill)];
assert(isDefined(deposits) && deposits.length > 0, "Deposit should exist in relay hash dictionary.");
const associatedDeposit = deposits[0];
assert(isDefined(associatedDeposit), "Deposit should exist in relay hash dictionary.");
const { chainToSendRefundTo, repaymentToken } = getRefundInformationFromFill(
fill,
this.clients.hubPoolClient,
blockRangesForChains,
chainIds,
associatedDeposit!.fromLiteChain
associatedDeposit.fromLiteChain
);
updateBundleFillsV3(bundleFillsV3, fill, realizedLpFeePct, chainToSendRefundTo, repaymentToken, fill.relayer);
});
Expand Down
2 changes: 1 addition & 1 deletion src/relayFeeCalculator/chain-queries/baseQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@ import {
BigNumber,
toBNWei,
bnZero,
assert,
chainIsOPStack,
fixedPointAdjustment,
} from "../../utils";
import assert from "assert";
import { Logger, QueryInterface } from "../relayFeeCalculator";
import { Transport } from "viem";
import { getGasPriceEstimate } from "../../gasPriceOracle/oracle";
Expand Down
2 changes: 1 addition & 1 deletion src/utils/CachingUtils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { DEFAULT_CACHING_SAFE_LAG, DEFAULT_CACHING_TTL } from "../constants";
import { CachingMechanismInterface, Deposit, Fill, SlowFillRequest } from "../interfaces";
import { assert } from "./LogUtils";
import assert from "assert";
import { composeRevivers, objectWithBigNumberReviver } from "./ReviverUtils";
import { getRelayHashFromEvent } from "./SpokeUtils";
import { getCurrentTime } from "./TimeUtils";
Expand Down
12 changes: 0 additions & 12 deletions src/utils/LogUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,3 @@ export function formattedLog(
});
}
}

/**
* Asserts the truth of a condition. If the condition is false, an error is thrown with the provided message.
* @param condition The condition to assert.
* @param message The message to throw if the condition is false.
* @throws Error if the condition is false.
*/
export function assert(condition: boolean, message: string): void {
if (!condition) {
throw new Error(message);
}
}
2 changes: 1 addition & 1 deletion test/SpokePoolClient.SpeedUp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { Deposit, SpeedUp } from "../src/interfaces";
import { bnOne, getMessageHash } from "../src/utils";
import { destinationChainId, originChainId } from "./constants";
import {
assert,
assertPromiseError,
Contract,
BigNumber,
Expand All @@ -18,6 +17,7 @@ import {
getUpdatedV3DepositSignature,
setupTokensForWallet,
} from "./utils";
import assert from "assert";

describe("SpokePoolClient: SpeedUp", function () {
const ignoredFields = [
Expand Down
2 changes: 1 addition & 1 deletion test/SpokePoolClient.ValidateFill.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import {
} from "../src/utils";
import { CHAIN_ID_TEST_LIST, originChainId, destinationChainId, repaymentChainId } from "./constants";
import {
assert,
expect,
BigNumber,
toBNWei,
Expand All @@ -37,6 +36,7 @@ import {
winston,
lastSpyLogIncludes,
} from "./utils";
import assert from "assert";
import { MockConfigStoreClient, MockHubPoolClient, MockSpokePoolClient } from "./mocks";

let spokePool_1: Contract, erc20_1: Contract, spokePool_2: Contract, erc20_2: Contract, hubPool: Contract;
Expand Down
2 changes: 1 addition & 1 deletion test/relayFeeCalculator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ import {
BigNumber,
Contract,
SignerWithAddress,
assert,
assertPromiseError,
assertPromisePasses,
buildDepositForRelayerFeeTest,
Expand All @@ -28,6 +27,7 @@ import {
setupTokensForWallet,
makeCustomTransport,
} from "./utils";
import assert from "assert";
import { TOKEN_SYMBOLS_MAP } from "@across-protocol/constants";
import { EMPTY_MESSAGE, ZERO_ADDRESS } from "../src/constants";
import { SpokePool } from "@across-protocol/contracts";
Expand Down
18 changes: 9 additions & 9 deletions test/utils/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ import { EMPTY_MESSAGE, PROTOCOL_DEFAULT_CHAIN_ID_INDICES, ZERO_ADDRESS } from "
import { SpyTransport } from "./SpyTransport";

chai.use(chaiExclude);
const assert = chai.assert;
const chaiAssert = chai.assert;

export type SignerWithAddress = utils.SignerWithAddress;

Expand All @@ -49,7 +49,7 @@ export const {
zeroAddress,
} = utils;

export { assert, BigNumber, expect, chai, Contract, sinon, toBN, toBNWei, toWei, utf8ToHex, winston };
export { chaiAssert, BigNumber, expect, chai, Contract, sinon, toBN, toBNWei, toWei, utf8ToHex, winston };

const TokenRolesEnum = {
OWNER: "0",
Expand All @@ -71,7 +71,7 @@ export function deepEqualsWithBigNumber(x: unknown, y: unknown, omitKeys: string
.sort()
.map((key) => [key, y?.[key]])
);
assert.deepStrictEqual(_.omit(sortedKeysX, omitKeys), _.omit(sortedKeysY, omitKeys));
chaiAssert.deepStrictEqual(_.omit(sortedKeysX, omitKeys), _.omit(sortedKeysY, omitKeys));
return true;
}

Expand All @@ -86,7 +86,7 @@ export async function assertPromiseError<T>(promise: Promise<T>, errMessage?: st
throw err;
}
if (errMessage) {
assert.isTrue(err.message.includes(errMessage));
chaiAssert.isTrue(err.message.includes(errMessage));
}
}
}
Expand Down Expand Up @@ -314,7 +314,7 @@ export async function depositV3(

const lastEvent = events.at(-1);
let args = lastEvent?.args;
assert.exists(args);
chaiAssert.exists(args);
args = args!;

const { blockNumber, transactionHash, transactionIndex, logIndex } = lastEvent!;
Expand Down Expand Up @@ -351,14 +351,14 @@ export async function requestV3SlowFill(
signer: SignerWithAddress
): Promise<SlowFillRequestWithBlock> {
const destinationChainId = Number(await spokePool.chainId());
assert.notEqual(relayData.originChainId, destinationChainId);
chaiAssert.notEqual(relayData.originChainId, destinationChainId);

await spokePool.connect(signer).requestV3SlowFill(relayData);

const events = await spokePool.queryFilter(spokePool.filters.RequestedV3SlowFill());
const lastEvent = events.at(-1);
let args = lastEvent!.args;
assert.exists(args);
chaiAssert.exists(args);
args = args!;

const { blockNumber, transactionHash, transactionIndex, logIndex } = lastEvent!;
Expand Down Expand Up @@ -392,14 +392,14 @@ export async function fillV3Relay(
repaymentChainId?: number
): Promise<FillWithBlock> {
const destinationChainId = Number(await spokePool.chainId());
assert.notEqual(deposit.originChainId, destinationChainId);
chaiAssert.notEqual(deposit.originChainId, destinationChainId);

await spokePool.connect(signer).fillV3Relay(deposit, repaymentChainId ?? destinationChainId);

const events = await spokePool.queryFilter(spokePool.filters.FilledV3Relay());
const lastEvent = events.at(-1);
let args = lastEvent!.args;
assert.exists(args);
chaiAssert.exists(args);
args = args!;

const { blockNumber, transactionHash, transactionIndex, logIndex } = lastEvent!;
Expand Down
Loading