Root

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

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

import "github.com/x402-foundation/x402/go/v2"

Constants

Version constants

Source: constants.go:6

const (
	// Version is the SDK version
	Version = "2.21.0"

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

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

Common error codes

Source: errors.go:18

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"
)

Facilitator error constants

Source: errors.go:32

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"
)

Server error constants

Source: errors.go:43

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

Source: server_hooks.go:96

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"
	// CancellationReasonAfterVerifyAborted indicates an AfterVerifyHook aborted verification
	// after a successful (or recovered) verify, so schemes can clear committed reservations.
	CancellationReasonAfterVerifyAborted VerifiedPaymentCancellationReason = "after_verify_aborted"
)

Functions

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

Source: server_hook_policy.go:96

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( baseline, current []types.PaymentRequirements, extensionKey string, ) error

Source: server_hook_policy.go:48

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(payload, enrichment map[string]interface{}, callerLabel string) error

Source: server_hook_policy.go:190

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

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

Source: server_hook_policy.go:202

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

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

Source: server_hook_policy.go:160

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

func DeepEqual(a, b interface{}) bool

Source: types.go:178

DeepEqual performs deep equality check on payment requirements

func DefaultPaymentSelector(requirements []PaymentRequirementsView) PaymentRequirementsView

Source: types.go:166

DefaultPaymentSelector chooses the first available payment option

func IsVacantStringField(value string) bool

Source: server_hook_policy.go:25

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

func IsWildcardNetwork(network Network) bool

Source: types.go:209

IsWildcardNetwork checks if network is a wildcard pattern

func MatchesNetwork(pattern Network, network Network) bool

Source: types.go:214

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

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

Source: server_hook_policy.go:208

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

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

Source: interfaces.go:180

NewFacilitatorContext creates a FacilitatorContext from the given extensions map.

func NewFacilitatorExtension(key string) FacilitatorExtension

Source: interfaces.go:168

NewFacilitatorExtension creates a FacilitatorExtension with the given key.

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

Source: errors.go:48

NewPaymentError creates a new payment error

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

Source: errors.go:123

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 NewVerifyError(reason string, payer string, message string) *VerifyError

Source: errors.go:84

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 Newx402Client(opts ...ClientOption) *x402Client

Source: client.go:55

Newx402Client creates a new x402 client

func Newx402Facilitator() *x402Facilitator

Source: facilitator.go:39

func Newx402ResourceServer(opts ...ResourceServerOption) *x402ResourceServer

Source: server.go:193

func ParseNetwork(s string) Network

Source: types.go:204

ParseNetwork parses a network string into Network type

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

Source: server.go:28

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(requirements []types.PaymentRequirements) []types.PaymentRequirements

Source: server_hook_policy.go:31

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

func SnapshotSettleResponseCore(result *SettleResponse) SettleResponseCoreSnapshot

Source: server_hook_policy.go:143

SnapshotSettleResponseCore captures facilitator-settled fields.

func ValidatePaymentPayload(p PaymentPayload) error

Source: utils.go:7

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

func ValidatePaymentRequirements(r PaymentRequirements) error

Source: utils.go:33

ValidatePaymentRequirements performs basic validation on payment requirements

func WithAfterPaymentCreationHook(hook AfterPaymentCreationHook) ClientOption

Source: client_hooks.go:88

WithAfterPaymentCreationHook registers a hook to execute after successful payment creation

func WithAfterSettleHook(hook AfterSettleHook) ResourceServerOption

Source: server_hooks.go:244

WithAfterSettleHook registers a hook to execute after successful payment settlement

func WithAfterVerifyHook(hook AfterVerifyHook) ResourceServerOption

Source: server_hooks.go:223

WithAfterVerifyHook registers a hook to execute after successful payment verification

func WithBeforePaymentCreationHook(hook BeforePaymentCreationHook) ClientOption

Source: client_hooks.go:81

WithBeforePaymentCreationHook registers a hook to execute before payment creation

func WithBeforeSettleHook(hook BeforeSettleHook) ResourceServerOption

Source: server_hooks.go:237

WithBeforeSettleHook registers a hook to execute before payment settlement

func WithBeforeVerifyHook(hook BeforeVerifyHook) ResourceServerOption

Source: server_hooks.go:216

WithBeforeVerifyHook registers a hook to execute before payment verification

func WithCacheTTL(ttl time.Duration) ResourceServerOption

Source: server.go:187

WithCacheTTL sets the cache TTL for supported kinds

func WithFacilitatorClient(client FacilitatorClient) ResourceServerOption

Source: server.go:169

WithFacilitatorClient adds a facilitator client

func WithOnPaymentCreationFailureHook(hook OnPaymentCreationFailureHook) ClientOption

Source: client_hooks.go:95

WithOnPaymentCreationFailureHook registers a hook to execute when payment creation fails

func WithOnPaymentResponseHook(hook OnPaymentResponseHook) ClientOption

Source: client_hooks.go:102

WithOnPaymentResponseHook registers a hook to execute after each paid response.

func WithOnSettleFailureHook(hook OnSettleFailureHook) ResourceServerOption

Source: server_hooks.go:251

WithOnSettleFailureHook registers a hook to execute when payment settlement fails

func WithOnVerifiedPaymentCanceledHook(hook OnVerifiedPaymentCanceledHook) ResourceServerOption

Source: server_hooks.go:259

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

func WithOnVerifyFailureHook(hook OnVerifyFailureHook) ResourceServerOption

Source: server_hooks.go:230

WithOnVerifyFailureHook registers a hook to execute when payment verification fails

func WithPaymentSelector(selector PaymentRequirementsSelector) ClientOption

Source: client.go:41

WithPaymentSelector sets a custom payment requirements selector

func WithPolicy(policy PaymentPolicy) ClientOption

Source: client.go:48

WithPolicy registers a payment policy at creation time

func WithSchemeServer(network Network, schemeServer SchemeNetworkServer) ResourceServerOption

Source: server.go:180

WithSchemeServer registers a scheme server implementation (V2, default)

Types

type AfterPaymentCreationHook

Source: client_hooks.go:60

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

type AfterPaymentCreationHook func(PaymentCreatedContext) error

type AfterSettleHook

Source: server_hooks.go:199

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

type AfterSettleHook func(SettleResultContext) error

type AfterSettleHookProvider

Source: server_hooks.go:302

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

type AfterSettleHookProvider interface {
	AfterSettleHook() AfterSettleHook
}
Methods
  • AfterSettleHook func() AfterSettleHook

type AfterVerifyHook

Source: server_hooks.go:185

AfterVerifyHook is called after successful payment verification (including BeforeVerify skip and onVerifyFailure recovery). Any error returned will be logged but will not affect the verification result. Returning an AfterVerifyResult with Abort=true fails verification closed and dispatches after_verify_aborted cancellation. Returning 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 (unless a later hook aborts).

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

type AfterVerifyHookProvider

Source: server_hooks.go:284

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

type AfterVerifyHookProvider interface {
	AfterVerifyHook() AfterVerifyHook
}
Methods
  • AfterVerifyHook func() AfterVerifyHook

type AfterVerifyResult

Source: server_hooks.go:55

AfterVerifyResult is the optional return value of an AfterVerifyHook. When Abort is true, verification fails closed: remaining after-verify hooks are skipped, verified-payment cancellation runs with after_verify_aborted, and VerifyPayment returns an invalid verify error. When SkipHandler is true, the resource handler is bypassed and settlement is performed inline; the optional Response is used to craft the success body. Abort takes precedence over SkipHandler.

type AfterVerifyResult struct {
	Abort       bool
	Reason      string
	Message     string
	SkipHandler bool
	Response    *SkipHandlerDirective
}
Fields
  • Abort bool
  • Reason string
  • Message string
  • SkipHandler bool
  • Response *SkipHandlerDirective

type AssetAmount

Source: types.go:53

AssetAmount represents an amount of a specific asset

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

type AssetDecimalsProvider

Source: interfaces.go:208

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 AssetDecimalsProvider interface {
	GetAssetDecimals(asset string, network Network) int
}
Methods
  • GetAssetDecimals func(asset string, network Network) int

type BeforeHookResult

Source: server_hooks.go:146

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 BeforeHookResult struct {
	Abort            bool
	Reason           string
	Message          string
	Skip             bool
	SkipResult       *SettleResponse
	SkipVerifyResult *VerifyResponse
}
Fields
  • Abort bool
  • Reason string
  • Message string
  • Skip bool
  • SkipResult *SettleResponse
  • SkipVerifyResult *VerifyResponse

type BeforePaymentCreationHook

Source: client_hooks.go:56

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 BeforePaymentCreationHook func(PaymentCreationContext) (*BeforePaymentCreationHookResult, error)

type BeforePaymentCreationHookResult

Source: client_hooks.go:37

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 BeforePaymentCreationHookResult struct {
	Abort  bool
	Reason string
}
Fields
  • Abort bool
  • Reason string

type BeforeSettleHook

Source: server_hooks.go:195

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 BeforeSettleHook func(SettleContext) (*BeforeHookResult, error)

type BeforeSettleHookProvider

Source: server_hooks.go:296

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

type BeforeSettleHookProvider interface {
	BeforeSettleHook() BeforeSettleHook
}
Methods
  • BeforeSettleHook func() BeforeSettleHook

type BeforeVerifyHook

Source: server_hooks.go:175

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 BeforeVerifyHook func(VerifyContext) (*BeforeHookResult, error)

type BeforeVerifyHookProvider

Source: server_hooks.go:278

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

type BeforeVerifyHookProvider interface {
	BeforeVerifyHook() BeforeVerifyHook
}
Methods
  • BeforeVerifyHook func() BeforeVerifyHook

type ClientExtension

Source: interfaces.go:141

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. Optional transport-specific capabilities can be exposed through package-level provider interfaces such as the HTTP client's payment-required hook provider.

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 for every registered
	// extension. Allows the extension to enrich the payload with extension-specific
	// data (e.g., builder-code service codes). Extensions that require a server
	// declaration must no-op when the server did not advertise them.
	EnrichPaymentPayload(ctx context.Context, payload types.PaymentPayload, required types.PaymentRequired) (types.PaymentPayload, error)
}
Methods
  • Key func() string

    Key returns the unique extension identifier (e.g., "eip2612GasSponsoring"). Must match the extension key used in PaymentRequired.Extensions.

  • EnrichPaymentPayload func(ctx context.Context, payload types.PaymentPayload, required types.PaymentRequired) (types.PaymentPayload, error)

    EnrichPaymentPayload is called after payload creation for every registered extension. Allows the extension to enrich the payload with extension-specific data (e.g., builder-code service codes). Extensions that require a server declaration must no-op when the server did not advertise them.

type ClientOption

Source: client.go:38

ClientOption configures the client

type ClientOption func(*x402Client)

type EnrichSettlementPayloadProvider

Source: server_hooks.go:335

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 EnrichSettlementPayloadProvider interface {
	EnrichSettlementPayload(ctx SettleContext) (map[string]interface{}, error)
}
Methods
  • EnrichSettlementPayload func(ctx SettleContext) (map[string]interface{}, error)

type EnrichSettlementResponseProvider

Source: server_hooks.go:344

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 EnrichSettlementResponseProvider interface {
	EnrichSettlementResponse(ctx SettleResultContext) (map[string]interface{}, error)
}
Methods
  • EnrichSettlementResponse func(ctx SettleResultContext) (map[string]interface{}, error)

type ExtensionAwareClient

Source: interfaces.go:96

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 ExtensionAwareClient interface {
	SchemeNetworkClient
	CreatePaymentPayloadWithExtensions(ctx context.Context, requirements types.PaymentRequirements, extensions map[string]interface{}) (types.PaymentPayload, error)
}
Methods
  • SchemeNetworkClient
  • CreatePaymentPayloadWithExtensions func(ctx context.Context, requirements types.PaymentRequirements, extensions map[string]interface{}) (types.PaymentPayload, error)

type ExtensionValidationResult

Source: server.go:738

ExtensionValidationResult is returned by ValidateExtensions. Valid is true when the client either omitted extensions or echoed every server-advertised field; otherwise InvalidReason/ExtensionKey describe the mismatch.

type ExtensionValidationResult struct {
	Valid         bool
	InvalidReason string
	ExtensionKey  string
}
Fields
  • Valid bool
  • InvalidReason string
  • ExtensionKey string

type FacilitatorAfterSettleHook

Source: facilitator_hooks.go:107

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

type FacilitatorAfterSettleHook func(FacilitatorSettleResultContext) error

type FacilitatorAfterVerifyHook

Source: facilitator_hooks.go:93

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

type FacilitatorAfterVerifyHook func(FacilitatorVerifyResultContext) error

type FacilitatorBeforeHookResult

Source: facilitator_hooks.go:63

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

type FacilitatorBeforeHookResult struct {
	Abort   bool
	Reason  string
	Message string
}
Fields
  • Abort bool
  • Reason string
  • Message string

type FacilitatorBeforeSettleHook

Source: facilitator_hooks.go:103

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 FacilitatorBeforeSettleHook func(FacilitatorSettleContext) (*FacilitatorBeforeHookResult, error)

type FacilitatorBeforeVerifyHook

Source: facilitator_hooks.go:89

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 FacilitatorBeforeVerifyHook func(FacilitatorVerifyContext) (*FacilitatorBeforeHookResult, error)

type FacilitatorClient

Source: interfaces.go:292

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 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)
}
Methods
  • Verify func(ctx context.Context, payloadBytes []byte, requirementsBytes []byte) (*VerifyResponse, error)

    Verify a payment (detects version from bytes, routes internally)

  • Settle func(ctx context.Context, payloadBytes []byte, requirementsBytes []byte) (*SettleResponse, error)

    Settle a payment (detects version from bytes, routes internally)

  • GetSupported func(ctx context.Context) (SupportedResponse, error)

    GetSupported returns supported payment kinds in flat array format with x402Version in each element (backward compatible)

type FacilitatorContext

Source: interfaces.go:175

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

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

func GetExtension(key string) FacilitatorExtension

Source: interfaces.go:185

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

type FacilitatorExtension

Source: interfaces.go:156

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).

type FacilitatorExtension interface {
	Key() string
}
Methods
  • Key func() string

type FacilitatorOnSettleFailureHook

Source: facilitator_hooks.go:112

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 FacilitatorOnSettleFailureHook func(FacilitatorSettleFailureContext) (*FacilitatorSettleFailureHookResult, error)

type FacilitatorOnVerifyFailureHook

Source: facilitator_hooks.go:98

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 FacilitatorOnVerifyFailureHook func(FacilitatorVerifyFailureContext) (*FacilitatorVerifyFailureHookResult, error)

type FacilitatorSettleContext

Source: facilitator_hooks.go:37

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 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
}
Fields
  • 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

type FacilitatorSettleFailureContext

Source: facilitator_hooks.go:52

FacilitatorSettleFailureContext contains facilitator settle operation failure and context

type FacilitatorSettleFailureContext struct {
	FacilitatorSettleContext
	Error error
}
Fields
  • FacilitatorSettleContext
  • Error error

type FacilitatorSettleFailureHookResult

Source: facilitator_hooks.go:77

FacilitatorSettleFailureHookResult represents the result of a facilitator settle failure hook

type FacilitatorSettleFailureHookResult struct {
	Recovered bool
	Result    *SettleResponse
}
Fields
  • Recovered bool
  • Result *SettleResponse

type FacilitatorSettleResultContext

Source: facilitator_hooks.go:46

FacilitatorSettleResultContext contains facilitator settle operation result and context

type FacilitatorSettleResultContext struct {
	FacilitatorSettleContext
	Result *SettleResponse
}
Fields
  • FacilitatorSettleContext
  • Result *SettleResponse

type FacilitatorSupportValidator

Source: interfaces.go:235

FacilitatorSupportValidator is an optional interface that SchemeNetworkServer implementations can satisfy to validate facilitator capabilities at startup. Invoked during Initialize(), only when the facilitator supports the scheme/network. Returns a non-nil error describing the problem when the configuration cannot be fulfilled, or nil when valid.

type FacilitatorSupportValidator interface {
	ValidateFacilitatorSupport(network Network, supportedKind types.SupportedKind, facilitatorExtensions []string) error
}
Methods
  • ValidateFacilitatorSupport func(network Network, supportedKind types.SupportedKind, facilitatorExtensions []string) error

type FacilitatorVerifyContext

Source: facilitator_hooks.go:14

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 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
}
Fields
  • 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

type FacilitatorVerifyFailureContext

Source: facilitator_hooks.go:29

FacilitatorVerifyFailureContext contains facilitator verify operation failure and context

type FacilitatorVerifyFailureContext struct {
	FacilitatorVerifyContext
	Error error
}
Fields
  • FacilitatorVerifyContext
  • Error error

type FacilitatorVerifyFailureHookResult

Source: facilitator_hooks.go:71

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 FacilitatorVerifyFailureHookResult struct {
	Recovered bool
	Result    *VerifyResponse
}
Fields
  • Recovered bool
  • Result *VerifyResponse

type FacilitatorVerifyResultContext

Source: facilitator_hooks.go:23

FacilitatorVerifyResultContext contains facilitator verify operation result and context

type FacilitatorVerifyResultContext struct {
	FacilitatorVerifyContext
	Result *VerifyResponse
}
Fields
  • FacilitatorVerifyContext
  • Result *VerifyResponse

type MoneyParser

Source: interfaces.go:22

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 MoneyParser func(amount float64, network Network) (*AssetAmount, error)

type Network

Source: types.go:13

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

type Network string

func Match(pattern Network) bool

Source: types.go:26

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

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

Source: types.go:16

Parse splits the network into namespace and reference components

type OnPaymentCreationFailureHook

Source: client_hooks.go:65

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 OnPaymentCreationFailureHook func(PaymentCreationFailureContext) (*PaymentCreationFailureHookResult, error)

type OnPaymentResponseHook

Source: client_hooks.go:74

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 OnPaymentResponseHook func(context.Context, PaymentResponseContext) (PaymentResponseResult, error)

type OnSettleFailureHook

Source: server_hooks.go:204

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 OnSettleFailureHook func(SettleFailureContext) (*SettleFailureHookResult, error)

type OnSettleFailureHookProvider

Source: server_hooks.go:308

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

type OnSettleFailureHookProvider interface {
	OnSettleFailureHook() OnSettleFailureHook
}
Methods
  • OnSettleFailureHook func() OnSettleFailureHook

type OnVerifiedPaymentCanceledHook

Source: server_hooks.go:209

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 OnVerifiedPaymentCanceledHook func(VerifiedPaymentCanceledContext) error

type OnVerifiedPaymentCanceledHookProvider

Source: server_hooks.go:314

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

type OnVerifiedPaymentCanceledHookProvider interface {
	OnVerifiedPaymentCanceledHook() OnVerifiedPaymentCanceledHook
}
Methods
  • OnVerifiedPaymentCanceledHook func() OnVerifiedPaymentCanceledHook

type OnVerifyFailureHook

Source: server_hooks.go:190

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 OnVerifyFailureHook func(VerifyFailureContext) (*VerifyFailureHookResult, error)

type OnVerifyFailureHookProvider

Source: server_hooks.go:290

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

type OnVerifyFailureHookProvider interface {
	OnVerifyFailureHook() OnVerifyFailureHook
}
Methods
  • OnVerifyFailureHook func() OnVerifyFailureHook

type PartialPaymentPayload

Source: types.go:61

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

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

type PaymentCancellationDispatcher

Source: server_hooks.go:122

PaymentCancellationDispatcher fires onVerifiedPaymentCanceled hooks at most once.

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

func CancellationDispatcher) Cancel(opts VerifiedPaymentCancelOptions)

Source: server_hooks.go:128

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

type PaymentCreatedContext

Source: client_hooks.go:20

PaymentCreatedContext contains payment creation result and context

type PaymentCreatedContext struct {
	PaymentCreationContext
	Payload PaymentPayloadView
}
Fields
  • PaymentCreationContext
  • Payload PaymentPayloadView

type PaymentCreationContext

Source: client_hooks.go:13

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

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

    V1 or V2

  • SelectedRequirements PaymentRequirementsView

type PaymentCreationFailureContext

Source: client_hooks.go:26

PaymentCreationFailureContext contains payment creation failure and context

type PaymentCreationFailureContext struct {
	PaymentCreationContext
	Error error
}
Fields
  • PaymentCreationContext
  • Error error

type PaymentCreationFailureHookResult

Source: client_hooks.go:44

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 PaymentCreationFailureHookResult struct {
	Recovered bool
	Payload   PaymentPayloadView
}
Fields
  • Recovered bool
  • Payload PaymentPayloadView

type PaymentError

Source: errors.go:6

PaymentError represents a payment-specific error

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

func Error) Error() string

Source: errors.go:12

type PaymentPayload

Source: types.go:69

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

type PaymentPayload = types.PaymentPayload

type PaymentPayloadView

Source: types.go:150

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

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

    Returns network as string (can be converted to Network type)

  • GetPayload func() map[string]interface{}

type PaymentPolicy

Source: types.go:163

PaymentPolicy filters or transforms payment requirements Works with unified view interface

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

type PaymentRequired

Source: types.go:70

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

type PaymentRequired = types.PaymentRequired

type PaymentRequiredContext

Source: interfaces.go:214

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

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

type PaymentRequiredEnricher

Source: interfaces.go:226

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 PaymentRequiredEnricher interface {
	EnrichPaymentRequiredResponse(ctx PaymentRequiredContext)
}
Methods
  • EnrichPaymentRequiredResponse func(ctx PaymentRequiredContext)

type PaymentRequirements

Source: types.go:68

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

type PaymentRequirements = types.PaymentRequirements

type PaymentRequirementsSelector

Source: types.go:159

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

type PaymentRequirementsSelector func(requirements []PaymentRequirementsView) PaymentRequirementsView

type PaymentRequirementsView

Source: types.go:138

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

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{}
}
Methods
  • GetScheme func() string
  • GetNetwork func() string

    Returns network as string (can be converted to Network type)

  • GetAsset func() string
  • GetAmount func() string

    V1: MaxAmountRequired, V2: Amount

  • GetPayTo func() string
  • GetMaxTimeoutSeconds func() int
  • GetExtra func() map[string]interface{}

type PaymentResponseContext

Source: interfaces.go:111

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 PaymentResponseContext struct {
	PaymentPayload  types.PaymentPayload
	Requirements    types.PaymentRequirements
	SettleResponse  *SettleResponse
	PaymentRequired *types.PaymentRequired
}
Fields
  • PaymentPayload types.PaymentPayload
  • Requirements types.PaymentRequirements
  • SettleResponse *SettleResponse
  • PaymentRequired *types.PaymentRequired

type PaymentResponseHandler

Source: interfaces.go:132

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 PaymentResponseHandler interface {
	OnPaymentResponse(ctx context.Context, prCtx PaymentResponseContext) (PaymentResponseResult, error)
}
Methods
  • OnPaymentResponse func(ctx context.Context, prCtx PaymentResponseContext) (PaymentResponseResult, error)

type PaymentResponseResult

Source: interfaces.go:122

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 PaymentResponseResult struct {
	Recovered bool
}
Fields
  • Recovered bool

type Price

Source: types.go:50

Price represents a price that can be specified in various formats

type Price interface{}

type ResourceConfig

Source: types.go:123

ResourceConfig defines payment configuration for a protected resource

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"`
}
Fields
  • 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"`

type ResourceInfo

Source: types.go:71

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

type ResourceInfo = types.ResourceInfo

type ResourceServerExtensionDynamicInfoFieldsProvider

Source: server_hooks.go:372

ResourceServerExtensionDynamicInfoFieldsProvider lets an extension declare the names of fields under its info that are dynamic - regenerated on every PaymentRequired response (e.g. nonces, timestamps) rather than static committed terms. Dynamic fields are excluded from client echo validation.

type ResourceServerExtensionDynamicInfoFieldsProvider interface {
	DynamicInfoFields() []string
}
Methods
  • DynamicInfoFields func() []string

type ResourceServerExtensionHookProvider

Source: server_hooks.go:364

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 ResourceServerExtensionHookProvider interface {
	ResourceServerExtensionHooks() ResourceServerExtensionHooks
}
Methods
  • ResourceServerExtensionHooks func() ResourceServerExtensionHooks

type ResourceServerExtensionHooks

Source: server_hooks.go:379

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 ResourceServerExtensionHooks struct {
	OnBeforeVerify            BeforeVerifyHook
	OnAfterVerify             AfterVerifyHook
	OnVerifyFailure           OnVerifyFailureHook
	OnBeforeSettle            BeforeSettleHook
	OnAfterSettle             AfterSettleHook
	OnSettleFailure           OnSettleFailureHook
	OnVerifiedPaymentCanceled OnVerifiedPaymentCanceledHook
}
Fields
  • OnBeforeVerify BeforeVerifyHook
  • OnAfterVerify AfterVerifyHook
  • OnVerifyFailure OnVerifyFailureHook
  • OnBeforeSettle BeforeSettleHook
  • OnAfterSettle AfterSettleHook
  • OnSettleFailure OnSettleFailureHook
  • OnVerifiedPaymentCanceled OnVerifiedPaymentCanceledHook

type ResourceServerOption

Source: server.go:166

ResourceServerOption configures the server

type ResourceServerOption func(*x402ResourceServer)

type SchemeNetworkClient

Source: interfaces.go:87

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

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

type SchemeNetworkClientV1

Source: interfaces.go:29

SchemeNetworkClientV1 is implemented by client-side V1 payment mechanisms

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

type SchemeNetworkFacilitator

Source: interfaces.go:240

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

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)
}
Methods
  • Scheme func() string
  • CaipFamily func() 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:*"
  • GetExtra func(network Network) map[string]interface{}

    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

  • GetSigners func(network Network) []string

    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
  • Verify func(ctx context.Context, payload types.PaymentPayload, requirements types.PaymentRequirements, fctx *FacilitatorContext) (*VerifyResponse, error)
  • Settle func(ctx context.Context, payload types.PaymentPayload, requirements types.PaymentRequirements, fctx *FacilitatorContext) (*SettleResponse, error)

type SchemeNetworkFacilitatorV1

Source: interfaces.go:35

SchemeNetworkFacilitatorV1 is implemented by facilitator-side V1 payment mechanisms

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)
}
Methods
  • Scheme func() string
  • CaipFamily func() 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:*"
  • GetExtra func(network Network) map[string]interface{}

    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

  • GetSigners func(network Network) []string

    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
  • Verify func(ctx context.Context, payload types.PaymentPayloadV1, requirements types.PaymentRequirementsV1, fctx *FacilitatorContext) (*VerifyResponse, error)
  • Settle func(ctx context.Context, payload types.PaymentPayloadV1, requirements types.PaymentRequirementsV1, fctx *FacilitatorContext) (*SettleResponse, error)

type SchemeNetworkServer

Source: interfaces.go:193

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

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)
}
Methods
  • Scheme func() string
  • ParsePrice func(price Price, network Network) (AssetAmount, error)
  • EnhancePaymentRequirements func( ctx context.Context, requirements types.PaymentRequirements, supportedKind types.SupportedKind, extensions []string, ) (types.PaymentRequirements, error)

type SettleContext

Source: server_hooks.go:66

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 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
}
Fields
  • Ctx context.Context
  • Payload PaymentPayloadView
  • Requirements PaymentRequirementsView
  • DeclaredExtensions map[string]interface{}

    DeclaredExtensions carries the extension declarations attached to the route. Extension hooks gate on DeclaredExtensions[extKey] being set before firing - mirrors TS ctx.declaredExtensions[extensionKey].

  • PayloadBytes []byte

    Raw bytes for extensions needing full data

  • RequirementsBytes []byte

    Raw bytes for extensions needing full data

type SettleError

Source: errors.go:94

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

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
}
Fields
  • 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

func Error) Error() string

Source: errors.go:103

Error implements the error interface

type SettleFailureContext

Source: server_hooks.go:85

SettleFailureContext contains settle operation failure and context

type SettleFailureContext struct {
	SettleContext
	Error error
}
Fields
  • SettleContext
  • Error error

type SettleFailureHookResult

Source: server_hooks.go:163

SettleFailureHookResult represents the result of a settle failure hook

type SettleFailureHookResult struct {
	Recovered bool
	Result    *SettleResponse
}
Fields
  • Recovered bool
  • Result *SettleResponse

type SettleResponse

Source: types.go:99

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

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"`
}
Fields
  • 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"`

type SettleResponseCoreSnapshot

Source: server_hook_policy.go:132

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

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

type SettleResultContext

Source: server_hooks.go:79

SettleResultContext contains settle operation result and context

type SettleResultContext struct {
	SettleContext
	Result *SettleResponse
}
Fields
  • SettleContext
  • Result *SettleResponse

type SettlementOverrides

Source: types.go:113

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

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"`
}
Fields
  • Amount string `json:"amount,omitempty"`

    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.

type SkipHandlerDirective

Source: server_hooks.go:43

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 SkipHandlerDirective struct {
	ContentType string
	Body        interface{}
}
Fields
  • ContentType string
  • Body interface{}

type SupportedCache

Source: server.go:123

SupportedCache caches facilitator capabilities

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

func Clear()

Source: server.go:157

Clear removes all cached supported responses and expiry entries

func Get(key string) (SupportedResponse, bool)

Source: server.go:139

Get retrieves a supported response from the cache

func Set(key string, response SupportedResponse)

Source: server.go:131

Set stores a supported response in the cache

type SupportedKind

Source: types.go:72

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

type SupportedKind = types.SupportedKind

type SupportedResponse

Source: types.go:73

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 = types.SupportedResponse

type SupportedResponseV1

Source: types.go:78

Re-export V1 types for legacy facilitator support

type SupportedResponseV1 = types.SupportedResponseV1

type VerifiedPaymentCancelOptions

Source: server_hooks.go:115

VerifiedPaymentCancelOptions describes a single cancellation event.

type VerifiedPaymentCancelOptions struct {
	Reason         VerifiedPaymentCancellationReason
	Err            error
	ResponseStatus int
}
Fields
  • Reason VerifiedPaymentCancellationReason
  • Err error
  • ResponseStatus int

type VerifiedPaymentCanceledContext

Source: server_hooks.go:107

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

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

type VerifiedPaymentCancellationReason

Source: server_hooks.go:92

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

type VerifiedPaymentCancellationReason string

type VerifyContext

Source: server_hooks.go:15

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 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
}
Fields
  • Ctx context.Context
  • Payload PaymentPayloadView
  • Requirements PaymentRequirementsView
  • DeclaredExtensions map[string]interface{}

    DeclaredExtensions carries the extension declarations attached to the route. Extension hooks gate on DeclaredExtensions[extKey] being set before firing - mirrors TS ctx.declaredExtensions[extensionKey].

  • PayloadBytes []byte

    Raw bytes for extensions needing full data

  • RequirementsBytes []byte

    Raw bytes for extensions needing full data

type VerifyError

Source: errors.go:58

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

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
}
Fields
  • InvalidReason string

    Error reason/code (e.g., "insufficient_balance", "invalid_signature")

  • Payer string

    Payer address (if known)

  • InvalidMessage string

    Optional invalid message details

func Error) Error() string

Source: errors.go:65

Error implements the error interface

type VerifyFailureContext

Source: server_hooks.go:34

VerifyFailureContext contains verify operation failure and context

type VerifyFailureContext struct {
	VerifyContext
	Error error
}
Fields
  • VerifyContext
  • Error error

type VerifyFailureHookResult

Source: server_hooks.go:157

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 VerifyFailureHookResult struct {
	Recovered bool
	Result    *VerifyResponse
}
Fields
  • Recovered bool
  • Result *VerifyResponse

type VerifyResponse

Source: types.go:83

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

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:"-"`
}
Fields
  • 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 *SkipHandlerDirective `json:"-"`

    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.

type VerifyResultContext

Source: server_hooks.go:28

VerifyResultContext contains verify operation result and context

type VerifyResultContext struct {
	VerifyContext
	Result *VerifyResponse
}
Fields
  • VerifyContext
  • Result *VerifyResponse

type X402Client

Source: constants.go:18

X402Client is the exported type for x402Client

type X402Client = x402Client

type X402Facilitator

Source: constants.go:24

X402Facilitator is the exported type for x402Facilitator

type X402Facilitator = x402Facilitator

type X402ResourceServer

Source: constants.go:21

X402ResourceServer is the exported type for x402ResourceServer

type X402ResourceServer = x402ResourceServer