mechanisms/evm/batch-settlement/client
import "github.com/x402-foundation/x402/go/v2/mechanisms/evm/batch-settlement/client"
Constants
Source: mechanisms/evm/batch-settlement/client/scheme.go:21
const (
// DefaultDepositMultiplier is the default multiplier for the initial deposit.
// It is applied to the per-request amount.
DefaultDepositMultiplier = 5
// DefaultWithdrawDelay is the default withdraw delay in seconds (15 min).
DefaultWithdrawDelay = 900
// DefaultSalt is the default channel salt (zero).
DefaultSalt = "0x0000000000000000000000000000000000000000000000000000000000000000"
)Functions
func CreateBatchedEIP3009DepositPayload( ctx context.Context, signer evm.ClientEvmSigner, requirements types.PaymentRequirements, channelConfig batchsettlement.ChannelConfig, depositAmount string, maxClaimableAmount string, voucherSigner evm.ClientEvmSigner, ) (types.PaymentPayload, error)
Source: mechanisms/evm/batch-settlement/client/eip3009.go:16
CreateBatchedEIP3009DepositPayload creates a deposit + voucher payload using ERC-3009. Signs ReceiveWithAuthorization for the deposit and a cumulative voucher.
func CreateBatchedPermit2DepositPayload( ctx context.Context, signer evm.ClientEvmSigner, requirements types.PaymentRequirements, channelConfig batchsettlement.ChannelConfig, depositAmount string, maxClaimableAmount string, voucherSigner evm.ClientEvmSigner, ) (types.PaymentPayload, error)
Source: mechanisms/evm/batch-settlement/client/permit2.go:19
CreateBatchedPermit2DepositPayload builds a deposit + voucher payload that
funds the channel via the universal Permit2 contract using a channel-bound
PermitWitnessTransferFrom authorization. The witness binds the transfer to
the derived channelId so the Permit2DepositCollector can verify which
channel the funds belong to.
func NewBatchSettlementEvmScheme(signer evm.ClientEvmSigner, config *BatchSettlementEvmSchemeOptions) *BatchSettlementEvmScheme
Source: mechanisms/evm/batch-settlement/client/scheme.go:89
NewBatchSettlementEvmScheme creates a new batched client scheme.
func NewFileClientChannelStorage(opts batchsettlement.FileChannelStorageOptions) *FileClientChannelStorage
Source: mechanisms/evm/batch-settlement/client/file_storage.go:17
NewFileClientChannelStorage returns a file-backed client session storage rooted at opts.Directory.
func NewInMemoryClientChannelStorage() *InMemoryClientChannelStorage
Source: mechanisms/evm/batch-settlement/client/storage.go:33
NewInMemoryClientChannelStorage creates a new in-memory client session storage.
func RefundChannel(ctx context.Context, scheme RefundContext, url string, options *RefundOptions) (*x402.SettleResponse, error)
Source: mechanisms/evm/batch-settlement/client/refund.go:64
RefundChannel sends a cooperative refund request to the channel that backs url.
Flow:
- Probe the URL with
GET(no payment) to obtain the route's payment requirements. - Build the ChannelConfig and resolve the local session (or recover it).
- Sign a zero-charge voucher (maxClaimableAmount = chargedCumulativeAmount) with refund=true and the optional refundAmount (partial refund).
- Send the voucher via PAYMENT-SIGNATURE. On a corrective 402, run the standard recovery path and retry once.
- Return the parsed SettleResponse from the server.
func SignVoucher( ctx context.Context, signer evm.ClientEvmSigner, channelId string, maxClaimableAmount string, network string, ) (*batchsettlement.BatchSettlementVoucherFields, error)
Source: mechanisms/evm/batch-settlement/client/voucher.go:14
SignVoucher signs a cumulative voucher using EIP-712. Voucher(bytes32 channelId, uint128 maxClaimableAmount)
func UpdateSessionAfterRefund(storage ClientChannelStorage, channelKey string, settleExtra map[string]interface{}) error
Source: mechanisms/evm/batch-settlement/client/refund.go:90
UpdateSessionAfterRefund reconciles local session state with the outcome of a cooperative refund. Deletes the session when the post-refund balance is zero (full refund), otherwise updates balance/chargedCumulativeAmount/totalClaimed from the server snapshot (partial refund - channel stays open).
Types
type BatchSettlementClientContext
Source: mechanisms/evm/batch-settlement/client/storage.go:10
BatchSettlementClientContext holds per-channel session state on the client side.
type BatchSettlementClientContext struct {
ChargedCumulativeAmount string `json:"chargedCumulativeAmount"`
Balance string `json:"balance"`
TotalClaimed string `json:"totalClaimed"`
DepositAmount string `json:"depositAmount,omitempty"`
SignedMaxClaimable string `json:"signedMaxClaimable,omitempty"`
Signature string `json:"signature,omitempty"`
}Fields
ChargedCumulativeAmount string`json:"chargedCumulativeAmount"`Balance string`json:"balance"`TotalClaimed string`json:"totalClaimed"`DepositAmount string`json:"depositAmount,omitempty"`SignedMaxClaimable string`json:"signedMaxClaimable,omitempty"`Signature string`json:"signature,omitempty"`
type BatchSettlementEvmScheme
Source: mechanisms/evm/batch-settlement/client/scheme.go:82
BatchSettlementEvmScheme implements SchemeNetworkClient for batched EVM payments.
type BatchSettlementEvmScheme struct {
// contains filtered or unexported fields
}func BuildChannelConfig(requirements types.PaymentRequirements) (batchsettlement.ChannelConfig, error)
Source: mechanisms/evm/batch-settlement/client/scheme.go:264
BuildChannelConfig constructs a ChannelConfig from payment requirements and scheme config.
Returns an error when requirements.Extra["receiverAuthorizer"] is missing
or zero - without it the derived channelId would not match the onchain
channel and the deposit transaction would revert.
func CreatePaymentPayload( ctx context.Context, requirements types.PaymentRequirements, ) (types.PaymentPayload, error)
Source: mechanisms/evm/batch-settlement/client/scheme.go:130
CreatePaymentPayload creates a batched payment payload.
The client loads local session state, falls back to onchain recovery when storage is empty, then chooses deposit vs voucher from the resulting context.
func CreatePaymentPayloadWithExtensions( ctx context.Context, requirements types.PaymentRequirements, extensions map[string]interface{}, ) (types.PaymentPayload, error)
Source: mechanisms/evm/batch-settlement/client/extensions.go:46
CreatePaymentPayloadWithExtensions creates a batched payment payload with
extension awareness when paymentRequired.extensions advertises EIP-2612 or
ERC-20 approval gas sponsoring.
Behavior matches the exact / upto schemes:
- Build the base payload (deposit-or-voucher) via the standard CreatePaymentPayload flow.
- Skip extension enrichment for non-deposit payloads (vouchers don't need a token approve).
- Skip extension enrichment for non-Permit2 deposits (ERC-3009 carries its own gas-funded transfer authorization).
- Try EIP-2612 first; on a successful permit signature, attach
extensions.eip2612GasSponsoring.infoand return. - Fall back to ERC-20 approval; on success, attach
extensions.erc20ApprovalGasSponsoring.info. - If neither extension applies (allowance already sufficient, or token does not advertise EIP-712 domain fields), return the base payload.
Implements the optional x402.ExtensionAwareClient interface so
x402Client.CreatePaymentPayload calls this path automatically when the
server's 402 contains extension declarations.
func GetSession(channelId string) (*BatchSettlementClientContext, bool)
Source: mechanisms/evm/batch-settlement/client/scheme.go:404
GetSession returns the session for the given channel ID.
func HasSession(channelId string) bool
Source: mechanisms/evm/batch-settlement/client/scheme.go:398
HasSession checks if a session exists for the given channel ID.
func OnPaymentResponse( ctx context.Context, prCtx x402.PaymentResponseContext, ) (x402.PaymentResponseResult, error)
Source: mechanisms/evm/batch-settlement/client/scheme.go:327
OnPaymentResponse implements x402.PaymentResponseHandler so the transport can auto-sync local session state after every paid response.
On a successful settle (HTTP 200 + PAYMENT-RESPONSE), folds the server-tracked channel snapshot back into the local session so the next request signs a voucher built from the right cumulative base.
On a corrective 402 (PAYMENT-REQUIRED carrying batch_settlement_cumulative_* or signature recovery data), runs ProcessCorrectivePaymentRequired and reports Recovered=true so the transport retries once with a freshly built payload.
func ProcessCorrectivePaymentRequired( ctx context.Context, errorReason string, accepts []types.PaymentRequirements, ) (bool, error)
Source: mechanisms/evm/batch-settlement/client/scheme.go:477
ProcessCorrectivePaymentRequired handles a corrective 402 response when the client's cumulative base is out of sync. It validates the server-provided ChannelState (under accept.Extra) against onchain data and updates the local session, falling back to pure onchain recovery if no recovery data is sent. Returns true when the session was resynced and the request can be retried.
func ProcessSettleResponse(settle map[string]interface{}) error
Source: mechanisms/evm/batch-settlement/client/scheme.go:359
ProcessSettleResponse updates local session state from a settle response. It merges present fields into the existing session. Refund-specific reconciliation is handled at the refund call site via UpdateSessionAfterRefund.
func RecoverSession(ctx context.Context, requirements types.PaymentRequirements) (*BatchSettlementClientContext, error)
Source: mechanisms/evm/batch-settlement/client/scheme.go:415
RecoverSession rebuilds a client session from onchain channel state. Requires the signer to implement ClientEvmSignerWithReadContract. This allows recovery after a cold start or in-memory session loss.
func Refund(ctx context.Context, url string, options *RefundOptions) (*x402.SettleResponse, error)
Source: mechanisms/evm/batch-settlement/client/scheme.go:313
Refund sends a cooperative refund request to the channel that backs url.
On success, the local session is updated (or deleted on full refund) and the
parsed SettleResponse is returned.
func Scheme) Scheme() string
Source: mechanisms/evm/batch-settlement/client/scheme.go:122
Scheme returns the scheme identifier.
type BatchSettlementEvmSchemeOptions
Source: mechanisms/evm/batch-settlement/client/scheme.go:61
BatchSettlementEvmSchemeOptions configures the batched client scheme.
Use DepositStrategy for app-specific sizing or skipping.
type BatchSettlementEvmSchemeOptions struct {
// DepositMultiplier is the multiplier applied to the required amount for deposits.
// E.g., 5 means deposit 5× the per-request amount. Defaults to 5.
DepositMultiplier int
// DepositStrategy lets the caller override the computed deposit amount or
// skip the deposit entirely (returning Skip=true sends a voucher-only
// payload that will fail at verify if the channel balance is insufficient).
// Optional.
DepositStrategy DepositStrategy
// Storage is the session persistence backend. Defaults to in-memory.
Storage ClientChannelStorage
// Salt is the channel salt for differentiating identical configs. Defaults to zero.
Salt string
// PayerAuthorizer is the EOA address used for voucher signing (separate from payer).
// Zero address means the payer signs vouchers directly (ERC-1271).
PayerAuthorizer string
// VoucherSigner is an optional separate key for signing vouchers.
VoucherSigner evm.ClientEvmSigner
}Fields
DepositMultiplier intDepositMultiplier is the multiplier applied to the required amount for deposits. E.g., 5 means deposit 5× the per-request amount. Defaults to 5.
DepositStrategy DepositStrategyDepositStrategy lets the caller override the computed deposit amount or skip the deposit entirely (returning Skip=true sends a voucher-only payload that will fail at verify if the channel balance is insufficient). Optional.
Storage ClientChannelStorageStorage is the session persistence backend. Defaults to in-memory.
Salt stringSalt is the channel salt for differentiating identical configs. Defaults to zero.
PayerAuthorizer stringPayerAuthorizer is the EOA address used for voucher signing (separate from payer). Zero address means the payer signs vouchers directly (ERC-1271).
VoucherSigner evm.ClientEvmSignerVoucherSigner is an optional separate key for signing vouchers.
type ClientChannelStorage
Source: mechanisms/evm/batch-settlement/client/storage.go:20
ClientChannelStorage is the interface for persisting client-side channel sessions.
type ClientChannelStorage interface {
Get(channelId string) (*BatchSettlementClientContext, error)
Set(channelId string, ctx *BatchSettlementClientContext) error
Delete(channelId string) error
}Methods
Get func(channelId string) (*BatchSettlementClientContext, error)Set func(channelId string, ctx *BatchSettlementClientContext) errorDelete func(channelId string) error
type DepositStrategy
Source: mechanisms/evm/batch-settlement/client/scheme.go:56
DepositStrategy is an optional caller hook for per-request deposit sizing.
type DepositStrategy func(ctx context.Context, c DepositStrategyContext) (DepositStrategyResult, error)type DepositStrategyContext
Source: mechanisms/evm/batch-settlement/client/scheme.go:30
DepositStrategyContext is supplied to a DepositStrategy callback before the client signs a deposit authorization.
type DepositStrategyContext struct {
PaymentRequirements types.PaymentRequirements
ChannelConfig batchsettlement.ChannelConfig
ChannelId string
ClientContext *BatchSettlementClientContext
RequestAmount string
MaxClaimableAmount string
CurrentBalance string
MinimumDepositAmount string
DepositAmount string
}Fields
PaymentRequirements types.PaymentRequirementsChannelConfig batchsettlement.ChannelConfigChannelId stringClientContext *BatchSettlementClientContextRequestAmount stringMaxClaimableAmount stringCurrentBalance stringMinimumDepositAmount stringDepositAmount string
type DepositStrategyResult
Source: mechanisms/evm/batch-settlement/client/scheme.go:50
DepositStrategyResult is the return value of a DepositStrategy callback.
- Skip=true tells the client to send a voucher-only payload even when the channel balance is insufficient. The downstream request will fail at verify time; the caller is opting out of auto-top-up.
- Amount overrides the computed deposit. Must be a positive integer string (base units) and at least MinimumDepositAmount, or the call errors.
- Both empty/zero means "use the SDK-computed amount".
type DepositStrategyResult struct {
Skip bool
Amount string
}Fields
Skip boolAmount string
type FileClientChannelStorage
Source: mechanisms/evm/batch-settlement/client/file_storage.go:12
FileClientChannelStorage persists each channel's client context as {root}/client/{channelId}.json so sessions survive process restarts.
type FileClientChannelStorage struct {
// contains filtered or unexported fields
}func Delete(channelId string) error
Source: mechanisms/evm/batch-settlement/client/file_storage.go:53
func Get(channelId string) (*BatchSettlementClientContext, error)
Source: mechanisms/evm/batch-settlement/client/file_storage.go:29
func Set(channelId string, ctx *BatchSettlementClientContext) error
Source: mechanisms/evm/batch-settlement/client/file_storage.go:45
type InMemoryClientChannelStorage
Source: mechanisms/evm/batch-settlement/client/storage.go:27
InMemoryClientChannelStorage is a volatile in-memory implementation of ClientChannelStorage.
type InMemoryClientChannelStorage struct {
// contains filtered or unexported fields
}func Delete(channelId string) error
Source: mechanisms/evm/batch-settlement/client/storage.go:67
func Get(channelId string) (*BatchSettlementClientContext, error)
Source: mechanisms/evm/batch-settlement/client/storage.go:39
func Set(channelId string, ctx *BatchSettlementClientContext) error
Source: mechanisms/evm/batch-settlement/client/storage.go:55
type RefundContext
Source: mechanisms/evm/batch-settlement/client/refund.go:45
RefundContext is the narrow view of the client scheme that the refund flow needs. Defining a structural contract here (rather than depending directly on *BatchSettlementEvmScheme) keeps refund.go decoupled and enables alternate implementations in tests.
type RefundContext interface {
Storage() ClientChannelStorage
Signer() evm.ClientEvmSigner
VoucherSigner() evm.ClientEvmSigner
BuildChannelConfig(requirements types.PaymentRequirements) (batchsettlement.ChannelConfig, error)
RecoverSession(ctx context.Context, requirements types.PaymentRequirements) (*BatchSettlementClientContext, error)
ProcessCorrectivePaymentRequired(ctx context.Context, errorReason string, accepts []types.PaymentRequirements) (bool, error)
}Methods
Storage func() ClientChannelStorageSigner func() evm.ClientEvmSignerVoucherSigner func() evm.ClientEvmSignerBuildChannelConfig func(requirements types.PaymentRequirements) (batchsettlement.ChannelConfig, error)RecoverSession func(ctx context.Context, requirements types.PaymentRequirements) (*BatchSettlementClientContext, error)ProcessCorrectivePaymentRequired func(ctx context.Context, errorReason string, accepts []types.PaymentRequirements) (bool, error)
type RefundOptions
Source: mechanisms/evm/batch-settlement/client/refund.go:33
RefundOptions configures a cooperative refund call.
type RefundOptions struct {
// Amount is the optional partial refund (token base units, decimal string).
// Omit for a full refund (drains the channel's remaining balance).
Amount string
// HTTPClient is an optional HTTP client (defaults to http.DefaultClient).
HTTPClient *http.Client
}Fields
Amount stringAmount is the optional partial refund (token base units, decimal string). Omit for a full refund (drains the channel's remaining balance).
HTTPClient *http.ClientHTTPClient is an optional HTTP client (defaults to http.DefaultClient).
