diff --git a/boxes/boxes/react/tests/node.test.ts b/boxes/boxes/react/tests/node.test.ts index 48f06bb0aafc..4a7db647e971 100644 --- a/boxes/boxes/react/tests/node.test.ts +++ b/boxes/boxes/react/tests/node.test.ts @@ -16,11 +16,11 @@ describe('BoxReact Contract Tests', () => { .send({ contractAddressSalt: salt }) .deployed(); - logger(`L2 contract deployed at ${contract.address}`); + logger.info(`L2 contract deployed at ${contract.address}`); }, 60000); test('Can set a number', async () => { - logger(`${await wallet.getRegisteredAccounts()}`); + logger.info(`${await wallet.getRegisteredAccounts()}`); await contract.methods.setNumber(numberToSet, wallet.getCompleteAddress()).send().wait(); }, 40000); diff --git a/yarn-project/archiver/src/archiver/archiver.ts b/yarn-project/archiver/src/archiver/archiver.ts index 989a765d9120..24069e5c1a06 100644 --- a/yarn-project/archiver/src/archiver/archiver.ts +++ b/yarn-project/archiver/src/archiver/archiver.ts @@ -128,7 +128,7 @@ export class Archiver implements ArchiveSource { } if (blockUntilSynced) { - this.log(`Performing initial chain sync...`); + this.log.info(`Performing initial chain sync...`); await this.sync(blockUntilSynced); } @@ -197,7 +197,7 @@ export class Archiver implements ArchiveSource { ); if (retrievedL1ToL2Messages.retrievedData.length !== 0) { - this.log( + this.log.verbose( `Retrieved ${retrievedL1ToL2Messages.retrievedData.length} new L1 -> L2 messages between L1 blocks ${ l1SynchPoint.messagesSynchedTo + 1n } and ${currentL1BlockNumber}.`, @@ -250,7 +250,7 @@ export class Archiver implements ArchiveSource { if (blocks.length === 0) { return; } else { - this.log( + this.log.verbose( `Retrieved ${blocks.length} new L2 blocks between L1 blocks ${ l1SynchPoint.blocksSynchedTo + 1n } and ${currentL1BlockNumber}.`, @@ -296,7 +296,7 @@ export class Archiver implements ArchiveSource { e => e.toContractClassPublic(), ); if (contractClasses.length > 0) { - contractClasses.forEach(c => this.log(`Registering contract class ${c.id.toString()}`)); + contractClasses.forEach(c => this.log.verbose(`Registering contract class ${c.id.toString()}`)); await this.store.addContractClasses(contractClasses, blockNum); } } @@ -308,7 +308,7 @@ export class Archiver implements ArchiveSource { private async storeDeployedContractInstances(allLogs: UnencryptedL2Log[], blockNum: number) { const contractInstances = ContractInstanceDeployedEvent.fromLogs(allLogs).map(e => e.toContractInstance()); if (contractInstances.length > 0) { - contractInstances.forEach(c => this.log(`Storing contract instance at ${c.address.toString()}`)); + contractInstances.forEach(c => this.log.verbose(`Storing contract instance at ${c.address.toString()}`)); await this.store.addContractInstances(contractInstances, blockNum); } } @@ -351,7 +351,7 @@ export class Archiver implements ArchiveSource { // Store the functions in the contract class in a single operation if (validFnCount > 0) { - this.log(`Storing ${validFnCount} functions for contract class ${contractClassId.toString()}`); + this.log.verbose(`Storing ${validFnCount} functions for contract class ${contractClassId.toString()}`); } await this.store.addFunctions(contractClassId, validPrivateFns, validUnconstrainedFns); } @@ -362,10 +362,10 @@ export class Archiver implements ArchiveSource { * @returns A promise signalling completion of the stop process. */ public async stop(): Promise { - this.log('Stopping...'); + this.log.debug('Stopping...'); await this.runningPromise?.stop(); - this.log('Stopped.'); + this.log.info('Stopped.'); return Promise.resolve(); } diff --git a/yarn-project/archiver/src/archiver/kv_archiver_store/block_store.ts b/yarn-project/archiver/src/archiver/kv_archiver_store/block_store.ts index 873b80496d28..716c71e1cf48 100644 --- a/yarn-project/archiver/src/archiver/kv_archiver_store/block_store.ts +++ b/yarn-project/archiver/src/archiver/kv_archiver_store/block_store.ts @@ -186,7 +186,7 @@ export class BlockStore { } if (start < INITIAL_L2_BLOCK_NUM) { - this.#log(`Clamping start block ${start} to ${INITIAL_L2_BLOCK_NUM}`); + this.#log.verbose(`Clamping start block ${start} to ${INITIAL_L2_BLOCK_NUM}`); start = INITIAL_L2_BLOCK_NUM; } diff --git a/yarn-project/archiver/src/archiver/kv_archiver_store/log_store.ts b/yarn-project/archiver/src/archiver/kv_archiver_store/log_store.ts index 26590fb626c7..305c385d2544 100644 --- a/yarn-project/archiver/src/archiver/kv_archiver_store/log_store.ts +++ b/yarn-project/archiver/src/archiver/kv_archiver_store/log_store.ts @@ -131,7 +131,7 @@ export class LogStore { const txLogs = unencryptedLogsInBlock.txLogs[txIndex].unrollLogs(); maxLogsHit = this.#accumulateLogs(logs, blockNumber, txIndex, txLogs, filter); if (maxLogsHit) { - this.#log(`Max logs hit at block ${blockNumber}`); + this.#log.debug(`Max logs hit at block ${blockNumber}`); break loopOverBlocks; } } diff --git a/yarn-project/aztec-node/src/aztec-node/server.ts b/yarn-project/aztec-node/src/aztec-node/server.ts index e00c0b93f145..29fab24d9a39 100644 --- a/yarn-project/aztec-node/src/aztec-node/server.ts +++ b/yarn-project/aztec-node/src/aztec-node/server.ts @@ -102,7 +102,7 @@ export class AztecNodeService implements AztecNode { `Inbox: ${config.l1Contracts.inboxAddress.toString()}\n` + `Outbox: ${config.l1Contracts.outboxAddress.toString()}\n` + `Availability Oracle: ${config.l1Contracts.availabilityOracleAddress.toString()}`; - this.log(message); + this.log.info(message); } /** @@ -704,10 +704,10 @@ export class AztecNodeService implements AztecNode { // using a snapshot could be less efficient than using the committed db if (blockNumber === 'latest' || blockNumber === blockSyncedTo) { - this.log(`Using committed db for block ${blockNumber}, world state synced upto ${blockSyncedTo}`); + this.log.debug(`Using committed db for block ${blockNumber}, world state synced upto ${blockSyncedTo}`); return this.worldStateSynchronizer.getCommitted(); } else if (blockNumber < blockSyncedTo) { - this.log(`Using snapshot for block ${blockNumber}, world state synced upto ${blockSyncedTo}`); + this.log.debug(`Using snapshot for block ${blockNumber}, world state synced upto ${blockSyncedTo}`); return this.worldStateSynchronizer.getSnapshot(blockNumber); } else { throw new Error(`Block ${blockNumber} not yet synced`); diff --git a/yarn-project/aztec-node/src/aztec-node/simulator-factory.ts b/yarn-project/aztec-node/src/aztec-node/simulator-factory.ts index 0ccaf6be6e6c..9d947ae8665f 100644 --- a/yarn-project/aztec-node/src/aztec-node/simulator-factory.ts +++ b/yarn-project/aztec-node/src/aztec-node/simulator-factory.ts @@ -13,12 +13,14 @@ export async function getSimulationProvider( try { await fs.access(config.acvmBinaryPath, fs.constants.R_OK); await fs.mkdir(config.acvmWorkingDirectory, { recursive: true }); - logger?.(`Using native ACVM at ${config.acvmBinaryPath} and working directory ${config.acvmWorkingDirectory}`); + logger?.info( + `Using native ACVM at ${config.acvmBinaryPath} and working directory ${config.acvmWorkingDirectory}`, + ); return new NativeACVMSimulator(config.acvmWorkingDirectory, config.acvmBinaryPath); } catch { - logger?.(`Failed to access ACVM at ${config.acvmBinaryPath}, falling back to WASM`); + logger?.warn(`Failed to access ACVM at ${config.acvmBinaryPath}, falling back to WASM`); } } - logger?.('Using WASM ACVM simulation'); + logger?.info('Using WASM ACVM simulation'); return new WASMSimulator(); } diff --git a/yarn-project/aztec.js/src/contract/deploy_method.ts b/yarn-project/aztec.js/src/contract/deploy_method.ts index 795226cff019..eea033bce7fc 100644 --- a/yarn-project/aztec.js/src/contract/deploy_method.ts +++ b/yarn-project/aztec.js/src/contract/deploy_method.ts @@ -140,11 +140,11 @@ export class DeployMethod extends Bas // Register the contract class if it hasn't been published already. if (!options.skipClassRegistration) { if (await this.pxe.isContractClassPubliclyRegistered(contractClass.id)) { - this.log( + this.log.debug( `Skipping registration of already registered contract class ${contractClass.id.toString()} for ${instance.address.toString()}`, ); } else { - this.log( + this.log.info( `Creating request for registering contract class ${contractClass.id.toString()} as part of deployment for ${instance.address.toString()}`, ); calls.push((await registerContractClass(this.wallet, this.artifact)).request()); @@ -170,7 +170,7 @@ export class DeployMethod extends Bas public send(options: DeployOptions = {}): DeploySentTx { const txHashPromise = super.send(options).getTxHash(); const instance = this.getInstance(options); - this.log( + this.log.debug( `Sent deployment tx of ${this.artifact.name} contract with deployment address ${instance.address.toString()}`, ); return new DeploySentTx(this.pxe, txHashPromise, this.postDeployCtor, instance); diff --git a/yarn-project/aztec.js/src/contract/deploy_sent_tx.ts b/yarn-project/aztec.js/src/contract/deploy_sent_tx.ts index 5770333fa2db..d77150fbe7c2 100644 --- a/yarn-project/aztec.js/src/contract/deploy_sent_tx.ts +++ b/yarn-project/aztec.js/src/contract/deploy_sent_tx.ts @@ -44,7 +44,7 @@ export class DeploySentTx extends SentTx */ public async deployed(opts?: DeployedWaitOpts): Promise { const receipt = await this.wait(opts); - this.log(`Contract ${this.instance.address.toString()} successfully deployed.`); + this.log.info(`Contract ${this.instance.address.toString()} successfully deployed.`); return receipt.contract; } diff --git a/yarn-project/aztec.js/src/utils/cheat_codes.ts b/yarn-project/aztec.js/src/utils/cheat_codes.ts index b3a64e92ec8d..b3c0bcfbe97b 100644 --- a/yarn-project/aztec.js/src/utils/cheat_codes.ts +++ b/yarn-project/aztec.js/src/utils/cheat_codes.ts @@ -90,7 +90,7 @@ export class EthCheatCodes { if (res.error) { throw new Error(`Error mining: ${res.error.message}`); } - this.logger(`Mined ${numberOfBlocks} blocks`); + this.logger.info(`Mined ${numberOfBlocks} blocks`); } /** @@ -102,7 +102,7 @@ export class EthCheatCodes { if (res.error) { throw new Error(`Error setting next block timestamp: ${res.error.message}`); } - this.logger(`Set next block timestamp to ${timestamp}`); + this.logger.info(`Set next block timestamp to ${timestamp}`); } /** @@ -116,7 +116,7 @@ export class EthCheatCodes { } const jsonContent = JSON.stringify(res.result); fs.writeFileSync(`${fileName}.json`, jsonContent, 'utf8'); - this.logger(`Dumped state to ${fileName}`); + this.logger.info(`Dumped state to ${fileName}`); } /** @@ -129,7 +129,7 @@ export class EthCheatCodes { if (res.error) { throw new Error(`Error loading state: ${res.error.message}`); } - this.logger(`Loaded state from ${fileName}`); + this.logger.info(`Loaded state from ${fileName}`); } /** @@ -155,7 +155,7 @@ export class EthCheatCodes { if (res.error) { throw new Error(`Error setting storage for contract ${contract} at ${slot}: ${res.error.message}`); } - this.logger(`Set storage for contract ${contract} at ${slot} to ${value}`); + this.logger.info(`Set storage for contract ${contract} at ${slot} to ${value}`); } /** @@ -179,7 +179,7 @@ export class EthCheatCodes { if (res.error) { throw new Error(`Error impersonating ${who}: ${res.error.message}`); } - this.logger(`Impersonating ${who}`); + this.logger.info(`Impersonating ${who}`); } /** @@ -191,7 +191,7 @@ export class EthCheatCodes { if (res.error) { throw new Error(`Error when stopping the impersonation of ${who}: ${res.error.message}`); } - this.logger(`Stopped impersonating ${who}`); + this.logger.info(`Stopped impersonating ${who}`); } /** @@ -204,7 +204,7 @@ export class EthCheatCodes { if (res.error) { throw new Error(`Error setting bytecode for ${contract}: ${res.error.message}`); } - this.logger(`Set bytecode for ${contract} to ${bytecode}`); + this.logger.info(`Set bytecode for ${contract} to ${bytecode}`); } /** diff --git a/yarn-project/aztec.js/src/utils/pxe.ts b/yarn-project/aztec.js/src/utils/pxe.ts index 9b1a9222409c..700a003d217e 100644 --- a/yarn-project/aztec.js/src/utils/pxe.ts +++ b/yarn-project/aztec.js/src/utils/pxe.ts @@ -5,11 +5,11 @@ import { retryUntil } from '@aztec/foundation/retry'; export const waitForPXE = async (pxe: PXE, logger?: DebugLogger) => { await retryUntil(async () => { try { - logger?.('Attempting to contact PXE...'); + logger?.debug('Attempting to contact PXE...'); await pxe.getNodeInfo(); return true; } catch (error) { - logger?.('Failed to contact PXE!'); + logger?.verbose('Failed to contact PXE'); } return undefined; }, 'RPC Get Node Info'); diff --git a/yarn-project/aztec/src/bin/index.ts b/yarn-project/aztec/src/bin/index.ts index afd1f0a6d58b..70a34456c740 100644 --- a/yarn-project/aztec/src/bin/index.ts +++ b/yarn-project/aztec/src/bin/index.ts @@ -62,7 +62,7 @@ async function main() { } main().catch(err => { - debugLogger(`Error in command execution`); - debugLogger(err); + debugLogger.error(`Error in command execution`); + debugLogger.error(err); process.exit(1); }); diff --git a/yarn-project/aztec/src/cli/cli.ts b/yarn-project/aztec/src/cli/cli.ts index 09ba1a37fb22..525b3e5d741d 100644 --- a/yarn-project/aztec/src/cli/cli.ts +++ b/yarn-project/aztec/src/cli/cli.ts @@ -69,7 +69,7 @@ export function getProgram(userLog: LogFn, debugLogger: DebugLogger): Command { httpServer.listen(options.port); userLog(`Aztec Server listening on port ${options.port}`); } - installSignalHandlers(debugLogger, signalHandlers); + installSignalHandlers(debugLogger.info, signalHandlers); }); return program; } diff --git a/yarn-project/aztec/src/examples/token.ts b/yarn-project/aztec/src/examples/token.ts index 3dfcba2666f6..c4ec9f290232 100644 --- a/yarn-project/aztec/src/examples/token.ts +++ b/yarn-project/aztec/src/examples/token.ts @@ -30,25 +30,25 @@ const TRANSFER_AMOUNT = 33n; * Main function. */ async function main() { - logger('Running token contract test on HTTP interface.'); + logger.info('Running token contract test on HTTP interface.'); aliceWallet = await getSingleKeyAccount(pxe, alicePrivateKey).waitSetup(); bobWallet = await getSingleKeyAccount(pxe, bobPrivateKey).waitSetup(); const alice = aliceWallet.getCompleteAddress(); const bob = bobWallet.getCompleteAddress(); - logger(`Created Alice and Bob accounts: ${alice.address.toString()}, ${bob.address.toString()}`); + logger.info(`Created Alice and Bob accounts: ${alice.address.toString()}, ${bob.address.toString()}`); - logger('Deploying Token...'); + logger.info('Deploying Token...'); const token = await TokenContract.deploy(aliceWallet, alice, 'TokenName', 'TokenSymbol', 18).send().deployed(); - logger('Token deployed'); + logger.info('Token deployed'); // Create the contract abstraction and link it to Alice's and Bob's wallet for future signing const tokenAlice = await TokenContract.at(token.address, aliceWallet); const tokenBob = await TokenContract.at(token.address, bobWallet); // Mint tokens to Alice - logger(`Minting ${ALICE_MINT_BALANCE} more coins to Alice...`); + logger.info(`Minting ${ALICE_MINT_BALANCE} more coins to Alice...`); // Create a secret and a corresponding hash that will be used to mint funds privately const aliceSecret = Fr.random(); @@ -73,26 +73,26 @@ async function main() { // Make the tokens spendable by redeeming them using the secret (converts the "pending shield note" created above // to a "token note") await tokenAlice.methods.redeem_shield(alice, ALICE_MINT_BALANCE, aliceSecret).send().wait(); - logger(`${ALICE_MINT_BALANCE} tokens were successfully minted and redeemed by Alice`); + logger.info(`${ALICE_MINT_BALANCE} tokens were successfully minted and redeemed by Alice`); const balanceAfterMint = await tokenAlice.methods.balance_of_private(alice).simulate(); - logger(`Tokens successfully minted. New Alice's balance: ${balanceAfterMint}`); + logger.info(`Tokens successfully minted. New Alice's balance: ${balanceAfterMint}`); // We will now transfer tokens from Alice to Bob - logger(`Transferring ${TRANSFER_AMOUNT} tokens from Alice to Bob...`); + logger.info(`Transferring ${TRANSFER_AMOUNT} tokens from Alice to Bob...`); await tokenAlice.methods.transfer(alice, bob, TRANSFER_AMOUNT, 0).send().wait(); // Check the new balances const aliceBalance = await tokenAlice.methods.balance_of_private(alice).simulate(); - logger(`Alice's balance ${aliceBalance}`); + logger.info(`Alice's balance ${aliceBalance}`); const bobBalance = await tokenBob.methods.balance_of_private(bob).simulate(); - logger(`Bob's balance ${bobBalance}`); + logger.info(`Bob's balance ${bobBalance}`); } main() .then(() => { - logger('Finished running successfully.'); + logger.info('Finished running successfully.'); process.exit(0); }) .catch(err => { diff --git a/yarn-project/aztec/src/sandbox.ts b/yarn-project/aztec/src/sandbox.ts index 54952cd331a2..7ee93045b6e9 100644 --- a/yarn-project/aztec/src/sandbox.ts +++ b/yarn-project/aztec/src/sandbox.ts @@ -156,7 +156,7 @@ async function initL1GasPortal( {} as any, ); - logger( + logger.info( `Initialized Gas Portal at ${l1ContractAddresses.gasPortalAddress} to bridge between L1 ${l1ContractAddresses.gasTokenAddress} to L2 ${l2GasTokenAddress}`, ); } @@ -179,7 +179,7 @@ async function deployCanonicalL2GasToken(deployer: Wallet, l1ContractAddresses: await batch.send().wait(); - logger(`Deployed Gas Token on L2 at ${canonicalGasToken.address}`); + logger.info(`Deployed Gas Token on L2 at ${canonicalGasToken.address}`); } /** Sandbox settings. */ diff --git a/yarn-project/circuits.js/src/barretenberg/crypto/grumpkin/index.test.ts b/yarn-project/circuits.js/src/barretenberg/crypto/grumpkin/index.test.ts index da7ec63df6d7..25f2de5f5d23 100644 --- a/yarn-project/circuits.js/src/barretenberg/crypto/grumpkin/index.test.ts +++ b/yarn-project/circuits.js/src/barretenberg/crypto/grumpkin/index.test.ts @@ -3,7 +3,7 @@ import { createDebugLogger } from '@aztec/foundation/log'; import { GrumpkinScalar, type Point } from '../../../index.js'; import { Grumpkin } from './index.js'; -const debug = createDebugLogger('bb:grumpkin_test'); +const log = createDebugLogger('bb:grumpkin_test'); describe('grumpkin', () => { let grumpkin!: Grumpkin; @@ -24,13 +24,13 @@ describe('grumpkin', () => { const start = new Date().getTime(); const outputPoints = grumpkin.batchMul(inputPoints, exponent); - debug(`batch mul in: ${new Date().getTime() - start}ms`); + log.debug(`batch mul in: ${new Date().getTime() - start}ms`); const start2 = new Date().getTime(); for (let i = 0; i < numPoints; ++i) { grumpkin.mul(inputPoints[i], exponent); } - debug(`regular mul in: ${new Date().getTime() - start2}ms`); + log.debug(`regular mul in: ${new Date().getTime() - start2}ms`); for (let i = 0; i < numPoints; ++i) { const lhs = outputPoints[i]; diff --git a/yarn-project/circuits.js/src/contract/artifact_hash.ts b/yarn-project/circuits.js/src/contract/artifact_hash.ts index ba6a259b48f1..efad51e999c7 100644 --- a/yarn-project/circuits.js/src/contract/artifact_hash.ts +++ b/yarn-project/circuits.js/src/contract/artifact_hash.ts @@ -47,7 +47,7 @@ export function computeArtifactHash( const preimage = computeArtifactHashPreimage(artifact); const artifactHash = computeArtifactHash(computeArtifactHashPreimage(artifact)); - getLogger().trace('Computed artifact hash', { artifactHash, ...preimage }); + getLogger().debug('Computed artifact hash', { artifactHash, ...preimage }); return artifactHash; } diff --git a/yarn-project/circuits.js/src/contract/private_function_membership_proof.ts b/yarn-project/circuits.js/src/contract/private_function_membership_proof.ts index 81e4f08f95d3..cbd39f5f2530 100644 --- a/yarn-project/circuits.js/src/contract/private_function_membership_proof.ts +++ b/yarn-project/circuits.js/src/contract/private_function_membership_proof.ts @@ -58,7 +58,7 @@ export function createPrivateFunctionMembershipProof( const artifactTreeLeafIndex = artifactTree.getIndex(functionArtifactHash.toBuffer()); const artifactTreeSiblingPath = artifactTree.getSiblingPath(artifactTreeLeafIndex).map(Fr.fromBuffer); - log.trace(`Computed proof for private function with selector ${selector.toString()}`, { + log.debug(`Computed proof for private function with selector ${selector.toString()}`, { functionArtifactHash, functionMetadataHash, functionLeaf: '0x' + functionLeaf.toString('hex'), @@ -118,7 +118,7 @@ export function isValidPrivateFunctionMembershipProof( ), ); if (!contractClass.privateFunctionsRoot.equals(computedPrivateFunctionTreeRoot)) { - log.trace(`Private function tree root mismatch`, { + log.debug(`Private function tree root mismatch`, { expectedPrivateFunctionTreeRoot: contractClass.privateFunctionsRoot, computedPrivateFunctionTreeRoot: computedPrivateFunctionTreeRoot, computedFunctionLeaf: '0x' + functionLeaf.toString('hex'), @@ -142,7 +142,7 @@ export function isValidPrivateFunctionMembershipProof( metadataHash: fn.artifactMetadataHash, }); if (!contractClass.artifactHash.equals(computedArtifactHash)) { - log.trace(`Artifact hash mismatch`, { + log.debug(`Artifact hash mismatch`, { expected: contractClass.artifactHash, computedArtifactHash, computedFunctionArtifactHash: functionArtifactHash, diff --git a/yarn-project/circuits.js/src/contract/unconstrained_function_membership_proof.ts b/yarn-project/circuits.js/src/contract/unconstrained_function_membership_proof.ts index 06cc292b68de..6df7afdb72e2 100644 --- a/yarn-project/circuits.js/src/contract/unconstrained_function_membership_proof.ts +++ b/yarn-project/circuits.js/src/contract/unconstrained_function_membership_proof.ts @@ -47,7 +47,7 @@ export function createUnconstrainedFunctionMembershipProof( const artifactTreeLeafIndex = artifactTree.getIndex(functionArtifactHash.toBuffer()); const artifactTreeSiblingPath = artifactTree.getSiblingPath(artifactTreeLeafIndex).map(Fr.fromBuffer); - log.trace(`Computed proof for unconstrained function with selector ${selector.toString()}`, { + log.debug(`Computed proof for unconstrained function with selector ${selector.toString()}`, { functionArtifactHash, functionMetadataHash, artifactMetadataHash, @@ -102,7 +102,7 @@ export function isValidUnconstrainedFunctionMembershipProof( metadataHash: fn.artifactMetadataHash, }); if (!contractClass.artifactHash.equals(computedArtifactHash)) { - log.trace(`Artifact hash mismatch`, { + log.debug(`Artifact hash mismatch`, { expected: contractClass.artifactHash, computedArtifactHash, computedFunctionArtifactHash: functionArtifactHash, diff --git a/yarn-project/cli/src/cmds/add_contract.ts b/yarn-project/cli/src/cmds/add_contract.ts index c77283083c8d..36b2a9fcbf43 100644 --- a/yarn-project/cli/src/cmds/add_contract.ts +++ b/yarn-project/cli/src/cmds/add_contract.ts @@ -24,7 +24,7 @@ export async function addContract( debugLogger: DebugLogger, log: LogFn, ) { - const artifact = await getContractArtifact(contractArtifactPath, log); + const artifact = await getContractArtifact(contractArtifactPath); const instance: ContractInstanceWithAddress = { version: 1, salt, diff --git a/yarn-project/cli/src/cmds/call.ts b/yarn-project/cli/src/cmds/call.ts index 2864e8985ac2..3efffe1668c2 100644 --- a/yarn-project/cli/src/cmds/call.ts +++ b/yarn-project/cli/src/cmds/call.ts @@ -16,7 +16,7 @@ export async function call( debugLogger: DebugLogger, log: LogFn, ) { - const { functionArgs, contractArtifact } = await prepTx(contractArtifactPath, functionName, functionArgsIn, log); + const { functionArgs, contractArtifact } = await prepTx(contractArtifactPath, functionName, functionArgsIn); const fnArtifact = getFunctionArtifact(contractArtifact, functionName); if (fnArtifact.parameters.length !== functionArgs.length) { diff --git a/yarn-project/cli/src/cmds/create_account.ts b/yarn-project/cli/src/cmds/create_account.ts index 09cdadc361aa..34a99f24e44a 100644 --- a/yarn-project/cli/src/cmds/create_account.ts +++ b/yarn-project/cli/src/cmds/create_account.ts @@ -19,7 +19,7 @@ export async function createAccount( const { address, publicKey, partialAddress } = account.getCompleteAddress(); const tx = await account.deploy(); const txHash = await tx.getTxHash(); - debugLogger(`Account contract tx sent with hash ${txHash}`); + debugLogger.verbose(`Account contract tx sent with hash ${txHash}`); if (wait) { log(`\nWaiting for account contract deployment...`); await tx.wait(); diff --git a/yarn-project/cli/src/cmds/deploy.ts b/yarn-project/cli/src/cmds/deploy.ts index 94cc35e5f276..904418fa629a 100644 --- a/yarn-project/cli/src/cmds/deploy.ts +++ b/yarn-project/cli/src/cmds/deploy.ts @@ -23,7 +23,7 @@ export async function deploy( log: LogFn, logJson: (output: any) => void, ) { - const contractArtifact = await getContractArtifact(artifactPath, log); + const contractArtifact = await getContractArtifact(artifactPath); const constructorArtifact = getInitializer(contractArtifact, initializer); const client = await createCompatibleClient(rpcUrl, debugLogger); @@ -43,9 +43,9 @@ export async function deploy( if (!constructorArtifact) { throw new Error(`Cannot process constructor arguments as no constructor was found`); } - debugLogger(`Input arguments: ${rawArgs.map((x: any) => `"${x}"`).join(', ')}`); + debugLogger.verbose(`Input arguments: ${rawArgs.map((x: any) => `"${x}"`).join(', ')}`); args = encodeArgs(rawArgs, constructorArtifact!.parameters); - debugLogger(`Encoded arguments: ${args.join(', ')}`); + debugLogger.verbose(`Encoded arguments: ${args.join(', ')}`); } const deploy = deployer.deploy(...args); @@ -53,7 +53,7 @@ export async function deploy( await deploy.create({ contractAddressSalt: salt, portalContract: portalAddress }); const tx = deploy.send({ contractAddressSalt: salt, portalContract: portalAddress }); const txHash = await tx.getTxHash(); - debugLogger(`Deploy tx sent with hash ${txHash}`); + debugLogger.verbose(`Deploy tx sent with hash ${txHash}`); if (wait) { const deployed = await tx.wait(); const { address, partialAddress } = deployed.contract; diff --git a/yarn-project/cli/src/cmds/inspect_contract.ts b/yarn-project/cli/src/cmds/inspect_contract.ts index 00823d218956..0156c1e8c77c 100644 --- a/yarn-project/cli/src/cmds/inspect_contract.ts +++ b/yarn-project/cli/src/cmds/inspect_contract.ts @@ -6,12 +6,12 @@ import { decodeFunctionSignatureWithParameterNames, } from '@aztec/foundation/abi'; import { sha256 } from '@aztec/foundation/crypto'; -import { type DebugLogger, type LogFn } from '@aztec/foundation/log'; +import { type LogFn } from '@aztec/foundation/log'; import { getContractArtifact } from '../utils.js'; -export async function inspectContract(contractArtifactFile: string, debugLogger: DebugLogger, log: LogFn) { - const contractArtifact = await getContractArtifact(contractArtifactFile, debugLogger); +export async function inspectContract(contractArtifactFile: string, log: LogFn) { + const contractArtifact = await getContractArtifact(contractArtifactFile); const contractFns = contractArtifact.functions.filter(f => f.name !== 'compute_note_hash_and_nullifier'); if (contractFns.length === 0) { log(`No functions found for contract ${contractArtifact.name}`); diff --git a/yarn-project/cli/src/cmds/parse_parameter_struct.ts b/yarn-project/cli/src/cmds/parse_parameter_struct.ts index 15bc057ede9b..e319b8fe8e04 100644 --- a/yarn-project/cli/src/cmds/parse_parameter_struct.ts +++ b/yarn-project/cli/src/cmds/parse_parameter_struct.ts @@ -11,7 +11,7 @@ export async function parseParameterStruct( parameterName: string, log: LogFn, ) { - const contractArtifact = await getContractArtifact(contractArtifactPath, log); + const contractArtifact = await getContractArtifact(contractArtifactPath); const parameterAbitype = contractArtifact.functions .map(({ parameters }) => parameters) .flat() diff --git a/yarn-project/cli/src/cmds/send.ts b/yarn-project/cli/src/cmds/send.ts index c5195057e74e..07f9c9c08a85 100644 --- a/yarn-project/cli/src/cmds/send.ts +++ b/yarn-project/cli/src/cmds/send.ts @@ -16,7 +16,7 @@ export async function send( debugLogger: DebugLogger, log: LogFn, ) { - const { functionArgs, contractArtifact } = await prepTx(contractArtifactPath, functionName, functionArgsIn, log); + const { functionArgs, contractArtifact } = await prepTx(contractArtifactPath, functionName, functionArgsIn); const client = await createCompatibleClient(rpcUrl, debugLogger); const wallet = await getSchnorrAccount(client, privateKey, privateKey, Fr.ZERO).getWallet(); diff --git a/yarn-project/cli/src/index.ts b/yarn-project/cli/src/index.ts index 13c56ba00010..607ebb9f44fe 100644 --- a/yarn-project/cli/src/index.ts +++ b/yarn-project/cli/src/index.ts @@ -475,7 +475,7 @@ export function getProgram(log: LogFn, debugLogger: DebugLogger): Command { ) .action(async (contractArtifactFile: string) => { const { inspectContract } = await import('./cmds/inspect_contract.js'); - await inspectContract(contractArtifactFile, debugLogger, log); + await inspectContract(contractArtifactFile, log); }); program diff --git a/yarn-project/cli/src/utils.ts b/yarn-project/cli/src/utils.ts index 56598653e2a9..e9e17997f2d2 100644 --- a/yarn-project/cli/src/utils.ts +++ b/yarn-project/cli/src/utils.ts @@ -2,7 +2,7 @@ import { type ContractArtifact, type FunctionArtifact, loadContractArtifact } fr import { AztecAddress } from '@aztec/aztec.js/aztec_address'; import { type L1ContractArtifactsForDeployment } from '@aztec/aztec.js/ethereum'; import { type PXE } from '@aztec/aztec.js/interfaces/pxe'; -import { type DebugLogger, type LogFn } from '@aztec/foundation/log'; +import { type DebugLogger } from '@aztec/foundation/log'; import { type NoirPackageConfig } from '@aztec/foundation/noir'; import TOML from '@iarna/toml'; @@ -116,7 +116,7 @@ export async function getExampleContractArtifacts(): Promise { * @param fileDir - The directory of the compiled contract ABI. * @returns The parsed contract artifact. */ -export async function getContractArtifact(fileDir: string, log: LogFn) { +export async function getContractArtifact(fileDir: string) { // first check if it's a noir-contracts example const artifacts = await getExampleContractArtifacts(); if (artifacts[fileDir]) { @@ -127,14 +127,13 @@ export async function getContractArtifact(fileDir: string, log: LogFn) { try { contents = await readFile(fileDir, 'utf8'); } catch { - throw Error(`Contract ${fileDir} not found`); + throw new Error(`Contract ${fileDir} not found`); } try { return loadContractArtifact(JSON.parse(contents)); } catch (err) { - log('Invalid file used. Please try again.'); - throw err; + throw new Error(`Invalid contract ABI file ${fileDir}: ${err}`); } } @@ -168,11 +167,10 @@ export async function getTxSender(pxe: PXE, _from?: string) { * @param contractFile - Directory of the compiled contract ABI. * @param functionName - Name of the function to be called. * @param _functionArgs - Arguments to call the function with. - * @param log - Logger instance that will output to the CLI * @returns Formatted contract address, function arguments and caller's aztec address. */ -export async function prepTx(contractFile: string, functionName: string, _functionArgs: string[], log: LogFn) { - const contractArtifact = await getContractArtifact(contractFile, log); +export async function prepTx(contractFile: string, functionName: string, _functionArgs: string[]) { + const contractArtifact = await getContractArtifact(contractFile); const functionArtifact = getFunctionArtifact(contractArtifact, functionName); const functionArgs = encodeArgs(_functionArgs, functionArtifact.parameters); diff --git a/yarn-project/end-to-end/package.json b/yarn-project/end-to-end/package.json index 27df3c3cada6..f0e61fa68a19 100644 --- a/yarn-project/end-to-end/package.json +++ b/yarn-project/end-to-end/package.json @@ -15,7 +15,7 @@ "clean": "rm -rf ./dest .tsbuildinfo", "formatting": "run -T prettier --check ./src \"!src/web/main.js\" && run -T eslint ./src", "formatting:fix": "run -T eslint --fix ./src && run -T prettier -w ./src", - "test": "DEBUG='aztec:*' NODE_NO_WARNINGS=1 node --experimental-vm-modules ../node_modules/.bin/jest --runInBand --testTimeout=60000 --forceExit", + "test": "LOG_LEVEL=verbose NODE_NO_WARNINGS=1 node --experimental-vm-modules ../node_modules/.bin/jest --runInBand --testTimeout=60000 --forceExit", "test:integration": "concurrently -k -s first -c reset,dim -n test,anvil \"yarn test:integration:run\" \"anvil\"", "test:integration:run": "NODE_NO_WARNINGS=1 node --experimental-vm-modules ../node_modules/.bin/jest --no-cache --runInBand --config jest.integration.config.json" }, diff --git a/yarn-project/end-to-end/package.local.json b/yarn-project/end-to-end/package.local.json index 70da0aee0917..49e20df89bfd 100644 --- a/yarn-project/end-to-end/package.local.json +++ b/yarn-project/end-to-end/package.local.json @@ -2,6 +2,6 @@ "scripts": { "build": "yarn clean && tsc -b && webpack", "formatting": "run -T prettier --check ./src \"!src/web/main.js\" && run -T eslint ./src", - "test": "DEBUG='aztec:*' NODE_NO_WARNINGS=1 node --experimental-vm-modules ../node_modules/.bin/jest --runInBand --testTimeout=60000 --forceExit" + "test": "LOG_LEVEL=verbose NODE_NO_WARNINGS=1 node --experimental-vm-modules ../node_modules/.bin/jest --runInBand --testTimeout=60000 --forceExit" } } diff --git a/yarn-project/end-to-end/src/benchmarks/bench_process_history.test.ts b/yarn-project/end-to-end/src/benchmarks/bench_process_history.test.ts index bc8fb1cfbb2d..69eabf8532d6 100644 --- a/yarn-project/end-to-end/src/benchmarks/bench_process_history.test.ts +++ b/yarn-project/end-to-end/src/benchmarks/bench_process_history.test.ts @@ -48,7 +48,7 @@ describe('benchmarks/process_history', () => { // Create a new node and measure how much time it takes it to sync const dataDirectory = makeDataDirectory(chainLength); - context.logger(`Set up data directory at ${dataDirectory}`); + context.logger.info(`Set up data directory at ${dataDirectory}`); const nodeConfig: AztecNodeConfig = { ...context.config, disableSequencer: true, dataDirectory }; const [nodeSyncTime, node] = await elapsed(async () => { const node = await AztecNodeService.createAndSync(nodeConfig); @@ -61,7 +61,7 @@ describe('benchmarks/process_history', () => { const blockNumber = await node.getBlockNumber(); expect(blockNumber).toEqual(chainLength + SETUP_BLOCK_COUNT); - context.logger(`Node synced chain up to block ${chainLength}`, { + context.logger.info(`Node synced chain up to block ${chainLength}`, { eventName: 'node-synced-chain-history', txCount: BLOCK_SIZE * chainLength, txsPerBlock: BLOCK_SIZE, @@ -73,17 +73,17 @@ describe('benchmarks/process_history', () => { // Create a new pxe and measure how much time it takes it to sync with failed and successful decryption // Skip the first two blocks used for setup (create account contract and deploy benchmarking contract) - context.logger(`Starting new pxe`); + context.logger.info(`Starting new pxe`); const pxe = await waitNewPXESynced(node, contract, INITIAL_L2_BLOCK_NUM + SETUP_BLOCK_COUNT); // Register the owner account and wait until it's synced so we measure how much time it took - context.logger(`Registering owner account on new pxe`); + context.logger.info(`Registering owner account on new pxe`); const partialAddress = context.wallet.getCompleteAddress().partialAddress; const privateKey = context.wallet.getEncryptionPrivateKey(); await waitRegisteredAccountSynced(pxe, privateKey, partialAddress); // Repeat for another account that didn't receive any notes for them, so we measure trial-decrypts - context.logger(`Registering fresh account on new pxe`); + context.logger.info(`Registering fresh account on new pxe`); await waitRegisteredAccountSynced(pxe, GrumpkinScalar.random(), Fr.random()); // Stop the external node and pxe diff --git a/yarn-project/end-to-end/src/benchmarks/bench_publish_rollup.test.ts b/yarn-project/end-to-end/src/benchmarks/bench_publish_rollup.test.ts index fbbdcf49f58d..70f8157877e6 100644 --- a/yarn-project/end-to-end/src/benchmarks/bench_publish_rollup.test.ts +++ b/yarn-project/end-to-end/src/benchmarks/bench_publish_rollup.test.ts @@ -22,7 +22,7 @@ describe('benchmarks/publish_rollup', () => { await sequencer.stop(); // Simulate and simultaneously send ROLLUP_SIZE txs. These should not yet be processed since sequencer is stopped. - context.logger(`Assembling rollup with ${txCount} txs`); + context.logger.info(`Assembling rollup with ${txCount} txs`); const sentTxs = await sendTxs(txCount, context, contract); context.logger.info(`Sent ${txCount} txs`); // Restart sequencer to process all txs together @@ -35,22 +35,22 @@ describe('benchmarks/publish_rollup', () => { // Create a new aztec node to measure sync time of the block // and call getPublicStorageAt (which calls #getWorldState, which calls #syncWorldState) to force a sync with // world state to ensure the node has caught up - context.logger(`Starting new aztec node`); + context.logger.info(`Starting new aztec node`); const node = await AztecNodeService.createAndSync({ ...context.config, disableSequencer: true }); await node.getPublicStorageAt(AztecAddress.random(), Fr.random()); // Spin up a new pxe and sync it, we'll use it to test sync times of new accounts for the last block - context.logger(`Starting new pxe`); + context.logger.info(`Starting new pxe`); const pxe = await waitNewPXESynced(node, contract, blockNumber! - 1); // Register the owner account and wait until it's synced so we measure how much time it took - context.logger(`Registering owner account on new pxe`); + context.logger.info(`Registering owner account on new pxe`); const partialAddress = context.wallet.getCompleteAddress().partialAddress; const privateKey = context.wallet.getEncryptionPrivateKey(); await waitRegisteredAccountSynced(pxe, privateKey, partialAddress); // Repeat for another account that didn't receive any notes for them, so we measure trial-decrypts - context.logger(`Registering fresh account on new pxe`); + context.logger.info(`Registering fresh account on new pxe`); await waitRegisteredAccountSynced(pxe, GrumpkinScalar.random(), Fr.random()); // Stop the external node and pxe diff --git a/yarn-project/end-to-end/src/benchmarks/utils.ts b/yarn-project/end-to-end/src/benchmarks/utils.ts index 4f2cc4362dae..5392e85227c4 100644 --- a/yarn-project/end-to-end/src/benchmarks/utils.ts +++ b/yarn-project/end-to-end/src/benchmarks/utils.ts @@ -27,7 +27,7 @@ import { type EndToEndContext, setup } from '../fixtures/utils.js'; export async function benchmarkSetup(opts: Partial) { const context = await setup(1, { ...opts }); const contract = await BenchmarkingContract.deploy(context.wallet).send().deployed(); - context.logger(`Deployed benchmarking contract at ${contract.address}`); + context.logger.info(`Deployed benchmarking contract at ${contract.address}`); const sequencer = (context.aztecNode as AztecNodeService).getSequencer()!; return { context, contract, sequencer }; } diff --git a/yarn-project/end-to-end/src/cli_docs_sandbox.test.ts b/yarn-project/end-to-end/src/cli_docs_sandbox.test.ts index ffb3a058b0b0..03f5f1de00d7 100644 --- a/yarn-project/end-to-end/src/cli_docs_sandbox.test.ts +++ b/yarn-project/end-to-end/src/cli_docs_sandbox.test.ts @@ -17,7 +17,7 @@ describe('CLI docs sandbox', () => { beforeAll(async () => { log = (msg: string) => { logs.push(msg); - debug(msg); + debug.verbose(msg); }; await waitForSandboxWithCli(); diff --git a/yarn-project/end-to-end/src/e2e_2_pxes.test.ts b/yarn-project/end-to-end/src/e2e_2_pxes.test.ts index 2ec022084006..3fac2ce5b74c 100644 --- a/yarn-project/end-to-end/src/e2e_2_pxes.test.ts +++ b/yarn-project/end-to-end/src/e2e_2_pxes.test.ts @@ -75,19 +75,19 @@ describe('e2e_2_pxes', () => { // Then check the balance const contractWithWallet = await TokenContract.at(tokenAddress, wallet); const balance = await contractWithWallet.methods.balance_of_private(owner).simulate({ from: owner }); - logger(`Account ${owner} balance: ${balance}`); + logger.info(`Account ${owner} balance: ${balance}`); expect(balance).toBe(expectedBalance); }; const deployTokenContract = async (initialAdminBalance: bigint, admin: AztecAddress, pxe: PXE) => { - logger(`Deploying Token contract...`); + logger.info(`Deploying Token contract...`); const contract = await TokenContract.deploy(walletA, admin, 'TokenName', 'TokenSymbol', 18).send().deployed(); if (initialAdminBalance > 0n) { await mintTokens(contract, admin, initialAdminBalance, pxe); } - logger('L2 contract deployed'); + logger.info('L2 contract deployed'); return contract.instance; }; @@ -167,9 +167,9 @@ describe('e2e_2_pxes', () => { }, 120_000); const deployChildContractViaServerA = async () => { - logger(`Deploying Child contract...`); + logger.info(`Deploying Child contract...`); const contract = await ChildContract.deploy(walletA).send().deployed(); - logger('Child contract deployed'); + logger.info('Child contract deployed'); return contract.instance; }; diff --git a/yarn-project/end-to-end/src/e2e_account_contracts.test.ts b/yarn-project/end-to-end/src/e2e_account_contracts.test.ts index 18aac67c1a01..89e8de6aa4a3 100644 --- a/yarn-project/end-to-end/src/e2e_account_contracts.test.ts +++ b/yarn-project/end-to-end/src/e2e_account_contracts.test.ts @@ -47,12 +47,12 @@ function itShouldBehaveLikeAnAccountContract( afterEach(() => teardown()); it('calls a private function', async () => { - logger('Calling private function...'); + logger.info('Calling private function...'); await child.methods.value(42).send().wait({ interval: 0.1 }); }, 60_000); it('calls a public function', async () => { - logger('Calling public function...'); + logger.info('Calling public function...'); await child.methods.pub_inc_value(42).send().wait({ interval: 0.1 }); const storedValue = await pxe.getPublicStorageAt(child.address, new Fr(1)); expect(storedValue).toEqual(new Fr(42n)); diff --git a/yarn-project/end-to-end/src/e2e_aztec_js_browser.test.ts b/yarn-project/end-to-end/src/e2e_aztec_js_browser.test.ts index fe12f518236d..d9fac6ce3d14 100644 --- a/yarn-project/end-to-end/src/e2e_aztec_js_browser.test.ts +++ b/yarn-project/end-to-end/src/e2e_aztec_js_browser.test.ts @@ -43,7 +43,7 @@ const setupApp = async () => { const app = new Koa(); app.use(serve(path.resolve(__dirname, './web'))); const server = app.listen(PORT, () => { - logger(`Web Server started at http://localhost:${PORT}`); + logger.info(`Web Server started at http://localhost:${PORT}`); }); return { server, webServerURL: `http://localhost:${PORT}`, pxeServer, pxeURL }; diff --git a/yarn-project/end-to-end/src/e2e_blacklist_token_contract.test.ts b/yarn-project/end-to-end/src/e2e_blacklist_token_contract.test.ts index 7fe2c4e887f0..592240844530 100644 --- a/yarn-project/end-to-end/src/e2e_blacklist_token_contract.test.ts +++ b/yarn-project/end-to-end/src/e2e_blacklist_token_contract.test.ts @@ -130,7 +130,7 @@ describe('e2e_blacklist_token_contract', () => { expect(roleLeaf['before']).toEqual(0n); expect(roleLeaf['after']).toEqual(4n); - logger(`Token deployed to ${asset.address}`); + logger.info(`Token deployed to ${asset.address}`); tokenSim = new TokenSimulator( asset as unknown as TokenContract, logger, @@ -138,7 +138,7 @@ describe('e2e_blacklist_token_contract', () => { ); asset.artifact.functions.forEach(fn => { - logger( + logger.info( `Function ${fn.name} has ${fn.bytecode.length} bytes and the selector: ${FunctionSelector.fromNameAndParameters( fn.name, fn.parameters, diff --git a/yarn-project/end-to-end/src/e2e_block_building.test.ts b/yarn-project/end-to-end/src/e2e_block_building.test.ts index bbc877c75575..b2f77702822f 100644 --- a/yarn-project/end-to-end/src/e2e_block_building.test.ts +++ b/yarn-project/end-to-end/src/e2e_block_building.test.ts @@ -62,9 +62,9 @@ describe('e2e_block_building', () => { // Send them simultaneously to be picked up by the sequencer const txs = await Promise.all(methods.map(method => method.send())); - logger(`Txs sent with hashes: `); + logger.info(`Txs sent with hashes: `); for (const tx of txs) { - logger(` ${await tx.getTxHash()}`); + logger.info(` ${await tx.getTxHash()}`); } // Await txs to be mined and assert they are all mined on the same block @@ -118,7 +118,7 @@ describe('e2e_block_building', () => { beforeAll(async () => { ({ teardown, pxe, logger, wallet: owner } = await setup(1)); contract = await TestContract.deploy(owner).send().deployed(); - logger(`Test contract deployed at ${contract.address}`); + logger.info(`Test contract deployed at ${contract.address}`); }, 100_000); afterAll(() => teardown()); diff --git a/yarn-project/end-to-end/src/e2e_card_game.test.ts b/yarn-project/end-to-end/src/e2e_card_game.test.ts index e92f0988880c..61d2f2399c4a 100644 --- a/yarn-project/end-to-end/src/e2e_card_game.test.ts +++ b/yarn-project/end-to-end/src/e2e_card_game.test.ts @@ -108,13 +108,13 @@ describe('e2e_card_game', () => { }); for (let i = 0; i < toRegister.length; i++) { - logger(`Deploying account contract ${i}/${toRegister.length}...`); + logger.info(`Deploying account contract ${i}/${toRegister.length}...`); const encryptionPrivateKey = toRegister[i]; const account = getSchnorrAccount(pxe, encryptionPrivateKey, GrumpkinScalar.random()); const wallet = await account.waitSetup({ interval: 0.1 }); wallets.push(wallet); } - logger('Account contracts deployed'); + logger.info('Account contracts deployed'); [firstPlayerWallet, secondPlayerWallet, thirdPlayerWallet] = wallets; [firstPlayer, secondPlayer, thirdPlayer] = wallets.map(a => a.getAddress()); @@ -129,11 +129,11 @@ describe('e2e_card_game', () => { afterAll(() => teardown()); const deployContract = async () => { - logger(`Deploying L2 contract...`); + logger.debug(`Deploying L2 contract...`); contract = await CardGameContract.deploy(firstPlayerWallet).send().deployed(); contractAsSecondPlayer = contract.withWallet(secondPlayerWallet); contractAsThirdPlayer = contract.withWallet(thirdPlayerWallet); - logger(`L2 contract deployed at ${contract.address}`); + logger.info(`L2 contract deployed at ${contract.address}`); }; const getWallet = (address: AztecAddress) => wallets.find(w => w.getAddress().equals(address))!; diff --git a/yarn-project/end-to-end/src/e2e_cli.test.ts b/yarn-project/end-to-end/src/e2e_cli.test.ts index 1edf7050eba8..7acb8ed63275 100644 --- a/yarn-project/end-to-end/src/e2e_cli.test.ts +++ b/yarn-project/end-to-end/src/e2e_cli.test.ts @@ -6,7 +6,7 @@ import { setup as e2eSetup } from './fixtures/utils.js'; import { cliTestSuite } from './shared/cli.js'; const HTTP_PORT = 9009; -const debug = createDebugLogger('aztec:e2e_cli'); +const log = createDebugLogger('aztec:e2e_cli'); const { PXE_URL = '' } = process.env; let RPC_URL = PXE_URL; @@ -17,11 +17,11 @@ let teardown: () => Promise; const testSetup = async () => { const context = await e2eSetup(2); - debug(`Environment set up`); + log.info(`Environment set up`); ({ pxe, teardown } = context); if (!RPC_URL) { http = startHttpRpcServer('pxe', pxe, createPXERpcServer, HTTP_PORT); - debug(`HTTP RPC server started on port ${HTTP_PORT}`); + log.info(`HTTP RPC server started on port ${HTTP_PORT}`); RPC_URL = `http://localhost:${HTTP_PORT}`; } return { pxe, rpcURL: RPC_URL }; diff --git a/yarn-project/end-to-end/src/e2e_counter_contract.test.ts b/yarn-project/end-to-end/src/e2e_counter_contract.test.ts index 98f4dd931b38..f2d75506afbe 100644 --- a/yarn-project/end-to-end/src/e2e_counter_contract.test.ts +++ b/yarn-project/end-to-end/src/e2e_counter_contract.test.ts @@ -18,7 +18,7 @@ describe('e2e_counter_contract', () => { counterContract = await CounterContract.deploy(wallet, 0, owner).send().deployed(); - logger(`Counter contract deployed at ${counterContract.address}`); + logger.info(`Counter contract deployed at ${counterContract.address}`); }, 25_000); afterAll(() => teardown()); diff --git a/yarn-project/end-to-end/src/e2e_cross_chain_messaging.test.ts b/yarn-project/end-to-end/src/e2e_cross_chain_messaging.test.ts index e6f45ed8df57..e7d3b42101fd 100644 --- a/yarn-project/end-to-end/src/e2e_cross_chain_messaging.test.ts +++ b/yarn-project/end-to-end/src/e2e_cross_chain_messaging.test.ts @@ -60,7 +60,7 @@ describe('e2e_cross_chain_messaging', () => { logger = logger_; aztecNode = aztecNode_; teardown = teardown_; - logger('Successfully deployed contracts and initialized portal'); + logger.info('Successfully deployed contracts and initialized portal'); }, 100_000); afterEach(async () => { @@ -101,7 +101,7 @@ describe('e2e_cross_chain_messaging', () => { await crossChainTestHarness.expectPrivateBalanceOnL2(ownerAddress, bridgeAmount); // time to withdraw the funds again! - logger('Withdrawing funds from L2'); + logger.info('Withdrawing funds from L2'); // docs:start:authwit_to_another_sc // 4. Give approval to bridge to burn owner's funds: diff --git a/yarn-project/end-to-end/src/e2e_crowdfunding_and_claim.test.ts b/yarn-project/end-to-end/src/e2e_crowdfunding_and_claim.test.ts index fd47b6b9515b..d694dc453d5a 100644 --- a/yarn-project/end-to-end/src/e2e_crowdfunding_and_claim.test.ts +++ b/yarn-project/end-to-end/src/e2e_crowdfunding_and_claim.test.ts @@ -93,7 +93,7 @@ describe('e2e_crowdfunding_and_claim', () => { ) .send() .deployed(); - logger(`Donation Token deployed to ${donationToken.address}`); + logger.info(`Donation Token deployed to ${donationToken.address}`); rewardToken = await TokenContract.deploy( operatorWallet, @@ -104,7 +104,7 @@ describe('e2e_crowdfunding_and_claim', () => { ) .send() .deployed(); - logger(`Reward Token deployed to ${rewardToken.address}`); + logger.info(`Reward Token deployed to ${rewardToken.address}`); crowdfundingPrivateKey = GrumpkinScalar.random(); crowdfundingPublicKey = generatePublicKey(crowdfundingPrivateKey); @@ -119,12 +119,12 @@ describe('e2e_crowdfunding_and_claim', () => { const crowdfundingInstance = crowdfundingDeployment.getInstance(); await pxe.registerAccount(crowdfundingPrivateKey, computePartialAddress(crowdfundingInstance)); crowdfundingContract = await crowdfundingDeployment.send().deployed(); - logger(`Crowdfunding contract deployed at ${crowdfundingContract.address}`); + logger.info(`Crowdfunding contract deployed at ${crowdfundingContract.address}`); claimContract = await ClaimContract.deploy(operatorWallet, crowdfundingContract.address, rewardToken.address) .send() .deployed(); - logger(`Claim contract deployed at ${claimContract.address}`); + logger.info(`Claim contract deployed at ${claimContract.address}`); await rewardToken.methods.set_minter(claimContract.address, true).send().wait(); diff --git a/yarn-project/end-to-end/src/e2e_deploy_contract.test.ts b/yarn-project/end-to-end/src/e2e_deploy_contract.test.ts index 6e22ae602960..c3adb1097456 100644 --- a/yarn-project/end-to-end/src/e2e_deploy_contract.test.ts +++ b/yarn-project/end-to-end/src/e2e_deploy_contract.test.ts @@ -76,7 +76,7 @@ describe('e2e_deploy_contract', () => { const deployer = new ContractDeployer(TestContractArtifact, wallet); for (let index = 0; index < 2; index++) { - logger(`Deploying contract ${index + 1}...`); + logger.info(`Deploying contract ${index + 1}...`); await deployer.deploy().send({ contractAddressSalt: Fr.random() }).wait({ wallet }); } }, 60_000); @@ -88,9 +88,9 @@ describe('e2e_deploy_contract', () => { const deployer = new ContractDeployer(TestContractArtifact, wallet); for (let index = 0; index < 2; index++) { - logger(`Deploying contract ${index + 1}...`); + logger.info(`Deploying contract ${index + 1}...`); const receipt = await deployer.deploy().send({ contractAddressSalt: Fr.random() }).wait({ wallet }); - logger(`Sending TX to contract ${index + 1}...`); + logger.info(`Sending TX to contract ${index + 1}...`); await receipt.contract.methods.get_public_key(wallet.getAddress()).send().wait(); } }, 90_000); @@ -341,7 +341,7 @@ describe('e2e_deploy_contract', () => { deployer: opts.deployer, }); const { address, contractClassId } = instance; - logger(`Deploying contract instance at ${address.toString()} class id ${contractClassId.toString()}`); + logger.info(`Deploying contract instance at ${address.toString()} class id ${contractClassId.toString()}`); await deployFn(instance); // TODO(@spalladino) We should **not** need the whole instance, including initArgs and salt, diff --git a/yarn-project/end-to-end/src/e2e_escrow_contract.test.ts b/yarn-project/end-to-end/src/e2e_escrow_contract.test.ts index 0669466aae10..ef80dcffca83 100644 --- a/yarn-project/end-to-end/src/e2e_escrow_contract.test.ts +++ b/yarn-project/end-to-end/src/e2e_escrow_contract.test.ts @@ -54,7 +54,7 @@ describe('e2e_escrow_contract', () => { const escrowInstance = escrowDeployment.getInstance(); await pxe.registerAccount(escrowPrivateKey, computePartialAddress(escrowInstance)); escrowContract = await escrowDeployment.send().deployed(); - logger(`Escrow contract deployed at ${escrowContract.address}`); + logger.info(`Escrow contract deployed at ${escrowContract.address}`); // Deploy Token contract and mint funds for the escrow contract token = await TokenContract.deploy(wallet, owner, 'TokenName', 'TokenSymbol', 18).send().deployed(); @@ -79,14 +79,14 @@ describe('e2e_escrow_contract', () => { await token.methods.redeem_shield(escrowContract.address, mintAmount, secret).send().wait(); - logger(`Token contract deployed at ${token.address}`); + logger.info(`Token contract deployed at ${token.address}`); }, 100_000); afterEach(() => teardown(), 30_000); const expectBalance = async (who: AztecAddress, expectedBalance: bigint) => { const balance = await token.methods.balance_of_private(who).simulate({ from: who }); - logger(`Account ${who} balance: ${balance}`); + logger.info(`Account ${who} balance: ${balance}`); expect(balance).toBe(expectedBalance); }; @@ -95,7 +95,7 @@ describe('e2e_escrow_contract', () => { await expectBalance(recipient, 0n); await expectBalance(escrowContract.address, 100n); - logger(`Withdrawing funds from token contract to ${recipient}`); + logger.info(`Withdrawing funds from token contract to ${recipient}`); await escrowContract.methods.withdraw(token.address, 30, recipient).send().wait(); await expectBalance(owner, 0n); @@ -110,7 +110,7 @@ describe('e2e_escrow_contract', () => { }, 60_000); it('moves funds using multiple keys on the same tx (#1010)', async () => { - logger(`Minting funds in token contract to ${owner}`); + logger.info(`Minting funds in token contract to ${owner}`); const mintAmount = 50n; const secret = Fr.random(); const secretHash = computeMessageSecretHash(secret); diff --git a/yarn-project/end-to-end/src/e2e_fees.test.ts b/yarn-project/end-to-end/src/e2e_fees.test.ts index c29e101fe5af..7aed8e282ebf 100644 --- a/yarn-project/end-to-end/src/e2e_fees.test.ts +++ b/yarn-project/end-to-end/src/e2e_fees.test.ts @@ -90,10 +90,10 @@ describe('e2e_fees', () => { .send() .deployed(); - logger(`BananaCoin deployed at ${bananaCoin.address}`); + logger.info(`BananaCoin deployed at ${bananaCoin.address}`); bananaFPC = await FPCContract.deploy(wallets[0], bananaCoin.address, gasTokenContract.address).send().deployed(); - logger(`bananaPay deployed at ${bananaFPC.address}`); + logger.info(`BananaPay deployed at ${bananaFPC.address}`); await publicDeployAccounts(wallets[0], wallets); await gasBridgeTestHarness.bridgeFromL1ToL2(BRIDGED_FPC_GAS, BRIDGED_FPC_GAS, bananaFPC.address); @@ -643,7 +643,7 @@ describe('e2e_fees', () => { function logFunctionSignatures(artifact: ContractArtifact, logger: DebugLogger) { artifact.functions.forEach(fn => { const sig = decodeFunctionSignature(fn.name, fn.parameters); - logger(`${FunctionSelector.fromNameAndParameters(fn.name, fn.parameters)} => ${artifact.name}.${sig} `); + logger.verbose(`${FunctionSelector.fromNameAndParameters(fn.name, fn.parameters)} => ${artifact.name}.${sig} `); }); } diff --git a/yarn-project/end-to-end/src/e2e_lending_contract.test.ts b/yarn-project/end-to-end/src/e2e_lending_contract.test.ts index b18131fdcce7..738887cdd42b 100644 --- a/yarn-project/end-to-end/src/e2e_lending_contract.test.ts +++ b/yarn-project/end-to-end/src/e2e_lending_contract.test.ts @@ -34,25 +34,25 @@ describe('e2e_lending_contract', () => { let lendingSim: LendingSimulator; const deployContracts = async () => { - logger(`Deploying price feed contract...`); + logger.info(`Deploying price feed contract...`); const priceFeedContract = await PriceFeedContract.deploy(wallet).send().deployed(); - logger(`Price feed deployed to ${priceFeedContract.address}`); + logger.info(`Price feed deployed to ${priceFeedContract.address}`); - logger(`Deploying collateral asset feed contract...`); + logger.info(`Deploying collateral asset feed contract...`); const collateralAsset = await TokenContract.deploy(wallet, wallet.getAddress(), 'TokenName', 'TokenSymbol', 18) .send() .deployed(); - logger(`Collateral asset deployed to ${collateralAsset.address}`); + logger.info(`Collateral asset deployed to ${collateralAsset.address}`); - logger(`Deploying stable coin contract...`); + logger.info(`Deploying stable coin contract...`); const stableCoin = await TokenContract.deploy(wallet, wallet.getAddress(), 'TokenName', 'TokenSymbol', 18) .send() .deployed(); - logger(`Stable coin asset deployed to ${stableCoin.address}`); + logger.info(`Stable coin asset deployed to ${stableCoin.address}`); - logger(`Deploying L2 public contract...`); + logger.info(`Deploying L2 public contract...`); const lendingContract = await LendingContract.deploy(wallet).send().deployed(); - logger(`CDP deployed at ${lendingContract.address}`); + logger.info(`CDP deployed at ${lendingContract.address}`); await collateralAsset.methods.set_minter(lendingContract.address, true).send().wait(); await stableCoin.methods.set_minter(lendingContract.address, true).send().wait(); @@ -129,7 +129,7 @@ describe('e2e_lending_contract', () => { it('Initialize the contract', async () => { await lendingSim.prepare(); - logger('Initializing contract'); + logger.info('Initializing contract'); await lendingContract.methods .init(priceFeedContract.address, 8000, collateralAsset.address, stableCoin.address) .send() @@ -152,7 +152,7 @@ describe('e2e_lending_contract', () => { // - increase the interest accumulator // - increase last updated timestamp. // - increase the private collateral. - logger('Depositing 🥸 : 💰 -> 🏦'); + logger.info('Depositing 🥸 : 💰 -> 🏦'); await lendingContract.methods .deposit_private( lendingAccount.address, @@ -181,7 +181,7 @@ describe('e2e_lending_contract', () => { // - increase the interest accumulator // - increase last updated timestamp. // - increase the public collateral. - logger('Depositing 🥸 on behalf of recipient: 💰 -> 🏦'); + logger.info('Depositing 🥸 on behalf of recipient: 💰 -> 🏦'); await lendingContract.methods .deposit_private( lendingAccount.address, @@ -226,7 +226,7 @@ describe('e2e_lending_contract', () => { // - increase last updated timestamp. // - increase the public collateral. - logger('Depositing: 💰 -> 🏦'); + logger.info('Depositing: 💰 -> 🏦'); await lendingContract.methods .deposit_public(depositAmount, nonce, lendingAccount.address, collateralAsset.address) .send() @@ -246,7 +246,7 @@ describe('e2e_lending_contract', () => { // - increase last updated timestamp. // - increase the private debt. - logger('Borrow 🥸 : 🏦 -> 🍌'); + logger.info('Borrow 🥸 : 🏦 -> 🍌'); await lendingContract.methods .borrow_private(lendingAccount.secret, lendingAccount.address, borrowAmount) .send() @@ -264,7 +264,7 @@ describe('e2e_lending_contract', () => { // - increase last updated timestamp. // - increase the public debt. - logger('Borrow: 🏦 -> 🍌'); + logger.info('Borrow: 🏦 -> 🍌'); await lendingContract.methods.borrow_public(lendingAccount.address, borrowAmount).send().wait(); }); }); @@ -287,7 +287,7 @@ describe('e2e_lending_contract', () => { // - increase last updated timestamp. // - decrease the private debt. - logger('Repay 🥸 : 🍌 -> 🏦'); + logger.info('Repay 🥸 : 🍌 -> 🏦'); await lendingContract.methods .repay_private(lendingAccount.address, repayAmount, nonce, lendingAccount.secret, 0n, stableCoin.address) .send() @@ -311,7 +311,7 @@ describe('e2e_lending_contract', () => { // - increase last updated timestamp. // - decrease the public debt. - logger('Repay 🥸 on behalf of public: 🍌 -> 🏦'); + logger.info('Repay 🥸 on behalf of public: 🍌 -> 🏦'); await lendingContract.methods .repay_private(lendingAccount.address, repayAmount, nonce, 0n, lendingAccount.address, stableCoin.address) .send() @@ -341,7 +341,7 @@ describe('e2e_lending_contract', () => { // - increase last updated timestamp. // - decrease the public debt. - logger('Repay: 🍌 -> 🏦'); + logger.info('Repay: 🍌 -> 🏦'); await lendingContract.methods .repay_public(repayAmount, nonce, lendingAccount.address, stableCoin.address) .send() @@ -361,7 +361,7 @@ describe('e2e_lending_contract', () => { // - increase last updated timestamp. // - decrease the public collateral. - logger('Withdraw: 🏦 -> 💰'); + logger.info('Withdraw: 🏦 -> 💰'); await lendingContract.methods.withdraw_public(lendingAccount.address, withdrawAmount).send().wait(); }); @@ -376,7 +376,7 @@ describe('e2e_lending_contract', () => { // - increase last updated timestamp. // - decrease the private collateral. - logger('Withdraw 🥸 : 🏦 -> 💰'); + logger.info('Withdraw 🥸 : 🏦 -> 💰'); await lendingContract.methods .withdraw_private(lendingAccount.secret, lendingAccount.address, withdrawAmount) .send() @@ -386,7 +386,7 @@ describe('e2e_lending_contract', () => { describe('failure cases', () => { it('withdraw more than possible to revert', async () => { // Withdraw more than possible to test the revert. - logger('Withdraw: trying to withdraw more than possible'); + logger.info('Withdraw: trying to withdraw more than possible'); await expect( lendingContract.methods.withdraw_public(lendingAccount.address, 10n ** 9n).prove(), ).rejects.toThrow(); diff --git a/yarn-project/end-to-end/src/e2e_multiple_accounts_1_enc_key.test.ts b/yarn-project/end-to-end/src/e2e_multiple_accounts_1_enc_key.test.ts index 10fa2c76cda3..b9b25a2f6acf 100644 --- a/yarn-project/end-to-end/src/e2e_multiple_accounts_1_enc_key.test.ts +++ b/yarn-project/end-to-end/src/e2e_multiple_accounts_1_enc_key.test.ts @@ -36,7 +36,7 @@ describe('e2e_multiple_accounts_1_enc_key', () => { const encryptionPrivateKey = GrumpkinScalar.random(); for (let i = 0; i < numAccounts; i++) { - logger(`Deploying account contract ${i}/3...`); + logger.info(`Deploying account contract ${i}/3...`); const signingPrivateKey = GrumpkinScalar.random(); const account = getSchnorrAccount(pxe, encryptionPrivateKey, signingPrivateKey); const wallet = await account.waitSetup({ interval: 0.1 }); @@ -44,7 +44,7 @@ describe('e2e_multiple_accounts_1_enc_key', () => { wallets.push(wallet); accounts.push(completeAddress); } - logger('Account contracts deployed'); + logger.info('Account contracts deployed'); // Verify that all accounts use the same encryption key const encryptionPublicKey = generatePublicKey(encryptionPrivateKey); @@ -53,10 +53,10 @@ describe('e2e_multiple_accounts_1_enc_key', () => { expect(account.publicKey).toEqual(encryptionPublicKey); } - logger(`Deploying Token...`); + logger.info(`Deploying Token...`); const token = await TokenContract.deploy(wallets[0], accounts[0], 'TokenName', 'TokenSymbol', 18).send().deployed(); tokenAddress = token.address; - logger(`Token deployed at ${tokenAddress}`); + logger.info(`Token deployed at ${tokenAddress}`); const secret = Fr.random(); const secretHash = computeMessageSecretHash(secret); @@ -86,7 +86,7 @@ describe('e2e_multiple_accounts_1_enc_key', () => { // Then check the balance const contractWithWallet = await TokenContract.at(tokenAddress, wallet); const balance = await contractWithWallet.methods.balance_of_private(owner).simulate({ from: owner.address }); - logger(`Account ${owner} balance: ${balance}`); + logger.info(`Account ${owner} balance: ${balance}`); expect(balance).toBe(expectedBalance); }; @@ -96,7 +96,7 @@ describe('e2e_multiple_accounts_1_enc_key', () => { transferAmount: bigint, expectedBalances: bigint[], ) => { - logger(`Transfer ${transferAmount} from ${accounts[senderIndex]} to ${accounts[receiverIndex]}...`); + logger.info(`Transfer ${transferAmount} from ${accounts[senderIndex]} to ${accounts[receiverIndex]}...`); const sender = accounts[senderIndex]; const receiver = accounts[receiverIndex]; @@ -111,7 +111,7 @@ describe('e2e_multiple_accounts_1_enc_key', () => { await expectsNumOfEncryptedLogsInTheLastBlockToBe(aztecNode, 2); - logger(`Transfer ${transferAmount} from ${sender} to ${receiver} successful`); + logger.info(`Transfer ${transferAmount} from ${sender} to ${receiver} successful`); }; /** diff --git a/yarn-project/end-to-end/src/e2e_nested_contract.test.ts b/yarn-project/end-to-end/src/e2e_nested_contract.test.ts index 919b775099fc..86b9410cb5ce 100644 --- a/yarn-project/end-to-end/src/e2e_nested_contract.test.ts +++ b/yarn-project/end-to-end/src/e2e_nested_contract.test.ts @@ -161,29 +161,29 @@ describe('e2e_nested_contract', () => { let testContract: TestContract; beforeEach(async () => { - logger(`Deploying importer test contract`); + logger.info(`Deploying importer test contract`); importerContract = await ImportTestContract.deploy(wallet).send().deployed(); - logger(`Deploying test contract`); + logger.info(`Deploying test contract`); testContract = await TestContract.deploy(wallet).send().deployed(); }, 30_000); it('calls a method with multiple arguments', async () => { - logger(`Calling main on importer contract`); + logger.info(`Calling main on importer contract`); await importerContract.methods.main(testContract.address).send().wait(); }, 30_000); it('calls a method no arguments', async () => { - logger(`Calling noargs on importer contract`); + logger.info(`Calling noargs on importer contract`); await importerContract.methods.call_no_args(testContract.address).send().wait(); }, 30_000); it('calls an open function', async () => { - logger(`Calling openfn on importer contract`); + logger.info(`Calling openfn on importer contract`); await importerContract.methods.call_open_fn(testContract.address).send().wait(); }, 30_000); it('calls an open function from an open function', async () => { - logger(`Calling pub openfn on importer contract`); + logger.info(`Calling pub openfn on importer contract`); await importerContract.methods.pub_call_open_fn(testContract.address).send().wait(); }, 30_000); }); diff --git a/yarn-project/end-to-end/src/e2e_non_contract_account.test.ts b/yarn-project/end-to-end/src/e2e_non_contract_account.test.ts index 65a56eb1d1bf..100ad4c7646f 100644 --- a/yarn-project/end-to-end/src/e2e_non_contract_account.test.ts +++ b/yarn-project/end-to-end/src/e2e_non_contract_account.test.ts @@ -27,9 +27,9 @@ describe('e2e_non_contract_account', () => { ({ teardown, pxe, wallet, logger } = await setup(1)); nonContractAccountWallet = new SignerlessWallet(pxe); - logger(`Deploying L2 contract...`); + logger.debug(`Deploying L2 contract...`); contract = await TestContract.deploy(wallet).send().deployed(); - logger('L2 contract deployed'); + logger.info(`L2 contract deployed at ${contract.address}`); }, 100_000); afterEach(() => teardown()); diff --git a/yarn-project/end-to-end/src/e2e_p2p_network.test.ts b/yarn-project/end-to-end/src/e2e_p2p_network.test.ts index 3f7cc1c469e3..7f70195b9405 100644 --- a/yarn-project/end-to-end/src/e2e_p2p_network.test.ts +++ b/yarn-project/end-to-end/src/e2e_p2p_network.test.ts @@ -122,7 +122,7 @@ describe('e2e_p2p_network', () => { const txs: SentTx[] = []; for (let i = 0; i < numTxs; i++) { const tx = await getSchnorrAccount(pxe, GrumpkinScalar.random(), GrumpkinScalar.random(), Fr.random()).deploy(); - logger(`Tx sent with hash ${await tx.getTxHash()}`); + logger.info(`Tx sent with hash ${await tx.getTxHash()}`); const receipt = await tx.getReceipt(); expect(receipt).toEqual( expect.objectContaining({ @@ -130,7 +130,7 @@ describe('e2e_p2p_network', () => { error: '', }), ); - logger(`Receipt received`); + logger.info(`Receipt received for ${await tx.getTxHash()}`); txs.push(tx); } return txs; diff --git a/yarn-project/end-to-end/src/e2e_pending_note_hashes_contract.test.ts b/yarn-project/end-to-end/src/e2e_pending_note_hashes_contract.test.ts index 61ef05c0df25..47cbd7202ed7 100644 --- a/yarn-project/end-to-end/src/e2e_pending_note_hashes_contract.test.ts +++ b/yarn-project/end-to-end/src/e2e_pending_note_hashes_contract.test.ts @@ -42,7 +42,7 @@ describe('e2e_pending_note_hashes_contract', () => { // 0th nullifier should be nonzero (txHash), all others should be zero (should be squashed) for (let n = 0; n < exceptFirstFew + 1; n++) { - logger(`Expecting nullifier ${n} to be nonzero`); + logger.info(`Expecting nullifier ${n} to be nonzero`); expect(nullifierArray[n]).not.toEqual(Fr.ZERO); // 0th nullifier is txHash } for (let n = exceptFirstFew + 1; n < nullifierArray.length; n++) { @@ -51,9 +51,9 @@ describe('e2e_pending_note_hashes_contract', () => { }; const deployContract = async () => { - logger(`Deploying L2 contract...`); + logger.debug(`Deploying L2 contract...`); contract = await PendingNoteHashesContract.deploy(wallet).send().deployed(); - logger('L2 contract deployed'); + logger.info(`L2 contract deployed at ${contract.address}`); return contract; }; diff --git a/yarn-project/end-to-end/src/e2e_private_voting_contract.test.ts b/yarn-project/end-to-end/src/e2e_private_voting_contract.test.ts index 1a0a9710fac9..71c1920c5ce4 100644 --- a/yarn-project/end-to-end/src/e2e_private_voting_contract.test.ts +++ b/yarn-project/end-to-end/src/e2e_private_voting_contract.test.ts @@ -19,7 +19,7 @@ describe('e2e_voting_contract', () => { votingContract = await EasyPrivateVotingContract.deploy(wallet, owner).send().deployed(); - logger(`Counter contract deployed at ${votingContract.address}`); + logger.info(`Counter contract deployed at ${votingContract.address}`); }, 25_000); afterAll(() => teardown()); diff --git a/yarn-project/end-to-end/src/e2e_public_cross_chain_messaging.test.ts b/yarn-project/end-to-end/src/e2e_public_cross_chain_messaging.test.ts index 1031824eaff7..b26721bd6724 100644 --- a/yarn-project/end-to-end/src/e2e_public_cross_chain_messaging.test.ts +++ b/yarn-project/end-to-end/src/e2e_public_cross_chain_messaging.test.ts @@ -67,7 +67,7 @@ describe('e2e_public_cross_chain_messaging', () => { inbox = crossChainTestHarness.inbox; outbox = crossChainTestHarness.outbox; - logger('Successfully deployed contracts and initialized portal'); + logger.info('Successfully deployed contracts and initialized portal'); }, 100_000); afterAll(async () => { @@ -98,7 +98,7 @@ describe('e2e_public_cross_chain_messaging', () => { const afterBalance = bridgeAmount; // time to withdraw the funds again! - logger('Withdrawing funds from L2'); + logger.info('Withdrawing funds from L2'); // 4. Give approval to bridge to burn owner's funds: const withdrawAmount = 9n; @@ -167,7 +167,7 @@ describe('e2e_public_cross_chain_messaging', () => { ).rejects.toThrow(`No non-nullified L1 to L2 message found for message hash ${wrongMessage.hash().toString()}`); // user2 consumes owner's L1-> L2 message on bridge contract and mints public tokens on L2 - logger("user2 consumes owner's message on L2 Publicly"); + logger.info("user2 consumes owner's message on L2 Publicly"); await l2Bridge.withWallet(user2Wallet).methods.claim_public(ownerAddress, bridgeAmount, secret).send().wait(); // ensure funds are gone to owner and not user2. await crossChainTestHarness.expectPublicBalanceOnL2(ownerAddress, bridgeAmount); diff --git a/yarn-project/end-to-end/src/e2e_public_to_private_messaging.test.ts b/yarn-project/end-to-end/src/e2e_public_to_private_messaging.test.ts index cd2eaccf9153..805628e74a85 100644 --- a/yarn-project/end-to-end/src/e2e_public_to_private_messaging.test.ts +++ b/yarn-project/end-to-end/src/e2e_public_to_private_messaging.test.ts @@ -32,7 +32,7 @@ describe('e2e_public_to_private_messaging', () => { teardown = teardown_; logger = logger_; - logger('Successfully deployed contracts and initialized portal'); + logger.info('Successfully deployed contracts and initialized portal'); }, 100_000); afterEach(async () => { diff --git a/yarn-project/end-to-end/src/e2e_sandbox_example.test.ts b/yarn-project/end-to-end/src/e2e_sandbox_example.test.ts index 28416e0d2485..f336bf40c777 100644 --- a/yarn-project/end-to-end/src/e2e_sandbox_example.test.ts +++ b/yarn-project/end-to-end/src/e2e_sandbox_example.test.ts @@ -32,7 +32,7 @@ describe('e2e_sandbox_example', () => { const nodeInfo = await pxe.getNodeInfo(); - logger(format('Aztec Sandbox Info ', nodeInfo)); + logger.info(format('Aztec Sandbox Info ', nodeInfo)); // docs:end:setup expect(typeof nodeInfo.protocolVersion).toBe('number'); @@ -50,19 +50,19 @@ describe('e2e_sandbox_example', () => { const bobWallet = accounts[1]; const alice = aliceWallet.getAddress(); const bob = bobWallet.getAddress(); - logger(`Loaded alice's account at ${alice.toShortString()}`); - logger(`Loaded bob's account at ${bob.toShortString()}`); + logger.info(`Loaded alice's account at ${alice.toShortString()}`); + logger.info(`Loaded bob's account at ${bob.toShortString()}`); // docs:end:load_accounts // docs:start:Deployment ////////////// DEPLOY OUR TOKEN CONTRACT ////////////// const initialSupply = 1_000_000n; - logger(`Deploying token contract...`); + logger.info(`Deploying token contract...`); // Deploy the contract and set Alice as the admin while doing so const contract = await TokenContract.deploy(aliceWallet, alice, 'TokenName', 'TokenSymbol', 18).send().deployed(); - logger(`Contract successfully deployed at address ${contract.address.toShortString()}`); + logger.info(`Contract successfully deployed at address ${contract.address.toShortString()}`); // Create the contract abstraction and link it to Alice's wallet for future signing const tokenContractAlice = await TokenContract.at(contract.address, aliceWallet); @@ -71,7 +71,7 @@ describe('e2e_sandbox_example', () => { const aliceSecret = Fr.random(); const aliceSecretHash = computeMessageSecretHash(aliceSecret); - logger(`Minting tokens to Alice...`); + logger.info(`Minting tokens to Alice...`); // Mint the initial supply privately "to secret hash" const receipt = await tokenContractAlice.methods.mint_private(initialSupply, aliceSecretHash).send().wait(); @@ -91,7 +91,7 @@ describe('e2e_sandbox_example', () => { // Make the tokens spendable by redeeming them using the secret (converts the "pending shield note" created above // to a "token note") await tokenContractAlice.methods.redeem_shield(alice, initialSupply, aliceSecret).send().wait(); - logger(`${initialSupply} tokens were successfully minted and redeemed by Alice`); + logger.info(`${initialSupply} tokens were successfully minted and redeemed by Alice`); // docs:end:Deployment // ensure that token contract is registered in PXE @@ -106,10 +106,10 @@ describe('e2e_sandbox_example', () => { const tokenContractBob = tokenContractAlice.withWallet(bobWallet); let aliceBalance = await tokenContractAlice.methods.balance_of_private(alice).simulate(); - logger(`Alice's balance ${aliceBalance}`); + logger.info(`Alice's balance ${aliceBalance}`); let bobBalance = await tokenContractBob.methods.balance_of_private(bob).simulate(); - logger(`Bob's balance ${bobBalance}`); + logger.info(`Bob's balance ${bobBalance}`); // docs:end:Balance @@ -121,15 +121,15 @@ describe('e2e_sandbox_example', () => { // We will now transfer tokens from ALice to Bob const transferQuantity = 543n; - logger(`Transferring ${transferQuantity} tokens from Alice to Bob...`); + logger.info(`Transferring ${transferQuantity} tokens from Alice to Bob...`); await tokenContractAlice.methods.transfer(alice, bob, transferQuantity, 0).send().wait(); // Check the new balances aliceBalance = await tokenContractAlice.methods.balance_of_private(alice).simulate(); - logger(`Alice's balance ${aliceBalance}`); + logger.info(`Alice's balance ${aliceBalance}`); bobBalance = await tokenContractBob.methods.balance_of_private(bob).simulate(); - logger(`Bob's balance ${bobBalance}`); + logger.info(`Bob's balance ${bobBalance}`); // docs:end:Transfer expect(aliceBalance).toBe(initialSupply - transferQuantity); @@ -148,7 +148,7 @@ describe('e2e_sandbox_example', () => { // Bob now has a secret 🥷 const mintQuantity = 10_000n; - logger(`Minting ${mintQuantity} tokens to Bob...`); + logger.info(`Minting ${mintQuantity} tokens to Bob...`); const mintPrivateReceipt = await tokenContractBob.methods.mint_private(mintQuantity, bobSecretHash).send().wait(); const bobPendingShield = new Note([new Fr(mintQuantity), bobSecretHash]); @@ -167,10 +167,10 @@ describe('e2e_sandbox_example', () => { // Check the new balances aliceBalance = await tokenContractAlice.methods.balance_of_private(alice).simulate(); - logger(`Alice's balance ${aliceBalance}`); + logger.info(`Alice's balance ${aliceBalance}`); bobBalance = await tokenContractBob.methods.balance_of_private(bob).simulate(); - logger(`Bob's balance ${bobBalance}`); + logger.info(`Bob's balance ${bobBalance}`); // docs:end:Mint expect(aliceBalance).toBe(initialSupply - transferQuantity); @@ -207,7 +207,7 @@ describe('e2e_sandbox_example', () => { }; // Create 2 accounts and wallets to go with each - logger(`Creating accounts using schnorr signers...`); + logger.info(`Creating accounts using schnorr signers...`); const accounts = await createSchnorrAccounts(2, pxe); ////////////// VERIFY THE ACCOUNTS WERE CREATED SUCCESSFULLY ////////////// @@ -221,10 +221,10 @@ describe('e2e_sandbox_example', () => { [bob, 'Bob'], ] as const) { if (registeredAccounts.find(acc => acc.equals(account))) { - logger(`Created ${name}'s account at ${account.toShortString()}`); + logger.info(`Created ${name}'s account at ${account.toShortString()}`); continue; } - logger(`Failed to create account for ${name}!`); + logger.info(`Failed to create account for ${name}!`); } // docs:end:create_accounts diff --git a/yarn-project/end-to-end/src/e2e_slow_tree.test.ts b/yarn-project/end-to-end/src/e2e_slow_tree.test.ts index 187535f00b9f..b1f583e9e543 100644 --- a/yarn-project/end-to-end/src/e2e_slow_tree.test.ts +++ b/yarn-project/end-to-end/src/e2e_slow_tree.test.ts @@ -96,7 +96,7 @@ describe('e2e_slow_tree', () => { await wallet.addCapsule(getMembershipCapsule(await getMembershipProof(key, true))); await contract.methods.read_at(key).send().wait(); - logger(`Updating tree[${key}] to 1 from public`); + logger.info(`Updating tree[${key}] to 1 from public`); const t1 = computeNextChange(BigInt(await cheatCodes.eth.timestamp())); await contract.methods .update_at_public(await getUpdateProof(1n, key)) @@ -114,17 +114,17 @@ describe('e2e_slow_tree', () => { await status(key, _root, _leaf); const zeroProof = await getMembershipProof(key, false); - logger(`"Reads" tree[${zeroProof.index}] from the tree, equal to ${zeroProof.value}`); + logger.info(`"Reads" tree[${zeroProof.index}] from the tree, equal to ${zeroProof.value}`); await wallet.addCapsule(getMembershipCapsule({ ...zeroProof, value: new Fr(0) })); await contract.methods.read_at(key).send().wait(); // Progress time to beyond the update and thereby commit it to the tree. await cheatCodes.aztec.warp((await cheatCodes.eth.timestamp()) + 1000); await slowUpdateTreeSimulator.commit(); - logger('--- Progressing time to after the update ---'); + logger.info('--- Progressing time to after the update ---'); await status(key, _root, _leaf); - logger( + logger.info( `Tries to "read" tree[${zeroProof.index}] from the tree, but is rejected as value is not ${zeroProof.value}`, ); await wallet.addCapsule(getMembershipCapsule({ ...zeroProof, value: new Fr(0) })); @@ -132,11 +132,11 @@ describe('e2e_slow_tree', () => { /Assertion failed: Root does not match expected/, ); - logger(`"Reads" tree[${key}], expect to be 1`); + logger.info(`"Reads" tree[${key}], expect to be 1`); await wallet.addCapsule(getMembershipCapsule({ ...zeroProof, value: new Fr(1) })); await contract.methods.read_at(key).send().wait(); - logger(`Updating tree[${key}] to 4 from private`); + logger.info(`Updating tree[${key}] to 4 from private`); const t2 = computeNextChange(BigInt(await cheatCodes.eth.timestamp())); await wallet.addCapsule(getUpdateCapsule(await getUpdateProof(4n, key))); await contract.methods.update_at_private(key, 4n).send().wait(); diff --git a/yarn-project/end-to-end/src/e2e_token_contract.test.ts b/yarn-project/end-to-end/src/e2e_token_contract.test.ts index 22e2ca2bd9eb..01e3b683488b 100644 --- a/yarn-project/end-to-end/src/e2e_token_contract.test.ts +++ b/yarn-project/end-to-end/src/e2e_token_contract.test.ts @@ -65,13 +65,15 @@ describe('e2e_token_contract', () => { TokenContract.artifact.functions.forEach(fn => { const sig = decodeFunctionSignature(fn.name, fn.parameters); - logger(`Function ${sig} and the selector: ${FunctionSelector.fromNameAndParameters(fn.name, fn.parameters)}`); + logger.verbose( + `Function ${sig} and the selector: ${FunctionSelector.fromNameAndParameters(fn.name, fn.parameters)}`, + ); }); asset = await TokenContract.deploy(wallets[0], wallets[0].getAddress(), TOKEN_NAME, TOKEN_SYMBOL, TOKEN_DECIMALS) .send() .deployed(); - logger(`Token deployed to ${asset.address}`); + logger.info(`Token deployed to ${asset.address}`); tokenSim = new TokenSimulator( asset, logger, diff --git a/yarn-project/end-to-end/src/fixtures/utils.ts b/yarn-project/end-to-end/src/fixtures/utils.ts index 6e97bcbfd4fe..39b4fba0df9d 100644 --- a/yarn-project/end-to-end/src/fixtures/utils.ts +++ b/yarn-project/end-to-end/src/fixtures/utils.ts @@ -95,14 +95,14 @@ const getACVMConfig = async (logger: DebugLogger) => { const tempWorkingDirectory = `${TEMP_DIR}/${randomBytes(4).toString('hex')}`; const acvmWorkingDirectory = ACVM_WORKING_DIRECTORY ? ACVM_WORKING_DIRECTORY : `${tempWorkingDirectory}/acvm`; await fs.mkdir(acvmWorkingDirectory, { recursive: true }); - logger(`Using native ACVM binary at ${expectedAcvmPath} with working directory ${acvmWorkingDirectory}`); + logger.info(`Using native ACVM binary at ${expectedAcvmPath} with working directory ${acvmWorkingDirectory}`); return { acvmWorkingDirectory, expectedAcvmPath, directoryToCleanup: ACVM_WORKING_DIRECTORY ? undefined : tempWorkingDirectory, }; } catch (err) { - logger(`Native ACVM not available, error: ${err}`); + logger.error(`Native ACVM not available, error: ${err}`); return undefined; } }; @@ -225,20 +225,20 @@ async function setupWithRemoteEnvironment( ) { // we are setting up against a remote environment, l1 contracts are already deployed const aztecNodeUrl = getAztecUrl(); - logger(`Creating Aztec Node client to remote host ${aztecNodeUrl}`); + logger.verbose(`Creating Aztec Node client to remote host ${aztecNodeUrl}`); const aztecNode = createAztecNodeClient(aztecNodeUrl); - logger(`Creating PXE client to remote host ${PXE_URL}`); + logger.verbose(`Creating PXE client to remote host ${PXE_URL}`); const pxeClient = createPXEClient(PXE_URL, makeFetch([1, 2, 3], true)); await waitForPXE(pxeClient, logger); - logger('JSON RPC client connected to PXE'); - logger(`Retrieving contract addresses from ${PXE_URL}`); + logger.verbose('JSON RPC client connected to PXE'); + logger.verbose(`Retrieving contract addresses from ${PXE_URL}`); const l1Contracts = (await pxeClient.getNodeInfo()).l1ContractAddresses; - logger('PXE created, constructing available wallets from already registered accounts...'); + logger.verbose('PXE created, constructing available wallets from already registered accounts...'); const wallets = await getDeployedTestAccountsWallets(pxeClient); if (wallets.length < numberOfAccounts) { const numNewAccounts = numberOfAccounts - wallets.length; - logger(`Deploying ${numNewAccounts} accounts...`); + logger.verbose(`Deploying ${numNewAccounts} accounts...`); wallets.push(...(await createAccounts(pxeClient, numNewAccounts))); } @@ -363,7 +363,7 @@ export async function setup( config.publisherPrivateKey = `0x${publisherPrivKey!.toString('hex')}`; config.l1Contracts = deployL1ContractsValues.l1ContractAddresses; - logger('Creating and synching an aztec node...'); + logger.verbose('Creating and synching an aztec node...'); const acvmConfig = await getACVMConfig(logger); if (acvmConfig) { @@ -392,7 +392,7 @@ export async function setup( if (acvmConfig?.directoryToCleanup) { // remove the temp directory created for the acvm - logger(`Cleaning up ACVM temp directory ${acvmConfig.directoryToCleanup}`); + logger.verbose(`Cleaning up ACVM temp directory ${acvmConfig.directoryToCleanup}`); await fs.rm(acvmConfig.directoryToCleanup, { recursive: true, force: true }); } @@ -522,7 +522,7 @@ export function getBalancesFn( const balances = async (...addresses: AztecAddress[]) => { const b = await Promise.all(addresses.map(address => method(address).simulate())); const debugString = `${symbol} balances: ${addresses.map((address, i) => `${address}: ${b[i]}`).join(', ')}`; - logger(debugString); + logger.verbose(debugString); return b; }; diff --git a/yarn-project/end-to-end/src/guides/writing_an_account_contract.test.ts b/yarn-project/end-to-end/src/guides/writing_an_account_contract.test.ts index 7f7237b6da62..31919be43857 100644 --- a/yarn-project/end-to-end/src/guides/writing_an_account_contract.test.ts +++ b/yarn-project/end-to-end/src/guides/writing_an_account_contract.test.ts @@ -61,11 +61,11 @@ describe('guides/writing_an_account_contract', () => { const wallet = await account.waitSetup(); const address = wallet.getCompleteAddress().address; // docs:end:account-contract-deploy - logger(`Deployed account contract at ${address}`); + logger.info(`Deployed account contract at ${address}`); // docs:start:account-contract-works const token = await TokenContract.deploy(wallet, { address }, 'TokenName', 'TokenSymbol', 18).send().deployed(); - logger(`Deployed token contract at ${token.address}`); + logger.info(`Deployed token contract at ${token.address}`); const secret = Fr.random(); const secretHash = computeMessageSecretHash(secret); @@ -87,7 +87,7 @@ describe('guides/writing_an_account_contract', () => { await token.methods.redeem_shield({ address }, mintAmount, secret).send().wait(); const balance = await token.methods.balance_of_private({ address }).simulate(); - logger(`Balance of wallet is now ${balance}`); + logger.info(`Balance of wallet is now ${balance}`); // docs:end:account-contract-works expect(balance).toEqual(50n); @@ -101,7 +101,7 @@ describe('guides/writing_an_account_contract', () => { try { await tokenWithWrongWallet.methods.mint_private(200, secretHash).prove(); } catch (err) { - logger(`Failed to send tx: ${err}`); + logger.info(`Failed to send tx: ${err}`); } // docs:end:account-contract-fails }, 60_000); diff --git a/yarn-project/end-to-end/src/shared/browser.ts b/yarn-project/end-to-end/src/shared/browser.ts index c9cc3d2098ed..81681ed6c6a6 100644 --- a/yarn-project/end-to-end/src/shared/browser.ts +++ b/yarn-project/end-to-end/src/shared/browser.ts @@ -91,14 +91,14 @@ export const browserTestSuite = ( }); page = await browser.newPage(); page.on('console', msg => { - pageLogger(msg.text()); + pageLogger.info(msg.text()); }); page.on('pageerror', err => { pageLogger.error(err.toString()); }); await page.goto(`${webServerURL}/index.html`); while (!(await page.evaluate(() => !!window.AztecJs))) { - pageLogger('Waiting for window.AztecJs...'); + pageLogger.verbose('Waiting for window.AztecJs...'); await AztecJs.sleep(1000); } }, 120_000); diff --git a/yarn-project/end-to-end/src/shared/cli.ts b/yarn-project/end-to-end/src/shared/cli.ts index 032a348eaf5e..b6738c2371ad 100644 --- a/yarn-project/end-to-end/src/shared/cli.ts +++ b/yarn-project/end-to-end/src/shared/cli.ts @@ -34,7 +34,7 @@ export const cliTestSuite = ( ({ pxe, rpcURL } = await setup()); log = (msg: string) => { logs.push(msg); - debug(msg); + debug.verbose(msg); }; }, 30_000); @@ -58,7 +58,7 @@ export const cliTestSuite = ( if (addRpcUrl) { args.push('--rpc-url', rpcURL); } - debug(`Running command ${args.join(' ')}`); + debug.info(`Running command ${args.join(' ')}`); const res = cli.parseAsync(args); resetCli(); return res; @@ -91,7 +91,7 @@ export const cliTestSuite = ( it('creates & retrieves an account', async () => { existingAccounts = await pxe.getRegisteredAccounts(); - debug('Create an account'); + debug.info('Create an account'); await run(`create-account`); const foundAddress = findInLogs(/Address:\s+(?
0x[a-fA-F0-9]+)/)?.groups?.address; expect(foundAddress).toBeDefined(); @@ -103,14 +103,14 @@ export const cliTestSuite = ( const newCompleteAddress = accountsAfter[accountsAfter.length - 1]; // Test get-accounts - debug('Check that account was added to the list of accounts in RPC'); + debug.info('Check that account was added to the list of accounts in RPC'); await run('get-accounts'); const fetchedAddresses = findMultipleInLogs(/Address:\s+(?
0x[a-fA-F0-9]+)/); const foundFetchedAddress = fetchedAddresses.find(match => match.groups?.address === newAddress.toString()); expect(foundFetchedAddress).toBeDefined(); // Test get-account - debug('Check we can retrieve the specific account'); + debug.info('Check we can retrieve the specific account'); clearLogs(); await run(`get-account ${newAddress.toString()}`); const fetchedAddress = findInLogs(/Public Key:\s+(?
0x[a-fA-F0-9]+)/)?.groups?.address; @@ -119,7 +119,7 @@ export const cliTestSuite = ( // Regression test for deploy cmd with a constructor not named "constructor" it('deploys a contract using a public initializer', async () => { - debug('Create an account using a private key'); + debug.info('Create an account using a private key'); await run('generate-private-key', false); const privKey = findInLogs(/Private\sKey:\s+0x(?[a-fA-F0-9]+)/)?.groups?.privKey; expect(privKey).toHaveLength(64); @@ -129,7 +129,7 @@ export const cliTestSuite = ( const ownerAddress = AztecAddress.fromString(foundAddress!); const salt = 42; - debug('Deploy StatefulTestContract with public_constructor using created account.'); + debug.info('Deploy StatefulTestContract with public_constructor using created account.'); await run( `deploy StatefulTestContractArtifact --private-key ${privKey} --salt ${salt} --initializer public_constructor --args ${ownerAddress} 100`, ); @@ -156,7 +156,7 @@ export const cliTestSuite = ( 'deploys %s & sends transactions', async (_, artifact, salt) => { // generate a private key - debug('Create an account using a private key'); + debug.info('Create an account using a private key'); await run('generate-private-key', false); const privKey = findInLogs(/Private\sKey:\s+0x(?[a-fA-F0-9]+)/)?.groups?.privKey; expect(privKey).toHaveLength(64); @@ -165,7 +165,7 @@ export const cliTestSuite = ( expect(foundAddress).toBeDefined(); const ownerAddress = AztecAddress.fromString(foundAddress!); - debug('Deploy Token Contract using created account.'); + debug.info('Deploy Token Contract using created account.'); await run( `deploy ${artifact} --private-key ${privKey} --salt ${salt} --args ${ownerAddress} 'TokenName' 'TKN' 18`, ); @@ -176,7 +176,7 @@ export const cliTestSuite = ( const deployedContract = await pxe.getContractInstance(contractAddress); expect(deployedContract?.address).toEqual(contractAddress); - debug('Check contract can be found in returned address'); + debug.info('Check contract can be found in returned address'); await run(`check-deploy -ca ${loggedAddress}`); const checkResult = findInLogs(/Contract.+\sat\s+(?
0x[a-fA-F0-9]+)/)?.groups?.address; expect(checkResult).toEqual(deployedContract?.address.toString()); @@ -184,19 +184,19 @@ export const cliTestSuite = ( const secret = Fr.random(); const secretHash = computeMessageSecretHash(secret); - debug('Mint initial tokens.'); + debug.info('Mint initial tokens.'); await run( `send mint_private --args ${INITIAL_BALANCE} ${secretHash} --contract-artifact TokenContractArtifact --contract-address ${contractAddress.toString()} --private-key ${privKey}`, ); - debug('Add note to the PXE.'); + debug.info('Add note to the PXE.'); const txHashes = findMultipleInLogs(/Transaction Hash: ([0-9a-f]{64})/i); const mintPrivateTxHash = txHashes[txHashes.length - 1][1]; await run( `add-note ${ownerAddress} ${contractAddress} 5 84114971101151129711410111011678111116101 ${mintPrivateTxHash} --note ${INITIAL_BALANCE} ${secretHash}`, ); - debug('Redeem tokens.'); + debug.info('Redeem tokens.'); await run( `send redeem_shield --args ${ownerAddress} ${INITIAL_BALANCE} ${secret} --contract-artifact TokenContractArtifact --contract-address ${contractAddress.toString()} --private-key ${privKey}`, ); @@ -206,14 +206,14 @@ export const cliTestSuite = ( const contractDataAddress = findInLogs(/^\s?Address:\s+(?
0x[a-fA-F0-9]+)/)?.groups?.address; expect(contractDataAddress).toEqual(deployedContract?.address.toString()); - debug("Check owner's balance"); + debug.info("Check owner's balance"); await run( `call balance_of_private --args ${ownerAddress} --contract-artifact TokenContractArtifact --contract-address ${contractAddress.toString()}`, ); const balance = findInLogs(/View\sresult:\s+(?\S+)/)?.groups?.data; expect(balance!).toEqual(`${BigInt(INITIAL_BALANCE).toString()}n`); - debug('Transfer some tokens'); + debug.info('Transfer some tokens'); const existingAccounts = await pxe.getRegisteredAccounts(); // ensure we pick a different acc const receiver = existingAccounts.find(acc => acc.address.toString() !== ownerAddress.toString()); @@ -223,13 +223,13 @@ export const cliTestSuite = ( ); const txHash = findInLogs(/Transaction\shash:\s+(?\S+)/)?.groups?.txHash; - debug('Check the transfer receipt'); + debug.info('Check the transfer receipt'); await run(`get-tx-receipt ${txHash}`); const txResult = findInLogs(/Transaction receipt:\s*(?[\s\S]*?\})/)?.groups?.txHash; const parsedResult = JSON.parse(txResult!); expect(parsedResult.txHash).toEqual(txHash); expect(parsedResult.status).toEqual('mined'); - debug("Check Receiver's balance"); + debug.info("Check Receiver's balance"); clearLogs(); await run( `call balance_of_private --args ${receiver?.address.toString()} --contract-artifact TokenContractArtifact --contract-address ${contractAddress.toString()}`, diff --git a/yarn-project/end-to-end/src/shared/cross_chain_test_harness.ts b/yarn-project/end-to-end/src/shared/cross_chain_test_harness.ts index c7ba3f88a829..342e0ce917f2 100644 --- a/yarn-project/end-to-end/src/shared/cross_chain_test_harness.ts +++ b/yarn-project/end-to-end/src/shared/cross_chain_test_harness.ts @@ -160,7 +160,7 @@ export class CrossChainTestHarness { }); // Deploy and initialize all required contracts - logger('Deploying and initializing token, portal and its bridge...'); + logger.info('Deploying and initializing token, portal and its bridge...'); const { token, bridge, tokenPortalAddress, tokenPortal, underlyingERC20 } = await deployAndInitializeTokenAndBridgeContracts( wallet, @@ -170,7 +170,7 @@ export class CrossChainTestHarness { owner.address, underlyingERC20Address, ); - logger('Deployed and initialized token, portal and its bridge.'); + logger.info('Deployed and initialized token, portal and its bridge.'); return new CrossChainTestHarness( aztecNode, @@ -226,15 +226,15 @@ export class CrossChainTestHarness { ) {} generateClaimSecret(): [Fr, Fr] { - this.logger("Generating a claim secret using pedersen's hash function"); + this.logger.debug("Generating a claim secret using pedersen's hash function"); const secret = Fr.random(); const secretHash = computeMessageSecretHash(secret); - this.logger('Generated claim secret: ' + secretHash.toString()); + this.logger.info('Generated claim secret: ' + secretHash.toString()); return [secret, secretHash]; } async mintTokensOnL1(amount: bigint) { - this.logger('Minting tokens on L1'); + this.logger.info('Minting tokens on L1'); const txHash = await this.underlyingERC20.write.mint([this.ethAccount.toString(), amount], {} as any); await this.publicClient.waitForTransactionReceipt({ hash: txHash }); expect(await this.underlyingERC20.read.balanceOf([this.ethAccount.toString()])).toBe(amount); @@ -252,7 +252,7 @@ export class CrossChainTestHarness { await this.publicClient.waitForTransactionReceipt({ hash: txHash1 }); // Deposit tokens to the TokenPortal - this.logger('Sending messages to L1 portal to be consumed publicly'); + this.logger.info('Sending messages to L1 portal to be consumed publicly'); const args = [this.ownerAddress.toString(), bridgeAmount, secretHash.toString()] as const; const { result: messageHash } = await this.tokenPortal.simulate.depositToAztecPublic(args, { account: this.ethAccount.toString(), @@ -274,7 +274,7 @@ export class CrossChainTestHarness { ); await this.publicClient.waitForTransactionReceipt({ hash: txHash1 }); // Deposit tokens to the TokenPortal - this.logger('Sending messages to L1 portal to be consumed privately'); + this.logger.info('Sending messages to L1 portal to be consumed privately'); const args = [ secretHashForRedeemingMintedNotes.toString(), bridgeAmount, @@ -290,7 +290,7 @@ export class CrossChainTestHarness { } async mintTokensPublicOnL2(amount: bigint) { - this.logger('Minting tokens on L2 publicly'); + this.logger.info('Minting tokens on L2 publicly'); await this.l2Token.methods.mint_public(this.ownerAddress, amount).send().wait(); } @@ -309,7 +309,7 @@ export class CrossChainTestHarness { bridgeAmount: bigint, secretForL2MessageConsumption: Fr, ) { - this.logger('Consuming messages on L2 privately'); + this.logger.info('Consuming messages on L2 privately'); // Call the mint tokens function on the Aztec.nr contract const consumptionReceipt = await this.l2Bridge.methods .claim_private(secretHashForRedeemingMintedNotes, bridgeAmount, secretForL2MessageConsumption) @@ -320,7 +320,7 @@ export class CrossChainTestHarness { } async consumeMessageOnAztecAndMintPublicly(bridgeAmount: bigint, secret: Fr) { - this.logger('Consuming messages on L2 Publicly'); + this.logger.info('Consuming messages on L2 Publicly'); // Call the mint tokens function on the Aztec.nr contract await this.l2Bridge.methods.claim_public(this.ownerAddress, bridgeAmount, secret).send().wait(); } @@ -349,7 +349,7 @@ export class CrossChainTestHarness { async expectPrivateBalanceOnL2(owner: AztecAddress, expectedBalance: bigint) { const balance = await this.getL2PrivateBalanceOf(owner); - this.logger(`Account ${owner} balance: ${balance}`); + this.logger.info(`Account ${owner} balance: ${balance}`); expect(balance).toBe(expectedBalance); } @@ -386,7 +386,7 @@ export class CrossChainTestHarness { messageIndex: bigint, siblingPath: SiblingPath, ) { - this.logger('Send L1 tx to consume message and withdraw funds'); + this.logger.info('Send L1 tx to consume message and withdraw funds'); // Call function on L1 contract to consume the message const { request: withdrawRequest } = await this.tokenPortal.simulate.withdraw([ this.ethAccount.toString(), @@ -412,7 +412,7 @@ export class CrossChainTestHarness { } async shieldFundsOnL2(shieldAmount: bigint, secretHash: Fr) { - this.logger('Shielding funds on L2'); + this.logger.info('Shielding funds on L2'); const shieldReceipt = await this.l2Token.methods .shield(this.ownerAddress, shieldAmount, secretHash, 0) .send() @@ -422,7 +422,7 @@ export class CrossChainTestHarness { } async addPendingShieldNoteToPXE(shieldAmount: bigint, secretHash: Fr, txHash: TxHash) { - this.logger('Adding note to PXE'); + this.logger.info('Adding note to PXE'); const note = new Note([new Fr(shieldAmount), secretHash]); const extendedNote = new ExtendedNote( note, @@ -436,12 +436,12 @@ export class CrossChainTestHarness { } async redeemShieldPrivatelyOnL2(shieldAmount: bigint, secret: Fr) { - this.logger('Spending note in private call'); + this.logger.info('Spending note in private call'); await this.l2Token.methods.redeem_shield(this.ownerAddress, shieldAmount, secret).send().wait(); } async unshieldTokensOnL2(unshieldAmount: bigint, nonce = Fr.ZERO) { - this.logger('Unshielding tokens'); + this.logger.info('Unshielding tokens'); await this.l2Token.methods.unshield(this.ownerAddress, this.ownerAddress, unshieldAmount, nonce).send().wait(); } diff --git a/yarn-project/end-to-end/src/shared/gas_portal_test_harness.ts b/yarn-project/end-to-end/src/shared/gas_portal_test_harness.ts index 6118be50591a..1897042ab050 100644 --- a/yarn-project/end-to-end/src/shared/gas_portal_test_harness.ts +++ b/yarn-project/end-to-end/src/shared/gas_portal_test_harness.ts @@ -144,15 +144,15 @@ class GasBridgingTestHarness implements IGasBridgingTestHarness { ) {} generateClaimSecret(): [Fr, Fr] { - this.logger("Generating a claim secret using pedersen's hash function"); + this.logger.debug("Generating a claim secret using pedersen's hash function"); const secret = Fr.random(); const secretHash = computeMessageSecretHash(secret); - this.logger('Generated claim secret: ' + secretHash.toString()); + this.logger.info('Generated claim secret: ' + secretHash.toString()); return [secret, secretHash]; } async mintTokensOnL1(amount: bigint) { - this.logger('Minting tokens on L1'); + this.logger.info('Minting tokens on L1'); await this.underlyingERC20.write.mint([this.ethAccount.toString(), amount], {} as any); expect(await this.underlyingERC20.read.balanceOf([this.ethAccount.toString()])).toBe(amount); } @@ -165,7 +165,7 @@ class GasBridgingTestHarness implements IGasBridgingTestHarness { await this.underlyingERC20.write.approve([this.tokenPortalAddress.toString(), bridgeAmount], {} as any); // Deposit tokens to the TokenPortal - this.logger('Sending messages to L1 portal to be consumed publicly'); + this.logger.info('Sending messages to L1 portal to be consumed publicly'); const args = [l2Address.toString(), bridgeAmount, secretHash.toString()] as const; const { result: messageHash } = await this.tokenPortal.simulate.depositToAztecPublic(args, { account: this.ethAccount.toString(), @@ -185,7 +185,7 @@ class GasBridgingTestHarness implements IGasBridgingTestHarness { // Deposit tokens to the TokenPortal const deadline = 2 ** 32 - 1; // max uint32 - this.logger('Sending messages to L1 portal to be consumed privately'); + this.logger.info('Sending messages to L1 portal to be consumed privately'); const args = [ secretHashForRedeemingMintedNotes.toString(), bridgeAmount, @@ -202,7 +202,7 @@ class GasBridgingTestHarness implements IGasBridgingTestHarness { } async consumeMessageOnAztecAndMintPublicly(bridgeAmount: bigint, owner: AztecAddress, secret: Fr) { - this.logger('Consuming messages on L2 Publicly'); + this.logger.info('Consuming messages on L2 Publicly'); // Call the mint tokens function on the Aztec.nr contract await this.l2Token.methods.claim_public(owner, bridgeAmount, secret).send().wait(); } diff --git a/yarn-project/end-to-end/src/shared/uniswap_l1_l2.ts b/yarn-project/end-to-end/src/shared/uniswap_l1_l2.ts index ef6d453af214..81dc6b3cb4c1 100644 --- a/yarn-project/end-to-end/src/shared/uniswap_l1_l2.ts +++ b/yarn-project/end-to-end/src/shared/uniswap_l1_l2.ts @@ -109,7 +109,7 @@ export const uniswapL1L2TestSuite = ( await publicDeployAccounts(ownerWallet, [ownerWallet, sponsorWallet]); - logger('Deploying DAI Portal, initializing and deploying l2 contract...'); + logger.info('Deploying DAI Portal, initializing and deploying l2 contract...'); daiCrossChainHarness = await CrossChainTestHarness.new( aztecNode, pxe, @@ -120,7 +120,7 @@ export const uniswapL1L2TestSuite = ( DAI_ADDRESS, ); - logger('Deploying WETH Portal, initializing and deploying l2 contract...'); + logger.info('Deploying WETH Portal, initializing and deploying l2 contract...'); wethCrossChainHarness = await CrossChainTestHarness.new( aztecNode, pxe, @@ -131,7 +131,7 @@ export const uniswapL1L2TestSuite = ( WETH9_ADDRESS, ); - logger('Deploy Uniswap portal on L1 and L2...'); + logger.info('Deploy Uniswap portal on L1 and L2...'); uniswapPortalAddress = await deployL1Contract( walletClient, publicClient, @@ -157,7 +157,7 @@ export const uniswapL1L2TestSuite = ( ); // Give me some WETH so I can deposit to L2 and do the swap... - logger('Getting some weth'); + logger.info('Getting some weth'); const hash = await walletClient.sendTransaction({ to: WETH9_ADDRESS.toString(), value: parseEther('1000') }); await publicClient.waitForTransactionReceipt({ hash }); @@ -194,7 +194,7 @@ export const uniswapL1L2TestSuite = ( await wethCrossChainHarness.makeMessageConsumable(tokenDepositMsgHash); // 2. Claim WETH on L2 - logger('Minting weth on L2'); + logger.info('Minting weth on L2'); await wethCrossChainHarness.consumeMessageOnAztecAndMintPrivately( secretHashForRedeemingWeth, wethAmountToBridge, @@ -212,7 +212,7 @@ export const uniswapL1L2TestSuite = ( const nonceForBurnApprovalBeforeSwap = await uniswapL2Contract.methods.nonce_for_burn_approval().simulate(); // 3. Owner gives uniswap approval to unshield funds to self on its behalf - logger('Approving uniswap to unshield funds to self on my behalf'); + logger.info('Approving uniswap to unshield funds to self on my behalf'); const nonceForWETHUnshieldApproval = new Fr(1n); await ownerWallet.createAuthWit({ caller: uniswapL2Contract.address, @@ -225,7 +225,7 @@ export const uniswapL1L2TestSuite = ( }); // 4. Swap on L1 - sends L2 to L1 message to withdraw WETH to L1 and another message to swap assets. - logger('Withdrawing weth to L1 and sending message to swap to dai'); + logger.info('Withdrawing weth to L1 and sending message to swap to dai'); const [secretForDepositingSwappedDai, secretHashForDepositingSwappedDai] = daiCrossChainHarness.generateClaimSecret(); const [secretForRedeemingDai, secretHashForRedeemingDai] = daiCrossChainHarness.generateClaimSecret(); @@ -295,7 +295,7 @@ export const uniswapL1L2TestSuite = ( expect(nonceForBurnApprovalAfterSwap).toBe(nonceForBurnApprovalBeforeSwap + 1n); // 5. Consume L2 to L1 message by calling uniswapPortal.swap_private() - logger('Execute withdraw and swap on the uniswapPortal!'); + logger.info('Execute withdraw and swap on the uniswapPortal!'); const daiL1BalanceOfPortalBeforeSwap = await daiCrossChainHarness.getL1BalanceOf( daiCrossChainHarness.tokenPortalAddress, ); @@ -367,7 +367,7 @@ export const uniswapL1L2TestSuite = ( await daiCrossChainHarness.makeMessageConsumable(tokenOutMsgHash); // 6. claim dai on L2 - logger('Consuming messages to mint dai on L2'); + logger.info('Consuming messages to mint dai on L2'); await daiCrossChainHarness.consumeMessageOnAztecAndMintPrivately( secretHashForRedeemingDai, daiAmountToBridge, @@ -379,11 +379,11 @@ export const uniswapL1L2TestSuite = ( const wethL2BalanceAfterSwap = await wethCrossChainHarness.getL2PrivateBalanceOf(ownerAddress); const daiL2BalanceAfterSwap = await daiCrossChainHarness.getL2PrivateBalanceOf(ownerAddress); - logger('WETH balance before swap: ' + wethL2BalanceBeforeSwap.toString()); - logger('DAI balance before swap : ' + daiL2BalanceBeforeSwap.toString()); - logger('***** 🧚‍♀️ SWAP L2 assets on L1 Uniswap 🧚‍♀️ *****'); - logger('WETH balance after swap : ', wethL2BalanceAfterSwap.toString()); - logger('DAI balance after swap : ', daiL2BalanceAfterSwap.toString()); + logger.info('WETH balance before swap: ' + wethL2BalanceBeforeSwap.toString()); + logger.info('DAI balance before swap : ' + daiL2BalanceBeforeSwap.toString()); + logger.info('***** 🧚‍♀️ SWAP L2 assets on L1 Uniswap 🧚‍♀️ *****'); + logger.info('WETH balance after swap : ', wethL2BalanceAfterSwap.toString()); + logger.info('DAI balance after swap : ', daiL2BalanceAfterSwap.toString()); }); // docs:end:uniswap_private @@ -410,7 +410,7 @@ export const uniswapL1L2TestSuite = ( await wethCrossChainHarness.makeMessageConsumable(wethDepositMsgHash); // 2. Claim WETH on L2 - logger('Minting weth on L2'); + logger.info('Minting weth on L2'); await wethCrossChainHarness.consumeMessageOnAztecAndMintPublicly(wethAmountToBridge, secretForMintingWeth); await wethCrossChainHarness.expectPublicBalanceOnL2(ownerAddress, wethAmountToBridge); @@ -514,7 +514,7 @@ export const uniswapL1L2TestSuite = ( expect(nonceForBurnApprovalAfterSwap).toBe(nonceForBurnApprovalBeforeSwap + 1n); // 5. Perform the swap on L1 with the `uniswapPortal.swap_private()` (consuming L2 to L1 messages) - logger('Execute withdraw and swap on the uniswapPortal!'); + logger.info('Execute withdraw and swap on the uniswapPortal!'); const daiL1BalanceOfPortalBeforeSwap = await daiCrossChainHarness.getL1BalanceOf( daiCrossChainHarness.tokenPortalAddress, ); @@ -586,18 +586,18 @@ export const uniswapL1L2TestSuite = ( await daiCrossChainHarness.makeMessageConsumable(outTokenDepositMsgHash); // 6. claim dai on L2 - logger('Consuming messages to mint dai on L2'); + logger.info('Consuming messages to mint dai on L2'); await daiCrossChainHarness.consumeMessageOnAztecAndMintPublicly(daiAmountToBridge, secretForDepositingSwappedDai); await daiCrossChainHarness.expectPublicBalanceOnL2(ownerAddress, daiL2BalanceBeforeSwap + daiAmountToBridge); const wethL2BalanceAfterSwap = await wethCrossChainHarness.getL2PublicBalanceOf(ownerAddress); const daiL2BalanceAfterSwap = await daiCrossChainHarness.getL2PublicBalanceOf(ownerAddress); - logger('WETH balance before swap: ', wethL2BalanceBeforeSwap.toString()); - logger('DAI balance before swap : ', daiL2BalanceBeforeSwap.toString()); - logger('***** 🧚‍♀️ SWAP L2 assets on L1 Uniswap 🧚‍♀️ *****'); - logger('WETH balance after swap : ', wethL2BalanceAfterSwap.toString()); - logger('DAI balance after swap : ', daiL2BalanceAfterSwap.toString()); + logger.info('WETH balance before swap: ', wethL2BalanceBeforeSwap.toString()); + logger.info('DAI balance before swap : ', daiL2BalanceBeforeSwap.toString()); + logger.info('***** 🧚‍♀️ SWAP L2 assets on L1 Uniswap 🧚‍♀️ *****'); + logger.info('WETH balance after swap : ', wethL2BalanceAfterSwap.toString()); + logger.info('DAI balance after swap : ', daiL2BalanceAfterSwap.toString()); }, 360_000); // docs:end:uniswap_public @@ -644,7 +644,7 @@ export const uniswapL1L2TestSuite = ( await wethCrossChainHarness.expectPrivateBalanceOnL2(ownerAddress, wethAmountToBridge); // 2. owner gives uniswap approval to unshield funds: - logger('Approving uniswap to unshield funds to self on my behalf'); + logger.info('Approving uniswap to unshield funds to self on my behalf'); const nonceForWETHUnshieldApproval = new Fr(3n); await ownerWallet.createAuthWit({ caller: uniswapL2Contract.address, @@ -657,7 +657,7 @@ export const uniswapL1L2TestSuite = ( }); // 3. Swap but send the wrong token address - logger('Swap but send the wrong token address'); + logger.info('Swap but send the wrong token address'); await expect( uniswapL2Contract.methods .swap_private( @@ -791,12 +791,12 @@ export const uniswapL1L2TestSuite = ( it("can't call swap_public on L1 if called swap_private on L2", async () => { // get tokens on L2: const [secretForRedeemingWeth, secretHashForRedeemingWeth] = wethCrossChainHarness.generateClaimSecret(); - logger('minting weth on L2'); + logger.info('minting weth on L2'); await wethCrossChainHarness.mintTokensPrivateOnL2(wethAmountToBridge, secretHashForRedeemingWeth); await wethCrossChainHarness.redeemShieldPrivatelyOnL2(wethAmountToBridge, secretForRedeemingWeth); // Owner gives uniswap approval to unshield funds to self on its behalf - logger('Approving uniswap to unshield funds to self on my behalf'); + logger.info('Approving uniswap to unshield funds to self on my behalf'); const nonceForWETHUnshieldApproval = new Fr(4n); await ownerWallet.createAuthWit({ caller: uniswapL2Contract.address, @@ -810,7 +810,7 @@ export const uniswapL1L2TestSuite = ( const wethL2BalanceBeforeSwap = await wethCrossChainHarness.getL2PrivateBalanceOf(ownerAddress); // Swap - logger('Withdrawing weth to L1 and sending message to swap to dai'); + logger.info('Withdrawing weth to L1 and sending message to swap to dai'); const [, secretHashForRedeemingDai] = daiCrossChainHarness.generateClaimSecret(); const [, secretHashForDepositingSwappedDai] = daiCrossChainHarness.generateClaimSecret(); @@ -899,7 +899,7 @@ export const uniswapL1L2TestSuite = ( await wethCrossChainHarness.expectPrivateBalanceOnL2(ownerAddress, wethL2BalanceBeforeSwap - wethAmountToBridge); // On L1 call swap_public! - logger('call swap_public on L1'); + logger.info('call swap_public on L1'); const swapArgs = [ wethCrossChainHarness.tokenPortalAddress.toString(), wethAmountToBridge, @@ -1023,7 +1023,7 @@ export const uniswapL1L2TestSuite = ( // Call swap_private on L1 const secretHashForRedeemingDai = Fr.random(); // creating my own secret hash - logger('Execute withdraw and swap on the uniswapPortal!'); + logger.info('Execute withdraw and swap on the uniswapPortal!'); const swapArgs = [ wethCrossChainHarness.tokenPortalAddress.toString(), diff --git a/yarn-project/ethereum/src/deploy_l1_contracts.ts b/yarn-project/ethereum/src/deploy_l1_contracts.ts index 1bb21fd76c0e..8856aa0fc94b 100644 --- a/yarn-project/ethereum/src/deploy_l1_contracts.ts +++ b/yarn-project/ethereum/src/deploy_l1_contracts.ts @@ -101,7 +101,7 @@ export const deployL1Contracts = async ( logger: DebugLogger, contractsToDeploy: L1ContractArtifactsForDeployment, ): Promise => { - logger('Deploying contracts...'); + logger.debug('Deploying contracts...'); const walletClient = createWalletClient({ account, @@ -119,7 +119,7 @@ export const deployL1Contracts = async ( contractsToDeploy.registry.contractAbi, contractsToDeploy.registry.contractBytecode, ); - logger(`Deployed Registry at ${registryAddress}`); + logger.info(`Deployed Registry at ${registryAddress}`); const availabilityOracleAddress = await deployL1Contract( walletClient, @@ -127,7 +127,7 @@ export const deployL1Contracts = async ( contractsToDeploy.availabilityOracle.contractAbi, contractsToDeploy.availabilityOracle.contractBytecode, ); - logger(`Deployed AvailabilityOracle at ${availabilityOracleAddress}`); + logger.info(`Deployed AvailabilityOracle at ${availabilityOracleAddress}`); const rollupAddress = await deployL1Contract( walletClient, @@ -136,7 +136,7 @@ export const deployL1Contracts = async ( contractsToDeploy.rollup.contractBytecode, [getAddress(registryAddress.toString()), getAddress(availabilityOracleAddress.toString())], ); - logger(`Deployed Rollup at ${rollupAddress}`); + logger.info(`Deployed Rollup at ${rollupAddress}`); // Inbox and Outbox are immutable and are deployed from Rollup's constructor so we just fetch them from the contract. let inboxAddress!: EthAddress; @@ -148,7 +148,7 @@ export const deployL1Contracts = async ( }); inboxAddress = EthAddress.fromString((await rollup.read.INBOX([])) as any); } - logger(`Inbox available at ${inboxAddress}`); + logger.info(`Inbox available at ${inboxAddress}`); let outboxAddress!: EthAddress; { @@ -159,7 +159,7 @@ export const deployL1Contracts = async ( }); outboxAddress = EthAddress.fromString((await rollup.read.OUTBOX([])) as any); } - logger(`Outbox available at ${outboxAddress}`); + logger.info(`Outbox available at ${outboxAddress}`); // We need to call a function on the registry to set the various contract addresses. const registryContract = getContract({ @@ -180,7 +180,7 @@ export const deployL1Contracts = async ( contractsToDeploy.gasToken.contractBytecode, ); - logger(`Deployed Gas Token at ${gasTokenAddress}`); + logger.info(`Deployed Gas Token at ${gasTokenAddress}`); // this contract remains uninitialized because at this point we don't know the address of the gas token on L2 const gasPortalAddress = await deployL1Contract( @@ -190,7 +190,7 @@ export const deployL1Contracts = async ( contractsToDeploy.gasPortal.contractBytecode, ); - logger(`Deployed Gas Portal at ${gasPortalAddress}`); + logger.info(`Deployed Gas Portal at ${gasPortalAddress}`); const l1Contracts: L1ContractAddresses = { availabilityOracleAddress, diff --git a/yarn-project/foundation/src/crypto/random/randomness_singleton.ts b/yarn-project/foundation/src/crypto/random/randomness_singleton.ts index fcdba51772d4..9e51f6da8ef2 100644 --- a/yarn-project/foundation/src/crypto/random/randomness_singleton.ts +++ b/yarn-project/foundation/src/crypto/random/randomness_singleton.ts @@ -18,10 +18,10 @@ export class RandomnessSingleton { private readonly log = createDebugLogger('aztec:randomness_singleton'), ) { if (seed !== undefined) { - this.log(`Using pseudo-randomness with seed: ${seed}`); + this.log.info(`Using pseudo-randomness with seed: ${seed}`); this.counter = seed; } else { - this.log('Using true randomness'); + this.log.info('Using true randomness'); } } diff --git a/yarn-project/foundation/src/json-rpc/client/json_rpc_client.ts b/yarn-project/foundation/src/json-rpc/client/json_rpc_client.ts index 46ab33f0da5f..b016dc2b629b 100644 --- a/yarn-project/foundation/src/json-rpc/client/json_rpc_client.ts +++ b/yarn-project/foundation/src/json-rpc/client/json_rpc_client.ts @@ -12,7 +12,7 @@ import { JsonStringify, convertFromJsonObj, convertToJsonObj } from '../convert. export { JsonStringify } from '../convert.js'; -const debug = createDebugLogger('json-rpc:json_rpc_client'); +const log = createDebugLogger('json-rpc:json_rpc_client'); /** * A normal fetch function that does not retry. * Alternatives are a fetch function with retries, or a mocked fetch. @@ -30,7 +30,7 @@ export async function defaultFetch( useApiEndpoints: boolean, noRetry = false, ) { - debug(format(`JsonRpcClient.fetch`, host, rpcMethod, '->', body)); + log.debug(format(`JsonRpcClient.fetch`, host, rpcMethod, '->', body)); let resp: Response; if (useApiEndpoints) { resp = await fetch(`${host}/${rpcMethod}`, { @@ -112,9 +112,9 @@ export function createJsonRpcClient( method, params: params.map(param => convertToJsonObj(classConverter, param)), }; - debug(format(`JsonRpcClient.request`, method, '<-', params)); + log.debug(format(`JsonRpcClient.request`, method, '<-', params)); const res = await fetch(host, method, body, useApiEndpoints); - debug(format(`JsonRpcClient.result`, method, '->', res)); + log.debug(format(`JsonRpcClient.result`, method, '->', res)); if (res.error) { throw res.error; } @@ -138,7 +138,7 @@ export function createJsonRpcClient( return Reflect.get(target, method); } return (...params: any[]) => { - debug(format(`JsonRpcClient.constructor`, 'proxy', rpcMethod, '<-', params)); + log.debug(format(`JsonRpcClient.constructor`, 'proxy', rpcMethod, '<-', params)); return request(rpcMethod, params); }; }, diff --git a/yarn-project/foundation/src/json-rpc/server/json_proxy.ts b/yarn-project/foundation/src/json-rpc/server/json_proxy.ts index 47cc279a401a..348ccc715fa5 100644 --- a/yarn-project/foundation/src/json-rpc/server/json_proxy.ts +++ b/yarn-project/foundation/src/json-rpc/server/json_proxy.ts @@ -5,7 +5,7 @@ import { ClassConverter, type JsonClassConverterInput, type StringClassConverter import { convertFromJsonObj, convertToJsonObj } from '../convert.js'; import { assert, hasOwnProperty } from '../js_utils.js'; -const debug = createDebugLogger('json-rpc:json_proxy'); +const log = createDebugLogger('json-rpc:json_proxy'); /** * A map of class names to class constructors. @@ -38,7 +38,7 @@ export class JsonProxy { * @returns The remote result. */ public async call(methodName: string, jsonParams: any[] = [], skipConversion = false) { - debug(format(`JsonProxy:call`, methodName, jsonParams)); + log.debug(format(`JsonProxy:call`, methodName, jsonParams)); // Get access to our class members const proto = Object.getPrototypeOf(this.handler); assert(hasOwnProperty(proto, methodName), `JsonProxy: Method ${methodName} not found!`); @@ -48,13 +48,13 @@ export class JsonProxy { if (!skipConversion) { convertedParams = jsonParams.map(param => convertFromJsonObj(this.classConverter, param)); } - debug(format('JsonProxy:call', methodName, '<-', convertedParams)); + log.debug(format('JsonProxy:call', methodName, '<-', convertedParams)); const rawRet = await (this.handler as any)[methodName](...convertedParams); let ret = rawRet; if (!skipConversion) { ret = convertToJsonObj(this.classConverter, rawRet); } - debug(format('JsonProxy:call', methodName, '->', ret)); + log.debug(format('JsonProxy:call', methodName, '->', ret)); return ret; } } diff --git a/yarn-project/foundation/src/log/logger.ts b/yarn-project/foundation/src/log/logger.ts index 2747618147d8..d85647c17bbe 100644 --- a/yarn-project/foundation/src/log/logger.ts +++ b/yarn-project/foundation/src/log/logger.ts @@ -4,8 +4,7 @@ import { isatty } from 'tty'; import { type LogData, type LogFn } from './log_fn.js'; -// Matches a subset of Winston log levels -const LogLevels = ['silent', 'error', 'warn', 'info', 'verbose', 'debug', 'trace'] as const; +const LogLevels = ['silent', 'error', 'warn', 'info', 'verbose', 'debug'] as const; const DefaultLogLevel = process.env.NODE_ENV === 'test' ? ('silent' as const) : ('info' as const); /** @@ -28,7 +27,7 @@ export type Logger = { [K in LogLevel]: LogFn } & { /** Error log function */ er * Logger that supports multiple severity levels and can be called directly to issue a debug statement. * Intended as a drop-in replacement for the debug module. */ -export type DebugLogger = LogFn & Logger; +export type DebugLogger = Logger; /** * Creates a new DebugLogger for the current module, defaulting to the LOG_LEVEL env var. @@ -50,7 +49,6 @@ export function createDebugLogger(name: string): DebugLogger { info: (msg: string, data?: LogData) => logWithDebug(debugLogger, 'info', msg, data), verbose: (msg: string, data?: LogData) => logWithDebug(debugLogger, 'verbose', msg, data), debug: (msg: string, data?: LogData) => logWithDebug(debugLogger, 'debug', msg, data), - trace: (msg: string, data?: LogData) => logWithDebug(debugLogger, 'trace', msg, data), }; return Object.assign((msg: string, data?: LogData) => logWithDebug(debugLogger, 'debug', msg, data), logger); } @@ -112,7 +110,8 @@ function getPrefix(debugLogger: debug.Debugger, level: LogLevel) { * @param msg - What to log. */ function printLog(msg: string) { - process.stderr.write(msg + '\n'); + // eslint-disable-next-line no-console + isNode ? process.stderr.write(msg + '\n') : console.error(msg); } /** diff --git a/yarn-project/foundation/src/retry/index.ts b/yarn-project/foundation/src/retry/index.ts index fab31b09432b..e03f78480bfc 100644 --- a/yarn-project/foundation/src/retry/index.ts +++ b/yarn-project/foundation/src/retry/index.ts @@ -63,7 +63,7 @@ export async function retry( if (s === undefined) { throw err; } - log(`${name} failed. Will retry in ${s}s...`); + log.verbose(`${name} failed. Will retry in ${s}s...`); !failSilently && log.error(err); await sleep(s * 1000); continue; diff --git a/yarn-project/foundation/src/transport/dispatch/create_dispatch_fn.ts b/yarn-project/foundation/src/transport/dispatch/create_dispatch_fn.ts index 43276da87c4b..944b1d6ef93c 100644 --- a/yarn-project/foundation/src/transport/dispatch/create_dispatch_fn.ts +++ b/yarn-project/foundation/src/transport/dispatch/create_dispatch_fn.ts @@ -23,13 +23,13 @@ export interface DispatchMsg { * the method to be called ('fn') and an array of arguments to be passed to the method ('args'). * * @param targetFn - A function that returns the target object containing the methods to be dispatched. - * @param debug - Optional logging function for debugging purposes. + * @param log - Optional logging function for debugging purposes. * @returns A dispatch function that accepts a DispatchMsg object and calls the target's method with provided arguments. */ -export function createDispatchFn(targetFn: () => any, debug = createDebugLogger('aztec:foundation:dispatch')) { +export function createDispatchFn(targetFn: () => any, log = createDebugLogger('aztec:foundation:dispatch')) { return async ({ fn, args }: DispatchMsg) => { const target = targetFn(); - debug(format(`dispatching to ${target}: ${fn}`, args)); + log.debug(format(`dispatching to ${target}: ${fn}`, args)); return await target[fn](...args); }; } diff --git a/yarn-project/foundation/src/transport/transport_client.ts b/yarn-project/foundation/src/transport/transport_client.ts index 5709e662edc8..292ca8c9f925 100644 --- a/yarn-project/foundation/src/transport/transport_client.ts +++ b/yarn-project/foundation/src/transport/transport_client.ts @@ -6,7 +6,7 @@ import { type EventMessage, type ResponseMessage, isEventMessage } from './dispa import { type Connector } from './interface/connector.js'; import { type Socket } from './interface/socket.js'; -const debug = createDebugLogger('aztec:transport_client'); +const log = createDebugLogger('aztec:transport_client'); /** * Represents a pending request in the TransportClient. @@ -92,7 +92,7 @@ export class TransportClient extends EventEmitter { } const msgId = this.msgId++; const msg = { msgId, payload }; - debug(format(`->`, msg)); + log.debug(format(`->`, msg)); return new Promise((resolve, reject) => { this.pendingRequests.push({ resolve, reject, msgId }); this.socket!.send(msg, transfer).catch(reject); @@ -112,7 +112,7 @@ export class TransportClient extends EventEmitter { this.close(); return; } - debug(format(`<-`, msg)); + log.debug(format(`<-`, msg)); if (isEventMessage(msg)) { this.emit('event_msg', msg.payload); return; diff --git a/yarn-project/foundation/src/worker/worker_pool.ts b/yarn-project/foundation/src/worker/worker_pool.ts index 7e1534895860..3d6689526723 100644 --- a/yarn-project/foundation/src/worker/worker_pool.ts +++ b/yarn-project/foundation/src/worker/worker_pool.ts @@ -1,7 +1,7 @@ import { createDebugLogger } from '../log/index.js'; import { type WasmWorker } from './wasm_worker.js'; -const debug = createDebugLogger('bb:worker_pool'); +const log = createDebugLogger('bb:worker_pool'); /** * Type of a worker factory. @@ -53,7 +53,7 @@ export class WorkerPool { * @param maxMem - Max memory pages. */ public async init(createWorker: CreateWorker, poolSize: number, maxMem = WorkerPool.MAX_PAGES) { - debug(`creating ${poolSize} workers...`); + log.debug(`creating ${poolSize} workers...`); const start = new Date().getTime(); this.workers = await Promise.all( Array(poolSize) @@ -61,7 +61,7 @@ export class WorkerPool { .map((_, i) => createWorker(`${i}`, i === 0 ? Math.min(WorkerPool.MAX_PAGES, maxMem) : 768, maxMem)), ); - debug(`created workers: ${new Date().getTime() - start}ms`); + log.debug(`created workers: ${new Date().getTime() - start}ms`); } /** diff --git a/yarn-project/merkle-tree/src/sparse_tree/sparse_tree.test.ts b/yarn-project/merkle-tree/src/sparse_tree/sparse_tree.test.ts index c7a97acffeec..e949192e9003 100644 --- a/yarn-project/merkle-tree/src/sparse_tree/sparse_tree.test.ts +++ b/yarn-project/merkle-tree/src/sparse_tree/sparse_tree.test.ts @@ -181,6 +181,6 @@ describe('SparseTreeSpecific', () => { const start = Date.now(); await Promise.all(leaves.map((leaf, i) => tree.updateLeaf(leaf, indices[i]))); const end = Date.now(); - log(`Inserting 1000 leaves at random positions for depth 254 took ${end - start}ms`); + log.info(`Inserting 1000 leaves at random positions for depth 254 took ${end - start}ms`); }, 300_000); }); diff --git a/yarn-project/merkle-tree/src/standard_indexed_tree/standard_indexed_tree.ts b/yarn-project/merkle-tree/src/standard_indexed_tree/standard_indexed_tree.ts index cfe3bc3ebdd6..75fb3a14a635 100644 --- a/yarn-project/merkle-tree/src/standard_indexed_tree/standard_indexed_tree.ts +++ b/yarn-project/merkle-tree/src/standard_indexed_tree/standard_indexed_tree.ts @@ -571,7 +571,7 @@ export class StandardIndexedTree extends TreeBase implements IndexedTree // inclusion. See {@link encodeLeaf} for a more through param explanation. this.encodeAndAppendLeaves(pendingInsertionSubtree, false); - this.log(`Inserted ${leaves.length} leaves into ${this.getName()} tree`, { + this.log.debug(`Inserted ${leaves.length} leaves into ${this.getName()} tree`, { eventName: 'tree-insertion', duration: timer.ms(), batchSize: leaves.length, diff --git a/yarn-project/merkle-tree/src/standard_tree/standard_tree.ts b/yarn-project/merkle-tree/src/standard_tree/standard_tree.ts index fe27a0fb7a52..ceb210e70948 100644 --- a/yarn-project/merkle-tree/src/standard_tree/standard_tree.ts +++ b/yarn-project/merkle-tree/src/standard_tree/standard_tree.ts @@ -22,7 +22,7 @@ export class StandardTree extends TreeBase imp this.hasher.reset(); const timer = new Timer(); super.appendLeaves(leaves); - this.log(`Inserted ${leaves.length} leaves into ${this.getName()} tree`, { + this.log.debug(`Inserted ${leaves.length} leaves into ${this.getName()} tree`, { eventName: 'tree-insertion', duration: timer.ms(), batchSize: leaves.length, diff --git a/yarn-project/noir-protocol-circuits-types/src/index.test.ts b/yarn-project/noir-protocol-circuits-types/src/index.test.ts index 19e1c28c0600..6f7b32e0c13a 100644 --- a/yarn-project/noir-protocol-circuits-types/src/index.test.ts +++ b/yarn-project/noir-protocol-circuits-types/src/index.test.ts @@ -20,7 +20,7 @@ describe('Private kernel', () => { // To regenerate fixture data run the following on the yarn-project/e2e folder // AZTEC_GENERATE_TEST_DATA=1 yarn test e2e_nested_contract -t 'performs nested calls' it('Executes private kernel inner for a nested call', async () => { - logger('Initialized Noir instance with private kernel init circuit'); + logger.info('Initialized Noir instance with private kernel init circuit'); const filepath = resolve( dirname(fileURLToPath(import.meta.url)), diff --git a/yarn-project/noir-protocol-circuits-types/src/index.ts b/yarn-project/noir-protocol-circuits-types/src/index.ts index 853b59de4d6a..dab4986b71d7 100644 --- a/yarn-project/noir-protocol-circuits-types/src/index.ts +++ b/yarn-project/noir-protocol-circuits-types/src/index.ts @@ -549,9 +549,9 @@ const foreignCallHandler = (name: string, args: ForeignCallInput[]) => { const log = createDebugLogger('aztec:noir-protocol-circuits:oracle'); if (name === 'debugLog') { - log(oracleDebugCallToFormattedStr(args)); + log.info(oracleDebugCallToFormattedStr(args)); } else if (name === 'debugLogWithPrefix') { - log(`${acvmFieldMessageToString(args[0])}: ${oracleDebugCallToFormattedStr(args.slice(1))}`); + log.info(`${acvmFieldMessageToString(args[0])}: ${oracleDebugCallToFormattedStr(args.slice(1))}`); } else { throw Error(`unexpected oracle during execution: ${name}`); } diff --git a/yarn-project/p2p-bootstrap/src/index.ts b/yarn-project/p2p-bootstrap/src/index.ts index f6de48946fe7..9207dd30c2b9 100644 --- a/yarn-project/p2p-bootstrap/src/index.ts +++ b/yarn-project/p2p-bootstrap/src/index.ts @@ -10,12 +10,12 @@ async function main() { const config = getP2PConfigEnvVars(); const bootstrapNode = new BootstrapNode(logger); await bootstrapNode.start(config); - logger('Node started'); + logger.info('Node started'); const stop = async () => { - logger('Stopping bootstrap node...'); + logger.debug('Stopping bootstrap node...'); await bootstrapNode.stop(); - logger('Node stopped'); + logger.info('Node stopped'); process.exit(0); }; process.on('SIGTERM', stop); diff --git a/yarn-project/p2p/src/bootstrap/bootstrap.ts b/yarn-project/p2p/src/bootstrap/bootstrap.ts index e70e871fbd6f..30145ff9d82f 100644 --- a/yarn-project/p2p/src/bootstrap/bootstrap.ts +++ b/yarn-project/p2p/src/bootstrap/bootstrap.ts @@ -30,7 +30,7 @@ export class BootstrapNode { const { peerIdPrivateKey, tcpListenIp, tcpListenPort, announceHostname, announcePort, minPeerCount, maxPeerCount } = config; const peerId = await createLibP2PPeerId(peerIdPrivateKey); - this.logger( + this.logger.info( `Starting bootstrap node ${peerId} on ${tcpListenIp}:${tcpListenPort} announced at ${announceHostname}:${ announcePort ?? tcpListenPort }`, @@ -75,24 +75,24 @@ export class BootstrapNode { }); await this.node.start(); - this.logger(`lib p2p has started`); + this.logger.debug(`lib p2p has started`); // print out listening addresses - this.logger('listening on addresses:'); + this.logger.info('Listening on addresses:'); this.node.getMultiaddrs().forEach(addr => { - this.logger(addr.toString()); + this.logger.info(addr.toString()); }); this.node.addEventListener('peer:discovery', evt => { - this.logger(format('Discovered %s', evt.detail.id.toString())); // Log discovered peer + this.logger.verbose(format('Discovered %s', evt.detail.id.toString())); // Log discovered peer }); this.node.addEventListener('peer:connect', evt => { - this.logger(format('Connected to %s', evt.detail.toString())); // Log connected peer + this.logger.verbose(format('Connected to %s', evt.detail.toString())); // Log connected peer }); this.node.addEventListener('peer:disconnect', evt => { - this.logger(format('Disconnected from %s', evt.detail.toString())); // Log connected peer + this.logger.verbose(format('Disconnected from %s', evt.detail.toString())); // Log connected peer }); } @@ -103,7 +103,7 @@ export class BootstrapNode { public async stop() { // stop libp2p await this.node?.stop(); - this.logger('libp2p has stopped'); + this.logger.debug('libp2p has stopped'); } /** diff --git a/yarn-project/p2p/src/client/p2p_client.ts b/yarn-project/p2p/src/client/p2p_client.ts index f00df9f9de0f..1320e741a081 100644 --- a/yarn-project/p2p/src/client/p2p_client.ts +++ b/yarn-project/p2p/src/client/p2p_client.ts @@ -153,13 +153,15 @@ export class P2PClient implements P2P { this.syncPromise = new Promise(resolve => { this.syncResolve = resolve; }); - this.log(`Starting sync from ${blockToDownloadFrom}, latest block ${this.latestBlockNumberAtStart}`); + this.log.verbose(`Starting sync from ${blockToDownloadFrom}, latest block ${this.latestBlockNumberAtStart}`); } else { // if no blocks to be retrieved, go straight to running this.setCurrentState(P2PClientState.RUNNING); this.syncPromise = Promise.resolve(); await this.p2pService.start(); - this.log(`Next block ${blockToDownloadFrom} already beyond latest block at ${this.latestBlockNumberAtStart}`); + this.log.verbose( + `Next block ${blockToDownloadFrom} already beyond latest block at ${this.latestBlockNumberAtStart}`, + ); } // publish any txs in TxPool after its doing initial sync @@ -174,7 +176,7 @@ export class P2PClient implements P2P { }; this.runningPromise = blockProcess(); this.blockDownloader.start(blockToDownloadFrom); - this.log(`Started block downloader from block ${blockToDownloadFrom}`); + this.log.verbose(`Started block downloader from block ${blockToDownloadFrom}`); return this.syncPromise; } @@ -184,15 +186,15 @@ export class P2PClient implements P2P { * 'ready' will now return 'false' and the running promise that keeps the client synced is interrupted. */ public async stop() { - this.log('Stopping p2p client...'); + this.log.debug('Stopping p2p client...'); this.stopping = true; await this.p2pService.stop(); - this.log('Stopped p2p service'); + this.log.debug('Stopped p2p service'); await this.blockDownloader.stop(); - this.log('Stopped block downloader'); + this.log.debug('Stopped block downloader'); await this.runningPromise; this.setCurrentState(P2PClientState.STOPPED); - this.log('P2P client stopped...'); + this.log.info('P2P client stopped...'); } /** @@ -292,7 +294,7 @@ export class P2PClient implements P2P { await this.reconcileTxPool(blocks); const lastBlockNum = blocks[blocks.length - 1].number; await this.synchedBlockNumber.set(lastBlockNum); - this.log(`Synched to block ${lastBlockNum}`); + this.log.debug(`Synched to block ${lastBlockNum}`); if (this.currentState === P2PClientState.SYNCHING && lastBlockNum >= this.latestBlockNumberAtStart) { this.setCurrentState(P2PClientState.RUNNING); @@ -309,7 +311,7 @@ export class P2PClient implements P2P { */ private setCurrentState(newState: P2PClientState) { this.currentState = newState; - this.log(`Moved to state ${P2PClientState[this.currentState]}`); + this.log.debug(`Moved to state ${P2PClientState[this.currentState]}`); } private async publishStoredTxs() { @@ -319,7 +321,7 @@ export class P2PClient implements P2P { const txs = this.txPool.getAllTxs(); if (txs.length > 0) { - this.log(`Publishing ${txs.length} previously stored txs`); + this.log.debug(`Publishing ${txs.length} previously stored txs`); await Promise.all(txs.map(tx => this.p2pService.propagateTx(tx))); } } diff --git a/yarn-project/p2p/src/service/libp2p_service.ts b/yarn-project/p2p/src/service/libp2p_service.ts index 4e73de1e5b09..9c7974e34108 100644 --- a/yarn-project/p2p/src/service/libp2p_service.ts +++ b/yarn-project/p2p/src/service/libp2p_service.ts @@ -79,18 +79,18 @@ export class LibP2PService implements P2PService { throw new Error('P2P service already started'); } const { enableNat, tcpListenIp, tcpListenPort, announceHostname, announcePort } = this.config; - this.logger(`Starting P2P node on ${tcpListenIp}:${tcpListenPort}`); + this.logger.info(`Starting P2P node on ${tcpListenIp}:${tcpListenPort}`); if (announceHostname) { - this.logger(`Announcing at ${announceHostname}/tcp/${announcePort ?? tcpListenPort}`); + this.logger.info(`Announcing at ${announceHostname}/tcp/${announcePort ?? tcpListenPort}`); } if (enableNat) { - this.logger(`Enabling NAT in libp2p module`); + this.logger.info(`Enabling NAT in libp2p module`); } this.node.addEventListener('peer:discovery', evt => { const peerId = evt.detail.id; if (this.isBootstrapPeer(peerId)) { - this.logger(`Discovered bootstrap peer ${peerId.toString()}`); + this.logger.verbose(`Discovered bootstrap peer ${peerId.toString()}`); } }); @@ -102,9 +102,9 @@ export class LibP2PService implements P2PService { this.node.addEventListener('peer:disconnect', evt => { const peerId = evt.detail; if (this.isBootstrapPeer(peerId)) { - this.logger(`Disconnect from bootstrap peer ${peerId.toString()}`); + this.logger.verbose(`Disconnect from bootstrap peer ${peerId.toString()}`); } else { - this.logger(`Disconnected from transaction peer ${peerId.toString()}`); + this.logger.verbose(`Disconnected from transaction peer ${peerId.toString()}`); } }); @@ -114,7 +114,7 @@ export class LibP2PService implements P2PService { this.jobQueue.put(() => Promise.resolve(this.handleProtocolDial(incoming))), ); const dht = this.node.services['kadDHT'] as DualKadDHT; - this.logger(`Started P2P client as ${await dht.getMode()} with Peer ID ${this.node.peerId.toString()}`); + this.logger.info(`Started P2P client as ${await dht.getMode()} with Peer ID ${this.node.peerId.toString()}`); } /** @@ -122,11 +122,11 @@ export class LibP2PService implements P2PService { * @returns An empty promise. */ public async stop() { - this.logger('Stopping job queue...'); + this.logger.debug('Stopping job queue...'); await this.jobQueue.end(); - this.logger('Stopping LibP2P...'); + this.logger.debug('Stopping LibP2P...'); await this.node.stop(); - this.logger('LibP2P service stopped'); + this.logger.info('LibP2P service stopped'); } /** @@ -221,7 +221,7 @@ export class LibP2PService implements P2PService { try { const { message, peer } = await this.consumeInboundStream(incomingStreamData); if (!message.length) { - this.logger(`Ignoring 0 byte message from peer${peer.toString()}`); + this.logger.verbose(`Ignoring 0 byte message from peer${peer.toString()}`); } await this.processMessage(message, peer); } catch (err) { @@ -246,9 +246,9 @@ export class LibP2PService implements P2PService { private handleNewConnection(peerId: PeerId) { if (this.isBootstrapPeer(peerId)) { - this.logger(`Connected to bootstrap peer ${peerId.toString()}`); + this.logger.verbose(`Connected to bootstrap peer ${peerId.toString()}`); } else { - this.logger(`Connected to transaction peer ${peerId.toString()}`); + this.logger.verbose(`Connected to transaction peer ${peerId.toString()}`); // send the peer our current pooled transaction hashes void this.jobQueue.put(async () => { await this.sendTxHashesMessageToPeer(peerId); @@ -276,7 +276,7 @@ export class LibP2PService implements P2PService { private async processReceivedTxHashes(encodedMessage: Buffer, peerId: PeerId) { try { const txHashes = decodeTransactionHashesMessage(encodedMessage); - this.logger(`Received tx hash messages from ${peerId.toString()}`); + this.logger.debug(`Received tx hash messages from ${peerId.toString()}`); // we send a message requesting the transactions that we don't have from the set of received hashes const requiredHashes = txHashes.filter(hash => !this.txPool.hasTx(hash)); if (!requiredHashes.length) { @@ -290,7 +290,7 @@ export class LibP2PService implements P2PService { private async processReceivedGetTransactionsRequest(encodedMessage: Buffer, peerId: PeerId) { try { - this.logger(`Received get txs messages from ${peerId.toString()}`); + this.logger.debug(`Received get txs messages from ${peerId.toString()}`); // get the transactions in the list that we have and return them const removeUndefined = (value: S | undefined): value is S => value != undefined; const txHashes = decodeGetTransactionsRequestMessage(encodedMessage); @@ -321,7 +321,7 @@ export class LibP2PService implements P2PService { const txHash = tx.getTxHash(); const txHashString = txHash.toString(); this.knownTxLookup.addPeerForTx(peerId, txHashString); - this.logger(`Received tx ${txHashString} from peer ${peerId.toString()}`); + this.logger.debug(`Received tx ${txHashString} from peer ${peerId.toString()}`); await this.txPool.addTxs([tx]); this.propagateTx(tx); } @@ -335,10 +335,10 @@ export class LibP2PService implements P2PService { for (const peer of peers) { try { if (this.knownTxLookup.hasPeerSeenTx(peer, txHashString)) { - this.logger(`Not sending tx ${txHashString} to peer ${peer.toString()} as they have already seen it`); + this.logger.debug(`Not sending tx ${txHashString} to peer ${peer.toString()} as they have already seen it`); continue; } - this.logger(`Sending tx ${txHashString} to peer ${peer.toString()}`); + this.logger.debug(`Sending tx ${txHashString} to peer ${peer.toString()}`); await this.sendRawMessageToPeer(payload, peer); this.knownTxLookup.addPeerForTx(peer, txHashString); } catch (err) { diff --git a/yarn-project/p2p/src/tx_pool/memory_tx_pool.ts b/yarn-project/p2p/src/tx_pool/memory_tx_pool.ts index 27aa1683fff4..858af51370c4 100644 --- a/yarn-project/p2p/src/tx_pool/memory_tx_pool.ts +++ b/yarn-project/p2p/src/tx_pool/memory_tx_pool.ts @@ -39,7 +39,7 @@ export class InMemoryTxPool implements TxPool { public addTxs(txs: Tx[]): Promise { for (const tx of txs) { const txHash = tx.getTxHash(); - this.log(`Adding tx with id ${txHash.toString()}`, { + this.log.debug(`Adding tx with id ${txHash.toString()}`, { eventName: 'tx-added-to-pool', ...tx.getStats(), } satisfies TxAddedToPoolStats); diff --git a/yarn-project/prover-client/src/orchestrator/block-building-helpers.ts b/yarn-project/prover-client/src/orchestrator/block-building-helpers.ts index 3d214ee8c0d6..b8aeea5e45a2 100644 --- a/yarn-project/prover-client/src/orchestrator/block-building-helpers.ts +++ b/yarn-project/prover-client/src/orchestrator/block-building-helpers.ts @@ -456,7 +456,7 @@ export async function executeBaseRollupCircuit( prover: RollupProver, logger?: DebugLogger, ): Promise<[BaseOrMergeRollupPublicInputs, Proof]> { - logger?.(`Running base rollup for ${tx.hash}`); + logger?.debug(`Running base rollup for ${tx.hash}`); const rollupOutput = await simulator.baseRollupCircuit(inputs); validatePartialState(rollupOutput.end, treeSnapshots); const proof = await prover.getBaseRollupProof(inputs, rollupOutput); diff --git a/yarn-project/prover-client/src/orchestrator/orchestrator.ts b/yarn-project/prover-client/src/orchestrator/orchestrator.ts index 4d3baf6e150d..cd5770e30b81 100644 --- a/yarn-project/prover-client/src/orchestrator/orchestrator.ts +++ b/yarn-project/prover-client/src/orchestrator/orchestrator.ts @@ -290,7 +290,7 @@ export class ProvingOrchestrator { }); if (!l2Block.body.getTxsEffectsHash().equals(rootRollupOutputs.header.contentCommitment.txsEffectsHash)) { - logger(inspect(blockBody)); + logger.debug(inspect(blockBody)); throw new Error( `Txs effects hash mismatch, ${l2Block.body .getTxsEffectsHash() @@ -318,7 +318,7 @@ export class ProvingOrchestrator { */ private enqueueJob(provingState: ProvingState | undefined, jobType: PROVING_JOB_TYPE, job: () => Promise) { if (!provingState?.verifyState()) { - logger(`Not enqueueing job, proving state invalid`); + logger.debug(`Not enqueueing job, proving state invalid`); return; } // We use a 'safeJob'. We don't want promise rejections in the proving pool, we want to capture the error here @@ -341,7 +341,7 @@ export class ProvingOrchestrator { // Updates the merkle trees for a transaction. The first enqueued job for a transaction private async prepareBaseRollupInputs(provingState: ProvingState | undefined, index: bigint, tx: ProcessedTx) { if (!provingState?.verifyState()) { - logger('Not preparing base rollup inputs, state invalid'); + logger.debug('Not preparing base rollup inputs, state invalid'); return; } const inputs = await buildBaseRollupInput(tx, provingState.globalVariables, this.db); @@ -355,7 +355,7 @@ export class ProvingOrchestrator { ); if (!provingState?.verifyState()) { - logger(`Discarding proving job, state no longer valid`); + logger.debug(`Discarding proving job, state no longer valid`); return; } this.enqueueJob(provingState, PROVING_JOB_TYPE.BASE_ROLLUP, () => @@ -389,7 +389,7 @@ export class ProvingOrchestrator { treeSnapshots: Map, ) { if (!provingState?.verifyState()) { - logger('Not running base rollup, state invalid'); + logger.debug('Not running base rollup, state invalid'); return; } const [duration, baseRollupOutputs] = await elapsed(() => @@ -403,7 +403,7 @@ export class ProvingOrchestrator { outputSize: baseRollupOutputs[0].toBuffer().length, } satisfies CircuitSimulationStats); if (!provingState?.verifyState()) { - logger(`Discarding job as state no longer valid`); + logger.debug(`Discarding job as state no longer valid`); return; } const currentLevel = provingState.numMergeLevels + 1n; @@ -420,7 +420,7 @@ export class ProvingOrchestrator { mergeInputData: MergeRollupInputData, ) { if (!provingState?.verifyState()) { - logger('Not running merge rollup, state invalid'); + logger.debug('Not running merge rollup, state invalid'); return; } const circuitInputs = createMergeRollupInputs( @@ -438,7 +438,7 @@ export class ProvingOrchestrator { outputSize: circuitOutputs[0].toBuffer().length, } satisfies CircuitSimulationStats); if (!provingState?.verifyState()) { - logger(`Discarding job as state no longer valid`); + logger.debug(`Discarding job as state no longer valid`); return; } logger.info(`Completed merge rollup at level ${level}, index ${index}`); @@ -448,7 +448,7 @@ export class ProvingOrchestrator { // Executes the root rollup circuit private async runRootRollup(provingState: ProvingState | undefined) { if (!provingState?.verifyState()) { - logger('Not running root rollup, state no longer valid'); + logger.debug('Not running root rollup, state no longer valid'); return; } const mergeInputData = provingState.getMergeInputs(0); @@ -480,7 +480,7 @@ export class ProvingOrchestrator { // Enqueues the root parity circuit if all inputs are available private async runBaseParityCircuit(provingState: ProvingState | undefined, inputs: BaseParityInputs, index: number) { if (!provingState?.verifyState()) { - logger('Not running base parity, state no longer valid'); + logger.debug('Not running base parity, state no longer valid'); return; } const [duration, circuitOutputs] = await elapsed(() => @@ -495,7 +495,7 @@ export class ProvingOrchestrator { } satisfies CircuitSimulationStats); if (!provingState?.verifyState()) { - logger(`Discarding job as state no longer valid`); + logger.debug(`Discarding job as state no longer valid`); return; } provingState.setRootParityInputs(circuitOutputs, index); @@ -516,7 +516,7 @@ export class ProvingOrchestrator { // Enqueues the root rollup proof if all inputs are available private async runRootParityCircuit(provingState: ProvingState | undefined, inputs: RootParityInputs) { if (!provingState?.verifyState()) { - logger(`Not running root parity circuit as state is no longer valid`); + logger.debug(`Not running root parity circuit as state is no longer valid`); return; } const [duration, circuitOutputs] = await elapsed(() => @@ -531,7 +531,7 @@ export class ProvingOrchestrator { } satisfies CircuitSimulationStats); if (!provingState?.verifyState()) { - logger(`Discarding job as state no longer valid`); + logger.debug(`Discarding job as state no longer valid`); return; } provingState!.finalRootParityInput = circuitOutputs; @@ -540,7 +540,7 @@ export class ProvingOrchestrator { private checkAndExecuteRootRollup(provingState: ProvingState | undefined) { if (!provingState?.isReadyForRootRollup()) { - logger('Not ready for root rollup'); + logger.debug('Not ready for root rollup'); return; } this.enqueueJob(provingState, PROVING_JOB_TYPE.ROOT_ROLLUP, () => this.runRootRollup(provingState)); diff --git a/yarn-project/prover-client/src/simulator/rollup.ts b/yarn-project/prover-client/src/simulator/rollup.ts index 9faf8bc158e7..624f7d41d19d 100644 --- a/yarn-project/prover-client/src/simulator/rollup.ts +++ b/yarn-project/prover-client/src/simulator/rollup.ts @@ -148,7 +148,7 @@ export class RealRollupCircuitSimulator implements RollupSimulator { const result = convertRootRollupOutputsFromWitnessMap(witness); - this.log(`Simulated root rollup circuit`, { + this.log.debug(`Simulated root rollup circuit`, { eventName: 'circuit-simulation', circuitName: 'root-rollup', duration, diff --git a/yarn-project/pxe/src/kernel_prover/proof_creator.ts b/yarn-project/pxe/src/kernel_prover/proof_creator.ts index 9e79d1fc5520..4f48bf15a92e 100644 --- a/yarn-project/pxe/src/kernel_prover/proof_creator.ts +++ b/yarn-project/pxe/src/kernel_prover/proof_creator.ts @@ -103,14 +103,13 @@ export class KernelProofCreator implements ProofCreator { public async createProofInit(privateInputs: PrivateKernelInitCircuitPrivateInputs): Promise { const [duration, result] = await elapsed(() => executeInit(privateInputs)); - this.log(`Simulated private kernel init`, { + this.log.debug(`Simulated private kernel init`, { eventName: 'circuit-simulation', circuitName: 'private-kernel-init', duration, inputSize: privateInputs.toBuffer().length, outputSize: result.toBuffer().length, } satisfies CircuitSimulationStats); - this.log('Skipping private kernel init proving...'); const proof = makeEmptyProof(); return { @@ -121,14 +120,13 @@ export class KernelProofCreator implements ProofCreator { public async createProofInner(privateInputs: PrivateKernelInnerCircuitPrivateInputs): Promise { const [duration, result] = await elapsed(() => executeInner(privateInputs)); - this.log(`Simulated private kernel inner`, { + this.log.debug(`Simulated private kernel inner`, { eventName: 'circuit-simulation', circuitName: 'private-kernel-inner', duration, inputSize: privateInputs.toBuffer().length, outputSize: result.toBuffer().length, } satisfies CircuitSimulationStats); - this.log('Skipping private kernel inner proving...'); const proof = makeEmptyProof(); return { @@ -142,14 +140,13 @@ export class KernelProofCreator implements ProofCreator { const [duration, result] = await elapsed(() => isForPublic ? executeTailForPublic(privateInputs) : executeTail(privateInputs), ); - this.log(`Simulated private kernel ordering`, { + this.log.debug(`Simulated private kernel ordering`, { eventName: 'circuit-simulation', circuitName: 'private-kernel-ordering', duration, inputSize: privateInputs.toBuffer().length, outputSize: result.toBuffer().length, } satisfies CircuitSimulationStats); - this.log('Skipping private kernel ordering proving...'); const proof = makeEmptyProof(); return { diff --git a/yarn-project/pxe/src/note_processor/note_processor.ts b/yarn-project/pxe/src/note_processor/note_processor.ts index dd78fd7fba54..e8955b5e2433 100644 --- a/yarn-project/pxe/src/note_processor/note_processor.ts +++ b/yarn-project/pxe/src/note_processor/note_processor.ts @@ -184,7 +184,7 @@ export class NoteProcessor { const syncedToBlock = l2Blocks[l2Blocks.length - 1].number; await this.db.setSynchedBlockNumberForPublicKey(this.publicKey, syncedToBlock); - this.log(`Synched block ${syncedToBlock}`); + this.log.debug(`Synched block ${syncedToBlock}`); } /** @@ -201,7 +201,7 @@ export class NoteProcessor { if (noteDaos.length) { await this.db.addNotes(noteDaos); noteDaos.forEach(noteDao => { - this.log( + this.log.verbose( `Added note for contract ${noteDao.contractAddress} at slot ${ noteDao.storageSlot } with nullifier ${noteDao.siloedNullifier.toString()}`, @@ -214,7 +214,7 @@ export class NoteProcessor { ); const removedNotes = await this.db.removeNullifiedNotes(newNullifiers, this.publicKey); removedNotes.forEach(noteDao => { - this.log( + this.log.verbose( `Removed note for contract ${noteDao.contractAddress} at slot ${ noteDao.storageSlot } with nullifier ${noteDao.siloedNullifier.toString()}`, @@ -231,7 +231,7 @@ export class NoteProcessor { if (deferredNoteDaos.length) { await this.db.addDeferredNotes(deferredNoteDaos); deferredNoteDaos.forEach(noteDao => { - this.log( + this.log.verbose( `Deferred note for contract ${noteDao.contractAddress} at slot ${ noteDao.storageSlot } in tx ${noteDao.txHash.toString()}`, diff --git a/yarn-project/pxe/src/pxe_service/pxe_service.ts b/yarn-project/pxe/src/pxe_service/pxe_service.ts index 92079b73330e..45f0a9eb16ed 100644 --- a/yarn-project/pxe/src/pxe_service/pxe_service.ts +++ b/yarn-project/pxe/src/pxe_service/pxe_service.ts @@ -121,7 +121,7 @@ export class PXEService implements PXE { } if (count > 0) { - this.log(`Restored ${count} accounts`); + this.log.info(`Restored ${count} accounts`); } } @@ -409,7 +409,7 @@ export class PXEService implements PXE { // If we log, the `getTxHash` function will throw. if (!msgSender) { - this.log(`Processed private part of ${simulatedTx.tx.getTxHash()}`, { + this.log.debug(`Processed private part of ${simulatedTx.tx.getTxHash()}`, { eventName: 'tx-pxe-processing', duration: timer.ms(), ...simulatedTx.tx.getStats(), @@ -546,10 +546,10 @@ export class PXEService implements PXE { const { contractAddress, functionArtifact, portalContract } = await this.#getSimulationParameters(txRequest); - this.log('Executing simulator...'); + this.log.debug('Executing simulator...'); try { const result = await this.simulator.run(txRequest, functionArtifact, contractAddress, portalContract, msgSender); - this.log('Simulation completed!'); + this.log.verbose(`Simulation completed for ${contractAddress.toString()}:${functionArtifact.name}`); return result; } catch (err) { if (err instanceof SimulationError) { @@ -570,10 +570,10 @@ export class PXEService implements PXE { async #simulateUnconstrained(execRequest: FunctionCall) { const { contractAddress, functionArtifact } = await this.#getSimulationParameters(execRequest); - this.log('Executing unconstrained simulator...'); + this.log.debug('Executing unconstrained simulator...'); try { const result = await this.simulator.runUnconstrained(execRequest, functionArtifact, contractAddress); - this.log('Unconstrained simulation completed!'); + this.log.verbose(`Unconstrained simulation for ${contractAddress}.${functionArtifact.name} completed`); return result; } catch (err) { @@ -634,7 +634,7 @@ export class PXEService implements PXE { const kernelOracle = new KernelOracle(this.contractDataOracle, this.keyStore, this.node); const kernelProver = new KernelProver(kernelOracle); - this.log(`Executing kernel prover...`); + this.log.debug(`Executing kernel prover...`); const { proof, publicInputs } = await kernelProver.prove(txExecutionRequest.toTxRequest(), executionResult); const encryptedLogs = new EncryptedTxL2Logs(collectEncryptedLogs(executionResult)); diff --git a/yarn-project/pxe/src/synchronizer/synchronizer.ts b/yarn-project/pxe/src/synchronizer/synchronizer.ts index a25db92afe91..940571d47793 100644 --- a/yarn-project/pxe/src/synchronizer/synchronizer.ts +++ b/yarn-project/pxe/src/synchronizer/synchronizer.ts @@ -51,10 +51,10 @@ export class Synchronizer { this.running = true; await this.jobQueue.put(() => this.initialSync()); - this.log('Initial sync complete'); + this.log.info('Initial sync complete'); this.runningPromise = new RunningPromise(() => this.sync(limit), retryInterval); this.runningPromise.start(); - this.log('Started loop'); + this.log.debug('Started loop'); } protected async initialSync() { @@ -112,7 +112,9 @@ export class Synchronizer { await this.setHeaderFromBlock(latestBlock); const logCount = L2BlockL2Logs.getTotalLogCount(encryptedLogs); - this.log(`Forwarding ${logCount} encrypted logs and blocks to ${this.noteProcessors.length} note processors`); + this.log.debug( + `Forwarding ${logCount} encrypted logs and blocks to ${this.noteProcessors.length} note processors`, + ); for (const noteProcessor of this.noteProcessors) { await noteProcessor.process(blocks, encryptedLogs); } @@ -183,7 +185,7 @@ export class Synchronizer { const encryptedLogs = blocks.flatMap(block => block.body.encryptedLogs); const logCount = L2BlockL2Logs.getTotalLogCount(encryptedLogs); - this.log(`Forwarding ${logCount} encrypted logs and blocks to note processors in catch up mode`); + this.log.debug(`Forwarding ${logCount} encrypted logs and blocks to note processors in catch up mode`); for (const noteProcessor of catchUpGroup) { // find the index of the first block that the note processor is not yet synced to @@ -204,7 +206,7 @@ export class Synchronizer { if (noteProcessor.status.syncedToBlock === toBlockNumber) { // Note processor caught up, move it to `noteProcessors` from `noteProcessorsToCatchUp`. - this.log(`Note processor for ${noteProcessor.publicKey.toString()} has caught up`, { + this.log.debug(`Note processor for ${noteProcessor.publicKey.toString()} has caught up`, { eventName: 'note-processor-caught-up', publicKey: noteProcessor.publicKey.toString(), duration: noteProcessor.timer.ms(), @@ -244,7 +246,7 @@ export class Synchronizer { public async stop() { this.running = false; await this.runningPromise?.stop(); - this.log('Stopped'); + this.log.info('Stopped'); } /** @@ -354,7 +356,7 @@ export class Synchronizer { await this.db.addNotes(newNotes); newNotes.forEach(noteDao => { - this.log( + this.log.debug( `Decoded deferred note for contract ${noteDao.contractAddress} at slot ${ noteDao.storageSlot } with nullifier ${noteDao.siloedNullifier.toString()}`, diff --git a/yarn-project/sequencer-client/src/global_variable_builder/global_builder.ts b/yarn-project/sequencer-client/src/global_variable_builder/global_builder.ts index ea489d4dd3bd..d53a5336b73e 100644 --- a/yarn-project/sequencer-client/src/global_variable_builder/global_builder.ts +++ b/yarn-project/sequencer-client/src/global_variable_builder/global_builder.ts @@ -86,7 +86,7 @@ export class SimpleTestGlobalVariableBuilder implements GlobalVariableBuilder { lastTimestamp = new Fr(lastTimestamp.value + 1n); } - this.log( + this.log.debug( `Built global variables for block ${blockNumber}: (${chainId}, ${version}, ${blockNumber}, ${lastTimestamp}, ${coinbase}, ${feeRecipient})`, ); diff --git a/yarn-project/sequencer-client/src/publisher/l1-publisher.ts b/yarn-project/sequencer-client/src/publisher/l1-publisher.ts index c184a4fa4421..7afcfbc6e698 100644 --- a/yarn-project/sequencer-client/src/publisher/l1-publisher.ts +++ b/yarn-project/sequencer-client/src/publisher/l1-publisher.ts @@ -122,7 +122,7 @@ export class L1Publisher implements L2BlockReceiver { // TODO(#4148) Remove this block number check, it's here because we don't currently have proper genesis state on the contract const lastArchive = block.header.lastArchive.root.toBuffer(); if (block.number != 1 && !(await this.checkLastArchiveHash(lastArchive))) { - this.log(`Detected different last archive prior to publishing a block, aborting publish...`); + this.log.info(`Detected different last archive prior to publishing a block, aborting publish...`); return false; } @@ -131,7 +131,7 @@ export class L1Publisher implements L2BlockReceiver { // Publish block transaction effects while (!this.interrupted) { if (await this.txSender.checkIfTxsAreAvailable(block)) { - this.log(`Transaction effects of a block ${block.number} already published.`); + this.log.verbose(`Transaction effects of a block ${block.number} already published.`); break; } @@ -151,14 +151,14 @@ export class L1Publisher implements L2BlockReceiver { // txsEffectsHash from IAvailabilityOracle.TxsPublished event txsEffectsHash = receipt.logs[0].data; } else { - this.log(`Expected 1 log, got ${receipt.logs.length}`); + this.log.warn(`Expected 1 log, got ${receipt.logs.length}`); } this.log.info(`Block txs effects published, txsEffectsHash: ${txsEffectsHash}`); break; } - this.log(`AvailabilityOracle.publish tx status failed: ${receipt.transactionHash}`); + this.log.error(`AvailabilityOracle.publish tx status failed: ${receipt.transactionHash}`); await this.sleepOrInterrupted(); } @@ -196,15 +196,15 @@ export class L1Publisher implements L2BlockReceiver { // Check if someone else incremented the block number if (!(await this.checkLastArchiveHash(lastArchive))) { - this.log('Publish failed. Detected different last archive hash.'); + this.log.warn('Publish failed. Detected different last archive hash.'); break; } - this.log(`Rollup.process tx status failed: ${receipt.transactionHash}`); + this.log.error(`Rollup.process tx status failed: ${receipt.transactionHash}`); await this.sleepOrInterrupted(); } - this.log('L2 block data syncing interrupted while processing blocks.'); + this.log.verbose('L2 block data syncing interrupted while processing blocks.'); return false; } @@ -233,8 +233,8 @@ export class L1Publisher implements L2BlockReceiver { const fromChain = await this.txSender.getCurrentArchive(); const areSame = lastArchive.equals(fromChain); if (!areSame) { - this.log(`CONTRACT ARCHIVE: ${fromChain.toString('hex')}`); - this.log(`NEW BLOCK LAST ARCHIVE: ${lastArchive.toString('hex')}`); + this.log.debug(`Contract archive: ${fromChain.toString('hex')}`); + this.log.debug(`New block last archive: ${lastArchive.toString('hex')}`); } return areSame; } diff --git a/yarn-project/sequencer-client/src/publisher/viem-tx-sender.ts b/yarn-project/sequencer-client/src/publisher/viem-tx-sender.ts index 6691ac741da5..103860d9c91d 100644 --- a/yarn-project/sequencer-client/src/publisher/viem-tx-sender.ts +++ b/yarn-project/sequencer-client/src/publisher/viem-tx-sender.ts @@ -114,7 +114,7 @@ export class ViemTxSender implements L1PublisherTxSender { }; } - this.log(`Receipt not found for tx hash ${txHash}`); + this.log.debug(`Receipt not found for tx hash ${txHash}`); return undefined; } diff --git a/yarn-project/sequencer-client/src/sequencer/app_logic_phase_manager.ts b/yarn-project/sequencer-client/src/sequencer/app_logic_phase_manager.ts index 007910a0572a..06ff61023e31 100644 --- a/yarn-project/sequencer-client/src/sequencer/app_logic_phase_manager.ts +++ b/yarn-project/sequencer-client/src/sequencer/app_logic_phase_manager.ts @@ -38,7 +38,7 @@ export class AppLogicPhaseManager extends AbstractPhaseManager { // TODO(#4073): This is catching only private deployments, when we add public ones, we'll // have to capture contracts emitted in that phase as well. // TODO(@spalladino): Should we allow emitting contracts in the fee preparation phase? - this.log(`Processing tx ${tx.getTxHash()}`); + this.log.verbose(`Processing tx ${tx.getTxHash()}`); await this.publicContractsDB.addNewContracts(tx); const [publicKernelOutput, publicKernelProof, newUnencryptedFunctionLogs, revertReason, returnValues] = await this.processEnqueuedPublicCalls(tx, previousPublicKernelOutput, previousPublicKernelProof).catch( diff --git a/yarn-project/sequencer-client/src/sequencer/public_processor.ts b/yarn-project/sequencer-client/src/sequencer/public_processor.ts index 0d03d43d6d99..132b69d476f0 100644 --- a/yarn-project/sequencer-client/src/sequencer/public_processor.ts +++ b/yarn-project/sequencer-client/src/sequencer/public_processor.ts @@ -161,7 +161,7 @@ export class PublicProcessor { this.publicContractsDB, this.publicStateDB, ); - this.log(`Beginning processing in phase ${phase?.phase} for tx ${tx.getTxHash()}`); + this.log.debug(`Beginning processing in phase ${phase?.phase} for tx ${tx.getTxHash()}`); let proof = tx.proof; let publicKernelPublicInput = tx.data.toPublicKernelCircuitPublicInputs(); let finalKernelOutput: KernelCircuitPublicInputs | undefined; @@ -195,7 +195,7 @@ export class PublicProcessor { const processedTx = makeProcessedTx(tx, finalKernelOutput, proof, revertReason); - this.log(`Processed public part of ${tx.getTxHash()}`, { + this.log.debug(`Processed public part of ${tx.getTxHash()}`, { eventName: 'tx-sequencer-processing', duration: timer.ms(), effectsSize: toTxEffect(processedTx).toBuffer().length, diff --git a/yarn-project/sequencer-client/src/sequencer/sequencer.ts b/yarn-project/sequencer-client/src/sequencer/sequencer.ts index e400e3ba9356..2efab40df55a 100644 --- a/yarn-project/sequencer-client/src/sequencer/sequencer.ts +++ b/yarn-project/sequencer-client/src/sequencer/sequencer.ts @@ -52,7 +52,7 @@ export class Sequencer { private log = createDebugLogger('aztec:sequencer'), ) { this.updateConfig(config); - this.log(`Initialized sequencer with ${this.minTxsPerBLock}-${this.maxTxsPerBlock} txs per block.`); + this.log.verbose(`Initialized sequencer with ${this.minTxsPerBLock}-${this.maxTxsPerBlock} txs per block.`); } /** @@ -92,25 +92,25 @@ export class Sequencer { this.runningPromise = new RunningPromise(this.work.bind(this), this.pollingIntervalMs); this.runningPromise.start(); this.state = SequencerState.IDLE; - this.log('Sequencer started'); + this.log.info('Sequencer started'); } /** * Stops the sequencer from processing txs and moves to STOPPED state. */ public async stop(): Promise { - this.log(`Stopping sequencer`); + this.log.debug(`Stopping sequencer`); await this.runningPromise?.stop(); this.publisher.interrupt(); this.state = SequencerState.STOPPED; - this.log('Stopped sequencer'); + this.log.info('Stopped sequencer'); } /** * Starts a previously stopped sequencer. */ public restart() { - this.log('Restarting sequencer'); + this.log.info('Restarting sequencer'); this.publisher.restart(); this.runningPromise!.start(); this.state = SequencerState.IDLE; @@ -137,7 +137,7 @@ export class Sequencer { // Update state when the previous block has been synced const prevBlockSynced = await this.isBlockSynced(); if (prevBlockSynced && this.state === SequencerState.PUBLISHING_BLOCK) { - this.log(`Block has been synced`); + this.log.debug(`Block has been synced`); this.state = SequencerState.IDLE; } @@ -194,9 +194,9 @@ export class Sequencer { this.state = SequencerState.CREATING_BLOCK; // Get l1 to l2 messages from the contract - this.log('Requesting L1 to L2 messages from contract'); + this.log.debug('Requesting L1 to L2 messages from contract'); const l1ToL2Messages = await this.l1ToL2MessageSource.getL1ToL2Messages(BigInt(newBlockNumber)); - this.log(`Retrieved ${l1ToL2Messages.length} L1 to L2 messages for block ${newBlockNumber}`); + this.log.verbose(`Retrieved ${l1ToL2Messages.length} L1 to L2 messages for block ${newBlockNumber}`); // We create a fresh processor each time to reset any cached state (eg storage writes) const processor = await this.publicProcessorFactory.create(historicalHeader, newGlobalVariables); @@ -217,12 +217,12 @@ export class Sequencer { ); if (failedTxs.length > 0) { const failedTxData = failedTxs.map(fail => fail.tx); - this.log(`Dropping failed txs ${Tx.getHashes(failedTxData).join(', ')}`); + this.log.debug(`Dropping failed txs ${Tx.getHashes(failedTxData).join(', ')}`); await this.p2pClient.deleteTxs(Tx.getHashes(failedTxData)); } if (processedTxs.length === 0) { - this.log('No txs processed correctly to build block. Exiting'); + this.log.verbose('No txs processed correctly to build block. Exiting'); this.prover.cancelBlock(); return; } @@ -248,7 +248,7 @@ export class Sequencer { await assertBlockHeight(); - this.log(`Assembled block ${block.number}`, { + this.log.verbose(`Assembled block ${block.number}`, { eventName: 'l2-block-built', duration: workTimer.ms(), publicProcessDuration: publicProcessorDuration, @@ -275,7 +275,6 @@ export class Sequencer { this.state = SequencerState.PUBLISHING_BLOCK; const publishedL2Block = await this.publisher.processL2Block(block); if (publishedL2Block) { - this.log(`Successfully published block ${block.number}`); this.lastPublishedBlock = block.number; } else { throw new Error(`Failed to publish block`); @@ -285,7 +284,7 @@ export class Sequencer { protected async takeValidTxs(txs: T[], validator: TxValidator): Promise { const [valid, invalid] = await validator.validateTxs(txs); if (invalid.length > 0) { - this.log(`Dropping invalid txs from the p2p pool ${Tx.getHashes(invalid).join(', ')}`); + this.log.debug(`Dropping invalid txs from the p2p pool ${Tx.getHashes(invalid).join(', ')}`); await this.p2pClient.deleteTxs(Tx.getHashes(invalid)); } diff --git a/yarn-project/sequencer-client/src/sequencer/setup_phase_manager.ts b/yarn-project/sequencer-client/src/sequencer/setup_phase_manager.ts index 43e434d9b02f..a043cfdd47b6 100644 --- a/yarn-project/sequencer-client/src/sequencer/setup_phase_manager.ts +++ b/yarn-project/sequencer-client/src/sequencer/setup_phase_manager.ts @@ -34,7 +34,7 @@ export class SetupPhaseManager extends AbstractPhaseManager { previousPublicKernelOutput: PublicKernelCircuitPublicInputs, previousPublicKernelProof: Proof, ) { - this.log(`Processing tx ${tx.getTxHash()}`); + this.log.verbose(`Processing tx ${tx.getTxHash()}`); const [publicKernelOutput, publicKernelProof, newUnencryptedFunctionLogs, revertReason] = await this.processEnqueuedPublicCalls(tx, previousPublicKernelOutput, previousPublicKernelProof).catch( // the abstract phase manager throws if simulation gives error in a non-revertible phase diff --git a/yarn-project/sequencer-client/src/sequencer/tail_phase_manager.ts b/yarn-project/sequencer-client/src/sequencer/tail_phase_manager.ts index 748dca637cd1..d1859dd0167b 100644 --- a/yarn-project/sequencer-client/src/sequencer/tail_phase_manager.ts +++ b/yarn-project/sequencer-client/src/sequencer/tail_phase_manager.ts @@ -36,7 +36,7 @@ export class TailPhaseManager extends AbstractPhaseManager { } async handle(tx: Tx, previousPublicKernelOutput: PublicKernelCircuitPublicInputs, previousPublicKernelProof: Proof) { - this.log(`Processing tx ${tx.getTxHash()}`); + this.log.verbose(`Processing tx ${tx.getTxHash()}`); const [finalKernelOutput, publicKernelProof] = await this.runTailKernelCircuit( previousPublicKernelOutput, previousPublicKernelProof, diff --git a/yarn-project/sequencer-client/src/sequencer/teardown_phase_manager.ts b/yarn-project/sequencer-client/src/sequencer/teardown_phase_manager.ts index 825d2de24100..fb6820fc7999 100644 --- a/yarn-project/sequencer-client/src/sequencer/teardown_phase_manager.ts +++ b/yarn-project/sequencer-client/src/sequencer/teardown_phase_manager.ts @@ -34,7 +34,7 @@ export class TeardownPhaseManager extends AbstractPhaseManager { previousPublicKernelOutput: PublicKernelCircuitPublicInputs, previousPublicKernelProof: Proof, ) { - this.log(`Processing tx ${tx.getTxHash()}`); + this.log.verbose(`Processing tx ${tx.getTxHash()}`); const [publicKernelOutput, publicKernelProof, newUnencryptedFunctionLogs, revertReason] = await this.processEnqueuedPublicCalls(tx, previousPublicKernelOutput, previousPublicKernelProof).catch( // the abstract phase manager throws if simulation gives error in a non-revertible phase diff --git a/yarn-project/sequencer-client/src/simulator/public_executor.ts b/yarn-project/sequencer-client/src/simulator/public_executor.ts index d943af10530f..1f1bc28115ed 100644 --- a/yarn-project/sequencer-client/src/simulator/public_executor.ts +++ b/yarn-project/sequencer-client/src/simulator/public_executor.ts @@ -47,11 +47,11 @@ export class ContractsDataSourcePublicDB implements PublicContractsDB { // Extract contract class and instance data from logs and add to cache for this block const logs = tx.unencryptedLogs.unrollLogs(); ContractClassRegisteredEvent.fromLogs(logs, getCanonicalClassRegistererAddress()).forEach(e => { - this.log(`Adding class ${e.contractClassId.toString()} to public execution contract cache`); + this.log.debug(`Adding class ${e.contractClassId.toString()} to public execution contract cache`); this.classCache.set(e.contractClassId.toString(), e.toContractClassPublic()); }); ContractInstanceDeployedEvent.fromLogs(logs).forEach(e => { - this.log( + this.log.debug( `Adding instance ${e.address.toString()} with class ${e.contractClassId.toString()} to public execution contract cache`, ); this.instanceCache.set(e.address.toString(), e.toContractInstance()); diff --git a/yarn-project/sequencer-client/src/simulator/public_kernel.ts b/yarn-project/sequencer-client/src/simulator/public_kernel.ts index 04700d7c68c8..86bf06484ff0 100644 --- a/yarn-project/sequencer-client/src/simulator/public_kernel.ts +++ b/yarn-project/sequencer-client/src/simulator/public_kernel.ts @@ -52,7 +52,7 @@ export class RealPublicKernelCircuitSimulator implements PublicKernelCircuitSimu this.wasmSimulator.simulateCircuit(inputWitness, PublicKernelSetupArtifact), ); const result = convertPublicSetupRollupOutputFromWitnessMap(witness); - this.log(`Simulated public kernel setup circuit`, { + this.log.debug(`Simulated public kernel setup circuit`, { eventName: 'circuit-simulation', circuitName: 'public-kernel-setup', duration, @@ -78,7 +78,7 @@ export class RealPublicKernelCircuitSimulator implements PublicKernelCircuitSimu this.wasmSimulator.simulateCircuit(inputWitness, PublicKernelAppLogicArtifact), ); const result = convertPublicInnerRollupOutputFromWitnessMap(witness); - this.log(`Simulated public kernel app logic circuit`, { + this.log.debug(`Simulated public kernel app logic circuit`, { eventName: 'circuit-simulation', circuitName: 'public-kernel-app-logic', duration, @@ -104,7 +104,7 @@ export class RealPublicKernelCircuitSimulator implements PublicKernelCircuitSimu this.wasmSimulator.simulateCircuit(inputWitness, PublicKernelTeardownArtifact), ); const result = convertPublicTeardownRollupOutputFromWitnessMap(witness); - this.log(`Simulated public kernel teardown circuit`, { + this.log.debug(`Simulated public kernel teardown circuit`, { eventName: 'circuit-simulation', circuitName: 'public-kernel-teardown', duration, @@ -127,7 +127,7 @@ export class RealPublicKernelCircuitSimulator implements PublicKernelCircuitSimu this.wasmSimulator.simulateCircuit(inputWitness, PublicKernelTailArtifact), ); const result = convertPublicTailOutputFromWitnessMap(witness); - this.log(`Simulated public kernel tail circuit`, { + this.log.debug(`Simulated public kernel tail circuit`, { eventName: 'circuit-simulation', circuitName: 'public-kernel-tail', duration, diff --git a/yarn-project/simulator/src/acvm/acvm.ts b/yarn-project/simulator/src/acvm/acvm.ts index d33a660e92e7..4fc3056c1b6b 100644 --- a/yarn-project/simulator/src/acvm/acvm.ts +++ b/yarn-project/simulator/src/acvm/acvm.ts @@ -95,7 +95,7 @@ export async function acvm( initialWitness, async (name: string, args: ForeignCallInput[]) => { try { - logger(`Oracle callback ${name}`); + logger.verbose(`Oracle callback ${name}`); const oracleFunction = callback[name as ORACLE_NAMES]; if (!oracleFunction) { throw new Error(`Oracle callback ${name} not found`); diff --git a/yarn-project/simulator/src/acvm/oracle/oracle.ts b/yarn-project/simulator/src/acvm/oracle/oracle.ts index 81892640934c..50f9cec6c5b3 100644 --- a/yarn-project/simulator/src/acvm/oracle/oracle.ts +++ b/yarn-project/simulator/src/acvm/oracle/oracle.ts @@ -304,12 +304,12 @@ export class Oracle { } debugLog(...args: ACVMField[][]): ACVMField { - this.log(oracleDebugCallToFormattedStr(args)); + this.log.verbose(oracleDebugCallToFormattedStr(args)); return toACVMField(0); } debugLogWithPrefix(arg0: ACVMField[], ...args: ACVMField[][]): ACVMField { - this.log(`${acvmFieldMessageToString(arg0)}: ${oracleDebugCallToFormattedStr(args)}`); + this.log.verbose(`${acvmFieldMessageToString(arg0)}: ${oracleDebugCallToFormattedStr(args)}`); return toACVMField(0); } diff --git a/yarn-project/simulator/src/avm/avm_memory_types.ts b/yarn-project/simulator/src/avm/avm_memory_types.ts index becb59270385..f1cc421716e9 100644 --- a/yarn-project/simulator/src/avm/avm_memory_types.ts +++ b/yarn-project/simulator/src/avm/avm_memory_types.ts @@ -238,7 +238,7 @@ export class TaggedMemory implements TaggedMemoryInterface { public getAs(offset: number): T { assert(offset < TaggedMemory.MAX_MEMORY_SIZE); const word = this._mem[offset]; - TaggedMemory.log(`get(${offset}) = ${word}`); + TaggedMemory.log.debug(`get(${offset}) = ${word}`); if (word === undefined) { TaggedMemory.log.warn(`Memory at offset ${offset} is undefined! This might be OK if it's stack dumping.`); } @@ -249,7 +249,7 @@ export class TaggedMemory implements TaggedMemoryInterface { assert(offset < TaggedMemory.MAX_MEMORY_SIZE); assert(offset + size < TaggedMemory.MAX_MEMORY_SIZE); const value = this._mem.slice(offset, offset + size); - TaggedMemory.log(`getSlice(${offset}, ${size}) = ${value}`); + TaggedMemory.log.debug(`getSlice(${offset}, ${size}) = ${value}`); assert(!value.some(e => e === undefined), 'Memory slice contains undefined values.'); assert(value.length === size, `Expected slice of size ${size}, got ${value.length}.`); return value; @@ -270,7 +270,7 @@ export class TaggedMemory implements TaggedMemoryInterface { public set(offset: number, v: MemoryValue) { assert(offset < TaggedMemory.MAX_MEMORY_SIZE); this._mem[offset] = v; - TaggedMemory.log(`set(${offset}, ${v})`); + TaggedMemory.log.debug(`set(${offset}, ${v})`); } public setSlice(offset: number, vs: MemoryValue[]) { @@ -281,7 +281,7 @@ export class TaggedMemory implements TaggedMemoryInterface { this._mem.length = offset + vs.length; } this._mem.splice(offset, vs.length, ...vs); - TaggedMemory.log(`setSlice(${offset}, ${vs})`); + TaggedMemory.log.debug(`setSlice(${offset}, ${vs})`); } public getTag(offset: number): TypeTag { diff --git a/yarn-project/simulator/src/avm/avm_simulator.ts b/yarn-project/simulator/src/avm/avm_simulator.ts index 6cf9e5bb078b..97861a56f5c2 100644 --- a/yarn-project/simulator/src/avm/avm_simulator.ts +++ b/yarn-project/simulator/src/avm/avm_simulator.ts @@ -69,26 +69,26 @@ export class AvmSimulator { await instruction.execute(this.context); if (machineState.pc >= instructions.length) { - this.log('Passed end of program!'); + this.log.warn('Passed end of program'); throw new InvalidProgramCounterError(machineState.pc, /*max=*/ instructions.length); } } // Return results for processing by calling context const results = machineState.getResults(); - this.log(`Context execution results: ${results.toString()}`); + this.log.debug(`Context execution results: ${results.toString()}`); return results; } catch (e) { - this.log('Exceptional halt'); + this.log.verbose('Exceptional halt'); if (!(e instanceof AvmExecutionError)) { - this.log(`Unknown error thrown by avm: ${e}`); + this.log.verbose(`Unknown error thrown by avm: ${e}`); throw e; } // Return results for processing by calling context // Note: "exceptional halts" cannot return data const results = new AvmContractCallResults(/*reverted=*/ true, /*output=*/ [], /*revertReason=*/ e); - this.log(`Context execution results: ${results.toString()}`); + this.log.debug(`Context execution results: ${results.toString()}`); return results; } } diff --git a/yarn-project/simulator/src/client/client_execution_context.ts b/yarn-project/simulator/src/client/client_execution_context.ts index 3f6262931219..b9a3ab6036e1 100644 --- a/yarn-project/simulator/src/client/client_execution_context.ts +++ b/yarn-project/simulator/src/client/client_execution_context.ts @@ -235,7 +235,7 @@ export class ClientExecutionContext extends ViewDataOracle { offset, }); - this.log( + this.log.debug( `Returning ${notes.length} notes for ${this.callContext.storageContractAddress} at ${storageSlot}: ${notes .map(n => `${n.nonce.toString()}:[${n.note.items.map(i => i.toString()).join(',')}]`) .join(', ')}`, @@ -316,7 +316,7 @@ export class ClientExecutionContext extends ViewDataOracle { public emitUnencryptedLog(log: UnencryptedL2Log) { this.unencryptedLogs.push(log); const text = log.toHumanReadable(); - this.log(`Emitted unencrypted log: "${text.length > 100 ? text.slice(0, 100) + '...' : text}"`); + this.log.verbose(`Emitted unencrypted log: "${text.length > 100 ? text.slice(0, 100) + '...' : text}"`); } #checkValidStaticCall(childExecutionResult: ExecutionResult) { @@ -349,7 +349,7 @@ export class ClientExecutionContext extends ViewDataOracle { isStaticCall: boolean, isDelegateCall: boolean, ) { - this.log( + this.log.debug( `Calling private function ${this.contractAddress}:${functionSelector} from ${this.callContext.storageContractAddress}`, ); @@ -441,7 +441,7 @@ export class ClientExecutionContext extends ViewDataOracle { // side-effect counter, that will leak info about how many other private // side-effects occurred in the TX. Ultimately the private kernel should // just output everything in the proper order without any counters. - this.log( + this.log.verbose( `Enqueued call to public function (with side-effect counter #${sideEffectCounter}) ${targetContractAddress}:${functionSelector}(${targetArtifact.name})`, ); @@ -497,7 +497,7 @@ export class ClientExecutionContext extends ViewDataOracle { throw new Error(`No witness for slot ${storageSlot.toString()}`); } const value = witness.leafPreimage.value; - this.log(`Oracle storage read: slot=${storageSlot.toString()} value=${value}`); + this.log.debug(`Oracle storage read: slot=${storageSlot.toString()} value=${value}`); values.push(value); } return values; diff --git a/yarn-project/simulator/src/client/private_execution.test.ts b/yarn-project/simulator/src/client/private_execution.test.ts index 379bb25504e2..39a3ad5abd63 100644 --- a/yarn-project/simulator/src/client/private_execution.test.ts +++ b/yarn-project/simulator/src/client/private_execution.test.ts @@ -444,8 +444,8 @@ describe('Private Execution test suite', () => { oracle.getFunctionArtifact.mockImplementation(() => Promise.resolve(childArtifact)); oracle.getPortalContractAddress.mockImplementation(() => Promise.resolve(EthAddress.ZERO)); - logger(`Parent deployed at ${parentAddress.toShortString()}`); - logger(`Calling child function ${childSelector.toString()} at ${childAddress.toShortString()}`); + logger.info(`Parent deployed at ${parentAddress.toShortString()}`); + logger.info(`Calling child function ${childSelector.toString()} at ${childAddress.toShortString()}`); const args = [childAddress, childSelector]; const result = await runSimulator({ args, artifact: parentArtifact }); @@ -480,7 +480,7 @@ describe('Private Execution test suite', () => { }); it('test function should be directly callable', async () => { - logger(`Calling testCodeGen function`); + logger.info(`Calling testCodeGen function`); const result = await runSimulator({ args, artifact: testCodeGenArtifact }); expect(result.callStackItem.publicInputs.returnValues[0]).toEqual(argsHash); @@ -497,7 +497,7 @@ describe('Private Execution test suite', () => { oracle.getFunctionArtifact.mockResolvedValue(testCodeGenArtifact); oracle.getPortalContractAddress.mockResolvedValue(EthAddress.ZERO); - logger(`Calling importer main function`); + logger.info(`Calling importer main function`); const args = [testAddress]; const result = await runSimulator({ args, artifact: parentArtifact }); diff --git a/yarn-project/simulator/src/client/private_execution.ts b/yarn-project/simulator/src/client/private_execution.ts index 1c6e7fee97b1..964e51cf95f9 100644 --- a/yarn-project/simulator/src/client/private_execution.ts +++ b/yarn-project/simulator/src/client/private_execution.ts @@ -22,7 +22,7 @@ export async function executePrivateFunction( log = createDebugLogger('aztec:simulator:secret_execution'), ): Promise { const functionSelector = functionData.selector; - log(`Executing external function ${contractAddress}:${functionSelector}(${artifact.name})`); + log.verbose(`Executing external function ${contractAddress}:${functionSelector}(${artifact.name})`); const acir = artifact.bytecode; const initialWitness = context.getInitialWitness(artifact); const acvmCallback = new Oracle(context); @@ -66,7 +66,7 @@ export async function executePrivateFunction( const nestedExecutions = context.getNestedExecutions(); const enqueuedPublicFunctionCalls = context.getEnqueuedPublicFunctionCalls(); - log(`Returning from call to ${contractAddress.toString()}:${functionSelector}`); + log.debug(`Returning from call to ${contractAddress.toString()}:${functionSelector}`); return { acir, diff --git a/yarn-project/simulator/src/client/unconstrained_execution.ts b/yarn-project/simulator/src/client/unconstrained_execution.ts index 352c3a52e624..559a8cf1f480 100644 --- a/yarn-project/simulator/src/client/unconstrained_execution.ts +++ b/yarn-project/simulator/src/client/unconstrained_execution.ts @@ -23,7 +23,7 @@ export async function executeUnconstrainedFunction( log = createDebugLogger('aztec:simulator:unconstrained_execution'), ): Promise { const functionSelector = functionData.selector; - log(`Executing unconstrained function ${contractAddress}:${functionSelector}`); + log.verbose(`Executing unconstrained function ${contractAddress}:${functionSelector}(${artifact.name})`); const acir = artifact.bytecode; const initialWitness = toACVMWitness(0, args); diff --git a/yarn-project/simulator/src/client/view_data_oracle.ts b/yarn-project/simulator/src/client/view_data_oracle.ts index 92fac26f4ad9..13f0f929cb30 100644 --- a/yarn-project/simulator/src/client/view_data_oracle.ts +++ b/yarn-project/simulator/src/client/view_data_oracle.ts @@ -257,7 +257,7 @@ export class ViewDataOracle extends TypedOracle { const storageSlot = new Fr(startStorageSlot.value + i); const value = await this.aztecNode.getPublicStorageAt(this.contractAddress, storageSlot); - this.log(`Oracle storage read: slot=${storageSlot.toString()} value=${value}`); + this.log.debug(`Oracle storage read: slot=${storageSlot.toString()} value=${value}`); values.push(value); } return values; diff --git a/yarn-project/simulator/src/public/executor.ts b/yarn-project/simulator/src/public/executor.ts index 2f4d40175959..1e2d7f2c9951 100644 --- a/yarn-project/simulator/src/public/executor.ts +++ b/yarn-project/simulator/src/public/executor.ts @@ -37,7 +37,7 @@ export async function executePublicFunction( const execution = context.execution; const { contractAddress, functionData } = execution; const selector = functionData.selector; - log(`Executing public external function ${contractAddress.toString()}:${selector}`); + log.verbose(`Executing public external function ${contractAddress.toString()}:${selector}`); const initialWitness = context.getInitialWitness(); const acvmCallback = new Oracle(context); @@ -123,12 +123,12 @@ export async function executePublicFunction( const { contractStorageReads, contractStorageUpdateRequests } = context.getStorageActionData(); - log( + log.debug( `Contract storage reads: ${contractStorageReads .map(r => r.toFriendlyJSON() + ` - sec: ${r.sideEffectCounter}`) .join(', ')}`, ); - log( + log.debug( `Contract storage update requests: ${contractStorageUpdateRequests .map(r => r.toFriendlyJSON() + ` - sec: ${r.sideEffectCounter}`) .join(', ')}`, @@ -305,7 +305,7 @@ export class PublicExecutor { const bbExec = path.join(bbPath, 'build', 'bin', 'bb'); const bbArgs = ['avm_prove', '-b', bytecodePath, '-d', calldataPath, '-o', proofPath]; - this.log(`calling '${bbExec} ${bbArgs.join(' ')}'`); + this.log.debug(`calling '${bbExec} ${bbArgs.join(' ')}'`); const bbBinary = spawn(bbExec, bbArgs); // The binary writes the proof and the verification key to the write path. @@ -314,7 +314,7 @@ export class PublicExecutor { let stderr: string = ''; bbBinary.on('close', () => { - this.log(`Proof generation complete. Reading proof and vk from ${proofPath}.`); + this.log.verbose(`Proof generation complete. Reading proof and vk from ${proofPath}.`); return resolve(Promise.all([fs.readFile(proofPath), fs.readFile(path.join(artifactsPath, 'vk'))])); }); @@ -324,7 +324,7 @@ export class PublicExecutor { }); bbBinary.stdout.on('end', () => { if (stdout.length > 0) { - this.log(`stdout: ${stdout}`); + this.log.debug(`stdout: ${stdout}`); } }); @@ -334,7 +334,7 @@ export class PublicExecutor { }); bbBinary.stderr.on('end', () => { if (stderr.length > 0) { - this.log(`stderr: ${stderr}`); + this.log.warn(`stderr: ${stderr}`); } }); @@ -366,7 +366,7 @@ export class PublicExecutor { const bbExec = path.join(bbPath, 'build', 'bin', 'bb'); const bbArgs = ['avm_verify', '-p', proofPath]; - this.log(`calling '${bbPath} ${bbArgs.join(' ')}'`); + this.log.debug(`calling '${bbPath} ${bbArgs.join(' ')}'`); const bbBinary = spawn(bbExec, bbArgs); // The binary prints to stdout 1 if the proof is valid and 0 if it is not. diff --git a/yarn-project/simulator/src/public/public_execution_context.ts b/yarn-project/simulator/src/public/public_execution_context.ts index b999d27ad138..b2e5abe78d4f 100644 --- a/yarn-project/simulator/src/public/public_execution_context.ts +++ b/yarn-project/simulator/src/public/public_execution_context.ts @@ -120,7 +120,7 @@ export class PublicExecutionContext extends TypedOracle { public emitUnencryptedLog(log: UnencryptedL2Log) { // TODO(https://github.com/AztecProtocol/aztec-packages/issues/885) this.unencryptedLogs.push(log); - this.log(`Emitted unencrypted log: "${log.toHumanReadable()}"`); + this.log.verbose(`Emitted unencrypted log: "${log.toHumanReadable()}"`); } /** @@ -144,7 +144,7 @@ export class PublicExecutionContext extends TypedOracle { const storageSlot = new Fr(startStorageSlot.value + BigInt(i)); const sideEffectCounter = this.sideEffectCounter.count(); const value = await this.storageActions.read(storageSlot, sideEffectCounter); - this.log(`Oracle storage read: slot=${storageSlot.toString()} value=${value.toString()}`); + this.log.debug(`Oracle storage read: slot=${storageSlot.toString()} value=${value.toString()}`); values.push(value); } return values; @@ -163,7 +163,7 @@ export class PublicExecutionContext extends TypedOracle { const sideEffectCounter = this.sideEffectCounter.count(); this.storageActions.write(storageSlot, newValue, sideEffectCounter); await this.stateDb.storageWrite(this.execution.callContext.storageContractAddress, storageSlot, newValue); - this.log(`Oracle storage write: slot=${storageSlot.toString()} value=${newValue.toString()}`); + this.log.debug(`Oracle storage write: slot=${storageSlot.toString()} value=${newValue.toString()}`); newValues.push(newValue); } return newValues; @@ -187,7 +187,9 @@ export class PublicExecutionContext extends TypedOracle { isStaticCall = isStaticCall || this.execution.callContext.isStaticCall; const args = this.packedArgsCache.unpack(argsHash); - this.log(`Public function call: addr=${targetContractAddress} selector=${functionSelector} args=${args.join(',')}`); + this.log.verbose( + `Public function call: addr=${targetContractAddress} selector=${functionSelector} args=${args.join(',')}`, + ); const portalAddress = (await this.contractsDb.getPortalContractAddress(targetContractAddress)) ?? EthAddress.ZERO; @@ -240,7 +242,7 @@ export class PublicExecutionContext extends TypedOracle { } this.nestedExecutions.push(childExecutionResult); - this.log(`Returning from nested call: ret=${childExecutionResult.returnValues.join(', ')}`); + this.log.debug(`Returning from nested call: ret=${childExecutionResult.returnValues.join(', ')}`); return childExecutionResult.returnValues; } diff --git a/yarn-project/world-state/src/synchronizer/server_world_state_synchronizer.ts b/yarn-project/world-state/src/synchronizer/server_world_state_synchronizer.ts index 548c37a0f197..059fddfb4d8c 100644 --- a/yarn-project/world-state/src/synchronizer/server_world_state_synchronizer.ts +++ b/yarn-project/world-state/src/synchronizer/server_world_state_synchronizer.ts @@ -86,12 +86,14 @@ export class ServerWorldStateSynchronizer implements WorldStateSynchronizer { this.syncPromise = new Promise(resolve => { this.syncResolve = resolve; }); - this.log(`Starting sync from ${blockToDownloadFrom}, latest block ${this.latestBlockNumberAtStart}`); + this.log.info(`Starting sync from ${blockToDownloadFrom}, latest block ${this.latestBlockNumberAtStart}`); } else { // if no blocks to be retrieved, go straight to running this.setCurrentState(WorldStateRunningState.RUNNING); this.syncPromise = Promise.resolve(); - this.log(`Next block ${blockToDownloadFrom} already beyond latest block at ${this.latestBlockNumberAtStart}`); + this.log.debug( + `Next block ${blockToDownloadFrom} already beyond latest block at ${this.latestBlockNumberAtStart}`, + ); } // start looking for further blocks @@ -103,21 +105,22 @@ export class ServerWorldStateSynchronizer implements WorldStateSynchronizer { this.jobQueue.start(); this.runningPromise = blockProcess(); this.l2BlockDownloader.start(blockToDownloadFrom); - this.log(`Started block downloader from block ${blockToDownloadFrom}`); + this.log.info(`Started block downloader from block ${blockToDownloadFrom}`); return this.syncPromise; } public async stop() { - this.log('Stopping world state...'); + this.log.debug('Stopping world state...'); this.stopping = true; await this.l2BlockDownloader.stop(); - this.log('Cancelling job queue...'); + this.log.debug('Cancelling job queue...'); await this.jobQueue.cancel(); - this.log('Stopping Merkle trees'); + this.log.debug('Stopping Merkle trees'); await this.merkleTreeDb.stop(); - this.log('Awaiting promise'); + this.log.debug('Awaiting promise'); await this.runningPromise; this.setCurrentState(WorldStateRunningState.STOPPED); + this.log.info(`Stopped`); } private get currentL2BlockNum(): number { @@ -147,7 +150,7 @@ export class ServerWorldStateSynchronizer implements WorldStateSynchronizer { return this.currentL2BlockNum; } const blockToSyncTo = minBlockNumber === undefined ? 'latest' : `${minBlockNumber}`; - this.log(`World State at block ${this.currentL2BlockNum}, told to sync to block ${blockToSyncTo}...`); + this.log.debug(`World State at block ${this.currentL2BlockNum}, told to sync to block ${blockToSyncTo}...`); // ensure any outstanding block updates are completed first. await this.jobQueue.syncPoint(); while (true) { @@ -157,7 +160,7 @@ export class ServerWorldStateSynchronizer implements WorldStateSynchronizer { } // Poll for more blocks const numBlocks = await this.l2BlockDownloader.pollImmediate(); - this.log(`Block download immediate poll yielded ${numBlocks} blocks`); + this.log.debug(`Block download immediate poll yielded ${numBlocks} blocks`); if (numBlocks) { // More blocks were received, process them and go round again await this.jobQueue.put(() => this.collectAndProcessBlocks()); @@ -194,7 +197,7 @@ export class ServerWorldStateSynchronizer implements WorldStateSynchronizer { private async handleL2BlocksAndMessages(l2Blocks: L2Block[], l1ToL2Messages: Fr[][]) { for (let i = 0; i < l2Blocks.length; i++) { const [duration, result] = await elapsed(() => this.handleL2BlockAndMessages(l2Blocks[i], l1ToL2Messages[i])); - this.log(`Handled new L2 block`, { + this.log.verbose(`Handled new L2 block`, { eventName: 'l2-block-handled', duration, isBlockOurs: result.isBlockOurs, @@ -238,7 +241,7 @@ export class ServerWorldStateSynchronizer implements WorldStateSynchronizer { */ private setCurrentState(newState: WorldStateRunningState) { this.currentState = newState; - this.log(`Moved to state ${WorldStateRunningState[this.currentState]}`); + this.log.debug(`Moved to state ${WorldStateRunningState[this.currentState]}`); } /** diff --git a/yarn-project/world-state/src/world-state-db/merkle_tree_operations.ts b/yarn-project/world-state/src/world-state-db/merkle_tree_operations.ts index fd6fc5801c05..bbfd04eae66e 100644 --- a/yarn-project/world-state/src/world-state-db/merkle_tree_operations.ts +++ b/yarn-project/world-state/src/world-state-db/merkle_tree_operations.ts @@ -208,5 +208,5 @@ export async function inspectTree( ` Leaf ${i}: ${await db.getLeafValue(treeId, BigInt(i)).then(x => x?.toString('hex') ?? '[undefined]')}`, ); } - log(output.join('\n')); + log.info(output.join('\n')); } diff --git a/yarn-project/world-state/src/world-state-db/merkle_trees.ts b/yarn-project/world-state/src/world-state-db/merkle_trees.ts index 9eb62d436966..b74b887094a6 100644 --- a/yarn-project/world-state/src/world-state-db/merkle_trees.ts +++ b/yarn-project/world-state/src/world-state-db/merkle_trees.ts @@ -568,10 +568,10 @@ export class MerkleTrees implements MerkleTreeDb { }; const ourBlock = treeRootWithIdPairs.every(([root, id]) => compareRoot(root, id)); if (ourBlock) { - this.log(`Block ${l2Block.number} is ours, committing world state`); + this.log.verbose(`Block ${l2Block.number} is ours, committing world state`); await this.#commit(); } else { - this.log(`Block ${l2Block.number} is not ours, rolling back world state and committing state from chain`); + this.log.verbose(`Block ${l2Block.number} is not ours, rolling back world state and committing state from chain`); await this.#rollback(); // We have to pad both the tx effects and the values within tx effects because that's how the trees are built @@ -637,7 +637,7 @@ export class MerkleTrees implements MerkleTreeDb { `Synced tree root ${treeName} does not match published L2 block root: ${syncedStr} != ${rootStr}`, ); } else { - this.log(`Tree ${treeName} synched with size ${info.size} root ${rootStr}`); + this.log.debug(`Tree ${treeName} synched with size ${info.size} root ${rootStr}`); } } await this.#snapshot(l2Block.number);