payra-sdk 1.2.2__py3-none-any.whl → 1.2.4__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.
payra_sdk/utils.py CHANGED
@@ -2,8 +2,10 @@
2
2
 
3
3
  import os
4
4
  import time
5
+ import json
5
6
  import requests
6
7
  from web3 import Web3
8
+ from pathlib import Path
7
9
  from typing import Any, Dict, Union
8
10
  from .exceptions import InvalidArgumentError
9
11
 
@@ -13,9 +15,8 @@ class PayraUtils:
13
15
  Provides helper methods for conversions and ABI-related operations.
14
16
  """
15
17
 
16
- _cache_data = None
17
- _cache_timestamp = 0
18
- _cache_ttl = 720 * 60
18
+ _cache_dir = Path.home() / ".payra_cache"
19
+ _cache_file = _cache_dir / "payra_cash_exchange_rate_cache.json"
19
20
 
20
21
  @staticmethod
21
22
  def find_function(abi: list[Dict[str, Any]], name: str) -> Dict[str, Any]:
@@ -79,43 +80,51 @@ class PayraUtils:
79
80
  def convert_to_usd(amount: float, from_currency: str) -> float:
80
81
  """
81
82
  Converts a given amount from another currency to USD using the ExchangeRate API.
82
- Requires:
83
- - EXCHANGE_RATE_API_KEY (API key only)
84
- - optional EXCHANGE_RATE_CACHE_TIME (minutes)
83
+ Caches data in ~/.payra_cache/exchange_rate.json to minimize API usage.
84
+ Default cache time: 720 minutes (12 hours).
85
85
  """
86
86
 
87
- api_key = os.getenv("EXCHANGE_RATE_API_KEY")
87
+ api_key = os.getenv("PAYRA_EXCHANGE_RATE_API_KEY")
88
88
  if not api_key:
89
- raise InvalidArgumentError("EXCHANGE_RATE_API_KEY is not set in .env")
89
+ raise InvalidArgumentError("PAYRA_EXCHANGE_RATE_API_KEY is not set in .env")
90
90
 
91
- # TTL in minutes (if not exists, use default 720)
92
- cache_minutes = int(os.getenv("EXCHANGE_RATE_CACHE_TIME", 720))
93
- PayraUtils._cache_ttl = cache_minutes * 60
91
+ cache_minutes = int(os.getenv("PAYRA_EXCHANGE_RATE_CACHE_TIME", 720))
92
+ cache_ttl = cache_minutes * 60
94
93
 
95
94
  api_url = f"https://v6.exchangerate-api.com/v6/{api_key}/latest/USD"
96
95
  from_currency = from_currency.upper()
97
-
98
96
  current_time = time.time()
99
97
 
100
- # use cache if < TTL
101
- if (
102
- PayraUtils._cache_data is not None
103
- and (current_time - PayraUtils._cache_timestamp) < PayraUtils._cache_ttl
104
- ):
105
- data = PayraUtils._cache_data
106
- else:
98
+ # Ensure cache directory exists
99
+ PayraUtils._cache_dir.mkdir(parents=True, exist_ok=True)
100
+
101
+ # Try to read cache from file
102
+ data = None
103
+ if PayraUtils._cache_file.exists():
104
+ try:
105
+ with open(PayraUtils._cache_file, "r") as f:
106
+ cache = json.load(f)
107
+ if (current_time - cache.get("timestamp", 0)) < cache_ttl:
108
+ data = cache.get("data")
109
+ except Exception:
110
+ pass # Ignore invalid cache
111
+
112
+ # Fetch new data if no valid cache
113
+ if data is None:
107
114
  try:
108
115
  response = requests.get(api_url, timeout=10)
109
116
  response.raise_for_status()
110
117
  data = response.json()
111
118
 
112
- PayraUtils._cache_data = data
113
- PayraUtils._cache_timestamp = current_time
119
+ # Save new cache
120
+ with open(PayraUtils._cache_file, "w") as f:
121
+ json.dump({"timestamp": current_time, "data": data}, f)
114
122
  except requests.RequestException as e:
115
123
  raise InvalidArgumentError(f"Failed to connect to ExchangeRate API: {e}")
116
124
  except (KeyError, ValueError) as e:
117
125
  raise InvalidArgumentError(f"Invalid data from ExchangeRate API: {e}")
118
126
 
127
+ # Validate and convert
119
128
  if "conversion_rates" not in data or from_currency not in data["conversion_rates"]:
120
129
  raise InvalidArgumentError(f"Conversion rate for {from_currency} not found in API response")
121
130
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: payra_sdk
3
- Version: 1.2.2
3
+ Version: 1.2.4
4
4
  Summary: Python SDK for Payra payment signature generation (backend)
5
5
  Author: Your Name
6
6
  Author-email: Wraith <contact@payra.cash>
@@ -26,7 +26,7 @@ Dynamic: license-file
26
26
 
27
27
  # Payra Python SDK
28
28
 
29
- Official Python SDK for integrating **Payra's on-chain payment system** into your backend applications.
29
+ Official **Python SDK** for integrating **Payra's on-chain payment system** into your backend applications.
30
30
 
31
31
  This SDK provides:
32
32
  - Secure generation of **ECDSA signatures** compatible with the Payra smart contract — used for order payment verification.
@@ -36,38 +36,38 @@ This SDK provides:
36
36
 
37
37
  The typical flow for signing and verifying a Payra transaction:
38
38
 
39
- 1. The **frontend** prepares all required payment parameters:
40
- - **Network** – blockchain name (e.g. Polygon, Linea)
41
- - **Token address** – ERC-20 token contract address
42
- - **Order ID** – unique order identifier
43
- - **AmountWei** – already converted to the smallest unit (e.g. wei, 10⁶)
44
- - **Timestamp** – Unix timestamp of the order
45
- - **Payer wallet address**
46
-
47
- 2. The frontend sends these parameters to your **backend**.
48
- 3. The **backend** uses this SDK to generate a cryptographic **ECDSA signature** with its private key (performed **offline**).
49
- 4. The backend returns the generated signature to the frontend.
50
- 5. The **frontend** calls the Payra smart contract (`payOrder`) with all parameters **plus** the signature.
39
+ 1. The **frontend** prepares all required payment parameters:
40
+ - **Network** – blockchain name (e.g. Polygon, Linea)
41
+ - **Token address** – ERC-20 token contract address
42
+ - **Order ID** – unique order identifier
43
+ - **Amount Wei** – already converted to the smallest unit (e.g. wei, 10⁶)
44
+ - **Timestamp** – Unix timestamp of the order
45
+ - **Payer wallet address** – the wallet address from which the user will make the on-chain payment
46
+ 2. The frontend sends these parameters to your **backend**.
47
+ 3. The **backend** uses this SDK to generate a cryptographic **ECDSA signature** with its private key (performed **offline**).
48
+ 4. The backend returns the generated signature to the frontend.
49
+ 5. The **frontend** calls the Payra smart contract (`payOrder`) with all parameters **plus** the signature.
51
50
 
52
51
  This process ensures full compatibility between your backend and Payra’s on-chain verification logic.
53
52
 
54
53
  ## Features
55
54
 
56
- - Generates **Ethereum ECDSA signatures** using the `secp256k1` curve.
55
+ - Generates **Ethereum ECDSA signatures** using the `secp256k1` curve.
57
56
  - Fully compatible with **Payra's Solidity smart contracts** (`ERC-1155` payment verification).
58
- - Includes built-in **ABI encoding and decoding** via [`web3.py`](https://github.com/ethereum/web3.py).
59
- - Supports environment-based configuration (`.env`) for managing multiple blockchain networks.
57
+ - Includes built-in **ABI encoding and decoding** via `web3.php`.
58
+ - Supports `.env` and `config/payra.php` configuration for multiple blockchain networks.
59
+ - Laravel IoC container integration (easy dependency injection)
60
60
  - Verifies **order payment status directly on-chain** via RPC or blockchain explorer API.
61
- - Provides **secure backend integration** using merchant private keys.
61
+ - Provides **secure backend integration** for signing and verifying transactions.
62
62
  - Includes optional utility helpers for:
63
- - **Currency conversion** (via [ExchangeRate API](https://www.exchangerate-api.com/))
64
- - **USD ⇄ WEI** conversion for token precision handling.
63
+ - **Currency conversion** (via [ExchangeRate API](https://www.exchangerate-api.com/))
64
+ - **USD ⇄ WEI** conversion for token precision handling.
65
65
 
66
66
  ## Setup
67
67
 
68
68
  Before installing this package, make sure you have an active **Payra** account:
69
69
 
70
- 👉 [https://payra.cash](https://payra.cash)
70
+ [https://payra.cash](https://payra.cash)
71
71
 
72
72
  You will need:
73
73
 
@@ -118,13 +118,13 @@ This SDK requires:
118
118
 
119
119
  ## Environment Configuration
120
120
 
121
- Create a (`.env`) file in your project root (you can copy from example):
121
+ Create a `.env` file in your project root (you can copy from example):
122
122
 
123
123
  ```bash
124
124
  cp .env.example .env
125
125
  ```
126
126
 
127
- This file stores your **private configuration** and connection settings for all supported networks. Never commit (`.env`) to version control.
127
+ This file stores your **private configuration** and connection settings for all supported networks. Never commit `.env` to version control.
128
128
 
129
129
  ### Required Variables
130
130
 
@@ -133,8 +133,9 @@ This file stores your **private configuration** and connection settings for all
133
133
  Used for automatic fiat → USD conversions via the built-in Payra utilities.
134
134
 
135
135
  ```bash
136
- EXCHANGE_RATE_API_KEY= # Your ExchangeRate API key (from exchangerate-api.com)
137
- EXCHANGE_RATE_CACHE_TIME=720 # Cache duration in minutes (default: 720 = 12h)
136
+ # Optional only needed if you want to use the built-in currency conversion helper
137
+ PAYRA_EXCHANGE_RATE_API_KEY= # Your ExchangeRate API key (from exchangerate-api.com)
138
+ PAYRA_EXCHANGE_RATE_CACHE_TIME=720 # Cache duration in minutes (default: 720 = 12h)
138
139
 
139
140
  PAYRA_POLYGON_CORE_FORWARD_CONTRACT_ADDRESS=0xf30070da76B55E5cB5750517E4DECBD6Cc5ce5a8
140
141
  PAYRA_POLYGON_PRIVATE_KEY=
@@ -158,7 +159,7 @@ PAYRA_LINEA_RPC_URL_2=
158
159
  #### Important Notes
159
160
 
160
161
  - The cache automatically refreshes when it expires.
161
- - You can adjust the cache duration by setting `EXCHANGE_RATE_CACHE_TIME`:
162
+ - You can adjust the cache duration by setting `PAYRA_EXCHANGE_RATE_CACHE_TIME`:
162
163
  - `5` → cache for 5 minutes
163
164
  - `60` → cache for 1 hour
164
165
  - `720` → cache for 12 hours (default)
@@ -208,10 +209,21 @@ except Exception as e:
208
209
  print(f"Unexpected error: {e}")
209
210
  ```
210
211
 
212
+ #### Input Parameters
213
+
214
+ | Field | Type | Description |
215
+ |--------------|----------|----------------------------------------------|
216
+ | **`network`** | `string` | Selected network name |
217
+ | **`tokenAddress`** | `string` | ERC20 token contract address |
218
+ | **`orderId`** | `string` | Unique order reference (e.g. ORDER-123) |
219
+ | **`amountWei`** | `string` or `integer` | Token amount in smallest unit (e.g. wei) |
220
+ | **`timestamp`** | `number` | Unix timestamp of signature creation |
221
+ | **`payerAddress`** | `string` | Payer Wallet Address
222
+
211
223
  #### Behind the Scenes
212
224
 
213
225
  1. The backend converts the amount to the smallest blockchain unit (e.g. wei).
214
- 3. A `PayraSignatureGenerator` instance is created using your private key from (`.env`).
226
+ 3. A `PayraSignatureGenerator` instance is created using your private key from `.env`
215
227
  4. It generates an ECDSA signature that is fully verifiable on-chain by the Payra smart contract.
216
228
  5. The resulting signature should be sent to the **frontend**, which must call `payOrder(...)` using the same parameters (`timestamp`, `orderId`, `amount`, `tokenAddress`, etc.) that were used to generate the signature.
217
229
 
@@ -305,11 +317,11 @@ python3 example_order_verification.py
305
317
  python3 example_utils.py
306
318
  ```
307
319
 
308
- Make sure your (`.env`) file contains correct values for the `network` being used.
320
+ Make sure your `.env` file contains correct values for the `network` being used.
309
321
 
310
322
  ### Tips
311
323
 
312
- - Always verify your (`.env`) configuration before running any signing or on-chain verification examples.
324
+ - Always verify your `.env` configuration before running any signing or on-chain verification examples.
313
325
  - The SDK examples are safe to run — they use **read-only RPC calls** (no real transactions are broadcast).
314
326
  - You can modify `example_signature.py` to test custom token addresses or order parameters.
315
327
 
@@ -2,9 +2,9 @@ payra_sdk/__init__.py,sha256=VMmHadXy0RLCjEPZhW_hCc3hg34pkmrL4VhTjqmVBiI,422
2
2
  payra_sdk/exceptions.py,sha256=Dr8dy0RohAYII_-YeSu_doPJSr0EsJPcp6Oj02sio9Q,425
3
3
  payra_sdk/order_verification.py,sha256=IWKV4V6gZRyrtJtXsDRPflUcSsuN5D1kFZn5QVTPi5Q,3379
4
4
  payra_sdk/signature.py,sha256=Vn85w4DAGzHK1y9h3hMETij_-Qa4aSNz0KwnzwCyFQw,8613
5
- payra_sdk/utils.py,sha256=zNQxq0u9oCO0J3je5jSVPeeT_blBbs5TsqZzL_801u0,4374
6
- payra_sdk-1.2.2.dist-info/licenses/LICENSE,sha256=mnnujAcvHr1ULEDD2l0ZT6lrpeTv_9bG3n8sngv7ew8,120
7
- payra_sdk-1.2.2.dist-info/METADATA,sha256=nbSzmSh6nNNGorxELDeqpFf67Ru4eioO4s5U_vfPyFE,11696
8
- payra_sdk-1.2.2.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
9
- payra_sdk-1.2.2.dist-info/top_level.txt,sha256=oC4dhGzjcpDRRwyU9JjtLu56Uc5moaa76utQGYsPL-g,10
10
- payra_sdk-1.2.2.dist-info/RECORD,,
5
+ payra_sdk/utils.py,sha256=gIQZX9N97Eneh5ScJ-YWY8_8wRqxBe0h5lDAVFYV8CE,4854
6
+ payra_sdk-1.2.4.dist-info/licenses/LICENSE,sha256=mnnujAcvHr1ULEDD2l0ZT6lrpeTv_9bG3n8sngv7ew8,120
7
+ payra_sdk-1.2.4.dist-info/METADATA,sha256=BF0bsVhP4ycHdUfzYPG1q6c6zR_z5aG2i2toHAGRW2c,12574
8
+ payra_sdk-1.2.4.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
9
+ payra_sdk-1.2.4.dist-info/top_level.txt,sha256=oC4dhGzjcpDRRwyU9JjtLu56Uc5moaa76utQGYsPL-g,10
10
+ payra_sdk-1.2.4.dist-info/RECORD,,