11import { toBigIntBE , toHex } from '@aztec/foundation/bigint-buffer' ;
22import { keccak256 } from '@aztec/foundation/crypto' ;
3- import type { EthAddress } from '@aztec/foundation/eth-address' ;
3+ import { EthAddress } from '@aztec/foundation/eth-address' ;
44import { jsonStringify } from '@aztec/foundation/json-rpc' ;
55import { createLogger } from '@aztec/foundation/log' ;
66import type { TestDateProvider } from '@aztec/foundation/timer' ;
@@ -112,7 +112,7 @@ export class EthCheatCodes {
112112 * @param account - The account to set the balance for
113113 * @param balance - The balance to set
114114 */
115- public async setBalance ( account : EthAddress , balance : bigint ) : Promise < void > {
115+ public async setBalance ( account : EthAddress | Hex , balance : bigint ) : Promise < void > {
116116 try {
117117 await this . rpcCall ( 'anvil_setBalance' , [ account . toString ( ) , toHex ( balance ) ] ) ;
118118 } catch ( err ) {
@@ -121,6 +121,11 @@ export class EthCheatCodes {
121121 this . logger . warn ( `Set balance for ${ account } to ${ balance } ` ) ;
122122 }
123123
124+ public async getBalance ( account : EthAddress | Hex ) : Promise < bigint > {
125+ const res = await this . rpcCall ( 'eth_getBalance' , [ account . toString ( ) , 'latest' ] ) ;
126+ return BigInt ( res ) ;
127+ }
128+
124129 /**
125130 * Set the interval between successive blocks (block time). This does NOT enable interval mining.
126131 * @param interval - The interval to use between blocks
@@ -300,6 +305,11 @@ export class EthCheatCodes {
300305 */
301306 public async startImpersonating ( who : EthAddress | Hex ) : Promise < void > {
302307 try {
308+ // Since the `who` impersonated will sometimes be a contract without funds, we fund it if needed.
309+ if ( ( await this . getBalance ( who ) ) === 0n ) {
310+ await this . setBalance ( who , 10n * 10n ** 18n ) ;
311+ }
312+
303313 await this . rpcCall ( 'hardhat_impersonateAccount' , [ who . toString ( ) ] ) ;
304314 } catch ( err ) {
305315 throw new Error ( `Error impersonating ${ who } : ${ err } ` ) ;
0 commit comments