solana-pay-kit 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- solana_pay_kit/__init__.py +135 -0
- solana_pay_kit/_middleware.py +417 -0
- solana_pay_kit/_paycore/__init__.py +48 -0
- solana_pay_kit/_paycore/currency.py +82 -0
- solana_pay_kit/_paycore/errors.py +178 -0
- solana_pay_kit/_paycore/mints.py +80 -0
- solana_pay_kit/_paycore/network.py +67 -0
- solana_pay_kit/_paycore/network_check.py +55 -0
- solana_pay_kit/_paycore/paymentchannels.py +554 -0
- solana_pay_kit/_paycore/protocol.py +19 -0
- solana_pay_kit/_paycore/rpc.py +204 -0
- solana_pay_kit/_paycore/solana.py +406 -0
- solana_pay_kit/_paycore/stablecoin.py +17 -0
- solana_pay_kit/_paycore/store.py +189 -0
- solana_pay_kit/_paycore/transaction.py +52 -0
- solana_pay_kit/config.py +433 -0
- solana_pay_kit/django.py +369 -0
- solana_pay_kit/errors.py +94 -0
- solana_pay_kit/fastapi.py +389 -0
- solana_pay_kit/fee.py +43 -0
- solana_pay_kit/flask.py +292 -0
- solana_pay_kit/gate.py +332 -0
- solana_pay_kit/kms.py +40 -0
- solana_pay_kit/operator.py +81 -0
- solana_pay_kit/payment.py +28 -0
- solana_pay_kit/preflight.py +226 -0
- solana_pay_kit/price.py +127 -0
- solana_pay_kit/pricing.py +123 -0
- solana_pay_kit/protocols/__init__.py +7 -0
- solana_pay_kit/protocols/mpp/__init__.py +426 -0
- solana_pay_kit/protocols/mpp/_paymentchannels.py +51 -0
- solana_pay_kit/protocols/mpp/client/__init__.py +86 -0
- solana_pay_kit/protocols/mpp/client/charge.py +424 -0
- solana_pay_kit/protocols/mpp/client/http_stream.py +371 -0
- solana_pay_kit/protocols/mpp/client/payment_channels.py +491 -0
- solana_pay_kit/protocols/mpp/client/session.py +447 -0
- solana_pay_kit/protocols/mpp/client/session_consumer.py +153 -0
- solana_pay_kit/protocols/mpp/client/transport.py +90 -0
- solana_pay_kit/protocols/mpp/core/__init__.py +3 -0
- solana_pay_kit/protocols/mpp/core/base64url.py +40 -0
- solana_pay_kit/protocols/mpp/core/challenge.py +32 -0
- solana_pay_kit/protocols/mpp/core/expires.py +35 -0
- solana_pay_kit/protocols/mpp/core/headers.py +411 -0
- solana_pay_kit/protocols/mpp/core/json.py +200 -0
- solana_pay_kit/protocols/mpp/core/types.py +204 -0
- solana_pay_kit/protocols/mpp/intents/__init__.py +69 -0
- solana_pay_kit/protocols/mpp/intents/charge.py +67 -0
- solana_pay_kit/protocols/mpp/intents/session.py +997 -0
- solana_pay_kit/protocols/mpp/server/__init__.py +76 -0
- solana_pay_kit/protocols/mpp/server/_tx_decode.py +545 -0
- solana_pay_kit/protocols/mpp/server/_verify.py +666 -0
- solana_pay_kit/protocols/mpp/server/charge.py +678 -0
- solana_pay_kit/protocols/mpp/server/defaults.py +39 -0
- solana_pay_kit/protocols/mpp/server/html/__init__.py +3 -0
- solana_pay_kit/protocols/mpp/server/html/service_worker.gen.js +1 -0
- solana_pay_kit/protocols/mpp/server/html/template.gen.html +173 -0
- solana_pay_kit/protocols/mpp/server/middleware.py +83 -0
- solana_pay_kit/protocols/mpp/server/payment_page.py +139 -0
- solana_pay_kit/protocols/mpp/server/session.py +743 -0
- solana_pay_kit/protocols/mpp/server/session_lifecycle.py +106 -0
- solana_pay_kit/protocols/mpp/server/session_method.py +940 -0
- solana_pay_kit/protocols/mpp/server/session_onchain.py +578 -0
- solana_pay_kit/protocols/mpp/server/session_routes.py +218 -0
- solana_pay_kit/protocols/mpp/server/session_store.py +382 -0
- solana_pay_kit/protocols/mpp/server/session_stream.py +136 -0
- solana_pay_kit/protocols/mpp/server/session_voucher.py +379 -0
- solana_pay_kit/protocols/programs/__init__.py +7 -0
- solana_pay_kit/protocols/programs/paymentchannels/__init__.py +7 -0
- solana_pay_kit/protocols/programs/paymentchannels/accounts/__init__.py +11 -0
- solana_pay_kit/protocols/programs/paymentchannels/accounts/channel.py +194 -0
- solana_pay_kit/protocols/programs/paymentchannels/accounts/closedChannel.py +88 -0
- solana_pay_kit/protocols/programs/paymentchannels/errors/__init__.py +23 -0
- solana_pay_kit/protocols/programs/paymentchannels/errors/paymentChannels.py +693 -0
- solana_pay_kit/protocols/programs/paymentchannels/instructions/__init__.py +8 -0
- solana_pay_kit/protocols/programs/paymentchannels/instructions/distribute.py +81 -0
- solana_pay_kit/protocols/programs/paymentchannels/instructions/emitEvent.py +46 -0
- solana_pay_kit/protocols/programs/paymentchannels/instructions/finalize.py +34 -0
- solana_pay_kit/protocols/programs/paymentchannels/instructions/open.py +89 -0
- solana_pay_kit/protocols/programs/paymentchannels/instructions/requestClose.py +36 -0
- solana_pay_kit/protocols/programs/paymentchannels/instructions/settle.py +36 -0
- solana_pay_kit/protocols/programs/paymentchannels/instructions/settleAndFinalize.py +51 -0
- solana_pay_kit/protocols/programs/paymentchannels/instructions/topUp.py +57 -0
- solana_pay_kit/protocols/programs/paymentchannels/instructions/withdrawPayer.py +44 -0
- solana_pay_kit/protocols/programs/paymentchannels/pdas/index.py +25 -0
- solana_pay_kit/protocols/programs/paymentchannels/program_id.py +11 -0
- solana_pay_kit/protocols/programs/paymentchannels/shared/__init__.py +8 -0
- solana_pay_kit/protocols/programs/paymentchannels/shared/extension.py +280 -0
- solana_pay_kit/protocols/programs/paymentchannels/types/__init__.py +33 -0
- solana_pay_kit/protocols/programs/paymentchannels/types/accountDiscriminator.py +87 -0
- solana_pay_kit/protocols/programs/paymentchannels/types/channelStatus.py +115 -0
- solana_pay_kit/protocols/programs/paymentchannels/types/distributeArgs.py +51 -0
- solana_pay_kit/protocols/programs/paymentchannels/types/distributionEntry.py +59 -0
- solana_pay_kit/protocols/programs/paymentchannels/types/openArgs.py +72 -0
- solana_pay_kit/protocols/programs/paymentchannels/types/opened.py +52 -0
- solana_pay_kit/protocols/programs/paymentchannels/types/payoutBeneficiary.py +115 -0
- solana_pay_kit/protocols/programs/paymentchannels/types/payoutRedirected.py +81 -0
- solana_pay_kit/protocols/programs/paymentchannels/types/redirectReason.py +143 -0
- solana_pay_kit/protocols/programs/paymentchannels/types/settleAndFinalizeArgs.py +50 -0
- solana_pay_kit/protocols/programs/paymentchannels/types/settlementWatermarks.py +57 -0
- solana_pay_kit/protocols/programs/paymentchannels/types/topUpArgs.py +50 -0
- solana_pay_kit/protocols/programs/paymentchannels/types/voucherArgs.py +66 -0
- solana_pay_kit/protocols/x402/__init__.py +545 -0
- solana_pay_kit/protocols/x402/client/__init__.py +28 -0
- solana_pay_kit/protocols/x402/client/exact/__init__.py +29 -0
- solana_pay_kit/protocols/x402/client/exact/payment.py +728 -0
- solana_pay_kit/protocols/x402/client/exact/transport.py +141 -0
- solana_pay_kit/protocols/x402/client/upto/__init__.py +21 -0
- solana_pay_kit/protocols/x402/client/upto/payment.py +199 -0
- solana_pay_kit/protocols/x402/exact/__init__.py +1 -0
- solana_pay_kit/protocols/x402/exact/extensions.py +185 -0
- solana_pay_kit/protocols/x402/exact/legacy.py +89 -0
- solana_pay_kit/protocols/x402/exact/types.py +113 -0
- solana_pay_kit/protocols/x402/exact/verify.py +348 -0
- solana_pay_kit/protocols/x402/upto/__init__.py +624 -0
- solana_pay_kit/protocols/x402/upto/types.py +154 -0
- solana_pay_kit/protocols/x402/upto/verify.py +187 -0
- solana_pay_kit/signer.py +364 -0
- solana_pay_kit/usage.py +182 -0
- solana_pay_kit-0.1.0.dist-info/METADATA +542 -0
- solana_pay_kit-0.1.0.dist-info/RECORD +121 -0
- solana_pay_kit-0.1.0.dist-info/WHEEL +4 -0
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
"""solana_pay_kit: unified payment surface over x402 and MPP on Solana.
|
|
2
|
+
|
|
3
|
+
Public entry point. Configure once with :func:`configure`, declare priced
|
|
4
|
+
routes with :class:`Gate` (or the :func:`gate` dynamic factory), and guard
|
|
5
|
+
handlers with the framework-agnostic trio :func:`require_payment`,
|
|
6
|
+
:func:`is_paid`, and :func:`payment`. Framework shims live in optional
|
|
7
|
+
submodules (``solana_pay_kit.fastapi``, ``solana_pay_kit.flask``, ``solana_pay_kit.django``) and are
|
|
8
|
+
imported on demand so the base install carries no web-framework dependency.
|
|
9
|
+
|
|
10
|
+
This package ships alongside :mod:`solana_pay_kit.protocols.mpp`, whose wire internals it reuses
|
|
11
|
+
rather than reimplements.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
from decimal import Decimal
|
|
17
|
+
|
|
18
|
+
from solana_pay_kit import errors, kms
|
|
19
|
+
from solana_pay_kit._middleware import (
|
|
20
|
+
PayCore,
|
|
21
|
+
is_paid,
|
|
22
|
+
is_paid_for,
|
|
23
|
+
payment,
|
|
24
|
+
require_payment,
|
|
25
|
+
)
|
|
26
|
+
from solana_pay_kit._paycore.currency import Currency
|
|
27
|
+
from solana_pay_kit._paycore.network import Network
|
|
28
|
+
from solana_pay_kit._paycore.protocol import Protocol
|
|
29
|
+
from solana_pay_kit._paycore.stablecoin import Stablecoin
|
|
30
|
+
from solana_pay_kit._paycore.store import FileReplayStore, MemoryStore, Store
|
|
31
|
+
from solana_pay_kit.config import (
|
|
32
|
+
Config,
|
|
33
|
+
MppConfig,
|
|
34
|
+
X402Config,
|
|
35
|
+
config,
|
|
36
|
+
configure,
|
|
37
|
+
configure_from,
|
|
38
|
+
reset,
|
|
39
|
+
)
|
|
40
|
+
from solana_pay_kit.errors import (
|
|
41
|
+
ChallengeExpiredError,
|
|
42
|
+
ConfigurationError,
|
|
43
|
+
DemoSignerOnMainnetError,
|
|
44
|
+
InvalidKeyError,
|
|
45
|
+
InvalidProofError,
|
|
46
|
+
MixedCurrenciesError,
|
|
47
|
+
PayKitError,
|
|
48
|
+
PaymentRequiredError,
|
|
49
|
+
ProtocolIncompatibleError,
|
|
50
|
+
ProtocolNotSupportedError,
|
|
51
|
+
)
|
|
52
|
+
from solana_pay_kit.fee import Fee
|
|
53
|
+
from solana_pay_kit.gate import Gate
|
|
54
|
+
from solana_pay_kit.gate import dynamic as gate
|
|
55
|
+
from solana_pay_kit.operator import Operator
|
|
56
|
+
from solana_pay_kit.payment import Payment
|
|
57
|
+
from solana_pay_kit.price import Price
|
|
58
|
+
from solana_pay_kit.pricing import Pricing
|
|
59
|
+
from solana_pay_kit.protocols.mpp.core.expires import days, hours, minutes, seconds, weeks
|
|
60
|
+
from solana_pay_kit.signer import LocalSigner, Signer
|
|
61
|
+
|
|
62
|
+
__all__ = [
|
|
63
|
+
# enums / paycore
|
|
64
|
+
"Protocol",
|
|
65
|
+
"Currency",
|
|
66
|
+
"Network",
|
|
67
|
+
"Stablecoin",
|
|
68
|
+
# value objects
|
|
69
|
+
"Price",
|
|
70
|
+
"Fee",
|
|
71
|
+
"Gate",
|
|
72
|
+
"gate",
|
|
73
|
+
"Operator",
|
|
74
|
+
"Pricing",
|
|
75
|
+
"usd",
|
|
76
|
+
"eur",
|
|
77
|
+
"gbp",
|
|
78
|
+
# signer
|
|
79
|
+
"Signer",
|
|
80
|
+
"LocalSigner",
|
|
81
|
+
"InvalidKeyError",
|
|
82
|
+
"kms",
|
|
83
|
+
# config
|
|
84
|
+
"Config",
|
|
85
|
+
"X402Config",
|
|
86
|
+
"MppConfig",
|
|
87
|
+
"configure",
|
|
88
|
+
"configure_from",
|
|
89
|
+
"config",
|
|
90
|
+
"reset",
|
|
91
|
+
# payment + store
|
|
92
|
+
"Payment",
|
|
93
|
+
"Store",
|
|
94
|
+
"MemoryStore",
|
|
95
|
+
"FileReplayStore",
|
|
96
|
+
# middleware trio (framework-agnostic)
|
|
97
|
+
"require_payment",
|
|
98
|
+
"is_paid",
|
|
99
|
+
"is_paid_for",
|
|
100
|
+
"payment",
|
|
101
|
+
# framework-agnostic umbrella core
|
|
102
|
+
"PayCore",
|
|
103
|
+
# errors
|
|
104
|
+
"errors",
|
|
105
|
+
"PayKitError",
|
|
106
|
+
"ConfigurationError",
|
|
107
|
+
"DemoSignerOnMainnetError",
|
|
108
|
+
"MixedCurrenciesError",
|
|
109
|
+
"ProtocolIncompatibleError",
|
|
110
|
+
"InvalidProofError",
|
|
111
|
+
"ChallengeExpiredError",
|
|
112
|
+
"PaymentRequiredError",
|
|
113
|
+
"ProtocolNotSupportedError",
|
|
114
|
+
# expiry helpers (re-exported from solana_pay_kit.protocols.mpp)
|
|
115
|
+
"seconds",
|
|
116
|
+
"minutes",
|
|
117
|
+
"hours",
|
|
118
|
+
"days",
|
|
119
|
+
"weeks",
|
|
120
|
+
]
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def usd(amount: str | int | Decimal, *settlements: Stablecoin) -> Price:
|
|
124
|
+
"""Build a USD-denominated :class:`Price` (top-level shorthand)."""
|
|
125
|
+
return Price.usd(amount, *settlements)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def eur(amount: str | int | Decimal, *settlements: Stablecoin) -> Price:
|
|
129
|
+
"""Build a EUR-denominated :class:`Price` (top-level shorthand)."""
|
|
130
|
+
return Price.eur(amount, *settlements)
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def gbp(amount: str | int | Decimal, *settlements: Stablecoin) -> Price:
|
|
134
|
+
"""Build a GBP-denominated :class:`Price` (top-level shorthand)."""
|
|
135
|
+
return Price.gbp(amount, *settlements)
|
|
@@ -0,0 +1,417 @@
|
|
|
1
|
+
"""Framework-agnostic payment-gating core plus the request-scoped trio.
|
|
2
|
+
|
|
3
|
+
The framework shims (``solana_pay_kit.fastapi`` / ``solana_pay_kit.flask`` / ``solana_pay_kit.django``)
|
|
4
|
+
all delegate to :class:`PayCore`. The split keeps every protocol/scheme decision,
|
|
5
|
+
402-challenge assembly, and adapter dispatch in one host-neutral place; the shims
|
|
6
|
+
only translate ``PayCore``'s outcome into their framework's response idioms
|
|
7
|
+
(caveat #6).
|
|
8
|
+
|
|
9
|
+
:class:`PayCore` mirrors the PHP ``Middleware\\RequirePayment`` and the Ruby Rack
|
|
10
|
+
middleware:
|
|
11
|
+
|
|
12
|
+
* :meth:`PayCore.resolve_gate` coerces the assorted gate-reference shapes
|
|
13
|
+
(inline :class:`~solana_pay_kit.gate.Gate`, registered name, request builder, bare
|
|
14
|
+
:class:`~solana_pay_kit.price.Price`) into a concrete validated gate.
|
|
15
|
+
* :meth:`PayCore.detect_adapter` walks the gate's accept list in order and picks
|
|
16
|
+
the scheme adapter whose proof header is present. x402 wins when both proofs
|
|
17
|
+
arrive; a fee-bearing gate disables x402 entirely (stock x402 facilitators
|
|
18
|
+
settle to a single address).
|
|
19
|
+
* :meth:`PayCore.process` runs verification and returns a settled
|
|
20
|
+
:class:`~solana_pay_kit.payment.Payment`, or raises :class:`PaymentRequiredError`
|
|
21
|
+
(carrying the 402 challenge headers + JSON body on the exception) /
|
|
22
|
+
:class:`InvalidProofError` / :class:`ProtocolNotSupportedError`.
|
|
23
|
+
|
|
24
|
+
The request-scoped trio (:func:`require_payment`, :func:`is_paid`,
|
|
25
|
+
:func:`is_paid_for`, :func:`payment`) read the verified
|
|
26
|
+
:class:`~solana_pay_kit.payment.Payment` the shims attach to the request under the
|
|
27
|
+
``paykit_payment`` attribute, matching the cross-SDK ``payment`` / ``paid?`` /
|
|
28
|
+
``require_payment!`` shape.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
from __future__ import annotations
|
|
32
|
+
|
|
33
|
+
import weakref
|
|
34
|
+
from collections.abc import Callable, Mapping
|
|
35
|
+
from typing import TYPE_CHECKING, Any, cast
|
|
36
|
+
|
|
37
|
+
from solana_pay_kit._paycore.protocol import Protocol
|
|
38
|
+
from solana_pay_kit.errors import (
|
|
39
|
+
InvalidProofError,
|
|
40
|
+
PaymentRequiredError,
|
|
41
|
+
ProtocolNotSupportedError,
|
|
42
|
+
)
|
|
43
|
+
from solana_pay_kit.gate import DynamicGate, Gate
|
|
44
|
+
from solana_pay_kit.payment import Payment
|
|
45
|
+
from solana_pay_kit.price import Price
|
|
46
|
+
from solana_pay_kit.pricing import Pricing, coerce
|
|
47
|
+
from solana_pay_kit.protocols.mpp import MppAdapter
|
|
48
|
+
from solana_pay_kit.protocols.x402 import X402Adapter
|
|
49
|
+
|
|
50
|
+
if TYPE_CHECKING:
|
|
51
|
+
from solana_pay_kit.config import Config
|
|
52
|
+
from solana_pay_kit.protocols.mpp import MppAcceptsEntry
|
|
53
|
+
from solana_pay_kit.protocols.x402.exact.types import X402AcceptsEntry
|
|
54
|
+
|
|
55
|
+
__all__ = [
|
|
56
|
+
"PayCore",
|
|
57
|
+
"require_payment",
|
|
58
|
+
"is_paid",
|
|
59
|
+
"is_paid_for",
|
|
60
|
+
"payment",
|
|
61
|
+
"PAYMENT_ATTR",
|
|
62
|
+
]
|
|
63
|
+
|
|
64
|
+
#: Request attribute the framework shims write the verified payment under.
|
|
65
|
+
PAYMENT_ATTR = "paykit_payment"
|
|
66
|
+
|
|
67
|
+
#: Gate reference shapes accepted by the middleware.
|
|
68
|
+
GateRef = "Gate | DynamicGate | Price | str | Callable[[Any], Gate]"
|
|
69
|
+
|
|
70
|
+
#: One ``PayCore`` (and its adapters + shared replay store) per Config. The
|
|
71
|
+
#: framework shims construct a gate per request, but a fresh adapter would mean
|
|
72
|
+
#: a fresh in-memory replay store, so a settled MPP signature could be replayed.
|
|
73
|
+
#: Caching the core per Config keeps the consumed-signature marker durable for
|
|
74
|
+
#: the lifetime of that config. Weak keys let a dropped config (e.g. a test
|
|
75
|
+
#: ``reset()``) and its cached core be collected. The Config is frozen, so a
|
|
76
|
+
#: cached core never observes stale settings.
|
|
77
|
+
_CORE_CACHE: weakref.WeakKeyDictionary[Config, PayCore] = weakref.WeakKeyDictionary()
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class PayCore:
|
|
81
|
+
"""Host-neutral payment-gating core shared by every framework shim.
|
|
82
|
+
|
|
83
|
+
One instance wraps a frozen :class:`~solana_pay_kit.config.Config` and lazily
|
|
84
|
+
constructs the MPP and (when x402 is accepted) x402 adapters. Callers can
|
|
85
|
+
inject pre-built adapters to override defaults, e.g. with an offline
|
|
86
|
+
``recent_blockhash_provider`` for tests.
|
|
87
|
+
"""
|
|
88
|
+
|
|
89
|
+
def __init__(
|
|
90
|
+
self,
|
|
91
|
+
config: Config,
|
|
92
|
+
*,
|
|
93
|
+
mpp: MppAdapter | None = None,
|
|
94
|
+
x402: X402Adapter | None = None,
|
|
95
|
+
) -> None:
|
|
96
|
+
"""Bind to ``config`` and resolve (or inject) the scheme adapters."""
|
|
97
|
+
self._config = config
|
|
98
|
+
self._mpp = mpp if mpp is not None else MppAdapter(config)
|
|
99
|
+
# Auto-wire the x402 adapter only when the config accept list includes
|
|
100
|
+
# it; mirrors the PHP constructor. An explicit adapter always wins.
|
|
101
|
+
if x402 is not None:
|
|
102
|
+
self._x402: X402Adapter | None = x402
|
|
103
|
+
elif Protocol.X402 in config.accept:
|
|
104
|
+
self._x402 = X402Adapter(config)
|
|
105
|
+
else:
|
|
106
|
+
self._x402 = None
|
|
107
|
+
|
|
108
|
+
@classmethod
|
|
109
|
+
def for_config(cls, config: Config) -> PayCore:
|
|
110
|
+
"""Return the cached per-Config core, building (and caching) one on miss.
|
|
111
|
+
|
|
112
|
+
The framework shims call this once per request; reusing one core per
|
|
113
|
+
Config keeps the MPP/x402 adapters and their shared in-memory replay
|
|
114
|
+
store alive across requests so a settled signature stays consumed and
|
|
115
|
+
cannot be replayed. A fresh ``PayCore(config)`` per request (the prior
|
|
116
|
+
behaviour) reset that store on every call.
|
|
117
|
+
"""
|
|
118
|
+
cached = _CORE_CACHE.get(config)
|
|
119
|
+
if cached is not None:
|
|
120
|
+
return cached
|
|
121
|
+
core = cls(config)
|
|
122
|
+
_CORE_CACHE[config] = core
|
|
123
|
+
return core
|
|
124
|
+
|
|
125
|
+
@property
|
|
126
|
+
def config(self) -> Config:
|
|
127
|
+
"""The frozen configuration this core gates against."""
|
|
128
|
+
return self._config
|
|
129
|
+
|
|
130
|
+
def resolve_gate(
|
|
131
|
+
self,
|
|
132
|
+
gate_ref: Gate | DynamicGate | Price | str | Callable[[Any], Gate],
|
|
133
|
+
pricing: Pricing | None,
|
|
134
|
+
request: Any,
|
|
135
|
+
) -> Gate:
|
|
136
|
+
"""Coerce any gate-reference shape into a concrete validated Gate.
|
|
137
|
+
|
|
138
|
+
A plain callable (not a :class:`DynamicGate`) is invoked with the
|
|
139
|
+
request and may return a :class:`Gate` or a :class:`~solana_pay_kit.price.Price`
|
|
140
|
+
(wrapped with Config defaults). A :class:`DynamicGate` is resolved with
|
|
141
|
+
the Config defaults the DSL omitted. Everything else funnels through
|
|
142
|
+
:func:`solana_pay_kit.pricing.coerce`.
|
|
143
|
+
"""
|
|
144
|
+
if isinstance(gate_ref, DynamicGate):
|
|
145
|
+
self._inject_dynamic_defaults(gate_ref)
|
|
146
|
+
return gate_ref.resolve(request)
|
|
147
|
+
if not isinstance(gate_ref, (Gate, Price, str)) and callable(gate_ref):
|
|
148
|
+
return self._resolve_callable(gate_ref, request)
|
|
149
|
+
return self._coerce_static(gate_ref, pricing, request)
|
|
150
|
+
|
|
151
|
+
def detect_adapter(
|
|
152
|
+
self,
|
|
153
|
+
gate: Gate,
|
|
154
|
+
headers: Mapping[str, str],
|
|
155
|
+
) -> X402Adapter | MppAdapter | None:
|
|
156
|
+
"""Pick the scheme adapter whose proof header is present, in accept order.
|
|
157
|
+
|
|
158
|
+
x402 requires a non-empty ``Payment-Signature`` header, the gate to
|
|
159
|
+
accept x402, no fees on the gate, and a wired x402 adapter. MPP requires
|
|
160
|
+
an ``Authorization`` header whose scheme is ``payment`` (case-insensitive).
|
|
161
|
+
When both proofs are present x402 wins, matching the PHP/Ruby reference.
|
|
162
|
+
"""
|
|
163
|
+
accept = gate.accept if gate.accept is not None else self._config.accept
|
|
164
|
+
authorization = _read_header(headers, "authorization")
|
|
165
|
+
signature = _read_header(headers, "payment-signature")
|
|
166
|
+
|
|
167
|
+
for scheme in accept:
|
|
168
|
+
if scheme == Protocol.X402 and signature and self._x402 is not None and not gate.has_fees():
|
|
169
|
+
return self._x402
|
|
170
|
+
if scheme == Protocol.MPP and authorization and authorization.strip().lower().startswith("payment "):
|
|
171
|
+
return self._mpp
|
|
172
|
+
return None
|
|
173
|
+
|
|
174
|
+
async def process(
|
|
175
|
+
self,
|
|
176
|
+
gate_ref: Gate | DynamicGate | Price | str | Callable[[Any], Gate],
|
|
177
|
+
pricing: Pricing | None,
|
|
178
|
+
request: Any,
|
|
179
|
+
) -> Payment:
|
|
180
|
+
"""Resolve, dispatch, verify, and return a settled :class:`Payment`.
|
|
181
|
+
|
|
182
|
+
Raises :class:`~solana_pay_kit.errors.PaymentRequiredError` (with
|
|
183
|
+
``challenge_headers`` and ``body`` attributes set for the shim to render
|
|
184
|
+
a 402) when no usable proof is present, and re-raises
|
|
185
|
+
:class:`~solana_pay_kit.errors.InvalidProofError` /
|
|
186
|
+
:class:`~solana_pay_kit.errors.ProtocolNotSupportedError` on verification or
|
|
187
|
+
protocol-mismatch failures.
|
|
188
|
+
"""
|
|
189
|
+
gate = self.resolve_gate(gate_ref, pricing, request)
|
|
190
|
+
headers = _request_headers(request)
|
|
191
|
+
adapter = self.detect_adapter(gate, headers)
|
|
192
|
+
|
|
193
|
+
if adapter is None:
|
|
194
|
+
raise self._payment_required(gate, request)
|
|
195
|
+
|
|
196
|
+
try:
|
|
197
|
+
return await adapter.verify_and_settle(gate, request)
|
|
198
|
+
except (InvalidProofError, ProtocolNotSupportedError):
|
|
199
|
+
raise
|
|
200
|
+
except PaymentRequiredError as exc:
|
|
201
|
+
raise self._payment_required(gate, request) from exc
|
|
202
|
+
|
|
203
|
+
def build_402(self, gate: Gate, request: Any) -> tuple[dict[str, str], dict[str, Any]]:
|
|
204
|
+
"""Assemble the 402 challenge headers and JSON body for ``gate``.
|
|
205
|
+
|
|
206
|
+
Returns ``(headers, body)`` where ``body`` is
|
|
207
|
+
``{"error", "resource", "accepts"}``. x402 is offered first when the
|
|
208
|
+
gate accepts it and carries no fees; MPP is offered whenever accepted.
|
|
209
|
+
"""
|
|
210
|
+
accept = gate.accept if gate.accept is not None else self._config.accept
|
|
211
|
+
accepts: list[X402AcceptsEntry | MppAcceptsEntry] = []
|
|
212
|
+
headers: dict[str, str] = {}
|
|
213
|
+
|
|
214
|
+
if self._x402 is not None and Protocol.X402 in accept and not gate.has_fees():
|
|
215
|
+
accepts.append(self._x402.accepts_entry(gate, request))
|
|
216
|
+
headers.update(self._x402.challenge_headers(gate, request))
|
|
217
|
+
if Protocol.MPP in accept:
|
|
218
|
+
accepts.append(self._mpp.accepts_entry(gate, request))
|
|
219
|
+
headers.update(self._mpp.challenge_headers(gate, request))
|
|
220
|
+
|
|
221
|
+
headers.setdefault("content-type", "application/json")
|
|
222
|
+
body = {
|
|
223
|
+
"error": "payment_required",
|
|
224
|
+
"resource": _request_path(request),
|
|
225
|
+
"accepts": accepts,
|
|
226
|
+
}
|
|
227
|
+
return headers, body
|
|
228
|
+
|
|
229
|
+
# -- internals ----------------------------------------------------------
|
|
230
|
+
|
|
231
|
+
def _payment_required(self, gate: Gate, request: Any) -> PaymentRequiredError:
|
|
232
|
+
"""Build a PaymentRequiredError carrying the 402 challenge for the shim."""
|
|
233
|
+
headers, body = self.build_402(gate, request)
|
|
234
|
+
error = PaymentRequiredError("solana_pay_kit: payment required")
|
|
235
|
+
# Stash the rendered challenge on the exception so framework shims can
|
|
236
|
+
# emit a 402 without re-deriving it; mirrors PHP's build402 short-circuit.
|
|
237
|
+
error.challenge_headers = headers # type: ignore[attr-defined]
|
|
238
|
+
error.body = body # type: ignore[attr-defined]
|
|
239
|
+
return error
|
|
240
|
+
|
|
241
|
+
def _resolve_callable(self, builder: Callable[[Any], object], request: Any) -> Gate:
|
|
242
|
+
"""Invoke a bare request-builder and coerce its Gate/Price result.
|
|
243
|
+
|
|
244
|
+
``builder`` is typed to return ``object`` because user request-builders
|
|
245
|
+
are untyped and may return a Gate, a Price, or an invalid value; the
|
|
246
|
+
isinstance ladder is the load-bearing runtime guard.
|
|
247
|
+
"""
|
|
248
|
+
result = builder(request)
|
|
249
|
+
if isinstance(result, Gate):
|
|
250
|
+
return result
|
|
251
|
+
if isinstance(result, Price):
|
|
252
|
+
return self._coerce_static(result, None, request)
|
|
253
|
+
raise ProtocolNotSupportedError(
|
|
254
|
+
f"solana_pay_kit: gate builder returned {type(result).__name__}, expected Gate or Price"
|
|
255
|
+
)
|
|
256
|
+
|
|
257
|
+
def _coerce_static(
|
|
258
|
+
self,
|
|
259
|
+
gate_ref: Gate | DynamicGate | Price | str,
|
|
260
|
+
pricing: Pricing | None,
|
|
261
|
+
request: Any,
|
|
262
|
+
) -> Gate:
|
|
263
|
+
"""Coerce a non-callable reference; resolve a DynamicGate against the request.
|
|
264
|
+
|
|
265
|
+
A registered name may resolve (via the pricing registry) to a
|
|
266
|
+
:class:`DynamicGate`. Such a gate still needs the current request to
|
|
267
|
+
evaluate its builder, so inject the Config defaults and resolve it here
|
|
268
|
+
rather than rejecting it; ``resolve_gate`` always has the request.
|
|
269
|
+
"""
|
|
270
|
+
coerced = coerce(gate_ref, registry=pricing, config=self._config)
|
|
271
|
+
if isinstance(coerced, DynamicGate):
|
|
272
|
+
self._inject_dynamic_defaults(coerced)
|
|
273
|
+
return coerced.resolve(request)
|
|
274
|
+
return coerced
|
|
275
|
+
|
|
276
|
+
def _inject_dynamic_defaults(self, gate: DynamicGate) -> None:
|
|
277
|
+
"""Seed a DynamicGate's lazy Config defaults (pay_to + accept list)."""
|
|
278
|
+
defaults = getattr(gate, "_defaults", None)
|
|
279
|
+
if isinstance(defaults, dict) and not defaults:
|
|
280
|
+
defaults["pay_to"] = self._config.effective_recipient()
|
|
281
|
+
defaults["accept"] = self._config.accept
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
# -- request-scoped trio ----------------------------------------------------
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def payment(request: Any) -> Payment | None:
|
|
288
|
+
"""The verified payment attached to ``request``, or ``None`` if unpaid.
|
|
289
|
+
|
|
290
|
+
Reads the ``paykit_payment`` attribute the framework shims write after a
|
|
291
|
+
successful :meth:`PayCore.process`. Tolerates an attribute bag, a mapping,
|
|
292
|
+
or a framework request exposing ``.state`` (FastAPI/Starlette).
|
|
293
|
+
"""
|
|
294
|
+
value = _read_attr(request, PAYMENT_ATTR)
|
|
295
|
+
return value if isinstance(value, Payment) else None
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def is_paid(request: Any) -> bool:
|
|
299
|
+
"""Whether a verified payment is attached to ``request``."""
|
|
300
|
+
return payment(request) is not None
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def is_paid_for(request: Any, gate: Gate | str) -> bool:
|
|
304
|
+
"""Whether ``request`` carries a verified payment for ``gate``.
|
|
305
|
+
|
|
306
|
+
A :class:`~solana_pay_kit.gate.Gate` instance trusts the middleware that wrote the
|
|
307
|
+
attribute (Payment does not carry gate identity beyond its name); a string
|
|
308
|
+
is matched against the payment's ``gate_name``.
|
|
309
|
+
"""
|
|
310
|
+
settled = payment(request)
|
|
311
|
+
if settled is None:
|
|
312
|
+
return False
|
|
313
|
+
if isinstance(gate, Gate):
|
|
314
|
+
return True
|
|
315
|
+
return settled.gate_name == gate
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def require_payment(request: Any) -> Payment:
|
|
319
|
+
"""Return the attached payment or raise :class:`PaymentRequiredError`.
|
|
320
|
+
|
|
321
|
+
Imperative gating from inside a handler that did not run the middleware
|
|
322
|
+
decorator/dependency. Mirrors the cross-SDK ``require_payment!``.
|
|
323
|
+
"""
|
|
324
|
+
settled = payment(request)
|
|
325
|
+
if settled is None:
|
|
326
|
+
raise PaymentRequiredError("solana_pay_kit: payment required")
|
|
327
|
+
return settled
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
# -- header / attribute helpers ---------------------------------------------
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def _request_headers(request: Any) -> Mapping[str, str]:
|
|
334
|
+
"""Extract a case-tolerant header mapping from a generic request bag."""
|
|
335
|
+
headers: object = getattr(request, "headers", None)
|
|
336
|
+
if headers is None and isinstance(request, Mapping):
|
|
337
|
+
request_map = cast("Mapping[str, object]", request)
|
|
338
|
+
headers = request_map.get("headers", request_map)
|
|
339
|
+
if headers is None:
|
|
340
|
+
return {}
|
|
341
|
+
if isinstance(headers, Mapping):
|
|
342
|
+
return cast("Mapping[str, str]", headers)
|
|
343
|
+
# Header objects exposing .get (e.g. Starlette Headers, WSGI EnvironHeaders).
|
|
344
|
+
if callable(getattr(headers, "get", None)):
|
|
345
|
+
return _HeaderProxy(headers)
|
|
346
|
+
return {}
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def _read_header(headers: Mapping[str, str], name: str) -> str:
|
|
350
|
+
"""Read a header case-insensitively from a mapping or proxy; "" if absent."""
|
|
351
|
+
getter = getattr(headers, "get", None)
|
|
352
|
+
if not callable(getter):
|
|
353
|
+
return ""
|
|
354
|
+
value = getter(name)
|
|
355
|
+
if value is None:
|
|
356
|
+
value = getter(name.title())
|
|
357
|
+
if value is None:
|
|
358
|
+
value = getter(name.upper())
|
|
359
|
+
return str(value) if value else ""
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
def _read_attr(request: Any, name: str) -> object:
|
|
363
|
+
"""Read an attribute off a request bag, mapping, or ``.state`` namespace."""
|
|
364
|
+
state = getattr(request, "state", None)
|
|
365
|
+
if state is not None and hasattr(state, name):
|
|
366
|
+
return getattr(state, name)
|
|
367
|
+
if hasattr(request, name):
|
|
368
|
+
return getattr(request, name)
|
|
369
|
+
if isinstance(request, Mapping):
|
|
370
|
+
return cast("Mapping[str, object]", request).get(name)
|
|
371
|
+
return None
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def _request_path(request: Any) -> str:
|
|
375
|
+
"""Best-effort request path for the 402 body ``resource`` field."""
|
|
376
|
+
url = getattr(request, "url", None)
|
|
377
|
+
if url is not None:
|
|
378
|
+
path = getattr(url, "path", None)
|
|
379
|
+
if isinstance(path, str):
|
|
380
|
+
return path
|
|
381
|
+
path = getattr(request, "path", None)
|
|
382
|
+
if isinstance(path, str):
|
|
383
|
+
return path
|
|
384
|
+
if isinstance(request, Mapping):
|
|
385
|
+
request_map = cast("Mapping[str, object]", request)
|
|
386
|
+
candidate = request_map.get("path") or request_map.get("PATH_INFO")
|
|
387
|
+
if isinstance(candidate, str):
|
|
388
|
+
return candidate
|
|
389
|
+
return "/"
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
class _HeaderProxy(Mapping[str, str]):
|
|
393
|
+
"""Adapts a ``.get``-bearing header object to a read-only Mapping."""
|
|
394
|
+
|
|
395
|
+
__slots__ = ("_headers",)
|
|
396
|
+
|
|
397
|
+
def __init__(self, headers: Any) -> None:
|
|
398
|
+
self._headers = headers
|
|
399
|
+
|
|
400
|
+
def __getitem__(self, key: str) -> str:
|
|
401
|
+
value = self._headers.get(key)
|
|
402
|
+
if value is None:
|
|
403
|
+
raise KeyError(key)
|
|
404
|
+
return str(value)
|
|
405
|
+
|
|
406
|
+
def get(self, key: str, default: Any = None) -> Any: # type: ignore[override]
|
|
407
|
+
value = self._headers.get(key)
|
|
408
|
+
return value if value is not None else default
|
|
409
|
+
|
|
410
|
+
def __iter__(self) -> Any:
|
|
411
|
+
return iter(getattr(self._headers, "keys", lambda: ())())
|
|
412
|
+
|
|
413
|
+
def __len__(self) -> int:
|
|
414
|
+
try:
|
|
415
|
+
return len(self._headers)
|
|
416
|
+
except TypeError:
|
|
417
|
+
return 0
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""Shared payment-core primitives used by both protocol packages.
|
|
2
|
+
|
|
3
|
+
The analog of the Rust ``core`` crate: enums, mints, RPC, replay store, network
|
|
4
|
+
check, transaction helpers, and the wire error model. x402 and MPP both depend
|
|
5
|
+
on ``_paycore``; neither protocol depends on the other.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from solana_pay_kit._paycore.currency import Currency
|
|
11
|
+
from solana_pay_kit._paycore.mints import (
|
|
12
|
+
ASSOCIATED_TOKEN_PROGRAM,
|
|
13
|
+
TOKEN_2022_PROGRAM,
|
|
14
|
+
TOKEN_PROGRAM,
|
|
15
|
+
derive_ata,
|
|
16
|
+
resolve,
|
|
17
|
+
resolve_stablecoin_mint,
|
|
18
|
+
symbol_for,
|
|
19
|
+
token_program_for,
|
|
20
|
+
)
|
|
21
|
+
from solana_pay_kit._paycore.network import (
|
|
22
|
+
AUTOFUND_LAMPORTS,
|
|
23
|
+
MIN_FEE_PAYER_LAMPORTS,
|
|
24
|
+
PUBLIC_RPC_URLS,
|
|
25
|
+
SOLANA_DEVNET_CAIP2,
|
|
26
|
+
SOLANA_MAINNET_CAIP2,
|
|
27
|
+
Network,
|
|
28
|
+
)
|
|
29
|
+
from solana_pay_kit._paycore.stablecoin import Stablecoin
|
|
30
|
+
|
|
31
|
+
__all__ = [
|
|
32
|
+
"Currency",
|
|
33
|
+
"Stablecoin",
|
|
34
|
+
"Network",
|
|
35
|
+
"PUBLIC_RPC_URLS",
|
|
36
|
+
"SOLANA_MAINNET_CAIP2",
|
|
37
|
+
"SOLANA_DEVNET_CAIP2",
|
|
38
|
+
"MIN_FEE_PAYER_LAMPORTS",
|
|
39
|
+
"AUTOFUND_LAMPORTS",
|
|
40
|
+
"resolve_stablecoin_mint",
|
|
41
|
+
"resolve",
|
|
42
|
+
"token_program_for",
|
|
43
|
+
"symbol_for",
|
|
44
|
+
"derive_ata",
|
|
45
|
+
"ASSOCIATED_TOKEN_PROGRAM",
|
|
46
|
+
"TOKEN_PROGRAM",
|
|
47
|
+
"TOKEN_2022_PROGRAM",
|
|
48
|
+
]
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"""Fiat currency denominations and decimal/base-unit conversion.
|
|
2
|
+
|
|
3
|
+
``parse_units`` is protocol-agnostic (both the MPP charge server and the x402
|
|
4
|
+
exact offer builder convert a human-readable decimal amount into integer base
|
|
5
|
+
units), so it lives in the shared core. Neither protocol package owns it and
|
|
6
|
+
neither imports the other to reach it (R2).
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from enum import StrEnum
|
|
12
|
+
|
|
13
|
+
__all__ = ["Currency", "parse_units"]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class Currency(StrEnum):
|
|
17
|
+
"""ISO 4217 fiat currency used to denominate a gate amount."""
|
|
18
|
+
|
|
19
|
+
USD = "USD"
|
|
20
|
+
EUR = "EUR"
|
|
21
|
+
GBP = "GBP"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def parse_units(amount: str, decimals: int) -> str:
|
|
25
|
+
"""Convert a human-readable decimal amount to integer base units.
|
|
26
|
+
|
|
27
|
+
Examples:
|
|
28
|
+
parse_units("1.5", 6) -> "1500000"
|
|
29
|
+
parse_units("0.01", 2) -> "1"
|
|
30
|
+
parse_units("100", 6) -> "100000000"
|
|
31
|
+
"""
|
|
32
|
+
amount = amount.strip()
|
|
33
|
+
if not amount:
|
|
34
|
+
raise ValueError("amount is required")
|
|
35
|
+
if amount.startswith("-"):
|
|
36
|
+
raise ValueError("amount cannot be negative")
|
|
37
|
+
|
|
38
|
+
parts = amount.split(".")
|
|
39
|
+
if len(parts) > 2:
|
|
40
|
+
raise ValueError(f"invalid amount: {amount}")
|
|
41
|
+
|
|
42
|
+
has_fraction = len(parts) == 2
|
|
43
|
+
whole = parts[0]
|
|
44
|
+
fractional = parts[1] if has_fraction else ""
|
|
45
|
+
|
|
46
|
+
# Audit #44/#45: reject malformed shapes that ``int()`` would otherwise
|
|
47
|
+
# silently accept. Mirrors the Rust ``parse_units`` guards
|
|
48
|
+
# (rust/crates/mpp/src/protocol/intents/mod.rs): no empty integer/fraction
|
|
49
|
+
# halves (".5", "5.", "."), and every digit must be an ASCII 0-9 — Python's
|
|
50
|
+
# ``int()`` accepts a leading "+", underscore grouping ("1_000"), and
|
|
51
|
+
# non-ASCII Unicode digits ("١٢٣"), all of which would silently corrupt the
|
|
52
|
+
# base-unit amount. ``str.isdigit()`` is too loose (it accepts superscripts
|
|
53
|
+
# and other numeric Unicode), so screen each char with ``isascii``+``isdigit``.
|
|
54
|
+
if has_fraction and (not whole or not fractional):
|
|
55
|
+
raise ValueError(f"invalid amount: {amount}")
|
|
56
|
+
if not whole:
|
|
57
|
+
raise ValueError(f"invalid amount: {amount}")
|
|
58
|
+
|
|
59
|
+
def _all_ascii_digits(s: str) -> bool:
|
|
60
|
+
return s != "" and all(c.isascii() and c.isdigit() for c in s)
|
|
61
|
+
|
|
62
|
+
if not _all_ascii_digits(whole):
|
|
63
|
+
raise ValueError(f"invalid amount: {amount}")
|
|
64
|
+
if fractional and not _all_ascii_digits(fractional):
|
|
65
|
+
raise ValueError(f"invalid amount: {amount}")
|
|
66
|
+
|
|
67
|
+
if len(fractional) > decimals:
|
|
68
|
+
raise ValueError(f"amount {amount} has too many decimal places for {decimals} decimals")
|
|
69
|
+
|
|
70
|
+
# Pad fractional part to fill decimals
|
|
71
|
+
value_str = whole + fractional + "0" * (decimals - len(fractional))
|
|
72
|
+
|
|
73
|
+
# Strip leading zeros
|
|
74
|
+
value_str = value_str.lstrip("0") or "0"
|
|
75
|
+
|
|
76
|
+
# Validate it's a valid integer (guards above already screened the digits)
|
|
77
|
+
try:
|
|
78
|
+
val = int(value_str)
|
|
79
|
+
except ValueError as exc:
|
|
80
|
+
raise ValueError(f"invalid amount: {amount}") from exc
|
|
81
|
+
|
|
82
|
+
return str(val)
|