x402

package module
v0.0.0-...-92f06b5 Latest Latest
Warning

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

Go to latest
Published: May 18, 2026 License: Apache-2.0 Imports: 11 Imported by: 0

README

x402 Go Package

Go implementation of the x402 protocol - a standard for HTTP 402 Payment Required responses with cryptocurrency micropayments.

What is x402?

x402 is a protocol that enables HTTP resources to require cryptocurrency payments. When a client requests a paid resource, the server responds with 402 Payment Required along with payment details. The client creates a payment, retries the request, and receives the resource after successful payment verification and settlement.

Installation

go get github.com/x402-foundation/x402/go

What This Package Exports

This package provides modules to support the x402 protocol in Go applications.

Core Classes

The package exports three core types that can be used by clients, servers, and facilitators:

  • x402.X402Client - Creates payment payloads for clients making paid requests
  • x402.X402ResourceServer - Verifies payments and builds requirements for servers accepting payments
  • x402.X402Facilitator - Verifies and settles payments for facilitator services

These core classes are framework-agnostic and can be used in any context (HTTP, gRPC, WebSockets, CLI tools, etc.).

HTTP Transport Wrappers

The package exports HTTP-specific wrappers around the core classes:

  • x402http.HTTPClient - Wraps http.Client with automatic payment handling for clients
  • x402http.HTTPServer - Integrates resource server with HTTP request processing
  • x402http.HTTPFacilitatorClient - HTTP client for calling facilitator endpoints

These wrappers handle HTTP-specific concerns like headers, status codes, and request/response serialization.

Middleware for Servers

Framework-specific middleware packages for easy server integration:

  • http/gin - Gin framework middleware

Additional framework middleware can be built using the HTTP transport wrappers as a foundation.

Client Helper Packages

Helper packages to simplify client implementation:

  • signers/evm - EVM signer helpers (creates signers from private keys)
  • signers/svm - SVM signer helpers (creates signers from private keys)

These eliminate 95-99% of boilerplate code for creating signers.

Mechanism Implementations (Schemes)

Payment scheme implementations that can be registered by clients, servers, and facilitators:

  • mechanisms/evm/exact - Ethereum/Base exact payment using EIP-3009

    • client/ - Client-side payment creation
    • server/ - Server-side payment verification
    • facilitator/ - Facilitator-side payment settlement
  • mechanisms/svm/exact - Solana exact payment using token transfers

    • client/ - Client-side payment creation
    • server/ - Server-side payment verification
    • facilitator/ - Facilitator-side payment settlement

Each role (client, server, facilitator) has its own mechanism implementation with appropriate functionality for that role.

Extensions

Protocol extension implementations:

  • extensions/bazaar - API discovery extension for making resources discoverable

Architecture

The package is designed with extreme modularity:

Layered Design
┌─────────────────────────────────────────┐
│         Your Application                │
└─────────────────────────────────────────┘
                  │
       ┌──────────┼──────────┐
       ▼          ▼          ▼
  [Client]   [Server]  [Facilitator]
       │          │          │
       ▼          ▼          ▼
┌─────────────────────────────────────────┐
│      HTTP Layer (Optional)              │
│  - HTTPClient wrapper                   │
│  - HTTPResourceServer                   │
│  - Middleware (Gin, etc.)               │
└─────────────────────────────────────────┘
                  │
       ┌──────────┼──────────┐
       ▼          ▼          ▼
┌─────────────────────────────────────────┐
│    Core Classes (Framework-Agnostic)    │
│  - X402Client                           │
│  - X402ResourceServer                   │
│  - X402Facilitator                      │
└─────────────────────────────────────────┘
                  │
                  ▼
┌─────────────────────────────────────────┐
│         Mechanisms (Pluggable)          │
│  - EVM exact (client/server/facil.)    │
│  - SVM exact (client/server/facil.)    │
└─────────────────────────────────────────┘
                  │
                  ▼
┌─────────────────────────────────────────┐
│         Signers (Helpers)               │
│  - EVM client signers                   │
│  - SVM client signers                   │
└─────────────────────────────────────────┘
Key Design Principles
  1. Framework-Agnostic Core - The core client/server/facilitator classes work independently of HTTP or any web framework

  2. HTTP as a Layer - HTTP functionality is isolated in the http package, making the core reusable for other transports

  3. Pluggable Mechanisms - Payment schemes are modular and can be registered independently by clients, servers, and facilitators

  4. Middleware Wraps Core - Framework middleware (like Gin) internally uses the core primitives, keeping framework concerns separate

This architecture enables:

  • Using core classes in non-HTTP contexts (gRPC, WebSockets, message queues)
  • Building custom middleware for any framework
  • Registering different mechanisms for different roles
  • Mixing and matching components as needed

Documentation by Role

This package serves three distinct roles. Choose the documentation for what you're building:

🔵 CLIENT.md - Building Payment-Enabled Clients

For applications that make requests to payment-protected resources.

Topics covered:

  • Creating payment-enabled HTTP clients
  • Registering payment mechanisms
  • Using signer helpers
  • Lifecycle hooks and error handling
  • Advanced patterns (concurrency, retry logic, custom transports)

See also: examples/go/clients/

🟢 SERVER.md - Building Payment-Accepting Servers

For services that protect resources with payment requirements.

Topics covered:

  • Protecting HTTP endpoints with payments
  • Route configuration and pattern matching
  • Using middleware (Gin and custom implementations)
  • Dynamic pricing and dynamic payment routing
  • Verification and settlement handling
  • Extensions (Bazaar discovery)

See also: examples/go/servers/

🟡 FACILITATOR.md - Building Payment Facilitators

For payment processing services that verify and settle payments.

Topics covered:

  • Payment signature verification
  • On-chain settlement
  • Lifecycle hooks for logging and metrics
  • Blockchain interaction
  • Production deployment considerations
  • Monitoring and alerting

See also: examples/go/facilitator/, e2e/facilitators/go/

Package Structure

github.com/x402-foundation/x402/go
│
├── Core (framework-agnostic)
│   ├── client.go              - x402.X402Client
│   ├── server.go              - x402.X402ResourceServer
│   ├── facilitator.go         - x402.X402Facilitator
│   ├── types.go               - Core types
│   └── *_hooks.go             - Lifecycle hooks
│
├── http/                      - HTTP transport layer
│   ├── http.go                - Type aliases and convenience functions
│   ├── client.go              - HTTP client wrapper
│   ├── server.go              - HTTP server integration
│   ├── facilitator_client.go  - Facilitator HTTP client
│   └── gin/                   - Gin middleware
│
├── mechanisms/                - Payment schemes
│   ├── evm/exact/
│   │   ├── client/            - EVM client mechanism
│   │   ├── server/            - EVM server mechanism
│   │   └── facilitator/       - EVM facilitator mechanism
│   └── svm/exact/
│       ├── client/            - SVM client mechanism
│       ├── server/            - SVM server mechanism
│       └── facilitator/       - SVM facilitator mechanism
│
├── signers/                   - Signer helpers
│   ├── evm/                   - EVM client signers
│   └── svm/                   - SVM client signers
│
├── extensions/                - Protocol extensions
│   └── bazaar/                - API discovery
│
└── types/                     - Type definitions
    ├── v1.go                  - V1 protocol types
    ├── v2.go                  - V2 protocol types
    ├── helpers.go             - Version detection utilities
    ├── raw.go                 - Raw type handling
    └── extensions.go          - Extension type definitions

Supported Networks

EVM (Ethereum Virtual Machine)

All EVM-compatible chains using CAIP-2 identifiers:

  • Ethereum Mainnet (eip155:1)
  • Base Mainnet (eip155:8453)
  • Base Sepolia (eip155:84532)
  • Optimism, Arbitrum, Polygon, and more

Use eip155:* wildcard to support all EVM chains.

SVM (Solana Virtual Machine)

All Solana networks using CAIP-2 identifiers:

  • Solana Mainnet (solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp)
  • Solana Devnet (solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1)
  • Solana Testnet (solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z)

Use solana:* wildcard to support all Solana networks.

Supported Schemes

Exact Payment

Transfer an exact amount to access a resource:

  • EVM: Uses EIP-3009 transferWithAuthorization (USDC compatible tokens)
  • SVM: Uses Solana token transfers (USDC SPL token)

Features

  • ✅ Protocol v2 with v1 backward compatibility
  • ✅ Multi-chain support (EVM and SVM)
  • ✅ Modular architecture - use core primitives directly or with helpers
  • ✅ Type safe with strong typing throughout
  • ✅ Framework agnostic core
  • ✅ Concurrent safe operations
  • ✅ Context-aware with proper cancellation support
  • ✅ Extensible plugin architecture
  • ✅ Production ready with comprehensive testing
  • ✅ Lifecycle hooks for customization

Package Documentation

Core Documentation
Component Documentation
Examples

Testing

# Run all tests
go test ./...

# Run with coverage
go test -cover ./...

# Run integration tests
go test ./test/integration/...

Contributing

See CONTRIBUTING.md for contribution guidelines.

License

Apache 2.0 - See LICENSE for details.

Documentation

Index

Constants

View Source
const (
	// Version is the SDK version
	Version = "2.11.0"

	// ProtocolVersion is the current x402 protocol version
	ProtocolVersion = 2

	// ProtocolVersionV1 is the legacy x402 protocol version
	ProtocolVersionV1 = 1
)

Version constants

View Source
const (
	ErrCodeInvalidPayment     = "invalid_payment"
	ErrCodePaymentRequired    = "payment_required"
	ErrCodeInsufficientFunds  = "insufficient_funds"
	ErrCodeNetworkMismatch    = "network_mismatch"
	ErrCodeSchemeMismatch     = "scheme_mismatch"
	ErrCodeSignatureInvalid   = "signature_invalid"
	ErrCodePaymentExpired     = "payment_expired"
	ErrCodeSettlementFailed   = "settlement_failed"
	ErrCodeUnsupportedScheme  = "unsupported_scheme"
	ErrCodeUnsupportedNetwork = "unsupported_network"
)

Common error codes

View Source
const (
	ErrInvalidVersion          = "invalid_version"
	ErrInvalidV1Payload        = "invalid_v1_payload"
	ErrInvalidV1Requirements   = "invalid_v1_requirements"
	ErrInvalidV2Payload        = "invalid_v2_payload"
	ErrInvalidV2Requirements   = "invalid_v2_requirements"
	ErrNoFacilitatorForNetwork = "no_facilitator_for_network"
	ErrInvalidResponse         = "invalid_response"
)

Facilitator error constants

View Source
const (
	ErrFailedToMarshalPayload      = "failed_to_marshal_payload"
	ErrFailedToMarshalRequirements = "failed_to_marshal_requirements"
)

Server error constants

Variables

This section is empty.

Functions

func AssertAcceptsAdditiveExtraAfterSchemeEnrich

func AssertAcceptsAdditiveExtraAfterSchemeEnrich(
	baseline, current []types.PaymentRequirements,
	scheme, network string,
) error

AssertAcceptsAdditiveExtraAfterSchemeEnrich enforces the scheme-side `enrichPaymentRequiredResponse` policy: schemes may only ADD new `extra` keys to the matching accept entry; payment terms (payTo / amount / asset / maxTimeoutSeconds) and scheme/network are immutable; non-matching accepts must be untouched.

func AssertAcceptsAllowlistedAfterExtensionEnrich

func AssertAcceptsAllowlistedAfterExtensionEnrich(
	baseline, current []types.PaymentRequirements,
	extensionKey string,
) error

AssertAcceptsAllowlistedAfterExtensionEnrich enforces the extension-side `enrichPaymentRequiredResponse` mutation policy: extensions may fill vacant `payTo` / `amount` / `asset` and add new `extra` keys; everything else is immutable.

func AssertAdditivePayloadEnrichment

func AssertAdditivePayloadEnrichment(payload, enrichment map[string]interface{}, callerLabel string) error

AssertAdditivePayloadEnrichment ensures a scheme's `EnrichSettlementPayload` only ADDS new keys to the existing payload.

func AssertAdditiveSettlementExtra

func AssertAdditiveSettlementExtra(extra, enrichment map[string]interface{}, callerLabel string) error

AssertAdditiveSettlementExtra ensures a scheme's `EnrichSettlementResponse` only ADDS new fields to the response extra, recursively for nested plain objects.

func AssertSettleResponseCoreUnchanged

func AssertSettleResponseCoreUnchanged(before SettleResponseCoreSnapshot, after *SettleResponse, extensionKey string) error

AssertSettleResponseCoreUnchanged enforces that an extension did not rewrite facilitator outcome fields.

func DeepEqual

func DeepEqual(a, b interface{}) bool

DeepEqual performs deep equality check on payment requirements

func IsVacantStringField

func IsVacantStringField(value string) bool

IsVacantStringField reports whether a string field is treated as unset and may be filled by `enrichPaymentRequiredResponse`.

func IsWildcardNetwork

func IsWildcardNetwork(network Network) bool

IsWildcardNetwork checks if network is a wildcard pattern

func MatchesNetwork

func MatchesNetwork(pattern Network, network Network) bool

MatchesNetwork checks if a network matches a pattern (supports wildcards)

func MergeAdditiveSettlementExtra

func MergeAdditiveSettlementExtra(extra, enrichment map[string]interface{}) map[string]interface{}

MergeAdditiveSettlementExtra deep-merges `enrichment` into `extra` after the additive policy has been validated.

func Newx402Client

func Newx402Client(opts ...ClientOption) *x402Client

Newx402Client creates a new x402 client

func Newx402Facilitator

func Newx402Facilitator() *x402Facilitator

func Newx402ResourceServer

func Newx402ResourceServer(opts ...ResourceServerOption) *x402ResourceServer

func ResolveSettlementOverrideAmount

func ResolveSettlementOverrideAmount(rawAmount string, requirements types.PaymentRequirements, decimals int) (string, error)

ResolveSettlementOverrideAmount resolves a settlement override amount string to a final atomic-unit string. Supports three formats:

  • Raw atomic units: "1000"
  • Percent of requirements.Amount: "50%" (up to 2 decimal places, floored)
  • Dollar price: "$0.05" (converted using the provided decimals)

func SnapshotPaymentRequirementsList

func SnapshotPaymentRequirementsList(requirements []types.PaymentRequirements) []types.PaymentRequirements

SnapshotPaymentRequirementsList deep-clones `requirements` so the result can serve as an immutable baseline for policy checks.

func ValidatePaymentPayload

func ValidatePaymentPayload(p PaymentPayload) error

ValidatePaymentPayload performs basic validation on a payment payload Version-aware: handles both v1 and v2 payload structures

func ValidatePaymentRequirements

func ValidatePaymentRequirements(r PaymentRequirements) error

ValidatePaymentRequirements performs basic validation on payment requirements

Types

type AfterPaymentCreationHook

type AfterPaymentCreationHook func(PaymentCreatedContext) error

AfterPaymentCreationHook is called after successful payment payload creation Any error returned will be logged but will not affect the payment creation result

type AfterSettleHook

type AfterSettleHook func(SettleResultContext) error

AfterSettleHook is called after successful payment settlement Any error returned will be logged but will not affect the settlement result

type AfterSettleHookProvider

type AfterSettleHookProvider interface {
	AfterSettleHook() AfterSettleHook
}

AfterSettleHookProvider is implemented by schemes that contribute an AfterSettleHook to the resource server's lifecycle pipeline.

type AfterVerifyHook

type AfterVerifyHook func(VerifyResultContext) (*AfterVerifyResult, error)

AfterVerifyHook is called after successful payment verification. Any error returned will be logged but will not affect the verification result. Returning an AfterVerifyResult with SkipHandler=true signals the HTTP layer to bypass the resource handler and perform settlement inline (e.g. cooperative refund). The last hook to return a SkipHandler directive wins.

type AfterVerifyHookProvider

type AfterVerifyHookProvider interface {
	AfterVerifyHook() AfterVerifyHook
}

AfterVerifyHookProvider is implemented by schemes that contribute an AfterVerifyHook to the resource server's lifecycle pipeline.

type AfterVerifyResult

type AfterVerifyResult struct {
	SkipHandler bool
	Response    *SkipHandlerDirective
}

AfterVerifyResult is the optional return value of an AfterVerifyHook. When SkipHandler is true, the resource handler is bypassed and settlement is performed inline; the optional Response is used to craft the success body.

type AssetAmount

type AssetAmount struct {
	Asset  string                 `json:"asset"`
	Amount string                 `json:"amount"`
	Extra  map[string]interface{} `json:"extra,omitempty"`
}

AssetAmount represents an amount of a specific asset

type AssetDecimalsProvider

type AssetDecimalsProvider interface {
	GetAssetDecimals(asset string, network Network) int
}

AssetDecimalsProvider is an optional interface that SchemeNetworkServer implementations can satisfy to report the decimal precision of the asset for a given network. SettlePayment uses this to convert dollar-format settlement overrides to atomic units. Falls back to 6 decimals when the scheme does not implement this interface.

type BeforeHookResult

type BeforeHookResult struct {
	Abort            bool
	Reason           string
	Message          string
	Skip             bool
	SkipResult       *SettleResponse
	SkipVerifyResult *VerifyResponse
}

BeforeHookResult represents the result of a "before" hook. If Abort is true, the operation will be aborted with the given Reason. If Skip is true, the operation will be short-circuited; the hook supplies either SkipResult (settle hooks) or SkipVerifyResult (verify hooks). The batched scheme uses this to handle voucher payloads without on-chain settlement and to short-circuit verification when local channel state is fresh enough to verify against.

type BeforePaymentCreationHook

type BeforePaymentCreationHook func(PaymentCreationContext) (*BeforePaymentCreationHookResult, error)

BeforePaymentCreationHook is called before payment payload creation If it returns a result with Abort=true, payment creation will be aborted and an error will be returned with the provided reason

type BeforePaymentCreationHookResult

type BeforePaymentCreationHookResult struct {
	Abort  bool
	Reason string
}

BeforePaymentCreationHookResult represents the result of a "before payment creation" hook If Abort is true, the payment creation will be aborted with the given Reason

type BeforeSettleHook

type BeforeSettleHook func(SettleContext) (*BeforeHookResult, error)

BeforeSettleHook is called before payment settlement If it returns a result with Abort=true, settlement will be aborted and an error will be returned with the provided reason

type BeforeSettleHookProvider

type BeforeSettleHookProvider interface {
	BeforeSettleHook() BeforeSettleHook
}

BeforeSettleHookProvider is implemented by schemes that contribute a BeforeSettleHook to the resource server's lifecycle pipeline.

type BeforeVerifyHook

type BeforeVerifyHook func(VerifyContext) (*BeforeHookResult, error)

BeforeVerifyHook is called before payment verification If it returns a result with Abort=true, verification will be skipped and an invalid VerifyResponse will be returned with the provided reason

type BeforeVerifyHookProvider

type BeforeVerifyHookProvider interface {
	BeforeVerifyHook() BeforeVerifyHook
}

BeforeVerifyHookProvider is implemented by schemes that contribute a BeforeVerifyHook to the resource server's lifecycle pipeline.

type ClientExtension

type ClientExtension interface {
	// Key returns the unique extension identifier (e.g., "eip2612GasSponsoring").
	// Must match the extension key used in PaymentRequired.Extensions.
	Key() string

	// EnrichPaymentPayload is called after payload creation when the extension key
	// is present in paymentRequired.Extensions. Allows the extension to enrich the
	// payload with extension-specific data (e.g., signing an EIP-2612 permit).
	EnrichPaymentPayload(ctx context.Context, payload types.PaymentPayload, required types.PaymentRequired) (types.PaymentPayload, error)
}

ClientExtension can enrich payment payloads on the client side. Client extensions are invoked after the scheme creates the base payload but before it is returned. This allows mechanism-specific logic (e.g., EVM EIP-2612 permit signing) to enrich the payload's extensions data.

type ClientOption

type ClientOption func(*x402Client)

ClientOption configures the client

func WithAfterPaymentCreationHook

func WithAfterPaymentCreationHook(hook AfterPaymentCreationHook) ClientOption

WithAfterPaymentCreationHook registers a hook to execute after successful payment creation

func WithBeforePaymentCreationHook

func WithBeforePaymentCreationHook(hook BeforePaymentCreationHook) ClientOption

WithBeforePaymentCreationHook registers a hook to execute before payment creation

func WithOnPaymentCreationFailureHook

func WithOnPaymentCreationFailureHook(hook OnPaymentCreationFailureHook) ClientOption

WithOnPaymentCreationFailureHook registers a hook to execute when payment creation fails

func WithOnPaymentResponseHook

func WithOnPaymentResponseHook(hook OnPaymentResponseHook) ClientOption

WithOnPaymentResponseHook registers a hook to execute after each paid response.

func WithPaymentSelector

func WithPaymentSelector(selector PaymentRequirementsSelector) ClientOption

WithPaymentSelector sets a custom payment requirements selector

func WithPolicy

func WithPolicy(policy PaymentPolicy) ClientOption

WithPolicy registers a payment policy at creation time

type EnrichSettlementPayloadProvider

type EnrichSettlementPayloadProvider interface {
	EnrichSettlementPayload(ctx SettleContext) (map[string]interface{}, error)
}

EnrichSettlementPayloadProvider is implemented by schemes that need to add server-owned fields to the payment payload before the facilitator settles. Return nil/empty for no-op. The framework asserts the result is additive (no existing payload key may be present in the returned map) before merging.

type EnrichSettlementResponseProvider

type EnrichSettlementResponseProvider interface {
	EnrichSettlementResponse(ctx SettleResultContext) (map[string]interface{}, error)
}

EnrichSettlementResponseProvider is implemented by schemes that need to add server-owned fields to the facilitator's settle response `extra`. Return nil/empty for no-op. The framework asserts the result is additive (no existing extra key may be present in the returned map, recursively for nested maps) before deep-merging.

type ExtensionAwareClient

type ExtensionAwareClient interface {
	SchemeNetworkClient
	CreatePaymentPayloadWithExtensions(ctx context.Context, requirements types.PaymentRequirements, extensions map[string]interface{}) (types.PaymentPayload, error)
}

ExtensionAwareClient is an optional interface for schemes that can handle extensions. When a scheme implements this, x402Client will call CreatePaymentPayloadWithExtensions instead of CreatePaymentPayload, passing the server-declared extensions so the scheme can enrich the payload (e.g., EIP-2612 gas sponsoring).

type FacilitatorAfterSettleHook

type FacilitatorAfterSettleHook func(FacilitatorSettleResultContext) error

FacilitatorAfterSettleHook is called after successful facilitator payment settlement Any error returned will be logged but will not affect the settlement result

type FacilitatorAfterVerifyHook

type FacilitatorAfterVerifyHook func(FacilitatorVerifyResultContext) error

FacilitatorAfterVerifyHook is called after successful facilitator payment verification Any error returned will be logged but will not affect the verification result

type FacilitatorBeforeHookResult

type FacilitatorBeforeHookResult struct {
	Abort   bool
	Reason  string
	Message string
}

FacilitatorBeforeHookResult represents the result of a facilitator "before" hook If Abort is true, the operation will be aborted with the given Reason

type FacilitatorBeforeSettleHook

type FacilitatorBeforeSettleHook func(FacilitatorSettleContext) (*FacilitatorBeforeHookResult, error)

FacilitatorBeforeSettleHook is called before facilitator payment settlement If it returns a result with Abort=true, settlement will be aborted and an error will be returned with the provided reason

type FacilitatorBeforeVerifyHook

type FacilitatorBeforeVerifyHook func(FacilitatorVerifyContext) (*FacilitatorBeforeHookResult, error)

FacilitatorBeforeVerifyHook is called before facilitator payment verification If it returns a result with Abort=true, verification will be skipped and an invalid VerifyResponse will be returned with the provided reason

type FacilitatorClient

type FacilitatorClient interface {
	// Verify a payment (detects version from bytes, routes internally)
	Verify(ctx context.Context, payloadBytes []byte, requirementsBytes []byte) (*VerifyResponse, error)

	// Settle a payment (detects version from bytes, routes internally)
	Settle(ctx context.Context, payloadBytes []byte, requirementsBytes []byte) (*SettleResponse, error)

	// GetSupported returns supported payment kinds in flat array format with x402Version in each element (backward compatible)
	GetSupported(ctx context.Context) (SupportedResponse, error)
}

FacilitatorClient interface for facilitators that support V1 and/or V2. Uses bytes at network boundary - SDK internal routing unmarshals and routes to typed mechanisms. Both modern facilitators (supporting V1+V2) and legacy facilitators (V1 only) implement this interface.

type FacilitatorContext

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

FacilitatorContext provides access to registered facilitator extensions. Passed to SchemeNetworkFacilitator.Verify/Settle so mechanism implementations can retrieve extension-provided capabilities.

func NewFacilitatorContext

func NewFacilitatorContext(extensions map[string]FacilitatorExtension) *FacilitatorContext

NewFacilitatorContext creates a FacilitatorContext from the given extensions map.

func (*FacilitatorContext) GetExtension

func (c *FacilitatorContext) GetExtension(key string) FacilitatorExtension

GetExtension returns the extension registered under the given key, or nil.

type FacilitatorExtension

type FacilitatorExtension interface {
	Key() string
}

FacilitatorExtension is the base interface for extensions registered with x402Facilitator. Extensions are stored by key and made available to mechanism implementations via FacilitatorContext. Specific extensions embed this and add their own capabilities (e.g., a batch signer).

func NewFacilitatorExtension

func NewFacilitatorExtension(key string) FacilitatorExtension

NewFacilitatorExtension creates a FacilitatorExtension with the given key.

type FacilitatorOnSettleFailureHook

type FacilitatorOnSettleFailureHook func(FacilitatorSettleFailureContext) (*FacilitatorSettleFailureHookResult, error)

FacilitatorOnSettleFailureHook is called when facilitator payment settlement fails If it returns a result with Recovered=true, the provided SettleResponse will be returned instead of the error

type FacilitatorOnVerifyFailureHook

type FacilitatorOnVerifyFailureHook func(FacilitatorVerifyFailureContext) (*FacilitatorVerifyFailureHookResult, error)

FacilitatorOnVerifyFailureHook is called when facilitator payment verification fails If it returns a result with Recovered=true, the provided VerifyResponse will be returned instead of the error

type FacilitatorSettleContext

type FacilitatorSettleContext struct {
	Ctx               context.Context
	Payload           PaymentPayloadView
	Requirements      PaymentRequirementsView
	PayloadBytes      []byte // Raw bytes for extensions needing full data
	RequirementsBytes []byte // Raw bytes for extensions needing full data
}

FacilitatorSettleContext contains information passed to facilitator settle hooks Uses view interfaces for version-agnostic hooks PayloadBytes and RequirementsBytes provide escape hatch for extensions (e.g., Bazaar)

type FacilitatorSettleFailureContext

type FacilitatorSettleFailureContext struct {
	FacilitatorSettleContext
	Error error
}

FacilitatorSettleFailureContext contains facilitator settle operation failure and context

type FacilitatorSettleFailureHookResult

type FacilitatorSettleFailureHookResult struct {
	Recovered bool
	Result    *SettleResponse
}

FacilitatorSettleFailureHookResult represents the result of a facilitator settle failure hook

type FacilitatorSettleResultContext

type FacilitatorSettleResultContext struct {
	FacilitatorSettleContext
	Result *SettleResponse
}

FacilitatorSettleResultContext contains facilitator settle operation result and context

type FacilitatorVerifyContext

type FacilitatorVerifyContext struct {
	Ctx               context.Context
	Payload           PaymentPayloadView
	Requirements      PaymentRequirementsView
	PayloadBytes      []byte // Raw bytes for extensions needing full data
	RequirementsBytes []byte // Raw bytes for extensions needing full data
}

FacilitatorVerifyContext contains information passed to facilitator verify hooks Uses view interfaces for version-agnostic hooks PayloadBytes and RequirementsBytes provide escape hatch for extensions (e.g., Bazaar)

type FacilitatorVerifyFailureContext

type FacilitatorVerifyFailureContext struct {
	FacilitatorVerifyContext
	Error error
}

FacilitatorVerifyFailureContext contains facilitator verify operation failure and context

type FacilitatorVerifyFailureHookResult

type FacilitatorVerifyFailureHookResult struct {
	Recovered bool
	Result    *VerifyResponse
}

FacilitatorVerifyFailureHookResult represents the result of a facilitator verify failure hook If Recovered is true, the hook has recovered from the failure with the given result

type FacilitatorVerifyResultContext

type FacilitatorVerifyResultContext struct {
	FacilitatorVerifyContext
	Result *VerifyResponse
}

FacilitatorVerifyResultContext contains facilitator verify operation result and context

type MoneyParser

type MoneyParser func(amount float64, network Network) (*AssetAmount, error)

MoneyParser is a function that converts a decimal amount to an AssetAmount If the parser cannot handle the conversion, it should return nil Multiple parsers can be registered and will be tried in order The default parser is always used as a fallback

Args:

amount: Decimal amount (e.g., 1.50 for $1.50)
network: Network identifier

Returns:

AssetAmount or nil if this parser cannot handle the conversion

type Network

type Network string

Network represents a blockchain network identifier in CAIP-2 format Format: namespace:reference (e.g., "eip155:1" for Ethereum mainnet)

func ParseNetwork

func ParseNetwork(s string) Network

ParseNetwork parses a network string into Network type

func (Network) Match

func (n Network) Match(pattern Network) bool

Match checks if this network matches a pattern (supports wildcards) e.g., "eip155:1" matches "eip155:*" and "eip155:*" matches "eip155:1"

func (Network) Parse

func (n Network) Parse() (namespace, reference string, err error)

Parse splits the network into namespace and reference components

type OnPaymentCreationFailureHook

type OnPaymentCreationFailureHook func(PaymentCreationFailureContext) (*PaymentCreationFailureHookResult, error)

OnPaymentCreationFailureHook is called when payment payload creation fails If it returns a result with Recovered=true, the provided PaymentPayload will be returned instead of the error

type OnPaymentResponseHook

type OnPaymentResponseHook func(context.Context, PaymentResponseContext) (PaymentResponseResult, error)

OnPaymentResponseHook is called by the transport after each paid response (HTTP 200 with PAYMENT-RESPONSE, or corrective HTTP 402 with PAYMENT-REQUIRED). Mirrors the TS x402Client.onPaymentResponse user-level hook.

Returning Recovered=true on a corrective 402 instructs the transport to retry once with a freshly built payment payload. The first hook to return Recovered wins; subsequent hooks still run for instrumentation.

type OnSettleFailureHook

type OnSettleFailureHook func(SettleFailureContext) (*SettleFailureHookResult, error)

OnSettleFailureHook is called when payment settlement fails If it returns a result with Recovered=true, the provided SettleResponse will be returned instead of the error

type OnSettleFailureHookProvider

type OnSettleFailureHookProvider interface {
	OnSettleFailureHook() OnSettleFailureHook
}

OnSettleFailureHookProvider is implemented by schemes that contribute an OnSettleFailureHook to the resource server's lifecycle pipeline.

type OnVerifiedPaymentCanceledHook

type OnVerifiedPaymentCanceledHook func(VerifiedPaymentCanceledContext) error

OnVerifiedPaymentCanceledHook is called when a verified payment is canceled before settlement runs (e.g. resource handler error or non-2xx response). Returned errors are logged but do not affect the response.

type OnVerifiedPaymentCanceledHookProvider

type OnVerifiedPaymentCanceledHookProvider interface {
	OnVerifiedPaymentCanceledHook() OnVerifiedPaymentCanceledHook
}

OnVerifiedPaymentCanceledHookProvider is implemented by schemes that contribute an OnVerifiedPaymentCanceledHook to the resource server's lifecycle pipeline.

type OnVerifyFailureHook

type OnVerifyFailureHook func(VerifyFailureContext) (*VerifyFailureHookResult, error)

OnVerifyFailureHook is called when payment verification fails If it returns a result with Recovered=true, the provided VerifyResponse will be returned instead of the error

type OnVerifyFailureHookProvider

type OnVerifyFailureHookProvider interface {
	OnVerifyFailureHook() OnVerifyFailureHook
}

OnVerifyFailureHookProvider is implemented by schemes that contribute an OnVerifyFailureHook to the resource server's lifecycle pipeline.

type PartialPaymentPayload

type PartialPaymentPayload struct {
	X402Version int `json:"x402Version"`
}

PartialPaymentPayload contains only x402Version for version detection Used to detect protocol version before unmarshaling to specific types

type PaymentCancellationDispatcher

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

PaymentCancellationDispatcher fires onVerifiedPaymentCanceled hooks at most once.

func (*PaymentCancellationDispatcher) Cancel

Cancel fires the underlying hooks. Safe to call multiple times — only the first call wins.

type PaymentCreatedContext

type PaymentCreatedContext struct {
	PaymentCreationContext
	Payload PaymentPayloadView
}

PaymentCreatedContext contains payment creation result and context

type PaymentCreationContext

type PaymentCreationContext struct {
	Ctx                  context.Context
	Version              int // V1 or V2
	SelectedRequirements PaymentRequirementsView
}

PaymentCreationContext contains information passed to payment creation hooks Uses view interfaces for version-agnostic hooks

type PaymentCreationFailureContext

type PaymentCreationFailureContext struct {
	PaymentCreationContext
	Error error
}

PaymentCreationFailureContext contains payment creation failure and context

type PaymentCreationFailureHookResult

type PaymentCreationFailureHookResult struct {
	Recovered bool
	Payload   PaymentPayloadView
}

PaymentCreationFailureHookResult represents the result of a payment creation failure hook If Recovered is true, the hook has recovered from the failure with the given payload

type PaymentError

type PaymentError struct {
	Code    string                 `json:"code"`
	Message string                 `json:"message"`
	Details map[string]interface{} `json:"details,omitempty"`
}

PaymentError represents a payment-specific error

func NewPaymentError

func NewPaymentError(code, message string, details map[string]interface{}) *PaymentError

NewPaymentError creates a new payment error

func (*PaymentError) Error

func (e *PaymentError) Error() string

type PaymentPayload

type PaymentPayload = types.PaymentPayload

Re-export V2 types as default in x402 package V2 types are defined in types/v2.go but re-exported here for convenience

type PaymentPayloadView

type PaymentPayloadView interface {
	GetVersion() int
	GetScheme() string
	GetNetwork() string // Returns network as string (can be converted to Network type)
	GetPayload() map[string]interface{}
}

PaymentPayloadView is a unified interface for payment payloads Both V1 and V2 types implement this to work with hooks

type PaymentPolicy

type PaymentPolicy func(requirements []PaymentRequirementsView) []PaymentRequirementsView

PaymentPolicy filters or transforms payment requirements Works with unified view interface

type PaymentRequired

type PaymentRequired = types.PaymentRequired

Re-export V2 types as default in x402 package V2 types are defined in types/v2.go but re-exported here for convenience

type PaymentRequiredContext

type PaymentRequiredContext struct {
	Requirements            []types.PaymentRequirements
	PaymentPayload          *types.PaymentPayload
	ResourceInfo            *types.ResourceInfo
	Error                   string
	PaymentRequiredResponse *types.PaymentRequired
}

PaymentRequiredContext is passed to PaymentRequiredEnricher.EnrichPaymentRequiredResponse. PaymentPayload is non-nil only on the verify-failure branch.

type PaymentRequiredEnricher

type PaymentRequiredEnricher interface {
	EnrichPaymentRequiredResponse(ctx PaymentRequiredContext)
}

PaymentRequiredEnricher is an optional interface for SchemeNetworkServer implementations that want to add per-scheme corrective state to the 402 response. Invoked once per matching scheme during PaymentRequired construction; implementations may mutate ctx.Requirements entries in place.

type PaymentRequirements

type PaymentRequirements = types.PaymentRequirements

Re-export V2 types as default in x402 package V2 types are defined in types/v2.go but re-exported here for convenience

type PaymentRequirementsSelector

type PaymentRequirementsSelector func(requirements []PaymentRequirementsView) PaymentRequirementsView

PaymentRequirementsSelector chooses which payment option to use Works with unified view interface

type PaymentRequirementsView

type PaymentRequirementsView interface {
	GetScheme() string
	GetNetwork() string // Returns network as string (can be converted to Network type)
	GetAsset() string
	GetAmount() string // V1: MaxAmountRequired, V2: Amount
	GetPayTo() string
	GetMaxTimeoutSeconds() int
	GetExtra() map[string]interface{}
}

PaymentRequirementsView is a unified interface for payment requirements Both V1 and V2 types implement this to work with selectors/policies/hooks

func DefaultPaymentSelector

func DefaultPaymentSelector(requirements []PaymentRequirementsView) PaymentRequirementsView

DefaultPaymentSelector chooses the first available payment option

type PaymentResponseContext

type PaymentResponseContext struct {
	PaymentPayload  types.PaymentPayload
	Requirements    types.PaymentRequirements
	SettleResponse  *SettleResponse
	PaymentRequired *types.PaymentRequired
}

PaymentResponseContext is passed to PaymentResponseHandler implementations after the transport receives the response to a paid request. Exactly one of SettleResponse or PaymentRequired is populated:

  • SettleResponse: the request succeeded (HTTP 200) and the server returned a PAYMENT-RESPONSE header carrying the settle outcome.
  • PaymentRequired: the request was rejected (HTTP 402) with a corrective PAYMENT-REQUIRED header (e.g. cumulative_amount_mismatch).

Mirrors the TS PaymentResponseContext shape consumed by SchemeClientHooks.onPaymentResponse.

type PaymentResponseHandler

type PaymentResponseHandler interface {
	OnPaymentResponse(ctx context.Context, prCtx PaymentResponseContext) (PaymentResponseResult, error)
}

PaymentResponseHandler is an optional interface that SchemeNetworkClient implementations satisfy to reconcile local state after a paid response. The transport (PaymentRoundTripper) invokes this hook automatically — user code does not need to call ProcessSettleResponse manually.

Mirrors the TS schemeHooks.onPaymentResponse field on SchemeClientHooks.

type PaymentResponseResult

type PaymentResponseResult struct {
	Recovered bool
}

PaymentResponseResult is returned by PaymentResponseHandler.OnPaymentResponse. When Recovered is true, the transport may attempt one additional retry with a freshly built payment payload. Used to handle corrective 402 responses where the scheme has resynced its session state.

type Price

type Price interface{}

Price represents a price that can be specified in various formats

type ResourceConfig

type ResourceConfig struct {
	Scheme            string                 `json:"scheme"`
	PayTo             string                 `json:"payTo"`
	Price             Price                  `json:"price"`
	Network           Network                `json:"network"`
	MaxTimeoutSeconds int                    `json:"maxTimeoutSeconds,omitempty"`
	Extra             map[string]interface{} `json:"extra,omitempty"`
}

ResourceConfig defines payment configuration for a protected resource

type ResourceInfo

type ResourceInfo = types.ResourceInfo

Re-export V2 types as default in x402 package V2 types are defined in types/v2.go but re-exported here for convenience

type ResourceServerExtensionHookProvider

type ResourceServerExtensionHookProvider interface {
	ResourceServerExtensionHooks() ResourceServerExtensionHooks
}

ResourceServerExtensionHookProvider lets an extension expose any subset of the seven lifecycle hooks. Returning nil from any phase means "no hook for that phase" — the server skips it.

type ResourceServerExtensionHooks

type ResourceServerExtensionHooks struct {
	OnBeforeVerify            BeforeVerifyHook
	OnAfterVerify             AfterVerifyHook
	OnVerifyFailure           OnVerifyFailureHook
	OnBeforeSettle            BeforeSettleHook
	OnAfterSettle             AfterSettleHook
	OnSettleFailure           OnSettleFailureHook
	OnVerifiedPaymentCanceled OnVerifiedPaymentCanceledHook
}

ResourceServerExtensionHooks is an extension's optional bundle of lifecycle hooks. Mirrors the TS `ResourceServerExtensionHooks` interface shape — fields left nil mean "no hook for that phase".

type ResourceServerOption

type ResourceServerOption func(*x402ResourceServer)

ResourceServerOption configures the server

func WithAfterSettleHook

func WithAfterSettleHook(hook AfterSettleHook) ResourceServerOption

WithAfterSettleHook registers a hook to execute after successful payment settlement

func WithAfterVerifyHook

func WithAfterVerifyHook(hook AfterVerifyHook) ResourceServerOption

WithAfterVerifyHook registers a hook to execute after successful payment verification

func WithBeforeSettleHook

func WithBeforeSettleHook(hook BeforeSettleHook) ResourceServerOption

WithBeforeSettleHook registers a hook to execute before payment settlement

func WithBeforeVerifyHook

func WithBeforeVerifyHook(hook BeforeVerifyHook) ResourceServerOption

WithBeforeVerifyHook registers a hook to execute before payment verification

func WithCacheTTL

func WithCacheTTL(ttl time.Duration) ResourceServerOption

WithCacheTTL sets the cache TTL for supported kinds

func WithFacilitatorClient

func WithFacilitatorClient(client FacilitatorClient) ResourceServerOption

WithFacilitatorClient adds a facilitator client

func WithOnSettleFailureHook

func WithOnSettleFailureHook(hook OnSettleFailureHook) ResourceServerOption

WithOnSettleFailureHook registers a hook to execute when payment settlement fails

func WithOnVerifiedPaymentCanceledHook

func WithOnVerifiedPaymentCanceledHook(hook OnVerifiedPaymentCanceledHook) ResourceServerOption

WithOnVerifiedPaymentCanceledHook registers a hook fired when a verified payment is canceled before settlement (handler error or non-2xx response).

func WithOnVerifyFailureHook

func WithOnVerifyFailureHook(hook OnVerifyFailureHook) ResourceServerOption

WithOnVerifyFailureHook registers a hook to execute when payment verification fails

func WithSchemeServer

func WithSchemeServer(network Network, schemeServer SchemeNetworkServer) ResourceServerOption

WithSchemeServer registers a scheme server implementation (V2, default)

type SchemeNetworkClient

type SchemeNetworkClient interface {
	Scheme() string
	CreatePaymentPayload(ctx context.Context, requirements types.PaymentRequirements) (types.PaymentPayload, error)
}

SchemeNetworkClient is implemented by client-side payment mechanisms (V2)

type SchemeNetworkClientV1

type SchemeNetworkClientV1 interface {
	Scheme() string
	CreatePaymentPayload(ctx context.Context, requirements types.PaymentRequirementsV1) (types.PaymentPayloadV1, error)
}

SchemeNetworkClientV1 is implemented by client-side V1 payment mechanisms

type SchemeNetworkFacilitator

type SchemeNetworkFacilitator interface {
	Scheme() string

	// CaipFamily returns the CAIP family pattern this facilitator supports.
	// Used to group signers by blockchain family in the supported response.
	//
	// Examples:
	//   - EVM facilitators return "eip155:*"
	//   - SVM facilitators return "solana:*"
	CaipFamily() string

	// GetExtra returns mechanism-specific extra data for the supported kinds endpoint.
	// This method is called when building the facilitator's supported response.
	//
	// For EVM schemes, return nil (no extra data needed).
	// For SVM schemes, return map with feePayer address.
	//
	// Args:
	//   network: Network identifier for context
	//
	// Returns:
	//   Extra data map or nil if no extra data is needed
	GetExtra(network Network) map[string]interface{}

	// GetSigners returns signer addresses used by this facilitator for a given network.
	// These are included in the supported response to help clients understand
	// which addresses might sign/pay for transactions.
	//
	// Supports multiple addresses for load balancing, key rotation, and high availability.
	//
	// Args:
	//   network: Network identifier
	//
	// Returns:
	//   Array of signer addresses
	//
	// Examples:
	//   - EVM: Returns facilitator wallet addresses
	//   - SVM: Returns fee payer addresses
	GetSigners(network Network) []string

	Verify(ctx context.Context, payload types.PaymentPayload, requirements types.PaymentRequirements, fctx *FacilitatorContext) (*VerifyResponse, error)
	Settle(ctx context.Context, payload types.PaymentPayload, requirements types.PaymentRequirements, fctx *FacilitatorContext) (*SettleResponse, error)
}

SchemeNetworkFacilitator is implemented by facilitator-side payment mechanisms (V2)

type SchemeNetworkFacilitatorV1

type SchemeNetworkFacilitatorV1 interface {
	Scheme() string

	// CaipFamily returns the CAIP family pattern this facilitator supports.
	// Used to group signers by blockchain family in the supported response.
	//
	// Examples:
	//   - EVM facilitators return "eip155:*"
	//   - SVM facilitators return "solana:*"
	CaipFamily() string

	// GetExtra returns mechanism-specific extra data for the supported kinds endpoint.
	// This method is called when building the facilitator's supported response.
	//
	// For EVM schemes, return nil (no extra data needed).
	// For SVM schemes, return map with feePayer address.
	//
	// Args:
	//   network: Network identifier for context
	//
	// Returns:
	//   Extra data map or nil if no extra data is needed
	GetExtra(network Network) map[string]interface{}

	// GetSigners returns signer addresses used by this facilitator for a given network.
	// These are included in the supported response to help clients understand
	// which addresses might sign/pay for transactions.
	//
	// Supports multiple addresses for load balancing, key rotation, and high availability.
	//
	// Args:
	//   network: Network identifier
	//
	// Returns:
	//   Array of signer addresses
	//
	// Examples:
	//   - EVM: Returns facilitator wallet addresses
	//   - SVM: Returns fee payer addresses
	GetSigners(network Network) []string

	Verify(ctx context.Context, payload types.PaymentPayloadV1, requirements types.PaymentRequirementsV1, fctx *FacilitatorContext) (*VerifyResponse, error)
	Settle(ctx context.Context, payload types.PaymentPayloadV1, requirements types.PaymentRequirementsV1, fctx *FacilitatorContext) (*SettleResponse, error)
}

SchemeNetworkFacilitatorV1 is implemented by facilitator-side V1 payment mechanisms

type SchemeNetworkServer

type SchemeNetworkServer interface {
	Scheme() string
	ParsePrice(price Price, network Network) (AssetAmount, error)
	EnhancePaymentRequirements(
		ctx context.Context,
		requirements types.PaymentRequirements,
		supportedKind types.SupportedKind,
		extensions []string,
	) (types.PaymentRequirements, error)
}

SchemeNetworkServer is implemented by server-side payment mechanisms (V2)

type SettleContext

type SettleContext struct {
	Ctx          context.Context
	Payload      PaymentPayloadView
	Requirements PaymentRequirementsView
	// DeclaredExtensions carries the extension declarations attached to the
	// route. Extension hooks gate on `DeclaredExtensions[extKey]` being set
	// before firing — mirrors TS `ctx.declaredExtensions[extensionKey]`.
	DeclaredExtensions map[string]interface{}
	PayloadBytes       []byte // Raw bytes for extensions needing full data
	RequirementsBytes  []byte // Raw bytes for extensions needing full data
}

SettleContext contains information passed to settle hooks Uses view interfaces for version-agnostic hooks PayloadBytes and RequirementsBytes provide escape hatch for extensions (e.g., Bazaar)

type SettleError

type SettleError struct {
	ErrorReason  string  // Error reason/code (e.g., "transaction_failed", "insufficient_balance")
	Payer        string  // Payer address (if known)
	Network      Network // Network identifier
	Transaction  string  // Transaction hash (if settlement was attempted)
	ErrorMessage string  // Optional error message details
}

SettleError represents a payment settlement failure All settlement failures (business logic and system errors) are returned as errors

func NewSettleError

func NewSettleError(reason string, payer string, network Network, transaction string, message string) *SettleError

NewSettleError creates a new settlement error

Args:

reason: Error reason/code
payer: Payer address (empty string if unknown)
network: Network identifier
transaction: Transaction hash (empty string if not submitted)
err: Optional underlying error

Returns:

*SettleError

func (*SettleError) Error

func (e *SettleError) Error() string

Error implements the error interface

type SettleFailureContext

type SettleFailureContext struct {
	SettleContext
	Error error
}

SettleFailureContext contains settle operation failure and context

type SettleFailureHookResult

type SettleFailureHookResult struct {
	Recovered bool
	Result    *SettleResponse
}

SettleFailureHookResult represents the result of a settle failure hook

type SettleResponse

type SettleResponse struct {
	Success      bool                   `json:"success"`
	ErrorReason  string                 `json:"errorReason,omitempty"`
	ErrorMessage string                 `json:"errorMessage,omitempty"`
	Payer        string                 `json:"payer,omitempty"`
	Transaction  string                 `json:"transaction"`
	Network      Network                `json:"network"`
	Amount       string                 `json:"amount,omitempty"`
	Extensions   map[string]interface{} `json:"extensions,omitempty"`
	Extra        map[string]interface{} `json:"extra,omitempty"`
}

SettleResponse contains the settlement result If settlement fails, an error (typically *SettleError) is returned and this will be nil

type SettleResponseCoreSnapshot

type SettleResponseCoreSnapshot struct {
	Success      bool
	Transaction  string
	Network      Network
	Amount       string
	Payer        string
	ErrorReason  string
	ErrorMessage string
}

SettleResponseCoreSnapshot captures facilitator-settled fields that extensions must not rewrite.

func SnapshotSettleResponseCore

func SnapshotSettleResponseCore(result *SettleResponse) SettleResponseCoreSnapshot

SnapshotSettleResponseCore captures facilitator-settled fields.

type SettleResultContext

type SettleResultContext struct {
	SettleContext
	Result *SettleResponse
}

SettleResultContext contains settle operation result and context

type SettlementOverrides

type SettlementOverrides struct {
	// Amount to settle. Supports three formats:
	//   - Raw atomic units: "1000" settles exactly 1000 atomic units.
	//   - Percent: "50%" settles 50% of PaymentRequirements.Amount (up to 2 decimal places, floored).
	//   - Dollar price: "$0.05" converts to atomic units using Extra["decimals"] (default 6).
	// The resolved amount must be <= the authorized maximum in PaymentRequirements.
	Amount string `json:"amount,omitempty"`
}

SettlementOverrides allows overriding settlement parameters. Used to support partial settlement (e.g., upto scheme billing by actual usage).

type SkipHandlerDirective

type SkipHandlerDirective struct {
	ContentType string
	Body        interface{}
}

SkipHandlerDirective is an optional acknowledgement body returned to the caller when an AfterVerifyHook requests that the resource handler be skipped for a self-contained operation. Travels in-process only — never on the facilitator wire.

type SupportedCache

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

SupportedCache caches facilitator capabilities

func (*SupportedCache) Clear

func (c *SupportedCache) Clear()

Clear removes all cached supported responses and expiry entries

func (*SupportedCache) Get

Get retrieves a supported response from the cache

func (*SupportedCache) Set

func (c *SupportedCache) Set(key string, response SupportedResponse)

Set stores a supported response in the cache

type SupportedKind

type SupportedKind = types.SupportedKind

Re-export V2 types as default in x402 package V2 types are defined in types/v2.go but re-exported here for convenience

type SupportedResponse

type SupportedResponse = types.SupportedResponse

Re-export V2 types as default in x402 package V2 types are defined in types/v2.go but re-exported here for convenience

type SupportedResponseV1

type SupportedResponseV1 = types.SupportedResponseV1

Re-export V1 types for legacy facilitator support

type VerifiedPaymentCancelOptions

type VerifiedPaymentCancelOptions struct {
	Reason         VerifiedPaymentCancellationReason
	Err            error
	ResponseStatus int
}

VerifiedPaymentCancelOptions describes a single cancellation event.

type VerifiedPaymentCanceledContext

type VerifiedPaymentCanceledContext struct {
	SettleContext
	Reason         VerifiedPaymentCancellationReason
	Err            error
	ResponseStatus int
}

VerifiedPaymentCanceledContext is delivered to OnVerifiedPaymentCanceled hooks when a verified payment is canceled before settlement.

type VerifiedPaymentCancellationReason

type VerifiedPaymentCancellationReason string

VerifiedPaymentCancellationReason describes why a verified payment is being canceled before settlement runs. Mirrors TS `VerifiedPaymentCancellationReason`.

const (
	// CancellationReasonHandlerThrew indicates the resource handler panicked or returned an error.
	CancellationReasonHandlerThrew VerifiedPaymentCancellationReason = "handler_threw"
	// CancellationReasonHandlerFailed indicates the resource handler completed but with a failing
	// response status (>= 400).
	CancellationReasonHandlerFailed VerifiedPaymentCancellationReason = "handler_failed"
)

type VerifyContext

type VerifyContext struct {
	Ctx          context.Context
	Payload      PaymentPayloadView
	Requirements PaymentRequirementsView
	// DeclaredExtensions carries the extension declarations attached to the
	// route. Extension hooks gate on `DeclaredExtensions[extKey]` being set
	// before firing — mirrors TS `ctx.declaredExtensions[extensionKey]`.
	DeclaredExtensions map[string]interface{}
	PayloadBytes       []byte // Raw bytes for extensions needing full data
	RequirementsBytes  []byte // Raw bytes for extensions needing full data
}

VerifyContext contains information passed to verify hooks Uses view interfaces for version-agnostic hooks PayloadBytes and RequirementsBytes provide escape hatch for extensions (e.g., Bazaar)

type VerifyError

type VerifyError struct {
	InvalidReason  string // Error reason/code (e.g., "insufficient_balance", "invalid_signature")
	Payer          string // Payer address (if known)
	InvalidMessage string // Optional invalid message details
}

VerifyError represents a payment verification failure All verification failures (business logic and system errors) are returned as errors

func NewVerifyError

func NewVerifyError(reason string, payer string, message string) *VerifyError

NewVerifyError creates a new verification error

Args:

reason: Error reason/code
payer: Payer address (empty string if unknown)
network: Network identifier (empty string if unknown)
message: Optional invalid message details

Returns:

*VerifyError

func (*VerifyError) Error

func (e *VerifyError) Error() string

Error implements the error interface

type VerifyFailureContext

type VerifyFailureContext struct {
	VerifyContext
	Error error
}

VerifyFailureContext contains verify operation failure and context

type VerifyFailureHookResult

type VerifyFailureHookResult struct {
	Recovered bool
	Result    *VerifyResponse
}

VerifyFailureHookResult represents the result of a verify failure hook If Recovered is true, the hook has recovered from the failure with the given result

type VerifyResponse

type VerifyResponse struct {
	IsValid        bool                   `json:"isValid"`
	InvalidReason  string                 `json:"invalidReason,omitempty"`
	InvalidMessage string                 `json:"invalidMessage,omitempty"`
	Payer          string                 `json:"payer,omitempty"`
	Extensions     map[string]interface{} `json:"extensions,omitempty"`
	Extra          map[string]interface{} `json:"extra,omitempty"`

	// SkipHandler is an in-process directive set by an AfterVerifyHook that wants
	// the HTTP layer to bypass the resource handler and settle inline. It is never
	// serialized to the facilitator wire.
	SkipHandler *SkipHandlerDirective `json:"-"`
}

VerifyResponse contains the verification result If verification fails, an error (typically *VerifyError) is returned and this will be nil

type VerifyResultContext

type VerifyResultContext struct {
	VerifyContext
	Result *VerifyResponse
}

VerifyResultContext contains verify operation result and context

type X402Client

type X402Client = x402Client

X402Client is the exported type for x402Client

type X402Facilitator

type X402Facilitator = x402Facilitator

X402Facilitator is the exported type for x402Facilitator

type X402ResourceServer

type X402ResourceServer = x402ResourceServer

X402ResourceServer is the exported type for x402ResourceServer

Directories

Path Synopsis
extensions
bazaar
Package bazaar provides the Bazaar Discovery Extension for x402 v2 and v1.
Package bazaar provides the Bazaar Discovery Extension for x402 v2 and v1.
eip2612gassponsor
Package eip2612gassponsor provides types and helpers for the EIP-2612 Gas Sponsoring extension.
Package eip2612gassponsor provides types and helpers for the EIP-2612 Gas Sponsoring extension.
erc20approvalgassponsor
Package erc20approvalgassponsor provides types and helpers for the ERC-20 Approval Gas Sponsoring extension.
Package erc20approvalgassponsor provides types and helpers for the ERC-20 Approval Gas Sponsoring extension.
paymentidentifier
Package paymentidentifier implements the payment-identifier extension for x402.
Package paymentidentifier implements the payment-identifier extension for x402.
v1
THIS FILE IS AUTO-GENERATED - DO NOT EDIT
THIS FILE IS AUTO-GENERATED - DO NOT EDIT
gin
Package mcp provides MCP (Model Context Protocol) transport integration for the x402 payment protocol.
Package mcp provides MCP (Model Context Protocol) transport integration for the x402 payment protocol.
mechanisms
evm
evm/batch-settlement
Package batched holds shared batch-settlement error constants used across client / facilitator / server.
Package batched holds shared batch-settlement error constants used across client / facilitator / server.
evm/batch-settlement/facilitator
Package facilitator emits canonical batch-settlement EVM rejection tokens.
Package facilitator emits canonical batch-settlement EVM rejection tokens.
svm
signers
evm
svm
test

Jump to

Keyboard shortcuts

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