grid402 2.2.0__tar.gz → 2.5.1__tar.gz
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.
- {grid402-2.2.0 → grid402-2.5.1}/PKG-INFO +47 -19
- {grid402-2.2.0 → grid402-2.5.1}/README.md +38 -11
- {grid402-2.2.0 → grid402-2.5.1}/grid402/__init__.py +25 -2
- {grid402-2.2.0 → grid402-2.5.1}/grid402/agentkit.py +35 -5
- {grid402-2.2.0 → grid402-2.5.1}/grid402/client.py +143 -1
- {grid402-2.2.0 → grid402-2.5.1}/grid402/exceptions.py +1 -1
- grid402-2.5.1/grid402/models.py +207 -0
- {grid402-2.2.0 → grid402-2.5.1}/grid402.egg-info/PKG-INFO +47 -19
- {grid402-2.2.0 → grid402-2.5.1}/grid402.egg-info/requires.txt +1 -0
- {grid402-2.2.0 → grid402-2.5.1}/pyproject.toml +11 -7
- {grid402-2.2.0 → grid402-2.5.1}/tests/test_live_sandbox.py +1 -1
- grid402-2.5.1/tests/test_sdk.py +361 -0
- grid402-2.2.0/grid402/models.py +0 -119
- grid402-2.2.0/tests/test_sdk.py +0 -205
- {grid402-2.2.0 → grid402-2.5.1}/LICENSE +0 -0
- {grid402-2.2.0 → grid402-2.5.1}/grid402/py.typed +0 -0
- {grid402-2.2.0 → grid402-2.5.1}/grid402.egg-info/SOURCES.txt +0 -0
- {grid402-2.2.0 → grid402-2.5.1}/grid402.egg-info/dependency_links.txt +0 -0
- {grid402-2.2.0 → grid402-2.5.1}/grid402.egg-info/top_level.txt +0 -0
- {grid402-2.2.0 → grid402-2.5.1}/setup.cfg +0 -0
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: grid402
|
|
3
|
-
Version: 2.
|
|
4
|
-
Summary: SDK Python oficial do Grid402: Micropagamentos HTTP 402 na Base para Agentes Autonomos e IA
|
|
5
|
-
Author-email: Grid402 Team <contato@grid402.
|
|
3
|
+
Version: 2.5.1
|
|
4
|
+
Summary: SDK Python oficial do Grid402: Micropagamentos HTTP 402 na Base e Prova Criptografica de Oraculo para Agentes Autonomos e IA
|
|
5
|
+
Author-email: Grid402 Team <contato@grid402.online>
|
|
6
6
|
License-Expression: MIT
|
|
7
|
-
Project-URL: Homepage, https://grid402.
|
|
8
|
-
Project-URL: Documentation, https://grid402.
|
|
9
|
-
Project-URL: Repository, https://github.com/
|
|
10
|
-
Project-URL: Issues, https://github.com/
|
|
11
|
-
Keywords: x402,http-402,micropayments,base,coinbase-agentkit,agentic-web,mcp,ai-agents
|
|
7
|
+
Project-URL: Homepage, https://grid402.online
|
|
8
|
+
Project-URL: Documentation, https://grid402.online
|
|
9
|
+
Project-URL: Repository, https://github.com/oliveiratc/Grid402
|
|
10
|
+
Project-URL: Issues, https://github.com/oliveiratc/Grid402/issues
|
|
11
|
+
Keywords: x402,http-402,micropayments,base,coinbase-agentkit,agentic-web,mcp,ai-agents,oracle,proof-of-data,secp256k1
|
|
12
12
|
Classifier: Development Status :: 5 - Production/Stable
|
|
13
13
|
Classifier: Intended Audience :: Developers
|
|
14
14
|
Classifier: Programming Language :: Python :: 3
|
|
@@ -24,6 +24,7 @@ Requires-Python: >=3.9
|
|
|
24
24
|
Description-Content-Type: text/markdown
|
|
25
25
|
License-File: LICENSE
|
|
26
26
|
Requires-Dist: pydantic>=2.0.0
|
|
27
|
+
Requires-Dist: cryptography>=41.0.0
|
|
27
28
|
Provides-Extra: dev
|
|
28
29
|
Requires-Dist: build; extra == "dev"
|
|
29
30
|
Requires-Dist: twine; extra == "dev"
|
|
@@ -39,7 +40,7 @@ Projetada especificamente para agentes autonomos de inteligencia artificial, fra
|
|
|
39
40
|
|
|
40
41
|
## Recursos Principais
|
|
41
42
|
|
|
42
|
-
- **
|
|
43
|
+
- **11 Ferramentas Integradas:** Indicadores macroeconomicos (Selic, CDI, IPCA), calculadora de dias uteis financeiros ANBIMA, feriados nacionais e bancarios ANBIMA, CNPJ da Receita Federal, CEP postal e IBGE, cotacoes Forex e Cripto spot, resolucao DNS, auditoria TLS e SSL, analise ASN e BGP e status do ecossistema.
|
|
43
44
|
- **Zero Cadastro e Zero Friccao:** Sem necessidade de chaves de API estaticas ou contratos mensais.
|
|
44
45
|
- **Modo Sandbox Gratuito:** Teste e homologue localmente sem custos informando `sandbox=True`.
|
|
45
46
|
- **Integracao Nativa com IA:** Compativel com Coinbase Developer Platform (CDP) AgentKit, LangChain e CrewAI.
|
|
@@ -131,13 +132,39 @@ print("Comprovante on-chain:", resultado.get("_x402_settlement"))
|
|
|
131
132
|
Para fluxos de trabalho tipados e validacao antecipada:
|
|
132
133
|
|
|
133
134
|
```python
|
|
134
|
-
from grid402 import CnpjInput, CepInput, DnsInput, SslInput, AsnInput,
|
|
135
|
+
from grid402 import CnpjInput, CepInput, DnsInput, SslInput, AsnInput, HolidaysInput, WorkdaysInput
|
|
135
136
|
|
|
136
137
|
# Validacao de entrada antes do envio
|
|
137
138
|
payload_cnpj = CnpjInput(cnpj="00.000.000/0001-91")
|
|
138
139
|
payload_cep = CepInput(code="01310100")
|
|
139
140
|
payload_dns = DnsInput(domain="base.org")
|
|
140
141
|
payload_holidays = HolidaysInput(year=2026)
|
|
142
|
+
payload_workdays = WorkdaysInput(start_date="2026-11-06", days=5)
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
---
|
|
146
|
+
|
|
147
|
+
### 5. Verificacao Criptografica de Prova de Autenticidade (Proof of Data)
|
|
148
|
+
|
|
149
|
+
Todas as respostas de dados pagas e em sandbox trazem uma prova matematica de oraculo (`_oracle_proof`) assinada via ECDSA secp256k1 pela carteira oficial do Grid402 (`0xa592625adbceb8e025ac383f1a3fd8ebb6a63f90`).
|
|
150
|
+
|
|
151
|
+
O SDK permite verificar matematicamente a integridade dos dados e a autenticidade do emissor em menos de 5 milissegundos sem chamadas de rede adicionais:
|
|
152
|
+
|
|
153
|
+
```python
|
|
154
|
+
from grid402 import Grid402Client
|
|
155
|
+
|
|
156
|
+
client = Grid402Client(sandbox=True)
|
|
157
|
+
dados = client.get_workdays(start_date="2026-11-06", days=5)
|
|
158
|
+
|
|
159
|
+
# Validacao matematica local e instantanea
|
|
160
|
+
verificacao = client.verify_proof(dados)
|
|
161
|
+
|
|
162
|
+
if verificacao.valid:
|
|
163
|
+
print("Dados autenticos assinados pelo oraculo Grid402!")
|
|
164
|
+
print("Endereco do oraculo:", verificacao.oracle_address)
|
|
165
|
+
print("Carimbo temporal:", verificacao.timestamp)
|
|
166
|
+
else:
|
|
167
|
+
print("Falha na autenticidade dos dados:", verificacao.error)
|
|
141
168
|
```
|
|
142
169
|
|
|
143
170
|
---
|
|
@@ -147,15 +174,16 @@ payload_holidays = HolidaysInput(year=2026)
|
|
|
147
174
|
| Metodo | Descricao | Preco Base (USDC) |
|
|
148
175
|
|---|---|---|
|
|
149
176
|
| `get_summary()` | Resumo operacional consolidado de saude | Gratuito |
|
|
150
|
-
| `get_forex()` | Cotacoes cambiais oficiais de USD, EUR e GBP para BRL | 0.
|
|
151
|
-
| `get_crypto(symbol)` | Precos spot de BTC, ETH, SOL e USDC | 0.
|
|
152
|
-
| `get_dns(domain)` | Resolucao DNS com registros A, AAAA, MX, TXT, NS e CNAME | 0.
|
|
153
|
-
| `get_ssl(host)` | Inspecao e auditoria de certificado TLS e SSL na porta 443 | 0.
|
|
154
|
-
| `get_asn(ip)` | Inteligencia de roteamento BGP, bloco alocado e ASN | 0.
|
|
155
|
-
| `get_cep(code)` | Consulta de logradouro postal brasileiro e codigo IBGE | 0.
|
|
156
|
-
| `get_cnpj(cnpj)` | Dados cadastrais completos de PJ na Receita Federal | 0.
|
|
157
|
-
| `get_indicators()` | Indicadores macroeconomicos oficiais (Selic meta e diaria, CDI anual e IPCA) | 0.
|
|
158
|
-
| `get_holidays(year)` | Calendario oficial de feriados nacionais e bancarios ANBIMA | 0.
|
|
177
|
+
| `get_forex()` | Cotacoes cambiais oficiais de USD, EUR e GBP para BRL | 0.0050 |
|
|
178
|
+
| `get_crypto(symbol)` | Precos spot de BTC, ETH, SOL e USDC | 0.0050 |
|
|
179
|
+
| `get_dns(domain)` | Resolucao DNS com registros A, AAAA, MX, TXT, NS e CNAME | 0.0050 |
|
|
180
|
+
| `get_ssl(host)` | Inspecao e auditoria de certificado TLS e SSL na porta 443 | 0.0050 |
|
|
181
|
+
| `get_asn(ip)` | Inteligencia de roteamento BGP, bloco alocado e ASN | 0.0050 |
|
|
182
|
+
| `get_cep(code)` | Consulta de logradouro postal brasileiro e codigo IBGE | 0.0050 |
|
|
183
|
+
| `get_cnpj(cnpj)` | Dados cadastrais completos de PJ na Receita Federal | 0.0200 |
|
|
184
|
+
| `get_indicators()` | Indicadores macroeconomicos oficiais (Selic meta e diaria, CDI anual e IPCA) | 0.0050 |
|
|
185
|
+
| `get_holidays(year)` | Calendario oficial de feriados nacionais e bancarios ANBIMA | 0.0050 |
|
|
186
|
+
| `get_workdays(start_date?, end_date?, days?, date?)` | Calculadora de dias uteis financeiros e projecao de vencimentos ANBIMA | 0.0050 |
|
|
159
187
|
|
|
160
188
|
---
|
|
161
189
|
|
|
@@ -8,7 +8,7 @@ Projetada especificamente para agentes autonomos de inteligencia artificial, fra
|
|
|
8
8
|
|
|
9
9
|
## Recursos Principais
|
|
10
10
|
|
|
11
|
-
- **
|
|
11
|
+
- **11 Ferramentas Integradas:** Indicadores macroeconomicos (Selic, CDI, IPCA), calculadora de dias uteis financeiros ANBIMA, feriados nacionais e bancarios ANBIMA, CNPJ da Receita Federal, CEP postal e IBGE, cotacoes Forex e Cripto spot, resolucao DNS, auditoria TLS e SSL, analise ASN e BGP e status do ecossistema.
|
|
12
12
|
- **Zero Cadastro e Zero Friccao:** Sem necessidade de chaves de API estaticas ou contratos mensais.
|
|
13
13
|
- **Modo Sandbox Gratuito:** Teste e homologue localmente sem custos informando `sandbox=True`.
|
|
14
14
|
- **Integracao Nativa com IA:** Compativel com Coinbase Developer Platform (CDP) AgentKit, LangChain e CrewAI.
|
|
@@ -100,13 +100,39 @@ print("Comprovante on-chain:", resultado.get("_x402_settlement"))
|
|
|
100
100
|
Para fluxos de trabalho tipados e validacao antecipada:
|
|
101
101
|
|
|
102
102
|
```python
|
|
103
|
-
from grid402 import CnpjInput, CepInput, DnsInput, SslInput, AsnInput,
|
|
103
|
+
from grid402 import CnpjInput, CepInput, DnsInput, SslInput, AsnInput, HolidaysInput, WorkdaysInput
|
|
104
104
|
|
|
105
105
|
# Validacao de entrada antes do envio
|
|
106
106
|
payload_cnpj = CnpjInput(cnpj="00.000.000/0001-91")
|
|
107
107
|
payload_cep = CepInput(code="01310100")
|
|
108
108
|
payload_dns = DnsInput(domain="base.org")
|
|
109
109
|
payload_holidays = HolidaysInput(year=2026)
|
|
110
|
+
payload_workdays = WorkdaysInput(start_date="2026-11-06", days=5)
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
---
|
|
114
|
+
|
|
115
|
+
### 5. Verificacao Criptografica de Prova de Autenticidade (Proof of Data)
|
|
116
|
+
|
|
117
|
+
Todas as respostas de dados pagas e em sandbox trazem uma prova matematica de oraculo (`_oracle_proof`) assinada via ECDSA secp256k1 pela carteira oficial do Grid402 (`0xa592625adbceb8e025ac383f1a3fd8ebb6a63f90`).
|
|
118
|
+
|
|
119
|
+
O SDK permite verificar matematicamente a integridade dos dados e a autenticidade do emissor em menos de 5 milissegundos sem chamadas de rede adicionais:
|
|
120
|
+
|
|
121
|
+
```python
|
|
122
|
+
from grid402 import Grid402Client
|
|
123
|
+
|
|
124
|
+
client = Grid402Client(sandbox=True)
|
|
125
|
+
dados = client.get_workdays(start_date="2026-11-06", days=5)
|
|
126
|
+
|
|
127
|
+
# Validacao matematica local e instantanea
|
|
128
|
+
verificacao = client.verify_proof(dados)
|
|
129
|
+
|
|
130
|
+
if verificacao.valid:
|
|
131
|
+
print("Dados autenticos assinados pelo oraculo Grid402!")
|
|
132
|
+
print("Endereco do oraculo:", verificacao.oracle_address)
|
|
133
|
+
print("Carimbo temporal:", verificacao.timestamp)
|
|
134
|
+
else:
|
|
135
|
+
print("Falha na autenticidade dos dados:", verificacao.error)
|
|
110
136
|
```
|
|
111
137
|
|
|
112
138
|
---
|
|
@@ -116,15 +142,16 @@ payload_holidays = HolidaysInput(year=2026)
|
|
|
116
142
|
| Metodo | Descricao | Preco Base (USDC) |
|
|
117
143
|
|---|---|---|
|
|
118
144
|
| `get_summary()` | Resumo operacional consolidado de saude | Gratuito |
|
|
119
|
-
| `get_forex()` | Cotacoes cambiais oficiais de USD, EUR e GBP para BRL | 0.
|
|
120
|
-
| `get_crypto(symbol)` | Precos spot de BTC, ETH, SOL e USDC | 0.
|
|
121
|
-
| `get_dns(domain)` | Resolucao DNS com registros A, AAAA, MX, TXT, NS e CNAME | 0.
|
|
122
|
-
| `get_ssl(host)` | Inspecao e auditoria de certificado TLS e SSL na porta 443 | 0.
|
|
123
|
-
| `get_asn(ip)` | Inteligencia de roteamento BGP, bloco alocado e ASN | 0.
|
|
124
|
-
| `get_cep(code)` | Consulta de logradouro postal brasileiro e codigo IBGE | 0.
|
|
125
|
-
| `get_cnpj(cnpj)` | Dados cadastrais completos de PJ na Receita Federal | 0.
|
|
126
|
-
| `get_indicators()` | Indicadores macroeconomicos oficiais (Selic meta e diaria, CDI anual e IPCA) | 0.
|
|
127
|
-
| `get_holidays(year)` | Calendario oficial de feriados nacionais e bancarios ANBIMA | 0.
|
|
145
|
+
| `get_forex()` | Cotacoes cambiais oficiais de USD, EUR e GBP para BRL | 0.0050 |
|
|
146
|
+
| `get_crypto(symbol)` | Precos spot de BTC, ETH, SOL e USDC | 0.0050 |
|
|
147
|
+
| `get_dns(domain)` | Resolucao DNS com registros A, AAAA, MX, TXT, NS e CNAME | 0.0050 |
|
|
148
|
+
| `get_ssl(host)` | Inspecao e auditoria de certificado TLS e SSL na porta 443 | 0.0050 |
|
|
149
|
+
| `get_asn(ip)` | Inteligencia de roteamento BGP, bloco alocado e ASN | 0.0050 |
|
|
150
|
+
| `get_cep(code)` | Consulta de logradouro postal brasileiro e codigo IBGE | 0.0050 |
|
|
151
|
+
| `get_cnpj(cnpj)` | Dados cadastrais completos de PJ na Receita Federal | 0.0200 |
|
|
152
|
+
| `get_indicators()` | Indicadores macroeconomicos oficiais (Selic meta e diaria, CDI anual e IPCA) | 0.0050 |
|
|
153
|
+
| `get_holidays(year)` | Calendario oficial de feriados nacionais e bancarios ANBIMA | 0.0050 |
|
|
154
|
+
| `get_workdays(start_date?, end_date?, days?, date?)` | Calculadora de dias uteis financeiros e projecao de vencimentos ANBIMA | 0.0050 |
|
|
128
155
|
|
|
129
156
|
---
|
|
130
157
|
|
|
@@ -6,7 +6,15 @@ LangChain, CrewAI e modo Sandbox gratuito.
|
|
|
6
6
|
"""
|
|
7
7
|
|
|
8
8
|
from grid402.agentkit import Grid402ActionProvider
|
|
9
|
-
from grid402.client import
|
|
9
|
+
from grid402.client import (
|
|
10
|
+
DEFAULT_ENDPOINT,
|
|
11
|
+
DEFAULT_ORACLE_PUBKEY,
|
|
12
|
+
GRID402_ORACLE_WALLET,
|
|
13
|
+
Grid402Client,
|
|
14
|
+
canonicalize_payload,
|
|
15
|
+
compute_data_hash,
|
|
16
|
+
verify_oracle_proof,
|
|
17
|
+
)
|
|
10
18
|
from grid402.exceptions import Grid402Error, Grid402PaymentRequiredError
|
|
11
19
|
from grid402.models import (
|
|
12
20
|
AsnInput,
|
|
@@ -19,11 +27,16 @@ from grid402.models import (
|
|
|
19
27
|
HolidaysInput,
|
|
20
28
|
HolidaysResponse,
|
|
21
29
|
IndicatorsResponse,
|
|
30
|
+
OracleProof,
|
|
31
|
+
OracleVerificationResult,
|
|
22
32
|
SettlementInfo,
|
|
23
33
|
SslInput,
|
|
34
|
+
WorkdaysHolidayItem,
|
|
35
|
+
WorkdaysInput,
|
|
36
|
+
WorkdaysResponse,
|
|
24
37
|
)
|
|
25
38
|
|
|
26
|
-
__version__ = "2.
|
|
39
|
+
__version__ = "2.5.1"
|
|
27
40
|
__author__ = "Grid402 Team"
|
|
28
41
|
__license__ = "MIT"
|
|
29
42
|
|
|
@@ -39,11 +52,21 @@ __all__ = [
|
|
|
39
52
|
"AsnInput",
|
|
40
53
|
"CryptoInput",
|
|
41
54
|
"HolidaysInput",
|
|
55
|
+
"WorkdaysInput",
|
|
42
56
|
"EconomicIndicators",
|
|
43
57
|
"IndicatorsResponse",
|
|
44
58
|
"HolidayItem",
|
|
45
59
|
"HolidaysResponse",
|
|
60
|
+
"WorkdaysHolidayItem",
|
|
61
|
+
"WorkdaysResponse",
|
|
46
62
|
"SettlementInfo",
|
|
63
|
+
"OracleProof",
|
|
64
|
+
"OracleVerificationResult",
|
|
65
|
+
"verify_oracle_proof",
|
|
66
|
+
"canonicalize_payload",
|
|
67
|
+
"compute_data_hash",
|
|
68
|
+
"DEFAULT_ORACLE_PUBKEY",
|
|
69
|
+
"GRID402_ORACLE_WALLET",
|
|
47
70
|
"DEFAULT_ENDPOINT",
|
|
48
71
|
"__version__",
|
|
49
72
|
]
|
|
@@ -13,10 +13,19 @@ import urllib.parse
|
|
|
13
13
|
import urllib.request
|
|
14
14
|
|
|
15
15
|
from grid402.client import DEFAULT_ENDPOINT
|
|
16
|
-
from grid402.models import
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
16
|
+
from grid402.models import (
|
|
17
|
+
AsnInput,
|
|
18
|
+
CepInput,
|
|
19
|
+
CnpjInput,
|
|
20
|
+
CryptoInput,
|
|
21
|
+
DnsInput,
|
|
22
|
+
HolidaysInput,
|
|
23
|
+
SslInput,
|
|
24
|
+
WorkdaysInput,
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
GRID402_ORACLE_WALLET = "0xa592625adbceb8e025ac383f1a3fd8ebb6a63f90"
|
|
20
29
|
BASE_USDC_CONTRACT = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
|
|
21
30
|
|
|
22
31
|
|
|
@@ -92,7 +101,7 @@ class Grid402ActionProvider:
|
|
|
92
101
|
if exc.code == 402:
|
|
93
102
|
# Se temos wallet_provider e nao estamos no sandbox, auto-liquida on-chain
|
|
94
103
|
if wallet_provider is not None and not self.sandbox:
|
|
95
|
-
price_usdc = challenge.get("price_usdc", "0.
|
|
104
|
+
price_usdc = challenge.get("price_usdc", "0.0050")
|
|
96
105
|
recipient = challenge.get("recipient_wallet", GRID402_ORACLE_WALLET)
|
|
97
106
|
|
|
98
107
|
try:
|
|
@@ -173,6 +182,26 @@ class Grid402ActionProvider:
|
|
|
173
182
|
params = {"year": year} if year is not None else {}
|
|
174
183
|
return self._execute_with_settlement("/api/v1/holidays", params, wallet_provider)
|
|
175
184
|
|
|
185
|
+
def query_workdays(
|
|
186
|
+
self,
|
|
187
|
+
start_date: Optional[str] = None,
|
|
188
|
+
end_date: Optional[str] = None,
|
|
189
|
+
days: Optional[int] = None,
|
|
190
|
+
date: Optional[str] = None,
|
|
191
|
+
wallet_provider: Any = None,
|
|
192
|
+
) -> Dict[str, Any]:
|
|
193
|
+
"""Calcula dias uteis financeiros e projecao de vencimentos ANBIMA."""
|
|
194
|
+
params: Dict[str, Any] = {}
|
|
195
|
+
if start_date is not None:
|
|
196
|
+
params["start_date"] = start_date
|
|
197
|
+
if end_date is not None:
|
|
198
|
+
params["end_date"] = end_date
|
|
199
|
+
if days is not None:
|
|
200
|
+
params["days"] = days
|
|
201
|
+
if date is not None:
|
|
202
|
+
params["date"] = date
|
|
203
|
+
return self._execute_with_settlement("/api/v1/workdays", params, wallet_provider)
|
|
204
|
+
|
|
176
205
|
# Aliases no padrao snake_case das ferramentas MCP
|
|
177
206
|
get_cnpj = query_cnpj
|
|
178
207
|
get_cep = query_cep
|
|
@@ -183,4 +212,5 @@ class Grid402ActionProvider:
|
|
|
183
212
|
get_asn = query_asn
|
|
184
213
|
get_indicators = query_indicators
|
|
185
214
|
get_holidays = query_holidays
|
|
215
|
+
get_workdays = query_workdays
|
|
186
216
|
|
|
@@ -3,6 +3,7 @@ Cliente HTTP oficial para a API de Micropagamentos Grid402.
|
|
|
3
3
|
"""
|
|
4
4
|
|
|
5
5
|
from typing import Any, Dict, Optional
|
|
6
|
+
import hashlib
|
|
6
7
|
import json
|
|
7
8
|
import ssl
|
|
8
9
|
import urllib.error
|
|
@@ -10,9 +11,116 @@ import urllib.parse
|
|
|
10
11
|
import urllib.request
|
|
11
12
|
|
|
12
13
|
from grid402.exceptions import Grid402Error, Grid402PaymentRequiredError
|
|
14
|
+
from grid402.models import OracleVerificationResult, WorkdaysResponse
|
|
13
15
|
|
|
14
16
|
|
|
15
|
-
DEFAULT_ENDPOINT = "https://grid402.
|
|
17
|
+
DEFAULT_ENDPOINT = "https://grid402.online"
|
|
18
|
+
GRID402_ORACLE_WALLET = "0xa592625adbceb8e025ac383f1a3fd8ebb6a63f90"
|
|
19
|
+
DEFAULT_ORACLE_PUBKEY = """-----BEGIN PUBLIC KEY-----
|
|
20
|
+
MFYwEAYHKoZIzj0CAQYFK4EEAAoDQgAEq8MF77hj4TAO3ktuRu5GPRdXQP9m9JhO
|
|
21
|
+
c89Y7XGoNGECnG/UiuoqDB/Y7/2s9ww3J7zJ8mC83Zc/Kd0FeDutaQ==
|
|
22
|
+
-----END PUBLIC KEY-----"""
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def canonicalize_payload(data: Any) -> Any:
|
|
26
|
+
"""Normaliza recursivamente o objeto ordenando chaves e excluindo metadados transientes."""
|
|
27
|
+
if data is None or not isinstance(data, (dict, list)):
|
|
28
|
+
return data
|
|
29
|
+
exclude = {"_oracle_proof", "sandbox_info", "_x402_settlement"}
|
|
30
|
+
if isinstance(data, list):
|
|
31
|
+
return [canonicalize_payload(item) for item in data]
|
|
32
|
+
clean: Dict[str, Any] = {}
|
|
33
|
+
for k in sorted(data.keys()):
|
|
34
|
+
if k not in exclude:
|
|
35
|
+
clean[k] = canonicalize_payload(data[k])
|
|
36
|
+
return clean
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def compute_data_hash(data: Any) -> str:
|
|
40
|
+
"""Calcula o hash SHA-256 em hexadecimal prefixado com 0x do payload normalizado."""
|
|
41
|
+
clean = canonicalize_payload(data)
|
|
42
|
+
serialized = json.dumps(clean, separators=(",", ":"), sort_keys=True)
|
|
43
|
+
digest = hashlib.sha256(serialized.encode("utf-8")).hexdigest()
|
|
44
|
+
return f"0x{digest}"
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def verify_oracle_proof(
|
|
48
|
+
response: Any,
|
|
49
|
+
expected_oracle_address: Optional[str] = None,
|
|
50
|
+
oracle_public_key: Optional[str] = None,
|
|
51
|
+
) -> OracleVerificationResult:
|
|
52
|
+
"""Valida a prova criptografica de oraculo emitida pelo Grid402."""
|
|
53
|
+
if hasattr(response, "_raw_data") and isinstance(response._raw_data, dict):
|
|
54
|
+
data_dict = response._raw_data
|
|
55
|
+
elif hasattr(response, "model_dump"):
|
|
56
|
+
data_dict = response.model_dump(exclude_none=True, by_alias=True)
|
|
57
|
+
elif isinstance(response, dict):
|
|
58
|
+
data_dict = dict(response)
|
|
59
|
+
else:
|
|
60
|
+
return OracleVerificationResult(valid=False, error="InvalidPayloadType")
|
|
61
|
+
|
|
62
|
+
proof_raw = data_dict.get("_oracle_proof")
|
|
63
|
+
if not proof_raw or not isinstance(proof_raw, dict):
|
|
64
|
+
return OracleVerificationResult(valid=False, error="MissingProofBlock")
|
|
65
|
+
|
|
66
|
+
computed_hash = compute_data_hash(data_dict)
|
|
67
|
+
received_hash = proof_raw.get("data_hash")
|
|
68
|
+
|
|
69
|
+
if computed_hash != received_hash:
|
|
70
|
+
return OracleVerificationResult(
|
|
71
|
+
valid=False,
|
|
72
|
+
error="DataHashMismatch",
|
|
73
|
+
expected_hash=computed_hash,
|
|
74
|
+
received_hash=received_hash,
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
expected_addr = (expected_oracle_address or GRID402_ORACLE_WALLET).lower()
|
|
78
|
+
proof_addr = str(proof_raw.get("oracle_address") or "").lower()
|
|
79
|
+
if expected_addr and proof_addr != expected_addr:
|
|
80
|
+
return OracleVerificationResult(
|
|
81
|
+
valid=False,
|
|
82
|
+
error="OracleAddressMismatch",
|
|
83
|
+
oracle_address=proof_addr,
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
timestamp = int(proof_raw.get("timestamp") or 0)
|
|
87
|
+
is_sandbox = bool(proof_raw.get("sandbox"))
|
|
88
|
+
mode_str = "sandbox" if is_sandbox else "mainnet"
|
|
89
|
+
message_to_sign = f"{computed_hash}:{timestamp}:{mode_str}".encode("utf-8")
|
|
90
|
+
|
|
91
|
+
sig_hex = str(proof_raw.get("signature") or "").replace("0x", "")
|
|
92
|
+
if not sig_hex:
|
|
93
|
+
return OracleVerificationResult(valid=False, error="MissingSignature")
|
|
94
|
+
|
|
95
|
+
try:
|
|
96
|
+
sig_bytes = bytes.fromhex(sig_hex)
|
|
97
|
+
except ValueError:
|
|
98
|
+
return OracleVerificationResult(valid=False, error="MalformedSignatureHex")
|
|
99
|
+
|
|
100
|
+
pub_pem = (oracle_public_key or DEFAULT_ORACLE_PUBKEY).encode("utf-8")
|
|
101
|
+
|
|
102
|
+
try:
|
|
103
|
+
from cryptography.hazmat.primitives.serialization import load_pem_public_key
|
|
104
|
+
from cryptography.hazmat.primitives.asymmetric import ec
|
|
105
|
+
from cryptography.hazmat.primitives import hashes
|
|
106
|
+
|
|
107
|
+
pubkey = load_pem_public_key(pub_pem)
|
|
108
|
+
pubkey.verify(sig_bytes, message_to_sign, ec.ECDSA(hashes.SHA256()))
|
|
109
|
+
|
|
110
|
+
return OracleVerificationResult(
|
|
111
|
+
valid=True,
|
|
112
|
+
oracle_address=proof_addr,
|
|
113
|
+
timestamp=timestamp,
|
|
114
|
+
sandbox=is_sandbox,
|
|
115
|
+
)
|
|
116
|
+
except Exception as exc:
|
|
117
|
+
return OracleVerificationResult(
|
|
118
|
+
valid=False,
|
|
119
|
+
error=f"InvalidSignature: {exc}",
|
|
120
|
+
oracle_address=proof_addr,
|
|
121
|
+
timestamp=timestamp,
|
|
122
|
+
sandbox=is_sandbox,
|
|
123
|
+
)
|
|
16
124
|
|
|
17
125
|
|
|
18
126
|
class Grid402Client:
|
|
@@ -154,3 +262,37 @@ class Grid402Client:
|
|
|
154
262
|
params = {"year": year} if year is not None else {}
|
|
155
263
|
return self._request("/api/v1/holidays", params=params, payment_tx_hash=payment_tx_hash)
|
|
156
264
|
|
|
265
|
+
def get_workdays(
|
|
266
|
+
self,
|
|
267
|
+
start_date: Optional[str] = None,
|
|
268
|
+
end_date: Optional[str] = None,
|
|
269
|
+
days: Optional[int] = None,
|
|
270
|
+
date: Optional[str] = None,
|
|
271
|
+
payment_tx_hash: Optional[str] = None,
|
|
272
|
+
) -> Any:
|
|
273
|
+
"""Calcula dias uteis financeiros e projecoes de vencimento na convencao ANBIMA."""
|
|
274
|
+
params: Dict[str, Any] = {}
|
|
275
|
+
if start_date is not None:
|
|
276
|
+
params["start_date"] = start_date
|
|
277
|
+
if end_date is not None:
|
|
278
|
+
params["end_date"] = end_date
|
|
279
|
+
if days is not None:
|
|
280
|
+
params["days"] = days
|
|
281
|
+
if date is not None:
|
|
282
|
+
params["date"] = date
|
|
283
|
+
raw = self._request("/api/v1/workdays", params=params, payment_tx_hash=payment_tx_hash)
|
|
284
|
+
if isinstance(raw, dict) and raw.get("status") == "success":
|
|
285
|
+
inst = WorkdaysResponse(**raw)
|
|
286
|
+
inst._raw_data = raw
|
|
287
|
+
return inst
|
|
288
|
+
return raw
|
|
289
|
+
|
|
290
|
+
def verify_proof(
|
|
291
|
+
self,
|
|
292
|
+
response: Any,
|
|
293
|
+
expected_oracle_address: Optional[str] = None,
|
|
294
|
+
oracle_public_key: Optional[str] = None,
|
|
295
|
+
) -> OracleVerificationResult:
|
|
296
|
+
"""Valida a prova matematica de autenticidade emitida pelo oraculo Grid402."""
|
|
297
|
+
return verify_oracle_proof(response, expected_oracle_address=expected_oracle_address, oracle_public_key=oracle_public_key)
|
|
298
|
+
|
|
@@ -19,7 +19,7 @@ class Grid402PaymentRequiredError(Grid402Error):
|
|
|
19
19
|
|
|
20
20
|
def __init__(self, challenge: Dict[str, Any], message: Optional[str] = None):
|
|
21
21
|
self.challenge = challenge
|
|
22
|
-
self.price_usdc: str = challenge.get("price_usdc", "0.
|
|
22
|
+
self.price_usdc: str = challenge.get("price_usdc", "0.0050")
|
|
23
23
|
self.recipient: str = challenge.get("recipient_wallet", "")
|
|
24
24
|
self.network: str = challenge.get("network", "Base")
|
|
25
25
|
self.token: str = challenge.get("token", "USDC")
|