Skip to content

Commit

Permalink
better logging
Browse files Browse the repository at this point in the history
  • Loading branch information
charlielye committed Apr 5, 2024
1 parent 04cdcad commit fe72e1f
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 24 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export class TokenContractTest {

constructor(testName: string) {
this.logger = createDebugLogger(`aztec:e2e_token_contract:${testName}`);
this.snapshotManager = new SnapshotManager(`e2e_token_contract/${testName}`, dataPath, this.logger);
this.snapshotManager = new SnapshotManager(`e2e_token_contract/${testName}`, dataPath);
}

/**
Expand All @@ -40,12 +40,11 @@ export class TokenContractTest {
* 2. Publicly deploy accounts, deploy token contract and a "bad account".
*/
async pushBaseSnapshots() {
await this.snapshotManager.snapshot('3_accounts', addAccounts(3), async ({ accountKeys }, { pxe }) => {
await this.snapshotManager.snapshot('3_accounts', addAccounts(3, this.logger), async ({ accountKeys }, { pxe }) => {
const accountManagers = accountKeys.map(ak => getSchnorrAccount(pxe, ak[0], ak[1], 1));
this.wallets = await Promise.all(accountManagers.map(a => a.getWallet()));
this.accounts = await pxe.getRegisteredAccounts();
this.logger(`Restored ${this.accounts.length} accounts.`);
this.logger(`Wallet 0 address: ${this.wallets[0].getAddress()}`);
this.wallets.forEach((w, i) => this.logger(`Wallet ${i} address: ${w.getAddress()}`));
});

await this.snapshotManager.snapshot(
Expand All @@ -68,7 +67,7 @@ export class TokenContractTest {
.deployed();
this.logger(`Token deployed to ${asset.address}`);

this.logger(`Deploying "bad account"...`);
this.logger(`Deploying bad account...`);
this.badAccount = await DocsExampleContract.deploy(this.wallets[0]).send().deployed();
this.logger(`Deployed to ${this.badAccount.address}.`);

Expand All @@ -77,7 +76,7 @@ export class TokenContractTest {
async ({ tokenContractAddress, badAccountAddress }) => {
// Restore the token contract state.
this.asset = await TokenContract.at(tokenContractAddress, this.wallets[0]);
this.logger(`Token contract restored to ${this.asset.address}.`);
this.logger(`Token contract address: ${this.asset.address}`);

this.tokenSim = new TokenSimulator(
this.asset,
Expand All @@ -86,7 +85,7 @@ export class TokenContractTest {
);

this.badAccount = await DocsExampleContract.at(badAccountAddress, this.wallets[0]);
this.logger(`Bad account restored to ${this.badAccount.address}.`);
this.logger(`Bad account address: ${this.badAccount.address}`);

expect(await this.asset.methods.admin().simulate()).toBe(this.accounts[0].address.toBigInt());
},
Expand Down Expand Up @@ -125,27 +124,44 @@ export class TokenContractTest {
async () => {
const { asset, accounts } = this;
const amount = 10000n;

this.logger(`Minting ${amount} publicly...`);
await asset.methods.mint_public(accounts[0].address, amount).send().wait();

this.logger(`Minting ${amount} privately...`);
const secret = Fr.random();
const secretHash = computeMessageSecretHash(secret);
const receipt = await asset.methods.mint_private(amount, secretHash).send().wait();

await this.addPendingShieldNoteToPXE(0, amount, secretHash, receipt.txHash);
const txClaim = asset.methods.redeem_shield(accounts[0].address, amount, secret).send();
await txClaim.wait({ debug: true });
this.logger(`Minting complete.`);

return { amount };
},
async ({ amount }) => {
const { asset, accounts, tokenSim } = this;
tokenSim.mintPublic(accounts[0].address, amount);
expect(await asset.methods.balance_of_public(accounts[0].address).simulate()).toEqual(
tokenSim.balanceOfPublic(accounts[0].address),
);
const {
asset,
accounts: [{ address }],
tokenSim,
} = this;
tokenSim.mintPublic(address, amount);

const publicBalance = await asset.methods.balance_of_public(address).simulate();
this.logger(`Public balance of wallet 0: ${publicBalance}`);
expect(publicBalance).toEqual(this.tokenSim.balanceOfPublic(address));

tokenSim.mintPrivate(amount);
tokenSim.redeemShield(accounts[0].address, amount);
expect(await asset.methods.total_supply().simulate()).toEqual(tokenSim.totalSupply);
tokenSim.redeemShield(address, amount);
const privateBalance = await asset.methods.balance_of_private(address).simulate();
this.logger(`Private balance of wallet 0: ${privateBalance}`);
expect(privateBalance).toEqual(tokenSim.balanceOfPrivate(address));

const totalSupply = await asset.methods.total_supply().simulate();
this.logger(`Total supply: ${totalSupply}`);
expect(totalSupply).toEqual(tokenSim.totalSupply);

return Promise.resolve();
},
);
Expand Down
23 changes: 13 additions & 10 deletions yarn-project/end-to-end/src/fixtures/snapshot_manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
import { deployInstance, registerContractClass } from '@aztec/aztec.js/deployment';
import { asyncMap } from '@aztec/foundation/async-map';
import { resolver, reviver } from '@aztec/foundation/serialize';
import { createDebugLogger } from '@aztec/foundation/log';
import { type PXEService, createPXEService, getPXEServiceConfig } from '@aztec/pxe';

import { type Anvil, createAnvil } from '@viem/anvil';
Expand All @@ -35,24 +36,26 @@ type SubsystemsContext = {

type SnapshotEntry = {
name: string;
apply: (context: SubsystemsContext, logger: DebugLogger) => Promise<any>;
restore: (snapshotData: any, context: SubsystemsContext, logger: DebugLogger) => Promise<any>;
apply: (context: SubsystemsContext) => Promise<any>;
restore: (snapshotData: any, context: SubsystemsContext) => Promise<any>;
snapshotPath: string;
};

export class SnapshotManager {
private snapshotStack: SnapshotEntry[] = [];
private context?: SubsystemsContext;
private livePath: string;
private logger: DebugLogger;

constructor(testName: string, private dataPath: string, private logger: DebugLogger) {
constructor(testName: string, private dataPath: string) {
this.livePath = join(this.dataPath, 'live', testName);
this.logger = createDebugLogger(`aztec:snapshot_manager:${testName}`);
}

public async snapshot<T>(
name: string,
apply: (context: SubsystemsContext, logger: DebugLogger) => Promise<T>,
restore: (snapshotData: T, context: SubsystemsContext, logger: DebugLogger) => Promise<void> = () =>
apply: (context: SubsystemsContext) => Promise<T>,
restore: (snapshotData: T, context: SubsystemsContext) => Promise<void> = () =>
Promise.resolve(),
) {
const snapshotPath = join(this.dataPath, 'snapshots', ...this.snapshotStack.map(e => e.name), name, 'snapshot');
Expand All @@ -76,11 +79,11 @@ export class SnapshotManager {

// Apply current state transition.
this.logger(`Applying state transition for ${name}...`);
const snapshotData = await apply(this.context, this.logger);
const snapshotData = await apply(this.context);
this.logger(`State transition for ${name} complete.`);

// Execute the restoration function.
await restore(snapshotData, this.context, this.logger);
await restore(snapshotData, this.context);

// Save the snapshot data.
const ethCheatCodes = new EthCheatCodes(this.context.aztecNodeConfig.rpcUrl);
Expand Down Expand Up @@ -121,7 +124,7 @@ export class SnapshotManager {
await asyncMap(this.snapshotStack, async e => {
const snapshotData = JSON.parse(readFileSync(`${e.snapshotPath}/${e.name}.json`, 'utf-8'), reviver);
this.logger(`Executing restoration function for ${e.name}...`);
await e.restore(snapshotData, this.context!, this.logger);
await e.restore(snapshotData, this.context!);
this.logger(`Restoration of ${e.name} complete.`);
});
} else {
Expand Down Expand Up @@ -263,8 +266,8 @@ export class SnapshotManager {
* The 'restore' function is not provided, as it must be a closure within the test context to capture the results.
*/
export const addAccounts =
(numberOfAccounts: number) =>
async ({ pxe }: SubsystemsContext, logger: DebugLogger) => {
(numberOfAccounts: number, logger: DebugLogger) =>
async ({ pxe }: SubsystemsContext) => {
// Generate account keys.
const accountKeys: [GrumpkinPrivateKey, GrumpkinPrivateKey][] = Array.from({ length: numberOfAccounts }).map(_ => [
GrumpkinPrivateKey.random(),
Expand Down

0 comments on commit fe72e1f

Please sign in to comment.