@@ -887,6 +887,11 @@ func DoEstimateGas(ctx context.Context, b Backend, args CallArgs, blockNrOrHash
887887 hi uint64
888888 cap uint64
889889 )
890+ // Use zero address if sender unspecified.
891+ if args .From == nil {
892+ return 0 , fmt .Errorf ("missing from address" )
893+ }
894+ // Determine the highest gas limit can be used during the estimation.
890895 if args .Gas != nil && uint64 (* args .Gas ) >= params .TxGas {
891896 hi = uint64 (* args .Gas )
892897 } else {
@@ -897,16 +902,40 @@ func DoEstimateGas(ctx context.Context, b Backend, args CallArgs, blockNrOrHash
897902 }
898903 hi = block .GasLimit ()
899904 }
905+ // Recap the highest gas limit with account's available balance.
906+ if args .GasPrice != nil && args .GasPrice .ToInt ().BitLen () != 0 {
907+ state , _ , err := b .StateAndHeaderByNumberOrHash (ctx , blockNrOrHash )
908+ if err != nil {
909+ return 0 , err
910+ }
911+ balance := state .GetBalance (* args .From ) // from can't be nil
912+ available := new (big.Int ).Set (balance )
913+ if args .Value != nil {
914+ if args .Value .ToInt ().Cmp (available ) >= 0 {
915+ return 0 , errors .New ("insufficient funds for transfer" )
916+ }
917+ available .Sub (available , args .Value .ToInt ())
918+ }
919+ allowance := new (big.Int ).Div (available , args .GasPrice .ToInt ())
920+
921+ // If the allowance is larger than maximum uint64, skip checking
922+ if allowance .IsUint64 () && hi > allowance .Uint64 () {
923+ transfer := args .Value
924+ if transfer == nil {
925+ transfer = new (hexutil.Big )
926+ }
927+ log .Warn ("Gas estimation capped by limited funds" , "original" , hi , "balance" , balance ,
928+ "sent" , transfer .ToInt (), "gasprice" , args .GasPrice .ToInt (), "fundable" , allowance )
929+ hi = allowance .Uint64 ()
930+ }
931+ }
932+ // Recap the highest gas allowance with specified gascap.
900933 if gasCap != nil && hi > gasCap .Uint64 () {
901934 log .Warn ("Caller gas above allowance, capping" , "requested" , hi , "cap" , gasCap )
902935 hi = gasCap .Uint64 ()
903936 }
904937 cap = hi
905938
906- // Use zero address if sender unspecified.
907- if args .From == nil {
908- args .From = new (common.Address )
909- }
910939 // Create a helper to check if a gas allowance results in an executable transaction
911940 executable := func (gas uint64 ) bool {
912941 args .Gas = (* hexutil .Uint64 )(& gas )
0 commit comments