Skip to content

Commit

Permalink
simplify acc & wallets
Browse files Browse the repository at this point in the history
  • Loading branch information
spypsy committed Nov 18, 2024
1 parent d066d51 commit 68af7ec
Show file tree
Hide file tree
Showing 6 changed files with 93 additions and 116 deletions.
20 changes: 20 additions & 0 deletions yarn-project/circuit-types/src/interfaces/aztec-node.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
L1_TO_L2_MSG_TREE_HEIGHT,
NOTE_HASH_TREE_HEIGHT,
NULLIFIER_TREE_HEIGHT,
type NodeInfo,
PUBLIC_DATA_TREE_HEIGHT,
type ProtocolContractAddresses,
ProtocolContractsNames,
Expand Down Expand Up @@ -155,6 +156,11 @@ describe('AztecNodeApiSchema', () => {
expect(response).toBe(true);
});

it('getNodeInfo', async () => {
const response = await context.client.getNodeInfo();
expect(response).toEqual(await handler.getNodeInfo());
});

it('getBlocks', async () => {
const response = await context.client.getBlocks(1, 1);
expect(response).toHaveLength(1);
Expand Down Expand Up @@ -404,6 +410,20 @@ class MockAztecNode implements AztecNode {
isReady(): Promise<boolean> {
return Promise.resolve(true);
}
getNodeInfo(): Promise<NodeInfo> {
return Promise.resolve({
nodeVersion: '1.0',
l1ChainId: 1,
protocolVersion: 1,
enr: 'enr',
l1ContractAddresses: Object.fromEntries(
L1ContractsNames.map(name => [name, EthAddress.random()]),
) as L1ContractAddresses,
protocolContractAddresses: Object.fromEntries(
ProtocolContractsNames.map(name => [name, AztecAddress.random()]),
) as ProtocolContractAddresses,
});
}
getBlocks(from: number, limit: number): Promise<L2Block[]> {
return Promise.resolve(times(limit, i => L2Block.random(from + i)));
}
Expand Down
5 changes: 4 additions & 1 deletion yarn-project/circuit-types/src/interfaces/aztec-node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ import {
L1_TO_L2_MSG_TREE_HEIGHT,
NOTE_HASH_TREE_HEIGHT,
NULLIFIER_TREE_HEIGHT,
NodeInfo,
type NodeInfo,
NodeInfoSchema,
PUBLIC_DATA_TREE_HEIGHT,
type ProtocolContractAddresses,
ProtocolContractAddressesSchema,
Expand Down Expand Up @@ -464,6 +465,8 @@ export const AztecNodeApiSchema: ApiSchemaFor<AztecNode> = {

isReady: z.function().returns(z.boolean()),

getNodeInfo: z.function().returns(NodeInfoSchema),

getBlocks: z.function().args(z.number(), z.number()).returns(z.array(L2Block.schema)),

getNodeVersion: z.function().returns(z.string()),
Expand Down
6 changes: 3 additions & 3 deletions yarn-project/ethereum/src/deploy_l1_contracts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -617,7 +617,7 @@ export async function deployL1Contract(
let txHash: Hex | undefined = undefined;
let resultingAddress: Hex | null | undefined = undefined;

const gasUtils = new GasUtils(publicClient, logger);
const gasUtils = new GasUtils(publicClient, walletClient, logger);

if (libraries) {
// @note Assumes that we wont have nested external libraries.
Expand Down Expand Up @@ -667,7 +667,7 @@ export async function deployL1Contract(
const existing = await publicClient.getBytecode({ address: resultingAddress });

if (existing === undefined || existing === '0x') {
const receipt = await gasUtils.sendAndMonitorTransaction(walletClient, walletClient.account!, {
const receipt = await gasUtils.sendAndMonitorTransaction({
to: deployer,
data: concatHex([salt, calldata]),
});
Expand All @@ -680,7 +680,7 @@ export async function deployL1Contract(
} else {
// Regular deployment path
const deployData = encodeDeployData({ abi, bytecode, args });
const receipt = await gasUtils.sendAndMonitorTransaction(walletClient, walletClient.account!, {
const receipt = await gasUtils.sendAndMonitorTransaction({
to: '0x', // Contract creation
data: deployData,
});
Expand Down
16 changes: 9 additions & 7 deletions yarn-project/ethereum/src/gas_utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ describe('GasUtils', () => {
let gasUtils: GasUtils;
let publicClient: any;
let walletClient: any;
let account: any;
let anvil: Anvil;
let initialBaseFee: bigint;
const logger = createDebugLogger('l1_gas_test');
Expand All @@ -43,7 +42,7 @@ describe('GasUtils', () => {
throw new Error('Failed to get private key');
}
const privKey = Buffer.from(privKeyRaw).toString('hex');
account = privateKeyToAccount(`0x${privKey}`);
const account = privateKeyToAccount(`0x${privKey}`);

publicClient = createPublicClient({
transport: http(rpcUrl),
Expand All @@ -58,6 +57,7 @@ describe('GasUtils', () => {

gasUtils = new GasUtils(
publicClient,
walletClient,
logger,
{
bufferPercentage: 20n,
Expand All @@ -77,7 +77,7 @@ describe('GasUtils', () => {
}, 5000);

it('sends and monitors a simple transaction', async () => {
const receipt = await gasUtils.sendAndMonitorTransaction(walletClient, account, {
const receipt = await gasUtils.sendAndMonitorTransaction({
to: '0x1234567890123456789012345678901234567890',
data: '0x',
value: 0n,
Expand All @@ -92,7 +92,7 @@ describe('GasUtils', () => {
initialBaseFee = initialBlock.baseFeePerGas ?? 0n;

// Start a transaction
const sendPromise = gasUtils.sendAndMonitorTransaction(walletClient, account, {
const sendPromise = gasUtils.sendAndMonitorTransaction({
to: '0x1234567890123456789012345678901234567890',
data: '0x',
value: 0n,
Expand Down Expand Up @@ -131,7 +131,7 @@ describe('GasUtils', () => {
params: [],
});

const receipt = await gasUtils.sendAndMonitorTransaction(walletClient, account, {
const receipt = await gasUtils.sendAndMonitorTransaction({
to: '0x1234567890123456789012345678901234567890',
data: '0x',
value: 0n,
Expand All @@ -154,6 +154,7 @@ describe('GasUtils', () => {
// First deploy without any buffer
const baselineGasUtils = new GasUtils(
publicClient,
walletClient,
logger,
{
bufferPercentage: 0n,
Expand All @@ -168,7 +169,7 @@ describe('GasUtils', () => {
},
);

const baselineTx = await baselineGasUtils.sendAndMonitorTransaction(walletClient, account, {
const baselineTx = await baselineGasUtils.sendAndMonitorTransaction({
to: EthAddress.ZERO.toString(),
data: SIMPLE_CONTRACT_BYTECODE,
});
Expand All @@ -181,6 +182,7 @@ describe('GasUtils', () => {
// Now deploy with 20% buffer
const bufferedGasUtils = new GasUtils(
publicClient,
walletClient,
logger,
{
bufferPercentage: 20n,
Expand All @@ -195,7 +197,7 @@ describe('GasUtils', () => {
},
);

const bufferedTx = await bufferedGasUtils.sendAndMonitorTransaction(walletClient, account, {
const bufferedTx = await bufferedGasUtils.sendAndMonitorTransaction({
to: EthAddress.ZERO.toString(),
data: SIMPLE_CONTRACT_BYTECODE,
});
Expand Down
27 changes: 14 additions & 13 deletions yarn-project/ethereum/src/gas_utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ import { sleep } from '@aztec/foundation/sleep';
import {
type Account,
type Address,
type Chain,
type Hex,
type HttpTransport,
type PublicClient,
type TransactionReceipt,
type WalletClient,
Expand Down Expand Up @@ -80,6 +82,7 @@ export class GasUtils {

constructor(
private readonly publicClient: PublicClient,
private readonly walletClient: WalletClient<HttpTransport, Chain, Account>,
private readonly logger?: DebugLogger,
gasConfig?: GasConfig,
monitorConfig?: L1TxMonitorConfig,
Expand All @@ -102,25 +105,21 @@ export class GasUtils {
* @returns The hash of the successful transaction
*/
public async sendAndMonitorTransaction(
walletClient: WalletClient,
account: Account,
request: L1TxRequest,
_gasConfig?: Partial<GasConfig>,
_monitorConfig?: Partial<L1TxMonitorConfig>,
): Promise<TransactionReceipt> {
const monitorConfig = { ...this.monitorConfig, ..._monitorConfig };
const gasConfig = { ...this.gasConfig, ..._gasConfig };

const account = this.walletClient.account;
// Estimate gas
const gasLimit = await this.estimateGas(account, request);

const gasPrice = await this.getGasPrice(gasConfig);
const nonce = await this.publicClient.getTransactionCount({ address: account.address });

// Send initial tx
const txHash = await walletClient.sendTransaction({
chain: null,
account,
const txHash = await this.walletClient.sendTransaction({
...request,
gas: gasLimit,
maxFeePerGas: gasPrice,
Expand Down Expand Up @@ -163,15 +162,19 @@ export class GasUtils {

// Check if current tx is pending
const tx = await this.publicClient.getTransaction({ hash: currentTxHash });
if (tx) {
this.logger?.debug(`L1 Transaction ${currentTxHash} pending`);

// Get time passed
const timePassed = Date.now() - lastSeen;

if (tx && timePassed < monitorConfig.stallTimeMs) {
this.logger?.debug(`L1 Transaction ${currentTxHash} pending. Time passed: ${timePassed}ms`);
lastSeen = Date.now();
await sleep(monitorConfig.checkIntervalMs);
continue;
}

// tx not found and enough time has passed - might be stuck
if (Date.now() - lastSeen > monitorConfig.stallTimeMs && attempts < monitorConfig.maxAttempts) {
// Enough time has passed - might be stuck
if (timePassed > monitorConfig.stallTimeMs && attempts < monitorConfig.maxAttempts) {
attempts++;
const newGasPrice = await this.getGasPrice();

Expand All @@ -181,9 +184,7 @@ export class GasUtils {
);

// Send replacement tx with higher gas price
currentTxHash = await walletClient.sendTransaction({
chain: null,
account,
currentTxHash = await this.walletClient.sendTransaction({
...request,
nonce,
gas: gasLimit,
Expand Down
Loading

0 comments on commit 68af7ec

Please sign in to comment.