service

package
v0.0.0-...-4d36670 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 30, 2026 License: MIT Imports: 32 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrRPCError = api.NewBusinessError(101, "RPC error, please try again later or check the detailed error message for more information")

	// Gas tank
	ErrGasTankTokenNotAllowed     = api.NewBusinessError(2001, "Token is not allowed in gas tank")
	ErrGasTankInsufficientBalance = api.NewBusinessError(2002, "Insufficient token balance in gas tank")

	// token pay
	ErrTokenPayPriceTooLow               = api.NewBusinessError(3001, "Gas price too low")
	ErrTokenPayGasCostTooHigh            = api.NewBusinessError(3002, "Gas cost too high")
	ErrTokenPayTransferTokenAmountTooLow = api.NewBusinessError(3003, "Transferred token amount too low")
	ErrTokenPaySimulateTxFailed          = api.NewBusinessError(3004, "Failed to simulate transaction")
	ErrTokenPaySponsorBalanceNotEnough   = api.NewBusinessError(3005, "Sponsor balance is insufficient, please contact the administrator")

	// verifying paymaster
	ErrVerifyingPaymasterMaxGasCostExceeded     = api.NewBusinessError(4001, "Max gas cost exceeded")
	ErrVerifyingPaymasterInvalidSmartAccount    = api.NewBusinessError(4002, "Smart account is not in whitelist")
	ErrVerifyingPaymasterContractNotWhitelisted = api.NewBusinessError(4003, "Contract is not in whitelist")
	ErrVerifyingPaymasterTooManyOps             = api.NewBusinessError(4004, "Too many user operations")

	// paymaster in common
	ErrPaymasterPaused              = api.NewBusinessError(5001, "Paymaster contract is paused")
	ErrPaymasterInsufficientBalance = api.NewBusinessError(5002, "Insufficient deposit balance in paymaster")
)
View Source
var DelegatedCodePrefix = hexutil.MustDecode(delegatedCodePrefixHex)

Functions

func GetDelegatedContract

func GetDelegatedContract(client *web3go.Client, authority common.Address) (common.Address, error)

GetDelegatedContract reads the on-chain code of authority and extracts the 20-byte contract address from the EIP-7702 delegation designator (prefix 0xef0100 + address). Returns empty address when the authority has no code (not yet delegated).

func NewRPCError

func NewRPCError(err error, message string, args ...any) *api.BusinessError

func SimulateTx

func SimulateTx(client *web3go.Client, tx *types.Transaction, sender common.Address) error

SimulateTx simulates the execution of the given transaction via eth_call RPC. It will return error if the transaction execution failed.

func UnpackArguments

func UnpackArguments(args abi.Arguments, packedData []byte, v any) error

UnpackArguments unpacks ABI encoded data into the provided target structure (of pointer type).

Generally, the length of the packedData should be 32x bytes, as per the ABI encoding rules.

Types

type CompositeExecutionPolicy

type CompositeExecutionPolicy map[common.Address]ExecutionPolicy

func (CompositeExecutionPolicy) Validate

func (policy CompositeExecutionPolicy) Validate(execution contract.Execution, whitelist map[common.Address]bool) error

type CompositeLimiter

type CompositeLimiter []Limiter

CompositeLimiter is a composite of multiple Limiter instances.

func (CompositeLimiter) Limit

func (limiter CompositeLimiter) Limit(userOp *contract.PackedUserOperation) error

type Config

type Config struct {
	RPC struct {
		URL            string
		PrivateKey     string
		RequestTimeout time.Duration `default:"3s"`
		LogEnabled     bool
	}

	Price PriceConfig

	VerifyingPaymaster VerifyingPaymasterConfig
	GasTank            PaymasterConfig
	TokenPay           TokenPayConfig
}

type DeFiConfig

type DeFiConfig struct {
	Uniswap struct {
		V2 struct {
			Router common.Address
		}
		V3 struct {
			Router common.Address
		}
	}
}

type ERC20TokenStub

type ERC20TokenStub struct {
	// contains filtered or unexported fields
}

type ExecutionPolicy

type ExecutionPolicy interface {
	// Validate checks whether the given contract execution is valid according to the execution policy and the contract whitelist.
	// It returns an error if the execution is not valid or if any error occurs during the validation. Otherwise, it returns nil.
	Validate(execution contract.Execution, whitelist map[common.Address]bool) error
}

ExecutionPolicy defines the interface for execution policies that validate contract executions.

func NewExecutionPolicy

func NewExecutionPolicy(config DeFiConfig, client *web3go.Client, whitelist map[common.Address]bool) (ExecutionPolicy, error)

type FinalizedLimiter

type FinalizedLimiter struct {
	// contains filtered or unexported fields
}

FinalizedLimiter limits the number of finalized user operations on chain.

func NewFinalizedLimiter

func NewFinalizedLimiter(duration time.Duration, max int64, store *store.Store) *FinalizedLimiter

func (*FinalizedLimiter) Limit

func (limiter *FinalizedLimiter) Limit(userOp *contract.PackedUserOperation) error

type GasTankData

type GasTankData struct {
	Token        common.Address
	MaxTokenCost *big.Int
}

func ParseGasTankData

func ParseGasTankData(data []byte) (GasTankData, error)

func (GasTankData) Bytes

func (data GasTankData) Bytes() []byte

type GasTankPaymaster

type GasTankPaymaster struct {
	// contains filtered or unexported fields
}

func NewGasTankPaymaster

func NewGasTankPaymaster(config PaymasterConfig, client *web3go.Client, priceOracle *PriceOracle) (*GasTankPaymaster, error)

func (*GasTankPaymaster) Sign

func (paymaster *GasTankPaymaster) Sign(userOp contract.PackedUserOperation) ([]byte, error)

Sign signs the given user operation with the paymaster's signature. It validates the user operation, updates the max token cost, reconstructs the paymaster data, and computes the paymaster signature.

func (*GasTankPaymaster) Stub

func (paymaster *GasTankPaymaster) Stub(sender, token common.Address) ([]byte, error)

Stub generates a stub paymaster and data for the given sender and token. It checks if the token is allowed and if the sender has sufficient available balance.

type LimitConfig

type LimitConfig struct {
	// Finalized defines the limits for finalized user operations on chain.
	// The key is a descriptive name (e.g., "daily", "monthly"), and the value specifies the duration
	// and the maximum number of user operations allowed within that duration. For example, use below
	// configuration for both daily and monthly limits:
	//
	// "daily": { 24h, 10 } means a maximum of 10 finalized user operations are allowed within a 24-hour period.
	// "monthly": { 720h, 100 } means a maximum of 100 finalized user operations are allowed within a 720-hour period.
	Finalized map[string]struct {
		Duration time.Duration
		Max      int64
	}
}

type Limiter

type Limiter interface {
	Limit(userOp *contract.PackedUserOperation) error
}

Limiter is an interface for limiting the signed user operations.

func NewLimiter

func NewLimiter(config LimitConfig, store *store.Store) Limiter

type Paymaster

type Paymaster[T PaymasterContractCaller] struct {
	// contains filtered or unexported fields
}

Paymaster represents a paymaster contract instance with its configuration, caller, and signer. It provides methods to generate stub paymasterAndData for gas estimation and to sign user operations.

func NewPaymaster

func NewPaymaster[T PaymasterContractCaller](config PaymasterConfig, client *web3go.Client, callerFactory func(common.Address, bind.ContractCaller) (T, error), paymasterName string) (*Paymaster[T], error)

NewPaymaster creates a new Paymaster instance with the specified configuration, RPC client, and caller factory. It validates the configuration, retrieves the default signer, and initializes the paymaster contract caller.

type PaymasterConfig

type PaymasterConfig struct {
	Address          common.Address
	SignatureTimeout time.Duration `default:"5m"`

	Monitor struct {
		Interval      time.Duration `default:"1m"`
		MinBalanceEth uint32        `default:"1"`
		Remind        time.Duration `default:"1h"`
		RPCHealth     struct {
			Threshold uint64 `default:"5"`
			Remind    uint64 `default:"60"`
		}
	}
}

PaymasterConfig holds the configuration for a paymaster, including its address and signature timeout.

type PaymasterContractCaller

type PaymasterContractCaller interface {
	IsSignerAllowed(opts *bind.CallOpts, signer common.Address) (bool, error)
	Paused(opts *bind.CallOpts) (bool, error)
	Balance(opts *bind.CallOpts) (*big.Int, error)
	GetPaymasterHash(opts *bind.CallOpts, userOp contract.PackedUserOperation) ([32]byte, error)
}

PaymasterContractCaller defines the interface that a paymaster contract caller must implement.

type PriceConfig

type PriceConfig struct {
	USDT []common.Address // e.g. USDT0, USDT, USDC, at least one
	CNH  []common.Address // e.g. AxCNH, AxCNH0

	RequestTimeout time.Duration `default:"3s"` // Total timeout for each external price HTTP request.
}

type PriceOracle

type PriceOracle struct {
	// contains filtered or unexported fields
}

func NewPriceOracle

func NewPriceOracle(config PriceConfig, client *web3go.Client) (*PriceOracle, error)

func (*PriceOracle) GetERC20TokenStub

func (oracle *PriceOracle) GetERC20TokenStub(token common.Address) (ERC20TokenStub, bool)

GetERC20TokenStub returns the ERC20TokenStub and a boolean indicating if the token is supported.

func (*PriceOracle) GetETHPrice

func (oracle *PriceOracle) GetETHPrice(quoteToken common.Address) (*big.Int, error)

GetETHPrice returns the price of ETH/token.

type Services

type Services struct {
	PriceOracle        *PriceOracle
	VerifyingPaymaster *VerifyingPaymaster
	GasTank            *GasTankPaymaster // may be nil if the gas tank paymaster is not specified
	TokenPay           *TokenPay
	// contains filtered or unexported fields
}

func New

func New(config Config, store *store.Store) (Services, error)

func (Services) Client

func (s Services) Client() *web3go.Client

func (Services) Config

func (s Services) Config() struct {
	VerifyingPaymaster VerifyingPaymasterConfig
	Price              PriceConfig
	TokenPay           TokenPayConfig
	GasTank            PaymasterConfig
}

type TokenPay

type TokenPay struct {
	*TxSender
	// contains filtered or unexported fields
}

func NewTokenPay

func NewTokenPay(config TokenPayConfig, sender *TxSender, priceOracle *PriceOracle) (*TokenPay, error)

func (*TokenPay) Sponsor

func (tp *TokenPay) Sponsor(rawTransferTokenTx, rawBusinessTx []byte, ip string) error

type TokenPayConfig

type TokenPayConfig struct {
	Recipient common.Address

	MinGasFeeRatio uint64 `default:"120"` // 120% of base fee, e.g. 20 Gdrip * 120% = 24 Gdrip

	MinGasTipRatio uint64 `default:"20"` // 20% of base fee, e.g. 20 Gdrip * 20% = 4 Gdrip

	MaxGasCost uint64 `default:"100000000000000000"` // 0.1 CFX

	MinSponsorBalance uint64 `default:"1000000000000000000"` // 1 CFX

	SuggestedGasPriceBumpRatio   uint64 `default:"10"` // 10% price bump for suggested gas price
	SuggestedTokenPriceBumpRatio uint64 `default:"5"`  // 5% price bump for suggested token price

	CheckReceiptInterval        time.Duration `default:"1s"`
	CheckFundingReceiptInterval time.Duration `default:"30ms"`
	// contains filtered or unexported fields
}

type TokenPayMonitorContext

type TokenPayMonitorContext struct {
	// contains filtered or unexported fields
}

type TxSender

type TxSender struct {
	// contains filtered or unexported fields
}

func NewTxSender

func NewTxSender(client *web3go.Client) (*TxSender, error)

func (*TxSender) Send

func (s *TxSender) Send(tx types.TransactionArgs) (common.Hash, error)

func (*TxSender) SendRawTransactionWithRetry

func (s *TxSender) SendRawTransactionWithRetry(rawTx []byte, maxRetry int, interval time.Duration) (common.Hash, error)

func (*TxSender) WaitForReceipt

func (s *TxSender) WaitForReceipt(txHash common.Hash, interval time.Duration, timeout time.Duration) (success bool, errMsg string, expired bool)

type UniswapV2ExecutionPolicy

type UniswapV2ExecutionPolicy struct {
	// contains filtered or unexported fields
}

func NewUniswapV2ExecutionPolicy

func NewUniswapV2ExecutionPolicy(router common.Address, client *web3go.Client) (*UniswapV2ExecutionPolicy, error)

func (*UniswapV2ExecutionPolicy) Validate

func (policy *UniswapV2ExecutionPolicy) Validate(execution contract.Execution, whitelist map[common.Address]bool) error

type UniswapV3ExecutionPolicy

type UniswapV3ExecutionPolicy struct {
	// contains filtered or unexported fields
}

func NewUniswapV3ExecutionPolicy

func NewUniswapV3ExecutionPolicy(router common.Address, client *web3go.Client) (*UniswapV3ExecutionPolicy, error)

func (*UniswapV3ExecutionPolicy) Validate

func (policy *UniswapV3ExecutionPolicy) Validate(execution contract.Execution, whitelist map[common.Address]bool) error

type VerifyingPaymaster

type VerifyingPaymaster struct {
	// contains filtered or unexported fields
}

func NewVerifyingPaymaster

func NewVerifyingPaymaster(config VerifyingPaymasterConfig, client *web3go.Client, store *store.Store) (*VerifyingPaymaster, error)

func (*VerifyingPaymaster) Sign

func (paymaster *VerifyingPaymaster) Sign(userOp contract.PackedUserOperation) ([]byte, error)

Sign validates the user operation and signs the user operation with the paymaster's private key. It returns the signed paymasterAndData, which includes the paymaster address, gas limits, delegation, validAfter, validUntil and signature.

func (*VerifyingPaymaster) Stub

func (paymaster *VerifyingPaymaster) Stub(sender, delegation common.Address) ([]byte, error)

Stub returns a stub paymasterAndData for gas estimation.

type VerifyingPaymasterConfig

type VerifyingPaymasterConfig struct {
	PaymasterConfig `mapstructure:",squash"`

	SmartAccountWhitelist []common.Address

	ContractWhitelist []common.Address

	MaxGasCost uint64 `default:"100000000000000000"` // 0.1 CFX by default, and could up to 1 CFX

	DeFi DeFiConfig

	Limiter LimitConfig
	// contains filtered or unexported fields
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL