@@ -673,6 +673,28 @@ function startUiSiteServer(args: {
673673 return `0x${ n . toString ( 16 ) } ` ;
674674 }
675675
676+ async function trySetLocalBalance ( rpcUrl : string , addr : string , wei : bigint ) : Promise < { ok : boolean ; method ?: string ; error ?: string } > {
677+ const qty = toHexQuantity ( wei ) ;
678+ const methods = [ 'anvil_setBalance' , 'hardhat_setBalance' ] ;
679+
680+ for ( const method of methods ) {
681+ try {
682+ await rpcRequest ( rpcUrl , method , [ addr , qty ] , 2000 ) ;
683+ return { ok : true , method } ;
684+ } catch ( e : any ) {
685+ const msg = String ( e ?. message ?? e ?? '' ) ;
686+ const unsupported =
687+ / m e t h o d n o t f o u n d / i. test ( msg ) ||
688+ / u n s u p p o r t e d / i. test ( msg ) ||
689+ / d o e s n o t e x i s t / i. test ( msg ) ||
690+ / - 3 2 6 0 1 / . test ( msg ) ;
691+ if ( ! unsupported ) return { ok : false , method, error : msg } ;
692+ }
693+ }
694+
695+ return { ok : false , error : 'No supported local balance RPC method found (anvil_setBalance, hardhat_setBalance).' } ;
696+ }
697+
676698 function readBody ( req : nodeHttp . IncomingMessage , maxBytes = 1024 * 1024 ) : Promise < string > {
677699 return new Promise ( ( resolve , reject ) => {
678700 let raw = '' ;
@@ -750,9 +772,14 @@ function startUiSiteServer(args: {
750772 const targetWei = faucet ! . targetWei ;
751773
752774 let didSet = false ;
775+ let setMethod : string | null = null ;
753776 if ( oldWei < targetWei ) {
754- await rpcRequest ( faucet ! . rpcUrl , 'anvil_setBalance' , [ addr , toHexQuantity ( targetWei ) ] , 2000 ) ;
777+ const setResult = await trySetLocalBalance ( faucet ! . rpcUrl , addr , targetWei ) ;
778+ if ( ! setResult . ok ) {
779+ return sendJson ( res , 400 , { ok : false , error : setResult . error ?? 'Failed to set balance.' } ) ;
780+ }
755781 didSet = true ;
782+ setMethod = setResult . method ?? null ;
756783 }
757784
758785 const newHex = ( await rpcRequest ( faucet ! . rpcUrl , 'eth_getBalance' , [ addr , 'latest' ] , 2000 ) ) as string ;
@@ -765,6 +792,7 @@ function startUiSiteServer(args: {
765792 targetWei : toHexQuantity ( targetWei ) ,
766793 oldBalanceWei : toHexQuantity ( oldWei ) ,
767794 newBalanceWei : toHexQuantity ( newWei ) ,
795+ method : setMethod ,
768796 didSet
769797 } ) ;
770798 } catch ( e : any ) {
0 commit comments