Skip to content
This repository was archived by the owner on Oct 20, 2024. It is now read-only.

Commit

Permalink
Add support for Arbitrum (#156)
Browse files Browse the repository at this point in the history
  • Loading branch information
hazim-j authored Apr 27, 2023
1 parent 2a046c9 commit 27e6fd7
Show file tree
Hide file tree
Showing 9 changed files with 177 additions and 33 deletions.
File renamed without changes.
2 changes: 1 addition & 1 deletion internal/start/private.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ func PrivateMode() {

ov := gas.NewDefaultOverhead()
if chain.Cmp(config.ArbitrumOneChainID) == 0 || chain.Cmp(config.ArbitrumGoerliChainID) == 0 {
ov.SetCalcPreVerificationGasFunc(gas.CalcArbitrumPVGWithEthClient(eth))
ov.SetCalcPreVerificationGasFunc(gas.CalcArbitrumPVGWithEthClient(rpc))
}

mem, err := mempool.New(db)
Expand Down
8 changes: 8 additions & 0 deletions pkg/arbitrum/nodeinterface/constants.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package nodeinterface

import "github.com/ethereum/go-ethereum/common"

var (
ERC4337GasHelperAddress = common.HexToAddress("0x559e3c6A74678FDBE1Fcc54153A8D7Dd7049FBCA")
PrecompileAddress = common.HexToAddress("0x00000000000000000000000000000000000000C8")
)
65 changes: 65 additions & 0 deletions pkg/arbitrum/nodeinterface/methods.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package nodeinterface

import (
"errors"
"fmt"
"math/big"

"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/common/hexutil"
)

var (
addressT, _ = abi.NewType("address", "", nil)
boolT, _ = abi.NewType("bool", "", nil)
bytesT, _ = abi.NewType("bytes", "", nil)
uint64T, _ = abi.NewType("uint64", "", nil)
uint256T, _ = abi.NewType("uint256", "", nil)

GasEstimateL1ComponentMethod = abi.NewMethod(
"gasEstimateL1Component",
"gasEstimateL1Component",
abi.Function,
"",
false,
true,
abi.Arguments{
{Name: "to", Type: addressT},
{Name: "contractCreation", Type: boolT},
{Name: "data", Type: bytesT},
},
abi.Arguments{
{Name: "gasEstimateForL1", Type: uint64T},
{Name: "baseFee", Type: uint256T},
{Name: "l1BaseFeeEstimate", Type: uint256T},
},
)
)

type GasEstimateL1ComponentOutput struct {
GasEstimateForL1 uint64
BaseFee *big.Int
L1BaseFeeEstimate *big.Int
}

func DecodeGasEstimateL1ComponentOutput(out any) (*GasEstimateL1ComponentOutput, error) {
hex, ok := out.(string)
if !ok {
return nil, errors.New("gasEstimateL1Component: cannot assert type: hex is not of type string")
}
data, err := hexutil.Decode(hex)
if err != nil {
return nil, fmt.Errorf("gasEstimateL1Component: %s", err)
}

args, err := GasEstimateL1ComponentMethod.Outputs.Unpack(data)
if err != nil {
return nil, fmt.Errorf("gasEstimateL1Component: %s", err)
}

return &GasEstimateL1ComponentOutput{
GasEstimateForL1: args[0].(uint64),
BaseFee: args[1].(*big.Int),
L1BaseFeeEstimate: args[2].(*big.Int),
}, nil
}
21 changes: 5 additions & 16 deletions pkg/client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
package client

import (
"bytes"
"errors"
"math/big"

Expand Down Expand Up @@ -173,28 +172,18 @@ func (i *Client) EstimateUserOperationGas(op map[string]any, ep string) (*gas.Ga
return nil, err
}

// Create a new op with updated gas limits
data, err := userOp.ToMap()
if err != nil {
l.Error(err, "eth_estimateUserOperationGas error")
return nil, err
}
data["verificationGasLimit"] = hexutil.EncodeBig(big.NewInt(int64(vg)))
data["callGasLimit"] = hexutil.EncodeBig(big.NewInt(int64(cg)))
data["signature"] = hexutil.Encode(bytes.Repeat([]byte{1}, len(userOp.Signature)))
userOp, err = userop.New(data)
// Calculate PreVerificationGas
pvg, err := i.ov.CalcPreVerificationGas(userOp)
if err != nil {
l.Error(err, "eth_estimateUserOperationGas error")
return nil, err
}

// Return gas values with a PVG calculation that takes into account updated gas limits and a signature
// with no zero bytes.
l.Info("eth_estimateUserOperationGas ok")
return &gas.GasEstimates{
PreVerificationGas: i.ov.CalcPreVerificationGas(userOp),
VerificationGas: userOp.VerificationGasLimit,
CallGasLimit: userOp.CallGasLimit,
PreVerificationGas: pvg,
VerificationGas: big.NewInt(int64(vg)),
CallGasLimit: big.NewInt(int64(cg)),
}, nil
}

Expand Down
36 changes: 31 additions & 5 deletions pkg/gas/overhead.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@
package gas

import (
"bytes"
"math"
"math/big"

"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/stackup-wallet/stackup-bundler/pkg/userop"
)

Expand All @@ -20,6 +22,9 @@ type Overhead struct {
nonZeroValueCall float64
callOpcode float64
nonZeroValueStipend float64
sanitizedPVG *big.Int
sanitizedVGL *big.Int
sanitizedCGL *big.Int
calcPVGFunc CalcPreVerificationGasFunc
}

Expand All @@ -36,6 +41,9 @@ func NewDefaultOverhead() *Overhead {
nonZeroValueCall: 9000,
callOpcode: 700,
nonZeroValueStipend: 2300,
sanitizedPVG: big.NewInt(100000),
sanitizedVGL: big.NewInt(1000000),
sanitizedCGL: big.NewInt(1000000),
calcPVGFunc: calcPVGFuncNoop(),
}
}
Expand All @@ -45,13 +53,31 @@ func (ov *Overhead) SetCalcPreVerificationGasFunc(fn CalcPreVerificationGasFunc)
}

// CalcPreVerificationGas returns an expected gas cost for processing a UserOperation from a batch.
func (ov *Overhead) CalcPreVerificationGas(op *userop.UserOperation) *big.Int {
g := ov.calcPVGFunc(op)
func (ov *Overhead) CalcPreVerificationGas(op *userop.UserOperation) (*big.Int, error) {
// Sanitize fields to reduce as much variability due to length and zero bytes
data, err := op.ToMap()
if err != nil {
return nil, err
}
data["preVerificationGas"] = hexutil.EncodeBig(ov.sanitizedPVG)
data["verificationGasLimit"] = hexutil.EncodeBig(ov.sanitizedVGL)
data["callGasLimit"] = hexutil.EncodeBig(ov.sanitizedCGL)
data["signature"] = hexutil.Encode(bytes.Repeat([]byte{1}, len(op.Signature)))
tmp, err := userop.New(data)
if err != nil {
return nil, err
}

// Use value from CalcPreVerificationGasFunc if set
g, err := ov.calcPVGFunc(tmp)
if err != nil {
return nil, err
}
if g != nil {
return g
return g, nil
}

packed := op.Pack()
packed := tmp.Pack()
lengthInWord := float64(len(packed)+31) / 32
callDataCost := float64(0)

Expand All @@ -64,7 +90,7 @@ func (ov *Overhead) CalcPreVerificationGas(op *userop.UserOperation) *big.Int {
}

pvg := callDataCost + (ov.fixed / ov.minBundleSize) + ov.perUserOp + (ov.perUserOpWord * lengthInWord)
return big.NewInt(int64(math.Round(pvg)))
return big.NewInt(int64(math.Round(pvg))), nil
}

// NonZeroValueCall returns an expected gas cost of using the CALL opcode in the context of EIP-4337.
Expand Down
67 changes: 60 additions & 7 deletions pkg/gas/pvg.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,73 @@ package gas
import (
"math/big"

"github.com/ethereum/go-ethereum/ethclient"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/rpc"
"github.com/stackup-wallet/stackup-bundler/pkg/arbitrum/nodeinterface"
"github.com/stackup-wallet/stackup-bundler/pkg/entrypoint"
"github.com/stackup-wallet/stackup-bundler/pkg/entrypoint/methods"
"github.com/stackup-wallet/stackup-bundler/pkg/signer"
"github.com/stackup-wallet/stackup-bundler/pkg/userop"
)

type CalcPreVerificationGasFunc = func(op *userop.UserOperation) *big.Int
type CalcPreVerificationGasFunc = func(op *userop.UserOperation) (*big.Int, error)

func calcPVGFuncNoop() CalcPreVerificationGasFunc {
return func(op *userop.UserOperation) *big.Int {
return nil
return func(op *userop.UserOperation) (*big.Int, error) {
return nil, nil
}
}

func CalcArbitrumPVGWithEthClient(eth *ethclient.Client) CalcPreVerificationGasFunc {
return func(op *userop.UserOperation) *big.Int {
return big.NewInt(0)
// CalcArbitrumPVGWithEthClient uses Arbitrum's NodeInterface precompile to get an estimate for
// preVerificationGas that takes into account the L1 gas component. see
// https://medium.com/offchainlabs/understanding-arbitrum-2-dimensional-fees-fd1d582596c9.
func CalcArbitrumPVGWithEthClient(
rpc *rpc.Client,
) CalcPreVerificationGasFunc {
pk, _ := crypto.GenerateKey()
dummy, _ := signer.New(hexutil.Encode(crypto.FromECDSA(pk))[2:])
return func(op *userop.UserOperation) (*big.Int, error) {
// Pack handleOps method inputs
ho, err := methods.HandleOpsMethod.Inputs.Pack(
[]entrypoint.UserOperation{entrypoint.UserOperation(*op)},
dummy.Address,
)
if err != nil {
return nil, err
}

// Encode function data for gasEstimateL1Component
create := false
if op.Nonce.Cmp(common.Big0) == 0 {
create = true
}
ge, err := nodeinterface.GasEstimateL1ComponentMethod.Inputs.Pack(
nodeinterface.ERC4337GasHelperAddress,
create,
append(methods.HandleOpsMethod.ID, ho...),
)
if err != nil {
return nil, err
}

// Use eth_call to call the NodeInterface precompile
req := map[string]any{
"from": common.HexToAddress("0x"),
"to": nodeinterface.PrecompileAddress,
"data": hexutil.Encode(append(nodeinterface.GasEstimateL1ComponentMethod.ID, ge...)),
}
var out any
if err := rpc.Call(&out, "eth_call", &req, "latest"); err != nil {
return nil, err
}

// Return GasEstimateForL1 as PVG
gas, err := nodeinterface.DecodeGasEstimateL1ComponentOutput(out)
if err != nil {
return nil, err
}
return big.NewInt(int64(gas.GasEstimateForL1)), nil
}
}
5 changes: 4 additions & 1 deletion pkg/modules/checks/verificationgas.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,10 @@ func ValidateVerificationGas(op *userop.UserOperation, ov *gas.Overhead, maxVeri
)
}

pvg := ov.CalcPreVerificationGas(op)
pvg, err := ov.CalcPreVerificationGas(op)
if err != nil {
return err
}
if op.PreVerificationGas.Cmp(pvg) < 0 {
return fmt.Errorf("preVerificationGas: below expected gas of %s", pvg.String())
}
Expand Down
6 changes: 3 additions & 3 deletions pkg/modules/checks/verificationgas_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ func TestOpVGMoreThanMaxVG(t *testing.T) {
func TestOpPVGMoreThanOH(t *testing.T) {
op := testutils.MockValidInitUserOp()
ov := gas.NewDefaultOverhead()
pvg := ov.CalcPreVerificationGas(op)
pvg, _ := ov.CalcPreVerificationGas(op)
op.PreVerificationGas = big.NewInt(0).Add(pvg, common.Big1)

if err := ValidateVerificationGas(op, ov, op.VerificationGasLimit); err != nil {
Expand All @@ -63,7 +63,7 @@ func TestOpPVGMoreThanOH(t *testing.T) {
func TestOpPVGEqualOH(t *testing.T) {
op := testutils.MockValidInitUserOp()
ov := gas.NewDefaultOverhead()
pvg := ov.CalcPreVerificationGas(op)
pvg, _ := ov.CalcPreVerificationGas(op)
op.PreVerificationGas = big.NewInt(0).Add(pvg, common.Big0)

if err := ValidateVerificationGas(op, ov, op.VerificationGasLimit); err != nil {
Expand All @@ -76,7 +76,7 @@ func TestOpPVGEqualOH(t *testing.T) {
func TestOpPVGLessThanOH(t *testing.T) {
op := testutils.MockValidInitUserOp()
ov := gas.NewDefaultOverhead()
pvg := ov.CalcPreVerificationGas(op)
pvg, _ := ov.CalcPreVerificationGas(op)
op.PreVerificationGas = big.NewInt(0).Sub(pvg, common.Big1)

if err := ValidateVerificationGas(op, ov, op.VerificationGasLimit); err == nil {
Expand Down

0 comments on commit 27e6fd7

Please sign in to comment.