forked from x402-foundation/x402
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathall_networks.py
More file actions
147 lines (119 loc) · 4.95 KB
/
Copy pathall_networks.py
File metadata and controls
147 lines (119 loc) · 4.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
"""All Networks Client Example.
Demonstrates how to create a client that supports all available networks with
optional chain configuration via environment variables.
New chain support should be added here in alphabetic order by network prefix
(e.g., "eip155" before "solana" before "tvm").
"""
import asyncio
import os
import sys
from dotenv import load_dotenv
from eth_account import Account
from x402 import x402Client
from x402.http import x402HTTPClient
from x402.http.clients import x402HttpxClient
from x402.mechanisms.evm import EthAccountSigner
from x402.mechanisms.evm.exact.register import register_exact_evm_client
from x402.mechanisms.svm import KeypairSigner
from x402.mechanisms.svm.exact.register import register_exact_svm_client
from x402.mechanisms.tvm import (
TVM_MAINNET,
TVM_PROVIDER_TONAPI,
TVM_TESTNET,
WalletV5R1Config,
WalletV5R1MnemonicSigner,
)
from x402.mechanisms.tvm.exact import ExactTvmClientScheme
# Load environment variables
load_dotenv()
def validate_environment() -> tuple[str | None, str | None, str | None, str, str]:
"""Validate required environment variables.
Returns:
Tuple of (evm_private_key, svm_private_key, tvm_private_key, base_url, endpoint_path).
Raises:
SystemExit: If required environment variables are missing.
"""
evm_private_key = os.getenv("EVM_PRIVATE_KEY")
svm_private_key = os.getenv("SVM_PRIVATE_KEY")
tvm_private_key = os.getenv("TVM_PRIVATE_KEY")
base_url = os.getenv("RESOURCE_SERVER_URL")
endpoint_path = os.getenv("ENDPOINT_PATH")
# Validate at least one signer credential is provided
if not evm_private_key and not svm_private_key and not tvm_private_key:
print("❌ At least one of EVM_PRIVATE_KEY, SVM_PRIVATE_KEY, or TVM_PRIVATE_KEY is required")
print("Please copy .env-local to .env and fill in the values.")
sys.exit(1)
if not base_url:
print("❌ RESOURCE_SERVER_URL is required")
sys.exit(1)
if not endpoint_path:
print("❌ ENDPOINT_PATH is required")
sys.exit(1)
return (
evm_private_key,
svm_private_key,
tvm_private_key,
base_url,
endpoint_path,
)
async def main() -> None:
"""Main entry point demonstrating httpx with x402 payments."""
# Validate environment
evm_private_key, svm_private_key, tvm_private_key, base_url, endpoint_path = (
validate_environment()
)
# Create x402 client
client = x402Client()
# Register EVM payment scheme if private key provided
if evm_private_key:
account = Account.from_key(evm_private_key)
register_exact_evm_client(client, EthAccountSigner(account))
print(f"Initialized EVM account: {account.address}")
# Register SVM payment scheme if private key provided
if svm_private_key:
svm_signer = KeypairSigner.from_base58(svm_private_key)
register_exact_svm_client(client, svm_signer)
print(f"Initialized SVM account: {svm_signer.address}")
# Register TVM payment scheme if private key provided
if tvm_private_key:
tvm_network = os.getenv("TVM_NETWORK", TVM_TESTNET)
if tvm_network not in {TVM_TESTNET, TVM_MAINNET}:
print(f"❌ Unsupported TVM network: {tvm_network}")
sys.exit(1)
tvm_config = WalletV5R1Config.from_private_key(tvm_network, tvm_private_key)
tvm_provider = (os.getenv("TVM_PROVIDER") or "").strip().lower()
tvm_config.provider = tvm_provider or tvm_config.provider
tvm_config.api_key = (
os.getenv("TONAPI_API_KEY")
if tvm_provider == TVM_PROVIDER_TONAPI
else os.getenv("TONCENTER_API_KEY")
)
tvm_config.provider_base_url = (
os.getenv("TONAPI_BASE_URL")
if tvm_provider == TVM_PROVIDER_TONAPI
else os.getenv("TONCENTER_BASE_URL")
)
tvm_signer = WalletV5R1MnemonicSigner(tvm_config)
client.register(tvm_network, ExactTvmClientScheme(tvm_signer))
print(f"Initialized TVM account: {tvm_signer.address}")
# Create HTTP client helper for payment response extraction
http_client = x402HTTPClient(client)
# Build full URL
url = f"{base_url}{endpoint_path}"
print(f"\nMaking request to: {url}\n")
# Make request using async context manager
async with x402HttpxClient(client, timeout=30.0) as http:
response = await http.get(url)
await response.aread()
print(f"Response status: {response.status_code}")
print(f"Response body: {response.text}")
# Extract and print payment response if present
try:
settle_response = http_client.get_payment_settle_response(
lambda name: response.headers.get(name)
)
print(f"\nPayment response: {settle_response.model_dump_json(indent=2)}")
except ValueError:
print("\nNo payment response header found")
if __name__ == "__main__":
asyncio.run(main())