sofizpay-python-sdk 1.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.
sofizpay/exceptions.py ADDED
@@ -0,0 +1,46 @@
1
+ """Custom exceptions for SofizPay SDK"""
2
+
3
+
4
+ class SofizPayError(Exception):
5
+ """Base exception for all SofizPay SDK errors"""
6
+ pass
7
+
8
+
9
+ class PaymentError(SofizPayError):
10
+ """Exception raised for payment-related errors"""
11
+ pass
12
+
13
+
14
+ class TransactionError(SofizPayError):
15
+ """Exception raised for transaction-related errors"""
16
+ pass
17
+
18
+
19
+ class NetworkError(SofizPayError):
20
+ """Exception raised for network-related errors"""
21
+ pass
22
+
23
+
24
+ class ValidationError(SofizPayError):
25
+ """Exception raised for validation errors"""
26
+ pass
27
+
28
+
29
+ class RateLimitError(NetworkError):
30
+ """Exception raised when API rate limit is exceeded"""
31
+ pass
32
+
33
+
34
+ class InsufficientBalanceError(PaymentError):
35
+ """Exception raised when account has insufficient balance"""
36
+ pass
37
+
38
+
39
+ class InvalidAccountError(ValidationError):
40
+ """Exception raised when account is invalid"""
41
+ pass
42
+
43
+
44
+ class InvalidAssetError(ValidationError):
45
+ """Exception raised when asset is invalid"""
46
+ pass
sofizpay/payments.py ADDED
@@ -0,0 +1,202 @@
1
+ """Payment management for SofizPay SDK"""
2
+
3
+ import time
4
+ from datetime import datetime
5
+ from typing import Optional, Dict, Any
6
+ from stellar_sdk import (
7
+ Server, Keypair, Asset, TransactionBuilder,
8
+ Network, Memo
9
+ )
10
+ from stellar_sdk.operation import Payment
11
+ from stellar_sdk.exceptions import SdkError
12
+
13
+ from .exceptions import PaymentError, ValidationError, NetworkError
14
+ from .utils import (
15
+ validate_public_key, validate_secret_key, get_public_key_from_secret,
16
+ validate_amount, validate_memo
17
+ )
18
+
19
+
20
+ class PaymentManager:
21
+ """Manages payment operations using Stellar network"""
22
+
23
+ ASSET_CODE = "DZT"
24
+ ASSET_ISSUER = "GCAZI7YBLIDJWIVEL7ETNAZGPP3LC24NO6KAOBWZHUERXQ7M5BC52DLV"
25
+
26
+ def __init__(self, server_url: str = "https://horizon.stellar.org"):
27
+ """
28
+ Initialize PaymentManager
29
+
30
+ Args:
31
+ server_url: Stellar Horizon server URL
32
+ """
33
+ self.server = Server(horizon_url=server_url)
34
+ self.network_passphrase = Network.PUBLIC_NETWORK_PASSPHRASE
35
+
36
+ async def send_payment(
37
+ self,
38
+ source_secret: str,
39
+ destination_public_key: str,
40
+ amount: str,
41
+ memo: Optional[str] = None
42
+ ) -> Dict[str, Any]:
43
+ """
44
+ Send a payment on the Stellar network
45
+
46
+ Args:
47
+ source_secret: Secret key of the source account
48
+ destination_public_key: Public key of the destination account
49
+ amount: Amount to send
50
+ memo: Optional memo to attach to transaction
51
+
52
+ Returns:
53
+ Dictionary with transaction result
54
+
55
+ Raises:
56
+ PaymentError: When payment fails
57
+ ValidationError: When input validation fails
58
+ """
59
+ start_time = time.time()
60
+
61
+ try:
62
+ asset_code = self.ASSET_CODE
63
+ asset_issuer = self.ASSET_ISSUER
64
+
65
+ if not validate_secret_key(source_secret):
66
+ raise ValidationError("Invalid source secret key")
67
+
68
+ if not validate_public_key(destination_public_key):
69
+ raise ValidationError("Invalid destination public key")
70
+
71
+ if not validate_amount(amount):
72
+ raise ValidationError("Invalid amount")
73
+
74
+ source_keypair = Keypair.from_secret(source_secret)
75
+ source_public_key = source_keypair.public_key
76
+
77
+ asset = Asset(asset_code, asset_issuer)
78
+
79
+ try:
80
+ source_account = self.server.load_account(source_public_key)
81
+ except Exception as e:
82
+ raise PaymentError(f"Failed to load source account: {e}")
83
+
84
+ transaction_builder = TransactionBuilder(
85
+ source_account=source_account,
86
+ network_passphrase=self.network_passphrase,
87
+ base_fee=200
88
+ )
89
+
90
+ payment_operation = Payment(
91
+ destination=destination_public_key,
92
+ asset=asset,
93
+ amount=str(amount)
94
+ )
95
+ transaction_builder.append_operation(payment_operation)
96
+
97
+ if memo:
98
+ is_valid, processed_memo = validate_memo(memo)
99
+ if is_valid and processed_memo:
100
+ transaction_builder.add_text_memo(processed_memo)
101
+
102
+ transaction_builder.set_timeout(60)
103
+ transaction = transaction_builder.build()
104
+
105
+ transaction.sign(source_keypair)
106
+
107
+ try:
108
+ response = self.server.submit_transaction(transaction)
109
+
110
+ return {
111
+ "success": True,
112
+ "transaction_id": response.get("hash"),
113
+ "transaction_hash": response.get("hash"),
114
+ "amount": amount,
115
+ "memo": memo,
116
+ "destination_public_key": destination_public_key,
117
+ "duration": time.time() - start_time,
118
+ "timestamp": datetime.now().isoformat()
119
+ }
120
+
121
+ except SdkError as e:
122
+ raise PaymentError(f"Transaction submission failed: {e}")
123
+
124
+ except (ValidationError, PaymentError):
125
+ raise
126
+ except Exception as e:
127
+ detailed_error = self._extract_error_details(e)
128
+ raise PaymentError(detailed_error)
129
+
130
+ def _extract_error_details(self, error: Exception) -> str:
131
+ """Extract detailed error information from Stellar SDK error"""
132
+ detailed_error = str(error)
133
+
134
+ if hasattr(error, 'response') and error.response:
135
+ if hasattr(error.response, 'json'):
136
+ try:
137
+ error_data = error.response.json()
138
+
139
+ if 'extras' in error_data:
140
+ extras = error_data['extras']
141
+
142
+ if 'result_codes' in extras:
143
+ codes = extras['result_codes']
144
+ if 'transaction' in codes:
145
+ detailed_error = f"Transaction error: {codes['transaction']}"
146
+ if 'operations' in codes and codes['operations']:
147
+ detailed_error += f" | Operation errors: {', '.join(codes['operations'])}"
148
+
149
+ if 'envelope_xdr' in extras:
150
+ pass
151
+ if 'result_xdr' in extras:
152
+ pass
153
+
154
+ except Exception:
155
+ pass
156
+
157
+ return detailed_error
158
+
159
+ async def get_balance(self, public_key: str) -> float:
160
+ """
161
+ Get balance for an account
162
+
163
+ Args:
164
+ public_key: Public key of the account
165
+
166
+ Returns:
167
+ balance as float
168
+
169
+ Raises:
170
+ ValidationError: When public key is invalid
171
+ NetworkError: When unable to fetch account data
172
+ """
173
+ if not validate_public_key(public_key):
174
+ raise ValidationError("Invalid public key")
175
+
176
+ try:
177
+ account_details = self.server.accounts().account_id(public_key).call()
178
+
179
+ for balance in account_details['balances']:
180
+ if (balance.get('asset_code') == self.ASSET_CODE and
181
+ balance.get('asset_issuer') == self.ASSET_ISSUER):
182
+ return float(balance['balance'])
183
+
184
+ return 0.0
185
+
186
+ except Exception as e:
187
+ raise NetworkError(f"Error fetching balance: {e}")
188
+
189
+ def get_public_key_from_secret(self, secret_key: str) -> str:
190
+ """
191
+ Extract public key from secret key
192
+
193
+ Args:
194
+ secret_key: The secret key
195
+
196
+ Returns:
197
+ The corresponding public key
198
+
199
+ Raises:
200
+ ValidationError: If secret key is invalid
201
+ """
202
+ return get_public_key_from_secret(secret_key)
@@ -0,0 +1,389 @@
1
+ """Transaction management and streaming for SofizPay SDK"""
2
+
3
+ import asyncio
4
+ import requests
5
+ from datetime import datetime, timezone
6
+ from typing import Dict, Any, List, Optional, Callable
7
+ from stellar_sdk import Server
8
+ from stellar_sdk.exceptions import SdkError
9
+
10
+ from .exceptions import TransactionError, ValidationError, NetworkError
11
+ from .utils import validate_public_key, fetch_with_retry, RateLimiter
12
+
13
+
14
+ class TransactionManager:
15
+ """Manages transaction operations and streaming"""
16
+
17
+ ASSET_CODE = "DZT"
18
+ ASSET_ISSUER = "GCAZI7YBLIDJWIVEL7ETNAZGPP3LC24NO6KAOBWZHUERXQ7M5BC52DLV"
19
+
20
+ def __init__(self, server_url: str = "https://horizon.stellar.org"):
21
+ """
22
+ Initialize TransactionManager
23
+ Args:
24
+ server_url: Stellar Horizon server URL
25
+ """
26
+ self.server = Server(horizon_url=server_url)
27
+ self.rate_limiter = RateLimiter(max_calls=10, time_window=1)
28
+ self._streaming_tasks = {}
29
+ self.session = requests.Session()
30
+ self.session.headers.update({
31
+ 'User-Agent': 'SofizPay SDK/Python',
32
+ 'Accept': 'application/json'
33
+ })
34
+
35
+ async def setup_transaction_stream(
36
+ self,
37
+ public_key: str,
38
+ transaction_callback: Callable[[Dict[str, Any]], None],
39
+ from_now: bool = True,
40
+ check_interval: int = 30
41
+ ) -> str:
42
+ """
43
+ Set up real-time transaction streaming for an account (يعمل مثل JavaScript تماماً)
44
+
45
+ Args:
46
+ public_key: Public key to monitor
47
+ transaction_callback: Callback function to handle new transactions
48
+ from_now: If True, only new transactions after stream start are sent, If False, both new and historical transactions are sent
49
+ check_interval: Duration in seconds for repeated network checks (default 30 seconds)
50
+
51
+ Returns:
52
+ Stream ID for managing the stream
53
+ """
54
+ if not validate_public_key(public_key):
55
+ raise ValidationError("Invalid public key")
56
+
57
+ if check_interval < 5 :
58
+ raise ValidationError("Check interval must be more then 5 seconds")
59
+
60
+ stream_id = f"stream_{public_key}_{id(transaction_callback)}"
61
+
62
+ from datetime import datetime, timezone
63
+ stream_start_time = datetime.now(timezone.utc)
64
+
65
+ if not from_now:
66
+ try:
67
+ previous_transactions = await self.get_transactions(public_key, 200)
68
+
69
+ if previous_transactions:
70
+ for tx in reversed(previous_transactions):
71
+ formatted_transaction = {
72
+ 'id': tx.get('hash') or tx.get('id'),
73
+ 'transactionId': tx.get('hash') or tx.get('id'),
74
+ 'hash': tx.get('hash') or tx.get('id'),
75
+ 'amount': str(tx.get('amount', '0')),
76
+ 'memo': tx.get('memo', ''),
77
+ 'type': tx.get('type', 'unknown'),
78
+ 'from': tx.get('from', ''),
79
+ 'to': tx.get('to', ''),
80
+ 'asset_code': tx.get('asset_code', ''),
81
+ 'asset_issuer': tx.get('asset_issuer', ''),
82
+ 'status': 'completed',
83
+ 'timestamp': tx.get('created_at'),
84
+ 'created_at': tx.get('created_at'),
85
+ 'processed_at': tx.get('created_at'),
86
+ 'isHistorical': True
87
+ }
88
+
89
+ try:
90
+ if asyncio.iscoroutinefunction(transaction_callback):
91
+ await transaction_callback(formatted_transaction)
92
+ else:
93
+ transaction_callback(formatted_transaction)
94
+ await asyncio.sleep(0.05)
95
+ except Exception as e:
96
+ print(f"Error in historical callback: {e}")
97
+
98
+ history_complete = {
99
+ 'id': 'HISTORY_COMPLETE',
100
+ 'isHistoryComplete': True,
101
+ 'historicalCount': len(previous_transactions),
102
+ 'message': f'{len(previous_transactions)} historical transactions loaded, now listening for new transactions...'
103
+ }
104
+
105
+ try:
106
+ if asyncio.iscoroutinefunction(transaction_callback):
107
+ await transaction_callback(history_complete)
108
+ else:
109
+ transaction_callback(history_complete)
110
+ except Exception as e:
111
+ print(f"Error in history complete callback: {e}")
112
+
113
+ except Exception as error:
114
+ print(f'{error}')
115
+
116
+ async def tx_handler(tx_response):
117
+
118
+ try:
119
+ if from_now:
120
+ transaction_time_str = tx_response.get('created_at', '')
121
+ if transaction_time_str:
122
+ try:
123
+ transaction_time = datetime.fromisoformat(transaction_time_str.replace('Z', '+00:00'))
124
+ if transaction_time <= stream_start_time:
125
+ return
126
+ except Exception as date_error:
127
+ print(f"{date_error}")
128
+ return
129
+
130
+ transaction_url = f"{self.server.horizon_url}/transactions/{tx_response.get('id')}"
131
+ transaction_data = await fetch_with_retry(transaction_url)
132
+ memo = transaction_data.get('memo', '')
133
+
134
+ operations_url = f"{self.server.horizon_url}/transactions/{transaction_data.get('id')}/operations"
135
+ operations_data = await fetch_with_retry(operations_url)
136
+
137
+ operations = [
138
+ op for op in operations_data.get('_embedded', {}).get('records', [])
139
+ if (op.get('asset_code') == self.ASSET_CODE and
140
+ op.get('asset_issuer') == self.ASSET_ISSUER and
141
+ op.get('amount'))
142
+ ]
143
+
144
+ for operation in operations:
145
+ transaction_type = 'sent' if operation.get('from') == public_key else 'received'
146
+
147
+ new_transaction = {
148
+ 'id': transaction_data.get('hash'),
149
+ 'transactionId': transaction_data.get('hash'),
150
+ 'hash': transaction_data.get('hash'),
151
+ 'amount': str(operation.get('amount', '0')),
152
+ 'memo': memo,
153
+ 'type': transaction_type,
154
+ 'from': operation.get('from', ''),
155
+ 'to': operation.get('to') or operation.get('destination', ''),
156
+ 'asset_code': operation.get('asset_code', ''),
157
+ 'asset_issuer': operation.get('asset_issuer', ''),
158
+ 'status': 'completed',
159
+ 'timestamp': transaction_data.get('created_at'),
160
+ 'created_at': transaction_data.get('created_at'),
161
+ 'processed_at': datetime.now().isoformat(),
162
+ 'isHistorical': False
163
+ }
164
+
165
+ try:
166
+ if asyncio.iscoroutinefunction(transaction_callback):
167
+ await transaction_callback(new_transaction)
168
+ else:
169
+ transaction_callback(new_transaction)
170
+ except Exception as e:
171
+ print(f"Error in callback: {e}")
172
+
173
+ except Exception as error:
174
+ print(f'Error fetching transaction details: {error}')
175
+
176
+ async def start_stream():
177
+ try:
178
+ while stream_id in self._streaming_tasks:
179
+ try:
180
+ stream_builder = (self.server.transactions()
181
+ .for_account(public_key)
182
+ .cursor('now')
183
+ .order('desc')
184
+ .limit(10))
185
+
186
+ response = stream_builder.call()
187
+
188
+ for transaction in response.get('_embedded', {}).get('records', []):
189
+ await tx_handler(transaction)
190
+
191
+ await asyncio.sleep(check_interval)
192
+
193
+ except Exception as error:
194
+ print(f'Error in transaction stream: {error}')
195
+
196
+ await asyncio.sleep(check_interval)
197
+
198
+ except asyncio.CancelledError:
199
+ print(f'Stream {stream_id} cancelled')
200
+ except Exception as error:
201
+ print(f'Error starting transaction stream: {error}')
202
+ await asyncio.sleep(check_interval)
203
+ await start_stream()
204
+
205
+ task = asyncio.create_task(start_stream())
206
+ self._streaming_tasks[stream_id] = task
207
+
208
+ return stream_id
209
+
210
+ def stop_transaction_stream(self, stream_id: str) -> bool:
211
+ """
212
+ Stop a transaction stream
213
+
214
+ Args:
215
+ stream_id: ID of the stream to stop
216
+
217
+ Returns:
218
+ True if stream was stopped, False if not found
219
+ """
220
+ if stream_id in self._streaming_tasks:
221
+ self._streaming_tasks[stream_id].cancel()
222
+ del self._streaming_tasks[stream_id]
223
+ return True
224
+ return False
225
+
226
+ async def get_all_transactions(
227
+ self,
228
+ public_key: str,
229
+ limit: int = 200
230
+ ) -> List[Dict[str, Any]]:
231
+ """
232
+ Get transactions for an account (filtering only operations)
233
+
234
+ Args:
235
+ public_key: Public key of the account
236
+ limit: Maximum number of transactions to retrieve
237
+
238
+ Returns:
239
+ List of transaction dictionaries
240
+
241
+ Raises:
242
+ ValidationError: When public key is invalid
243
+ NetworkError: When unable to fetch transactions
244
+ """
245
+ if not validate_public_key(public_key):
246
+ raise ValidationError("Invalid public key")
247
+ try:
248
+ transactions_response = (self.server.transactions()
249
+ .for_account(public_key)
250
+ .order('desc')
251
+ .limit(limit)
252
+ .call())
253
+ return transactions_response.get('_embedded', {}).get('records', [])
254
+ except Exception as e:
255
+ raise NetworkError(f"Error fetching transactions: {e}")
256
+
257
+ async def get_transactions(
258
+ self,
259
+ public_key: str,
260
+ limit: Optional[int] = None
261
+ ) -> List[Dict[str, Any]]:
262
+ """
263
+ Get comprehensive transactions for an account (Optimized & Complete)
264
+
265
+ Args:
266
+ public_key: Public key of the account
267
+ limit: Maximum number of transactions (fetch all if None)
268
+ """
269
+ if not validate_public_key(public_key):
270
+ raise ValidationError("Invalid public key")
271
+
272
+ page_size = 200 if limit is None or limit > 200 else limit
273
+ dzt_transactions = []
274
+ cursor = ""
275
+ has_more = True
276
+
277
+ try:
278
+ while has_more:
279
+ # Use /operations instead of /payments for 100% coverage
280
+ url = f"{self.server.horizon_url}/accounts/{public_key}/operations?limit={page_size}&order=desc&join=transactions"
281
+ if cursor:
282
+ url += f"&cursor={cursor}"
283
+
284
+ data = await fetch_with_retry(url, session=self.session)
285
+ records = data.get('_embedded', {}).get('records', [])
286
+
287
+ if not records:
288
+ break
289
+
290
+ for op in records:
291
+ tx_detail = op.get('transaction', {})
292
+
293
+ tx_data = {
294
+ 'id': op.get('transaction_hash'),
295
+ 'hash': op.get('transaction_hash'),
296
+ 'created_at': op.get('created_at'),
297
+ 'memo': tx_detail.get('memo', ''),
298
+ 'successful': tx_detail.get('successful', True),
299
+ 'paging_token': op.get('paging_token')
300
+ }
301
+
302
+ # 1. Handle Payments (Direct & Path)
303
+ is_payment = op.get('type') in ['payment', 'path_payment_strict_receive', 'path_payment_strict_send']
304
+ if is_payment and op.get('asset_code') == self.ASSET_CODE and op.get('asset_issuer') == self.ASSET_ISSUER:
305
+ tx_data.update({
306
+ 'type': 'sent' if op.get('from') == public_key else 'received',
307
+ 'amount': str(op.get('amount', '0')),
308
+ 'from': op.get('from'),
309
+ 'to': op.get('to') or op.get('destination', ''),
310
+ 'asset_code': op.get('asset_code'),
311
+ 'asset_issuer': op.get('asset_issuer'),
312
+ 'category': 'payment'
313
+ })
314
+ dzt_transactions.append(tx_data)
315
+
316
+ # 2. Handle Trustline (DZT)
317
+ elif op.get('type') == 'change_trust' and op.get('asset_code') == self.ASSET_CODE and op.get('asset_issuer') == self.ASSET_ISSUER:
318
+ tx_data.update({
319
+ 'type': 'trustline',
320
+ 'category': 'setup',
321
+ 'asset_code': op.get('asset_code'),
322
+ 'amount': '0'
323
+ })
324
+ dzt_transactions.append(tx_data)
325
+
326
+ # 3. Handle Account Creation
327
+ elif op.get('type') == 'create_account' and op.get('account') == public_key:
328
+ tx_data.update({
329
+ 'type': 'account_created',
330
+ 'category': 'setup',
331
+ 'amount': str(op.get('starting_balance', '0')),
332
+ 'from': op.get('funder'),
333
+ 'asset_code': 'XLM'
334
+ })
335
+ dzt_transactions.append(tx_data)
336
+
337
+ if limit and len(dzt_transactions) >= limit:
338
+ has_more = False
339
+ break
340
+
341
+ if not has_more:
342
+ break
343
+
344
+ if len(records) < page_size:
345
+ has_more = False
346
+ else:
347
+ cursor = records[-1].get('paging_token')
348
+
349
+ return dzt_transactions
350
+
351
+ except Exception as e:
352
+ raise NetworkError(f"Error fetching transactions: {e}")
353
+
354
+ async def get_transaction_by_hash(self, transaction_hash: str) -> Dict[str, Any]:
355
+ """
356
+ Get detailed transaction information by hash
357
+
358
+ Args:
359
+ transaction_hash: Hash of the transaction to retrieve
360
+
361
+ Returns:
362
+ Detailed transaction information
363
+
364
+ Raises:
365
+ TransactionError: When transaction is not found or error occurs
366
+ """
367
+ if not transaction_hash:
368
+ raise TransactionError("Transaction hash is required")
369
+ try:
370
+ transaction_data = self.server.transactions().transaction(transaction_hash).call()
371
+ return {
372
+ 'success': True,
373
+ 'found': True,
374
+ 'transaction': transaction_data,
375
+ 'hash': transaction_hash,
376
+ 'message': 'Transaction found'
377
+ }
378
+ except SdkError as e:
379
+ if "404" in str(e):
380
+ return {'success': True, 'found': False, 'transaction': None, 'hash': transaction_hash, 'message': 'Transaction not found'}
381
+ else:
382
+ raise TransactionError(f"Error fetching transaction: {e}")
383
+ except Exception as e:
384
+ return {'success': False, 'found': False, 'error': str(e), 'hash': transaction_hash}
385
+
386
+ def __del__(self):
387
+ """Cleanup streaming tasks when object is destroyed"""
388
+ for stream_id in list(self._streaming_tasks.keys()):
389
+ self.stop_transaction_stream(stream_id)