py-datacentslib 0.0.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.
datacents/__init__.py ADDED
@@ -0,0 +1,28 @@
1
+ """Clients for publishing Datacents events and issuing Circle USDC payouts."""
2
+
3
+ from .circle import (
4
+ CircleConfig,
5
+ CirclePaymentsClient,
6
+ CirclePayout,
7
+ CirclePayoutError,
8
+ CirclePayoutTimeout,
9
+ )
10
+ from .events import DATASETS, EventValidationError, validate_and_flatten_batch
11
+ from .snowpipe import BatchReceipt, SnowpipeConfig, SnowpipeStreamingPublisher
12
+ from .snowflake import SnowflakeConfig, SnowflakePublisher
13
+
14
+ __all__ = [
15
+ "BatchReceipt",
16
+ "CircleConfig",
17
+ "CirclePayout",
18
+ "CirclePayoutError",
19
+ "CirclePayoutTimeout",
20
+ "CirclePaymentsClient",
21
+ "DATASETS",
22
+ "EventValidationError",
23
+ "SnowpipeConfig",
24
+ "SnowpipeStreamingPublisher",
25
+ "SnowflakeConfig",
26
+ "SnowflakePublisher",
27
+ "validate_and_flatten_batch",
28
+ ]
datacents/circle.py ADDED
@@ -0,0 +1,322 @@
1
+ """Circle developer-controlled wallet payouts using Circle's Python SDK."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import time
7
+ import warnings
8
+ from dataclasses import dataclass
9
+ from datetime import datetime, timezone
10
+ from hmac import compare_digest
11
+ from typing import Any, Callable, Mapping
12
+ from uuid import UUID, uuid4
13
+
14
+
15
+ class CirclePayoutError(RuntimeError):
16
+ """Raised when Circle returns a non-success terminal transaction state."""
17
+
18
+ def __init__(
19
+ self,
20
+ message: str,
21
+ *,
22
+ transaction_id: str | None = None,
23
+ idempotency_key: str | None = None,
24
+ state: str | None = None,
25
+ ) -> None:
26
+ self.transaction_id = transaction_id
27
+ self.idempotency_key = idempotency_key
28
+ self.state = state
29
+ super().__init__(message)
30
+
31
+
32
+ class CirclePayoutTimeout(TimeoutError):
33
+ """Raised when a Circle transaction has not reached a terminal state in time."""
34
+
35
+ def __init__(self, transaction_id: str, idempotency_key: str) -> None:
36
+ self.transaction_id = transaction_id
37
+ self.idempotency_key = idempotency_key
38
+ super().__init__(
39
+ "Circle transaction did not reach a terminal state before timeout; "
40
+ f"resume polling transaction {transaction_id} with idempotency key "
41
+ f"{idempotency_key}"
42
+ )
43
+
44
+
45
+ @dataclass(frozen=True)
46
+ class CircleConfig:
47
+ api_key: str
48
+ entity_secret: str
49
+ environment: str
50
+ blockchain: str
51
+ token_address: str
52
+ source_wallet_id: str
53
+ source_wallet_address: str
54
+ poll_interval: float = 3.0
55
+ poll_timeout: float = 300.0
56
+ large_transfer_threshold_atomic: int = 100_000_000
57
+
58
+ def __post_init__(self) -> None:
59
+ for name in (
60
+ "api_key",
61
+ "entity_secret",
62
+ "blockchain",
63
+ "token_address",
64
+ "source_wallet_id",
65
+ "source_wallet_address",
66
+ ):
67
+ if not getattr(self, name):
68
+ raise ValueError(f"{name} must not be empty")
69
+ if self.environment not in {"TESTNET", "MAINNET"}:
70
+ raise ValueError("environment must be TESTNET or MAINNET")
71
+ if (
72
+ not math.isfinite(self.poll_interval)
73
+ or not math.isfinite(self.poll_timeout)
74
+ or self.poll_interval <= 0
75
+ or self.poll_timeout <= 0
76
+ ):
77
+ raise ValueError("poll_interval and poll_timeout must be positive")
78
+ if self.large_transfer_threshold_atomic <= 0:
79
+ raise ValueError("large_transfer_threshold_atomic must be positive")
80
+ if len(self.entity_secret) != 64:
81
+ raise ValueError("entity_secret must be a 32-byte hexadecimal value")
82
+ try:
83
+ int(self.entity_secret, 16)
84
+ except ValueError as exc:
85
+ raise ValueError("entity_secret must be a 32-byte hexadecimal value") from exc
86
+
87
+
88
+ @dataclass(frozen=True)
89
+ class CirclePayout:
90
+ contributor_id: str
91
+ environment: str
92
+ source_wallet_id: str
93
+ source_wallet_address: str
94
+ destination_address: str
95
+ asset: str
96
+ blockchain: str
97
+ amount_atomic: int
98
+ idempotency_key: str
99
+ transaction_id: str
100
+ state: str
101
+ settled_at: datetime | None
102
+ transaction_hash: str | None = None
103
+
104
+
105
+ def _circle_sdk(api_key: str, entity_secret: str) -> tuple[Any, Any]:
106
+ try:
107
+ from circle.web3 import developer_controlled_wallets, utils
108
+ except ImportError as exc:
109
+ raise RuntimeError(
110
+ "Circle's developer-controlled-wallets SDK is unavailable; "
111
+ "install the project dependencies"
112
+ ) from exc
113
+
114
+ client = utils.init_developer_controlled_wallets_client(
115
+ api_key=api_key,
116
+ entity_secret=entity_secret,
117
+ )
118
+ return (
119
+ developer_controlled_wallets.TransactionsApi(client),
120
+ developer_controlled_wallets.CreateTransferTransactionForDeveloperRequest,
121
+ )
122
+
123
+
124
+ def _as_mapping(value: Any) -> Mapping[str, Any]:
125
+ if isinstance(value, Mapping):
126
+ return value
127
+ to_dict = getattr(value, "to_dict", None)
128
+ if callable(to_dict):
129
+ return to_dict()
130
+ raise TypeError("Circle SDK returned a response in an unexpected format")
131
+
132
+
133
+ def _response_data(response: Any) -> Mapping[str, Any]:
134
+ data = getattr(response, "data", None)
135
+ if data is None:
136
+ raise CirclePayoutError("Circle response did not contain data")
137
+ return _as_mapping(data)
138
+
139
+
140
+ def _amount_in_usdc(amount_atomic: int) -> str:
141
+ whole, fractional = divmod(amount_atomic, 1_000_000)
142
+ if not fractional:
143
+ return str(whole)
144
+ return f"{whole}.{fractional:06d}".rstrip("0")
145
+
146
+
147
+ class CirclePaymentsClient:
148
+ """Submit USDC transfers and wait for Circle's terminal transaction state."""
149
+
150
+ TERMINAL_STATES = frozenset({"COMPLETE", "FAILED", "DENIED", "CANCELLED", "STUCK"})
151
+
152
+ def __init__(
153
+ self,
154
+ config: CircleConfig,
155
+ *,
156
+ transactions_api: Any | None = None,
157
+ request_factory: Callable[[Mapping[str, Any]], Any] | None = None,
158
+ sleep: Callable[[float], None] = time.sleep,
159
+ monotonic: Callable[[], float] = time.monotonic,
160
+ ) -> None:
161
+ self._config = config
162
+ if transactions_api is None or request_factory is None:
163
+ sdk_api, sdk_request_factory = _circle_sdk(
164
+ config.api_key, config.entity_secret
165
+ )
166
+ transactions_api = transactions_api or sdk_api
167
+ request_factory = request_factory or (
168
+ lambda payload: sdk_request_factory.from_dict(dict(payload))
169
+ )
170
+ self._transactions_api = transactions_api
171
+ self._request_factory = request_factory
172
+ self._sleep = sleep
173
+ self._monotonic = monotonic
174
+
175
+ @staticmethod
176
+ def mainnet_confirmation(
177
+ blockchain: str,
178
+ token_address: str,
179
+ source_wallet_id: str,
180
+ destination_address: str,
181
+ amount_atomic: int,
182
+ ) -> str:
183
+ """Return the exact value a caller must confirm before a mainnet payout."""
184
+ return (
185
+ f"{blockchain}|{token_address}|{source_wallet_id}|"
186
+ f"{destination_address}|{amount_atomic}"
187
+ )
188
+
189
+ def transfer_usdc(
190
+ self,
191
+ *,
192
+ contributor_id: str,
193
+ destination_address: str,
194
+ amount_atomic: int,
195
+ idempotency_key: str | None = None,
196
+ mainnet_confirmation: str | None = None,
197
+ wait: bool = True,
198
+ ) -> CirclePayout:
199
+ if not contributor_id:
200
+ raise ValueError("contributor_id must not be empty")
201
+ if not destination_address:
202
+ raise ValueError("destination_address must not be empty")
203
+ if isinstance(amount_atomic, bool) or not isinstance(amount_atomic, int):
204
+ raise TypeError("amount_atomic must be an integer number of USDC units")
205
+ if amount_atomic <= 0:
206
+ raise ValueError("amount_atomic must be a positive integer")
207
+ if self._config.environment == "MAINNET":
208
+ required_confirmation = self.mainnet_confirmation(
209
+ self._config.blockchain,
210
+ self._config.token_address,
211
+ self._config.source_wallet_id,
212
+ destination_address,
213
+ amount_atomic,
214
+ )
215
+ if mainnet_confirmation is None or not compare_digest(
216
+ mainnet_confirmation, required_confirmation
217
+ ):
218
+ raise ValueError(
219
+ "MAINNET payout requires confirmation of chain, token, source, "
220
+ "destination, and amount using mainnet_confirmation()"
221
+ )
222
+ if amount_atomic >= self._config.large_transfer_threshold_atomic:
223
+ warnings.warn(
224
+ "USDC payout is above the configured large-transfer threshold",
225
+ RuntimeWarning,
226
+ stacklevel=2,
227
+ )
228
+
229
+ key = idempotency_key or str(uuid4())
230
+ try:
231
+ parsed_key = UUID(key)
232
+ except (ValueError, AttributeError) as exc:
233
+ raise ValueError("idempotency_key must be a UUID v4") from exc
234
+ if parsed_key.version != 4:
235
+ raise ValueError("idempotency_key must be a UUID v4")
236
+
237
+ request = self._request_factory(
238
+ {
239
+ "walletId": self._config.source_wallet_id,
240
+ "blockchain": self._config.blockchain,
241
+ "destinationAddress": destination_address,
242
+ "tokenAddress": self._config.token_address,
243
+ "amounts": [_amount_in_usdc(amount_atomic)],
244
+ "feeLevel": "MEDIUM",
245
+ "idempotencyKey": key,
246
+ }
247
+ )
248
+ response = self._transactions_api.create_developer_transaction_transfer(
249
+ request
250
+ )
251
+ data = _response_data(response)
252
+ transaction_id = data.get("id")
253
+ state = data.get("state")
254
+ if not transaction_id or not state:
255
+ raise CirclePayoutError(
256
+ "Circle transfer response did not include transaction ID and state"
257
+ )
258
+
259
+ if wait:
260
+ data = self.wait_for_transaction(transaction_id, key, initial_data=data)
261
+ state = data["state"]
262
+ if state in {"FAILED", "DENIED", "CANCELLED", "STUCK"}:
263
+ raise CirclePayoutError(
264
+ f"Circle transaction {transaction_id} ended in state {state}",
265
+ transaction_id=str(transaction_id),
266
+ idempotency_key=key,
267
+ state=str(state),
268
+ )
269
+ settled_at = datetime.now(timezone.utc) if state == "COMPLETE" else None
270
+ return CirclePayout(
271
+ contributor_id=contributor_id,
272
+ environment=self._config.environment,
273
+ source_wallet_id=self._config.source_wallet_id,
274
+ source_wallet_address=self._config.source_wallet_address,
275
+ destination_address=destination_address,
276
+ asset="USDC",
277
+ blockchain=self._config.blockchain,
278
+ amount_atomic=amount_atomic,
279
+ idempotency_key=key,
280
+ transaction_id=str(transaction_id),
281
+ state=str(state),
282
+ settled_at=settled_at,
283
+ transaction_hash=data.get("txHash") or data.get("tx_hash"),
284
+ )
285
+
286
+ def wait_for_transaction(
287
+ self,
288
+ transaction_id: str,
289
+ idempotency_key: str,
290
+ *,
291
+ initial_data: Mapping[str, Any] | None = None,
292
+ ) -> Mapping[str, Any]:
293
+ current = dict(initial_data or {})
294
+ state = current.get("state")
295
+ deadline = self._monotonic() + self._config.poll_timeout
296
+ while state not in self.TERMINAL_STATES:
297
+ remaining = deadline - self._monotonic()
298
+ if remaining <= 0:
299
+ raise CirclePayoutTimeout(transaction_id, idempotency_key)
300
+ self._sleep(min(self._config.poll_interval, remaining))
301
+ response = self._transactions_api.get_transaction(id=transaction_id)
302
+ data = _response_data(response)
303
+ transaction = data.get("transaction")
304
+ if transaction is None:
305
+ raise CirclePayoutError(
306
+ f"Circle response omitted transaction {transaction_id}"
307
+ )
308
+ current = dict(_as_mapping(transaction))
309
+ state = current.get("state")
310
+ if not state:
311
+ raise CirclePayoutError(
312
+ f"Circle response omitted transaction state for {transaction_id}"
313
+ )
314
+
315
+ if state != "COMPLETE":
316
+ raise CirclePayoutError(
317
+ f"Circle transaction {transaction_id} ended in state {state}",
318
+ transaction_id=transaction_id,
319
+ idempotency_key=idempotency_key,
320
+ state=str(state),
321
+ )
322
+ return current