Skip to content

Commit

Permalink
feat: unify logging
Browse files Browse the repository at this point in the history
  • Loading branch information
mfw78 committed Sep 30, 2023
1 parent 787eba1 commit aa124cc
Show file tree
Hide file tree
Showing 11 changed files with 177 additions and 148 deletions.
5 changes: 3 additions & 2 deletions src/commands/dumpDb.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
import { DumpDbOptions, Registry } from "../types";
import { DBService } from "../utils";
import { logger, DBService } from "../utils";

/**
* Dump the database as JSON to STDOUT for a given chain ID
* @param options A dict, but essentially just the chainId
*/
export async function dumpDb(options: DumpDbOptions) {
const log = logger.getLogger("commands:dumpDb");
const { chainId } = options;

Registry.dump(DBService.getInstance(), chainId.toString())
.then((dump) => console.log(dump))
.catch((error) => {
console.error("Error dumping DB", error);
log.error("Unexpected thrown when dumping DB", error);
process.exit(1);
});
}
9 changes: 5 additions & 4 deletions src/commands/run.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,23 @@
import { RunOptions } from "../types";
import { DBService } from "../utils";
import { logger, DBService } from "../utils";
import { ChainContext } from "../domain";

/**
* Run the watch-tower 👀🐮
* @param options Specified by the CLI / environment for running the watch-tower
*/
export async function run(options: RunOptions) {
const log = logger.getLogger("commands:run");
const { rpc, deploymentBlock, oneShot } = options;

process.on("unhandledRejection", async (error) => {
console.log(error);
log.error("Unhandled promise rejection", error);
await DBService.getInstance().close();
process.exit(1);
});

process.on("SIGINT", async function () {
console.log("️⚠️ Caught interrupt signal. Closing DB connection.");
log.info("Caught interrupt signal. Closing DB connection.");
await DBService.getInstance().close();
process.exit(0);
});
Expand Down Expand Up @@ -44,7 +45,7 @@ export async function run(options: RunOptions) {
// Run all the chain contexts
await Promise.all(runPromises);
} catch (error) {
console.error(error);
log.error("Unexpected error thrown when running watchtower", error);
exitCode = 1;
} finally {
await DBService.getInstance().close();
Expand Down
63 changes: 37 additions & 26 deletions src/domain/addContract.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { logger } from "../utils";
import { BytesLike, ethers } from "ethers";

import {
Expand Down Expand Up @@ -33,6 +34,7 @@ async function _addContract(
context: ChainContext,
event: ConditionalOrderCreatedEvent
) {
const log = logger.getLogger("addContract:_addContract");
const composableCow = ComposableCoW__factory.createInterface();
const { provider, registry } = context;
const { transactionHash: tx, blockNumber } = event;
Expand All @@ -55,26 +57,24 @@ async function _addContract(
if (added) {
numContractsAdded++;
} else {
console.error(
`[addContract] Failed to register Smart Order from tx ${tx} on block ${blockNumber}. Error: ${error}`
log.error(
`Failed to register Smart Order from tx ${tx} on block ${blockNumber}. Error: ${error}`
);
}
hasErrors ||= error;

console.log(`[addContract] Added ${numContractsAdded} contracts`);

if (numContractsAdded > 0) {
console.log(`[addContract] Added ${numContractsAdded} contracts`);
log.info(`Added ${numContractsAdded} contracts`);

// Write the registry to disk. Don't catch errors, let them bubble up
await registry.write();

// Throw execution error if there was at least one error
if (hasErrors) {
throw Error(
"[addContract] Error adding conditional order. Event: " + event
);
throw Error("Error adding conditional order. Event: " + event);
}
} else {
log.info(`No contracts added for tx ${tx} on block ${blockNumber}`);
}
}

Expand All @@ -83,32 +83,40 @@ export async function _registerNewOrder(
composableCow: ComposableCoWInterface,
registry: Registry
): Promise<{ error: boolean; added: boolean }> {
const log = logger.getLogger("addContract:_registerNewOrder");
const { transactionHash: tx } = event;
let added = false;
try {
// Check if the log is a ConditionalOrderCreated event
if (
event.topics[0] === composableCow.getEventTopic("ConditionalOrderCreated")
) {
const log = event as ConditionalOrderCreatedEvent;
const eventLog = event as ConditionalOrderCreatedEvent;
// Decode the log
const [owner, params] = composableCow.decodeEventLog(
"ConditionalOrderCreated",
log.data,
log.topics
eventLog.data,
eventLog.topics
) as [string, IConditionalOrder.ConditionalOrderParamsStruct];

// Attempt to add the conditional order to the registry
add(log.transactionHash, owner, params, null, log.address, registry);
add(
eventLog.transactionHash,
owner,
params,
null,
eventLog.address,
registry
);
added = true;
} else if (
event.topics[0] == composableCow.getEventTopic("MerkleRootSet")
) {
const log = event as MerkleRootSetEvent;
const eventLog = event as MerkleRootSetEvent;
const [owner, root, proof] = composableCow.decodeEventLog(
"MerkleRootSet",
log.data,
log.topics
eventLog.data,
eventLog.topics
) as [string, BytesLike, ComposableCoW.ProofStruct];

// First need to flush the owner's conditional orders that do not have the merkle root set
Expand Down Expand Up @@ -137,17 +145,17 @@ export async function _registerNewOrder(
owner,
decodedOrder[1],
{ merkleRoot: root, path: decodedOrder[0] },
log.address,
eventLog.address,
registry
);
added = true;
}
}
}
} catch (error) {
console.error(
`[addContract] Error handling ConditionalOrderCreated/MerkleRootSet event for tx: ${tx}` +
error
} catch (err) {
log.error(
`Error handling ConditionalOrderCreated/MerkleRootSet event for tx: ${tx}` +
err
);
return { error: true, added };
}
Expand All @@ -172,11 +180,12 @@ export function add(
composableCow: string,
registry: Registry
) {
const log = logger.getLogger("addContract:add");
const { handler, salt, staticInput } = params;
if (registry.ownerOrders.has(owner)) {
const conditionalOrders = registry.ownerOrders.get(owner);
console.log(
`[register:add] Adding conditional order to already existing owner contract ${owner}`,
log.info(
`Adding conditional order to already existing owner contract ${owner}`,
{ tx, handler, salt, staticInput }
);
let exists = false;
Expand All @@ -200,10 +209,12 @@ export function add(
});
}
} else {
console.log(
`[register:add] Adding conditional order to new owner contract ${owner}:`,
{ tx, handler, salt, staticInput }
);
log.info(`Adding conditional order to new owner contract ${owner}:`, {
tx,
handler,
salt,
staticInput,
});
registry.ownerOrders.set(
owner,
new Set([{ tx, params, proof, orders: new Map(), composableCow }])
Expand Down
Loading

0 comments on commit aa124cc

Please sign in to comment.