stableops 0.7.1__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.
@@ -0,0 +1,235 @@
1
+ """Payment Orders API."""
2
+
3
+ from typing import Any, Dict, List, Optional
4
+
5
+ from stableops.http import AsyncHttpClient, HttpClient
6
+ from stableops.types import (
7
+ AmountMode,
8
+ PaymentOrder,
9
+ PaymentOrderDetail,
10
+ )
11
+
12
+
13
+ def _to_create_body(
14
+ merchant_order_id: str,
15
+ amount: str,
16
+ accepted_assets: List[Dict[str, Any]],
17
+ expires_at: str,
18
+ amount_mode: Optional[AmountMode],
19
+ metadata: Optional[Dict[str, Any]],
20
+ ) -> Dict[str, Any]:
21
+ """组装 create 请求体(结算资产由服务端导出,不再传入)。"""
22
+ body: Dict[str, Any] = {
23
+ "merchant_order_id": merchant_order_id,
24
+ "amount": amount,
25
+ "accepted_assets": accepted_assets,
26
+ "expires_at": expires_at,
27
+ }
28
+ if amount_mode is not None:
29
+ body["amount_mode"] = amount_mode
30
+ if metadata:
31
+ body["metadata"] = metadata
32
+ return body
33
+
34
+
35
+ def _from_wire(wire: Dict[str, Any]) -> Dict[str, Any]:
36
+ """Convert wire format (snake_case) to SDK model kwargs."""
37
+ return {
38
+ "id": wire["id"],
39
+ "merchant_order_id": wire["merchant_order_id"],
40
+ "amount": wire["amount"],
41
+ "requested_amount": wire.get("requested_amount"),
42
+ "settlement_asset": wire.get("settlement_asset"),
43
+ "status": wire["status"],
44
+ "expires_at": wire.get("expires_at"),
45
+ "metadata": wire.get("metadata"),
46
+ "created_at": wire["created_at"],
47
+ "accepted_assets": wire.get("accepted_assets"),
48
+ "payment_instructions": wire.get("payment_instructions", []),
49
+ }
50
+
51
+
52
+ def _from_wire_detail(wire: Dict[str, Any]) -> Dict[str, Any]:
53
+ """Convert wire format to SDK model kwargs with timeline."""
54
+ base = _from_wire(wire)
55
+ base["timeline"] = [
56
+ {
57
+ "from_status": entry.get("from"),
58
+ "to": entry["to"],
59
+ "reason": entry.get("reason"),
60
+ "at": entry["at"],
61
+ }
62
+ for entry in wire.get("timeline", [])
63
+ ]
64
+ return base
65
+
66
+
67
+ class PaymentOrdersApi:
68
+ """Payment Orders API (synchronous)."""
69
+
70
+ def __init__(self, http: HttpClient) -> None:
71
+ """Initialize Payment Orders API."""
72
+ self.http = http
73
+
74
+ def create(
75
+ self,
76
+ merchant_order_id: str,
77
+ amount: str,
78
+ accepted_assets: List[Dict[str, Any]],
79
+ expires_at: str,
80
+ amount_mode: Optional[AmountMode] = None,
81
+ metadata: Optional[Dict[str, Any]] = None,
82
+ ) -> PaymentOrder:
83
+ """Create a payment order.
84
+
85
+ Args:
86
+ merchant_order_id: Your unique order ID (idempotency key)
87
+ amount: Amount in settlement asset (e.g., "10.00")
88
+ accepted_assets: List of accepted payment methods
89
+ expires_at: ISO 8601 expiration timestamp (required; ≤30min in sandbox, ≤24h in live)
90
+ amount_mode: 'auto' 让服务端微调金额到唯一;省略默认 'exact'
91
+ metadata: Custom metadata (optional, max 16 keys)
92
+
93
+ Returns:
94
+ Created payment order
95
+
96
+ Example:
97
+ >>> order = client.payment_orders.create(
98
+ ... merchant_order_id="order_123",
99
+ ... amount="10.00",
100
+ ... accepted_assets=[{"chain": "base", "asset": "USDC"}],
101
+ ... expires_at="2026-06-20T12:30:00Z",
102
+ ... )
103
+ """
104
+ body = _to_create_body(
105
+ merchant_order_id, amount, accepted_assets, expires_at, amount_mode, metadata
106
+ )
107
+ response = self.http.request(
108
+ method="POST",
109
+ path="/v1/payment-orders",
110
+ body=body,
111
+ idempotency_key=merchant_order_id,
112
+ )
113
+ return PaymentOrder(**_from_wire(response))
114
+
115
+ def retrieve(self, order_id: str) -> PaymentOrderDetail:
116
+ """Retrieve a payment order by ID.
117
+
118
+ Args:
119
+ order_id: Payment order ID
120
+
121
+ Returns:
122
+ Payment order with timeline
123
+
124
+ Example:
125
+ >>> order = client.payment_orders.retrieve("po_abc123")
126
+ """
127
+ response = self.http.request(
128
+ method="GET",
129
+ path=f"/v1/payment-orders/{order_id}",
130
+ )
131
+ return PaymentOrderDetail(**_from_wire_detail(response))
132
+
133
+ def list(
134
+ self,
135
+ status: Optional[str] = None,
136
+ limit: Optional[int] = None,
137
+ ) -> List[PaymentOrder]:
138
+ """List payment orders.
139
+
140
+ Args:
141
+ status: Filter by status (optional)
142
+ limit: Maximum number of results (optional)
143
+
144
+ Returns:
145
+ List of payment orders
146
+
147
+ Example:
148
+ >>> orders = client.payment_orders.list(status="finalized", limit=10)
149
+ """
150
+ response = self.http.request(
151
+ method="GET",
152
+ path="/v1/payment-orders",
153
+ query={"status": status, "limit": limit},
154
+ )
155
+ return [PaymentOrder(**_from_wire(item)) for item in response["items"]]
156
+
157
+ def cancel(self, order_id: str) -> PaymentOrder:
158
+ """Cancel a payment order.
159
+
160
+ Args:
161
+ order_id: Payment order ID
162
+
163
+ Returns:
164
+ Cancelled payment order
165
+
166
+ Example:
167
+ >>> order = client.payment_orders.cancel("po_abc123")
168
+ """
169
+ response = self.http.request(
170
+ method="POST",
171
+ path=f"/v1/payment-orders/{order_id}/cancel",
172
+ )
173
+ return PaymentOrder(**_from_wire(response))
174
+
175
+
176
+ class AsyncPaymentOrdersApi:
177
+ """Payment Orders API (asynchronous)."""
178
+
179
+ def __init__(self, http: AsyncHttpClient) -> None:
180
+ """Initialize async Payment Orders API."""
181
+ self.http = http
182
+
183
+ async def create(
184
+ self,
185
+ merchant_order_id: str,
186
+ amount: str,
187
+ accepted_assets: List[Dict[str, Any]],
188
+ expires_at: str,
189
+ amount_mode: Optional[AmountMode] = None,
190
+ metadata: Optional[Dict[str, Any]] = None,
191
+ ) -> PaymentOrder:
192
+ """Create a payment order (async).
193
+
194
+ expires_at is required (≤30min in sandbox, ≤24h in live).
195
+ amount_mode='auto' 让服务端微调金额到唯一;省略默认 'exact'。
196
+ """
197
+ body = _to_create_body(
198
+ merchant_order_id, amount, accepted_assets, expires_at, amount_mode, metadata
199
+ )
200
+ response = await self.http.request(
201
+ method="POST",
202
+ path="/v1/payment-orders",
203
+ body=body,
204
+ idempotency_key=merchant_order_id,
205
+ )
206
+ return PaymentOrder(**_from_wire(response))
207
+
208
+ async def retrieve(self, order_id: str) -> PaymentOrderDetail:
209
+ """Retrieve a payment order by ID (async)."""
210
+ response = await self.http.request(
211
+ method="GET",
212
+ path=f"/v1/payment-orders/{order_id}",
213
+ )
214
+ return PaymentOrderDetail(**_from_wire_detail(response))
215
+
216
+ async def list(
217
+ self,
218
+ status: Optional[str] = None,
219
+ limit: Optional[int] = None,
220
+ ) -> List[PaymentOrder]:
221
+ """List payment orders (async)."""
222
+ response = await self.http.request(
223
+ method="GET",
224
+ path="/v1/payment-orders",
225
+ query={"status": status, "limit": limit},
226
+ )
227
+ return [PaymentOrder(**_from_wire(item)) for item in response["items"]]
228
+
229
+ async def cancel(self, order_id: str) -> PaymentOrder:
230
+ """Cancel a payment order (async)."""
231
+ response = await self.http.request(
232
+ method="POST",
233
+ path=f"/v1/payment-orders/{order_id}/cancel",
234
+ )
235
+ return PaymentOrder(**_from_wire(response))
stableops/types.py ADDED
@@ -0,0 +1,225 @@
1
+ """Type definitions for StableOps SDK."""
2
+
3
+ from typing import Any, Dict, List, Literal, Optional
4
+
5
+ from pydantic import BaseModel, Field
6
+
7
+ # Type aliases
8
+ ChainId = Literal[
9
+ "ethereum", "base", "base-sepolia", "arbitrum", "polygon",
10
+ "optimism", "bsc", "tron", "solana",
11
+ # 测试网(playground 用)
12
+ "ethereum-sepolia", "arbitrum-sepolia", "polygon-amoy",
13
+ "optimism-sepolia", "bsc-testnet", "solana-devnet", "tron-nile",
14
+ ]
15
+ Asset = Literal["USDC", "USDT"]
16
+ # 'auto' 让服务端把金额微调到唯一(SHARED 地址免手动错开金额);省略即默认 'exact'。
17
+ AmountMode = Literal["exact", "auto"]
18
+ PaymentOrderStatus = Literal[
19
+ "created", "detected", "confirmed", "finalized", "reverted", "expired", "canceled"
20
+ ]
21
+ CheckoutSessionStatus = Literal["open", "completed", "expired", "canceled"]
22
+ WebhookEventType = Literal[
23
+ "payment_order.created",
24
+ "payment.detected",
25
+ "payment.confirmed",
26
+ "payment.finalized",
27
+ "payment.reverted",
28
+ "payment.expired",
29
+ "payment_order.canceled",
30
+ "address.pool.low",
31
+ "webhook.delivery.failed",
32
+ "agent.action.requested",
33
+ "agent.action.approved",
34
+ "agent.action.executed",
35
+ ]
36
+ WebhookDeliveryStatus = Literal["pending", "succeeded", "failed", "dead_letter"]
37
+
38
+
39
+ class AcceptedAssetInput(BaseModel):
40
+ """Accepted asset configuration."""
41
+
42
+ chain: ChainId
43
+ asset: Asset
44
+
45
+
46
+ class CreatePaymentOrderInput(BaseModel):
47
+ """Input for creating a payment order."""
48
+
49
+ merchant_order_id: str = Field(..., description="Your unique order ID (idempotency key)")
50
+ amount: str = Field(..., description="Amount in settlement asset (e.g., '10.00')")
51
+ accepted_assets: List[AcceptedAssetInput] = Field(
52
+ ..., description="List of accepted payment methods"
53
+ )
54
+ expires_at: str = Field(
55
+ ...,
56
+ description="ISO 8601 expiration timestamp (required; ≤30min in sandbox, ≤24h in live)",
57
+ )
58
+ amount_mode: Optional[AmountMode] = Field(
59
+ None, description="'auto' 让服务端微调金额到唯一;省略默认 'exact'"
60
+ )
61
+ metadata: Optional[Dict[str, Any]] = Field(None, description="Custom metadata (max 16 keys)")
62
+
63
+
64
+ class PaymentOrderInstruction(BaseModel):
65
+ """Payment instruction with address."""
66
+
67
+ chain: ChainId
68
+ asset: Asset
69
+ address: str
70
+
71
+
72
+ class PaymentOrder(BaseModel):
73
+ """Payment order response."""
74
+
75
+ id: str
76
+ merchant_order_id: str
77
+ amount: str
78
+ # 商户传入的基准金额;exact 单 == amount,auto 单为微调前金额(对账用)。
79
+ requested_amount: Optional[str] = None
80
+ # 结算资产由服务端导出;创建时不再传入,可能为空。
81
+ settlement_asset: Optional[Asset] = None
82
+ status: PaymentOrderStatus
83
+ expires_at: Optional[str]
84
+ metadata: Optional[Dict[str, Any]]
85
+ created_at: str
86
+ accepted_assets: Optional[List[AcceptedAssetInput]] = None
87
+ payment_instructions: List[PaymentOrderInstruction] = Field(default_factory=list)
88
+
89
+
90
+ class PaymentOrderTimelineEntry(BaseModel):
91
+ """Timeline entry for payment order status changes."""
92
+
93
+ from_status: Optional[PaymentOrderStatus] = Field(None, alias="from")
94
+ to: PaymentOrderStatus
95
+ reason: Optional[str]
96
+ at: str
97
+
98
+
99
+ class PaymentOrderDetail(PaymentOrder):
100
+ """Detailed payment order with timeline."""
101
+
102
+ timeline: List[PaymentOrderTimelineEntry]
103
+
104
+
105
+ class CreateCheckoutSessionInput(CreatePaymentOrderInput):
106
+ """Input for creating a hosted checkout session."""
107
+
108
+ title: Optional[str] = Field(None, description="Checkout page title")
109
+ description: Optional[str] = Field(None, description="Checkout page description")
110
+ success_url: Optional[str] = Field(None, description="Redirect URL after successful payment")
111
+ cancel_url: Optional[str] = Field(None, description="Redirect URL after cancel")
112
+ walletconnect_project_id: Optional[str] = Field(
113
+ None, description="WalletConnect projectId for the hosted checkout"
114
+ )
115
+
116
+
117
+ class CheckoutSession(BaseModel):
118
+ """Hosted checkout session response."""
119
+
120
+ id: str
121
+ client_secret: Optional[str] = None
122
+ # 由 client_secret + checkout_base_url 拼出的收银台链接。
123
+ url: Optional[str] = None
124
+ status: CheckoutSessionStatus
125
+ title: Optional[str]
126
+ description: Optional[str]
127
+ success_url: Optional[str]
128
+ cancel_url: Optional[str]
129
+ walletconnect_project_id: Optional[str]
130
+ expires_at: Optional[str]
131
+ created_at: str
132
+ payment_order: PaymentOrder
133
+
134
+
135
+ class NormalizedEvent(BaseModel):
136
+ """Normalized blockchain event."""
137
+
138
+ id: str
139
+ chain: ChainId
140
+ asset: Asset
141
+ from_address: str
142
+ to_address: str
143
+ amount: str
144
+ tx_hash: str
145
+ log_index: int
146
+ block_number: str
147
+ payment_order_id: Optional[str]
148
+ confirmations: int
149
+ detected_at: str
150
+
151
+
152
+ class CreateWebhookEndpointInput(BaseModel):
153
+ """Input for creating a webhook endpoint."""
154
+
155
+ url: str = Field(..., description="Webhook URL (must be HTTPS in production)")
156
+ description: Optional[str] = Field(None, description="Optional description")
157
+ enabled_events: Optional[List[WebhookEventType]] = Field(
158
+ None, description="List of event types to receive"
159
+ )
160
+ redact_metadata: Optional[bool] = Field(
161
+ None, description="若为 true,投递 payload 中剔除订单 metadata"
162
+ )
163
+
164
+
165
+ class UpdateWebhookEndpointInput(BaseModel):
166
+ """Input for updating a webhook endpoint."""
167
+
168
+ description: Optional[str] = None
169
+ enabled_events: Optional[List[WebhookEventType]] = None
170
+ redact_metadata: Optional[bool] = None
171
+
172
+
173
+ class WebhookEndpoint(BaseModel):
174
+ """Webhook endpoint configuration."""
175
+
176
+ id: str
177
+ url: str
178
+ description: Optional[str]
179
+ enabled_events: List[WebhookEventType]
180
+ redact_metadata: bool = False
181
+ disabled_at: Optional[str]
182
+ created_at: str
183
+ secret: Optional[str] = None # Only returned on create/rotate
184
+
185
+
186
+ class WebhookDelivery(BaseModel):
187
+ """Webhook delivery record."""
188
+
189
+ id: str
190
+ webhook_endpoint_id: str
191
+ event_id: str
192
+ event_type: WebhookEventType
193
+ payment_order_id: Optional[str]
194
+ status: WebhookDeliveryStatus
195
+ attempts: int
196
+ response_status: Optional[int]
197
+ response_duration_ms: Optional[int]
198
+ error_message: Optional[str]
199
+ next_retry_at: Optional[str]
200
+ last_attempt_at: Optional[str]
201
+ succeeded_at: Optional[str]
202
+ dead_lettered_at: Optional[str]
203
+ created_at: str
204
+ # 完整事件 payload(与 replay 复用同一份)。
205
+ payload: Dict[str, Any] = Field(default_factory=dict)
206
+
207
+
208
+ class ReplayDeliveryResult(BaseModel):
209
+ """Result of replaying a single delivery / event."""
210
+
211
+ delivery_id: str
212
+
213
+
214
+ class ReplayDeadLetterItem(BaseModel):
215
+ """One replayed dead-letter mapping."""
216
+
217
+ original_id: str
218
+ delivery_id: str
219
+
220
+
221
+ class ReplayDeadLettersResult(BaseModel):
222
+ """Result of batch replaying dead-letter deliveries."""
223
+
224
+ replayed: int
225
+ items: List[ReplayDeadLetterItem] = Field(default_factory=list)