grid402 2.2.0__tar.gz → 2.5.0__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.0}/PKG-INFO +47 -19
- {grid402-2.2.0 → grid402-2.5.0}/README.md +38 -11
- {grid402-2.2.0 → grid402-2.5.0}/grid402/__init__.py +25 -2
- {grid402-2.2.0 → grid402-2.5.0}/grid402/agentkit.py +35 -5
- {grid402-2.2.0 → grid402-2.5.0}/grid402/client.py +142 -1
- {grid402-2.2.0 → grid402-2.5.0}/grid402/exceptions.py +1 -1
- grid402-2.5.0/grid402/models.py +207 -0
- {grid402-2.2.0 → grid402-2.5.0}/grid402.egg-info/PKG-INFO +47 -19
- {grid402-2.2.0 → grid402-2.5.0}/grid402.egg-info/requires.txt +1 -0
- {grid402-2.2.0 → grid402-2.5.0}/pyproject.toml +11 -7
- {grid402-2.2.0 → grid402-2.5.0}/tests/test_live_sandbox.py +1 -1
- {grid402-2.2.0 → grid402-2.5.0}/tests/test_sdk.py +162 -11
- grid402-2.2.0/grid402/models.py +0 -119
- {grid402-2.2.0 → grid402-2.5.0}/LICENSE +0 -0
- {grid402-2.2.0 → grid402-2.5.0}/grid402/py.typed +0 -0
- {grid402-2.2.0 → grid402-2.5.0}/grid402.egg-info/SOURCES.txt +0 -0
- {grid402-2.2.0 → grid402-2.5.0}/grid402.egg-info/dependency_links.txt +0 -0
- {grid402-2.2.0 → grid402-2.5.0}/grid402.egg-info/top_level.txt +0 -0
- {grid402-2.2.0 → grid402-2.5.0}/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.0
|
|
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.0"
|
|
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
|
+
MFYwEAYHKoZIzj0CAQYFK4EEAAoDQgAEZh7FI41OltM2/P7miW0L/D0OE6FzEQRk
|
|
21
|
+
2YJoMPEXO/mKiZ6oSi5l9MCIvS/W7IoIpe3z1EV9rYVEsADOgHHkJw==
|
|
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,36 @@ 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
|
+
) -> OracleVerificationResult:
|
|
295
|
+
"""Valida a prova matematica de autenticidade emitida pelo oraculo Grid402."""
|
|
296
|
+
return verify_oracle_proof(response, expected_oracle_address=expected_oracle_address)
|
|
297
|
+
|
|
@@ -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")
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Modelos tipados Pydantic para entradas e saidas do Grid402.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from typing import Any, Dict, Optional
|
|
6
|
+
from pydantic import BaseModel, Field
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class CnpjInput(BaseModel):
|
|
10
|
+
"""Parametros para consulta cadastral de Pessoa Juridica na Receita Federal."""
|
|
11
|
+
cnpj: str = Field(
|
|
12
|
+
...,
|
|
13
|
+
description="Numero do CNPJ com 14 digitos numericos, com ou sem mascara de pontuacao.",
|
|
14
|
+
examples=["00.000.000/0001-91", "00000000000191"],
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class CepInput(BaseModel):
|
|
19
|
+
"""Parametros para consulta de endereco postal e codigo IBGE por CEP."""
|
|
20
|
+
code: str = Field(
|
|
21
|
+
...,
|
|
22
|
+
description="Codigo de CEP brasileiro com 8 digitos numericos, com ou sem hifen.",
|
|
23
|
+
examples=["01310-100", "01310100"],
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class DnsInput(BaseModel):
|
|
28
|
+
"""Parametros para resolucao DNS autoritativa."""
|
|
29
|
+
domain: str = Field(
|
|
30
|
+
...,
|
|
31
|
+
description="Nome de dominio da internet para resolucao de registros A, AAAA, MX, TXT, NS e CNAME.",
|
|
32
|
+
examples=["base.org", "ethereum.org"],
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class SslInput(BaseModel):
|
|
37
|
+
"""Parametros para inspecao e auditoria de certificado TLS e SSL."""
|
|
38
|
+
host: str = Field(
|
|
39
|
+
...,
|
|
40
|
+
description="Hostname ou dominio para inspecao de certificado TLS na porta 443.",
|
|
41
|
+
examples=["base.org", "google.com"],
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class AsnInput(BaseModel):
|
|
46
|
+
"""Parametros para consulta de BGP e numero ASN."""
|
|
47
|
+
ip: Optional[str] = Field(
|
|
48
|
+
None,
|
|
49
|
+
description="Endereco IPv4 ou IPv6 a consultar. Se omitido, inspeciona o IP publico requisitante.",
|
|
50
|
+
examples=["1.1.1.1", "8.8.8.8"],
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class CryptoInput(BaseModel):
|
|
55
|
+
"""Parametros opcionais para cotacao spot de criptoativos."""
|
|
56
|
+
symbol: Optional[str] = Field(
|
|
57
|
+
None,
|
|
58
|
+
description="Simbolo opcional do criptoativo (ex: BTC, ETH, SOL, USDC, BASE).",
|
|
59
|
+
examples=["BTC", "ETH"],
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class HolidaysInput(BaseModel):
|
|
64
|
+
"""Parametros opcionais para consulta de feriados nacionais e bancarios."""
|
|
65
|
+
year: Optional[int] = Field(
|
|
66
|
+
None,
|
|
67
|
+
description="Ano calendario de 4 digitos entre 1900 e 2100. Se omitido, utiliza o ano corrente.",
|
|
68
|
+
ge=1900,
|
|
69
|
+
le=2100,
|
|
70
|
+
examples=[2026],
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class EconomicIndicators(BaseModel):
|
|
75
|
+
selic_target: float = Field(..., description="Taxa Selic meta anual em percentual.")
|
|
76
|
+
selic_daily: float = Field(..., description="Taxa Selic acumulada diaria anualizada.")
|
|
77
|
+
cdi_annual: float = Field(..., description="Taxa CDI anualizada em percentual.")
|
|
78
|
+
cdi_daily: float = Field(..., description="Taxa CDI diaria efetiva em percentual.")
|
|
79
|
+
ipca_12m: float = Field(..., description="IPCA acumulado nos ultimos 12 meses.")
|
|
80
|
+
ipca_monthly: float = Field(..., description="IPCA do ultimo mes fechado.")
|
|
81
|
+
reference_date: str = Field(..., description="Data de referencia dos indicadores diarios.")
|
|
82
|
+
ipca_reference_month: str = Field(..., description="Mes de referencia da divulgacao do IPCA.")
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class IndicatorsResponse(BaseModel):
|
|
86
|
+
model_config = {"extra": "allow", "populate_by_name": True}
|
|
87
|
+
|
|
88
|
+
status: str = Field(..., description="Status da consulta.")
|
|
89
|
+
service: str = Field("indicators", description="Nome do micro-servico.")
|
|
90
|
+
timestamp: str = Field(..., description="Data e hora ISO 8601 da resposta.")
|
|
91
|
+
indicators: EconomicIndicators = Field(..., description="Conjunto de indicadores economicos.")
|
|
92
|
+
source: str = Field(..., description="Fontes oficiais primarias.")
|
|
93
|
+
cached: Optional[bool] = Field(None, description="Indica se os dados foram servidos do cache.")
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class HolidayItem(BaseModel):
|
|
97
|
+
date: str = Field(..., description="Data do feriado no formato AAAA-MM-DD.")
|
|
98
|
+
name: str = Field(..., description="Nome oficial do feriado ou celebracao.")
|
|
99
|
+
type: str = Field(..., description="Tipo do feriado: national, banking ou religious.")
|
|
100
|
+
day_of_week: str = Field(..., description="Dia da semana correspondente em portugues.")
|
|
101
|
+
is_banking_holiday: bool = Field(..., description="Indica se nao ha expediente bancario ao publico.")
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
class HolidaysResponse(BaseModel):
|
|
105
|
+
model_config = {"extra": "allow", "populate_by_name": True}
|
|
106
|
+
|
|
107
|
+
status: str = Field(..., description="Status da consulta.")
|
|
108
|
+
service: str = Field("holidays", description="Nome do micro-servico.")
|
|
109
|
+
year: int = Field(..., description="Ano calendario consultado.")
|
|
110
|
+
total_holidays: int = Field(..., description="Contagem total de feriados cadastrados no ano.")
|
|
111
|
+
holidays: list[HolidayItem] = Field(..., description="Lista de feriados ordenada cronologicamente.")
|
|
112
|
+
source: str = Field(..., description="Fontes oficiais primarias.")
|
|
113
|
+
cached: Optional[bool] = Field(None, description="Indica se os dados foram servidos do cache.")
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
class WorkdaysInput(BaseModel):
|
|
117
|
+
"""Parametros para calculo de dias uteis financeiros e projecao ANBIMA."""
|
|
118
|
+
start_date: Optional[str] = Field(
|
|
119
|
+
None,
|
|
120
|
+
description="Data de inicio no formato AAAA-MM-DD para contagem ou projecao.",
|
|
121
|
+
examples=["2026-11-06"],
|
|
122
|
+
)
|
|
123
|
+
end_date: Optional[str] = Field(
|
|
124
|
+
None,
|
|
125
|
+
description="Data de termino no formato AAAA-MM-DD para contagem de intervalo.",
|
|
126
|
+
examples=["2026-11-20"],
|
|
127
|
+
)
|
|
128
|
+
days: Optional[int] = Field(
|
|
129
|
+
None,
|
|
130
|
+
description="Quantidade inteira de dias uteis para projecao de prazo (positivo ou negativo).",
|
|
131
|
+
examples=[5],
|
|
132
|
+
)
|
|
133
|
+
date: Optional[str] = Field(
|
|
134
|
+
None,
|
|
135
|
+
description="Data pontual no formato AAAA-MM-DD para checagem se e dia util.",
|
|
136
|
+
examples=["2026-12-25"],
|
|
137
|
+
)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
class WorkdaysHolidayItem(BaseModel):
|
|
141
|
+
date: str = Field(..., description="Data do feriado no formato AAAA-MM-DD.")
|
|
142
|
+
name: str = Field(..., description="Nome oficial do feriado bancario.")
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
class WorkdaysResponse(BaseModel):
|
|
146
|
+
model_config = {"extra": "allow", "populate_by_name": True}
|
|
147
|
+
|
|
148
|
+
status: str = Field(..., description="Status da consulta.")
|
|
149
|
+
service: str = Field("workdays", description="Nome do micro-servico.")
|
|
150
|
+
mode: str = Field(..., description="Modo executado: range, projection ou check.")
|
|
151
|
+
convention: str = Field(..., description="Convencao financeira adotada.")
|
|
152
|
+
start_date: Optional[str] = Field(None, description="Data de inicio considerada.")
|
|
153
|
+
end_date: Optional[str] = Field(None, description="Data de termino considerada.")
|
|
154
|
+
target_date: Optional[str] = Field(None, description="Data final calculada na projecao de dias uteis.")
|
|
155
|
+
workdays: Optional[int] = Field(None, description="Total de dias uteis calculados.")
|
|
156
|
+
calendar_days: Optional[int] = Field(None, description="Total de dias corridos no intervalo.")
|
|
157
|
+
start_is_workday: Optional[bool] = Field(None, description="Indica se a data inicial e dia util.")
|
|
158
|
+
end_is_workday: Optional[bool] = Field(None, description="Indica se a data final e dia util.")
|
|
159
|
+
target_is_workday: Optional[bool] = Field(None, description="Indica se a data de destino projetada e dia util.")
|
|
160
|
+
is_workday: Optional[bool] = Field(None, description="Indica se a data pontual e dia util.")
|
|
161
|
+
day_type: Optional[str] = Field(None, description="Tipo de dia: workday, weekend ou holiday.")
|
|
162
|
+
description: Optional[str] = Field(None, description="Descricao do status da data consultada.")
|
|
163
|
+
holiday_name: Optional[str] = Field(None, description="Nome do feriado bancario, se aplicavel.")
|
|
164
|
+
next_workday: Optional[str] = Field(None, description="Proximo dia util bancario seguinte.")
|
|
165
|
+
holidays_in_range: Optional[list[WorkdaysHolidayItem]] = Field(None, description="Feriados bancarios ocorridos no intervalo.")
|
|
166
|
+
holidays_in_projection: Optional[list[WorkdaysHolidayItem]] = Field(None, description="Feriados bancarios ocorridos durante a projecao.")
|
|
167
|
+
tariff_usdc: Optional[str] = Field(None, description="Tarifa cobrada em USDC.")
|
|
168
|
+
cached: Optional[bool] = Field(None, description="Indica se os dados foram servidos do cache.")
|
|
169
|
+
sandbox: Optional[bool] = Field(None, description="Indica se a requisicao foi executada em modo sandbox.")
|
|
170
|
+
error: Optional[str] = Field(None, description="Mensagem de erro caso a operacao falhe.")
|
|
171
|
+
|
|
172
|
+
def __getitem__(self, item: str) -> Any:
|
|
173
|
+
return getattr(self, item)
|
|
174
|
+
|
|
175
|
+
def get(self, item: str, default: Any = None) -> Any:
|
|
176
|
+
return getattr(self, item, default)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
class SettlementInfo(BaseModel):
|
|
180
|
+
"""Informacoes de liquidacao on-chain de micropagamento x402."""
|
|
181
|
+
settled: bool = Field(True, description="Indica se o pagamento foi liquidado com sucesso.")
|
|
182
|
+
tx_hash: str = Field(..., description="Hash da transacao confirmada na rede Base.")
|
|
183
|
+
price_usdc: str = Field(..., description="Valor pago em USDC.")
|
|
184
|
+
network: str = Field("Base", description="Rede blockchain da liquidacao.")
|
|
185
|
+
token: str = Field("USDC", description="Token utilizado no pagamento.")
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
class OracleProof(BaseModel):
|
|
189
|
+
"""Prova criptografica de autenticidade e integridade emitida pelo oraculo Grid402."""
|
|
190
|
+
oracle_address: str = Field(..., description="Endereco da carteira Ethereum do oraculo que assinou os dados.")
|
|
191
|
+
timestamp: int = Field(..., description="Timestamp Unix em segundos no momento da assinatura.")
|
|
192
|
+
data_hash: str = Field(..., description="Hash SHA-256 em hexadecimal prefixado com 0x do payload normalizado.")
|
|
193
|
+
signature: str = Field(..., description="Assinatura digital ECDSA secp256k1 em formato DER codificada em hexadecimal.")
|
|
194
|
+
algorithm: str = Field("secp256k1-sha256", description="Algoritmo de assinatura utilizado.")
|
|
195
|
+
sandbox: bool = Field(False, description="Indica se a assinatura foi gerada em modo sandbox ou producao.")
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
class OracleVerificationResult(BaseModel):
|
|
199
|
+
"""Resultado detalhado da verificacao matematica da prova do oraculo."""
|
|
200
|
+
valid: bool = Field(..., description="Indica se os dados sao autenticos e nao foram adulterados.")
|
|
201
|
+
oracle_address: Optional[str] = Field(None, description="Endereco do oraculo verificado.")
|
|
202
|
+
timestamp: Optional[int] = Field(None, description="Timestamp da assinatura do oraculo.")
|
|
203
|
+
sandbox: Optional[bool] = Field(None, description="Modo sandbox da assinatura.")
|
|
204
|
+
error: Optional[str] = Field(None, description="Codigo descritivo do erro em caso de falha de verificacao.")
|
|
205
|
+
expected_hash: Optional[str] = Field(None, description="Hash computado localmente a partir dos dados recebidos.")
|
|
206
|
+
received_hash: Optional[str] = Field(None, description="Hash informado no bloco de prova do oraculo.")
|
|
207
|
+
|
|
@@ -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.0
|
|
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
|
|
|
@@ -4,13 +4,13 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "grid402"
|
|
7
|
-
version = "2.
|
|
8
|
-
description = "SDK Python oficial do Grid402: Micropagamentos HTTP 402 na Base para Agentes Autonomos e IA"
|
|
7
|
+
version = "2.5.0"
|
|
8
|
+
description = "SDK Python oficial do Grid402: Micropagamentos HTTP 402 na Base e Prova Criptografica de Oraculo para Agentes Autonomos e IA"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.9"
|
|
11
11
|
license = "MIT"
|
|
12
12
|
authors = [
|
|
13
|
-
{ name = "Grid402 Team", email = "contato@grid402.
|
|
13
|
+
{ name = "Grid402 Team", email = "contato@grid402.online" },
|
|
14
14
|
]
|
|
15
15
|
keywords = [
|
|
16
16
|
"x402",
|
|
@@ -21,6 +21,9 @@ keywords = [
|
|
|
21
21
|
"agentic-web",
|
|
22
22
|
"mcp",
|
|
23
23
|
"ai-agents",
|
|
24
|
+
"oracle",
|
|
25
|
+
"proof-of-data",
|
|
26
|
+
"secp256k1",
|
|
24
27
|
]
|
|
25
28
|
classifiers = [
|
|
26
29
|
"Development Status :: 5 - Production/Stable",
|
|
@@ -37,6 +40,7 @@ classifiers = [
|
|
|
37
40
|
]
|
|
38
41
|
dependencies = [
|
|
39
42
|
"pydantic>=2.0.0",
|
|
43
|
+
"cryptography>=41.0.0",
|
|
40
44
|
]
|
|
41
45
|
|
|
42
46
|
[project.optional-dependencies]
|
|
@@ -46,10 +50,10 @@ dev = [
|
|
|
46
50
|
]
|
|
47
51
|
|
|
48
52
|
[project.urls]
|
|
49
|
-
Homepage = "https://grid402.
|
|
50
|
-
Documentation = "https://grid402.
|
|
51
|
-
Repository = "https://github.com/
|
|
52
|
-
Issues = "https://github.com/
|
|
53
|
+
Homepage = "https://grid402.online"
|
|
54
|
+
Documentation = "https://grid402.online"
|
|
55
|
+
Repository = "https://github.com/oliveiratc/Grid402"
|
|
56
|
+
Issues = "https://github.com/oliveiratc/Grid402/issues"
|
|
53
57
|
|
|
54
58
|
[tool.setuptools.packages.find]
|
|
55
59
|
where = ["."]
|
|
@@ -14,7 +14,7 @@ class TestLiveSandboxGrid402(unittest.TestCase):
|
|
|
14
14
|
def setUpClass(cls) -> None:
|
|
15
15
|
# Usa o endpoint oficial da Hostinger para testes ponta a ponta
|
|
16
16
|
cls.client = Grid402Client(
|
|
17
|
-
base_url="https://
|
|
17
|
+
base_url="https://grid402.online",
|
|
18
18
|
sandbox=True,
|
|
19
19
|
timeout=15,
|
|
20
20
|
)
|
|
@@ -20,16 +20,58 @@ from grid402 import (
|
|
|
20
20
|
HolidaysResponse,
|
|
21
21
|
IndicatorsResponse,
|
|
22
22
|
SslInput,
|
|
23
|
+
WorkdaysHolidayItem,
|
|
24
|
+
WorkdaysInput,
|
|
25
|
+
WorkdaysResponse,
|
|
26
|
+
DEFAULT_ORACLE_PUBKEY,
|
|
27
|
+
GRID402_ORACLE_WALLET,
|
|
28
|
+
OracleProof,
|
|
29
|
+
OracleVerificationResult,
|
|
30
|
+
compute_data_hash,
|
|
31
|
+
verify_oracle_proof,
|
|
23
32
|
__version__,
|
|
24
33
|
)
|
|
25
34
|
|
|
26
35
|
|
|
36
|
+
TEST_ORACLE_PRIVKEY_PEM = b"""-----BEGIN PRIVATE KEY-----
|
|
37
|
+
MIGEAgEAMBAGByqGSM49AgEGBSuBBAAKBG0wawIBAQQgbx7yBcDIEAJOTpIxrSji
|
|
38
|
+
FuMG+zevhna+MX1NMJ1+yZ+hRANCAARmHsUjjU6W0zb8/uaJbQv8PQ4ToXMRBGTZ
|
|
39
|
+
gmgw8Rc7+YqJnqhKLmX0wIi9L9bsigil7fPURX2thUSwAM6AceQn
|
|
40
|
+
-----END PRIVATE KEY-----"""
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def generate_signed_payload(data: dict, is_sandbox: bool = False) -> dict:
|
|
44
|
+
import time
|
|
45
|
+
from cryptography.hazmat.primitives.serialization import load_pem_private_key
|
|
46
|
+
from cryptography.hazmat.primitives.asymmetric import ec
|
|
47
|
+
from cryptography.hazmat.primitives import hashes
|
|
48
|
+
|
|
49
|
+
data_hash = compute_data_hash(data)
|
|
50
|
+
timestamp = int(time.time())
|
|
51
|
+
mode_str = "sandbox" if is_sandbox else "mainnet"
|
|
52
|
+
msg = f"{data_hash}:{timestamp}:{mode_str}".encode("utf-8")
|
|
53
|
+
|
|
54
|
+
privkey = load_pem_private_key(TEST_ORACLE_PRIVKEY_PEM, password=None)
|
|
55
|
+
sig_bytes = privkey.sign(msg, ec.ECDSA(hashes.SHA256()))
|
|
56
|
+
|
|
57
|
+
signed = dict(data)
|
|
58
|
+
signed["_oracle_proof"] = {
|
|
59
|
+
"oracle_address": GRID402_ORACLE_WALLET,
|
|
60
|
+
"timestamp": timestamp,
|
|
61
|
+
"data_hash": data_hash,
|
|
62
|
+
"signature": "0x" + sig_bytes.hex(),
|
|
63
|
+
"algorithm": "secp256k1-sha256",
|
|
64
|
+
"sandbox": is_sandbox,
|
|
65
|
+
}
|
|
66
|
+
return signed
|
|
67
|
+
|
|
68
|
+
|
|
27
69
|
class TestGrid402SDK(unittest.TestCase):
|
|
28
70
|
"""Testes de integridade de modelos, cliente e provedor de acoes do Grid402."""
|
|
29
71
|
|
|
30
72
|
def test_version_and_exports(self) -> None:
|
|
31
73
|
"""Verifica versao semantica e exportacoes principais."""
|
|
32
|
-
self.assertEqual(__version__, "2.
|
|
74
|
+
self.assertEqual(__version__, "2.5.0")
|
|
33
75
|
self.assertTrue(issubclass(Grid402PaymentRequiredError, Grid402Error))
|
|
34
76
|
|
|
35
77
|
def test_pydantic_models(self) -> None:
|
|
@@ -89,6 +131,29 @@ class TestGrid402SDK(unittest.TestCase):
|
|
|
89
131
|
self.assertEqual(len(hol_resp.holidays), 1)
|
|
90
132
|
self.assertTrue(hol_resp.holidays[0].is_banking_holiday)
|
|
91
133
|
|
|
134
|
+
workdays_input = WorkdaysInput(start_date="2026-11-06", days=5)
|
|
135
|
+
self.assertEqual(workdays_input.start_date, "2026-11-06")
|
|
136
|
+
self.assertEqual(workdays_input.days, 5)
|
|
137
|
+
|
|
138
|
+
workdays_resp = WorkdaysResponse(
|
|
139
|
+
status="success",
|
|
140
|
+
service="workdays",
|
|
141
|
+
mode="projection",
|
|
142
|
+
convention="ANBIMA D+0 exclusivo no inicio e inclusivo no fim",
|
|
143
|
+
start_date="2026-11-06",
|
|
144
|
+
target_date="2026-11-13",
|
|
145
|
+
workdays=5,
|
|
146
|
+
calendar_days=7,
|
|
147
|
+
start_is_workday=True,
|
|
148
|
+
target_is_workday=True,
|
|
149
|
+
holidays_in_projection=[],
|
|
150
|
+
tariff_usdc="0.0050",
|
|
151
|
+
)
|
|
152
|
+
self.assertEqual(workdays_resp.workdays, 5)
|
|
153
|
+
self.assertEqual(workdays_resp.target_date, "2026-11-13")
|
|
154
|
+
self.assertEqual(workdays_resp.get("service"), "workdays")
|
|
155
|
+
self.assertEqual(workdays_resp["mode"], "projection")
|
|
156
|
+
|
|
92
157
|
def test_client_sandbox_headers(self) -> None:
|
|
93
158
|
"""Verifica se o modo Sandbox envia o cabecalho de demonstracao."""
|
|
94
159
|
client = Grid402Client(sandbox=True)
|
|
@@ -111,14 +176,14 @@ class TestGrid402SDK(unittest.TestCase):
|
|
|
111
176
|
client = Grid402Client(sandbox=False, raise_for_payment=True)
|
|
112
177
|
|
|
113
178
|
challenge_body = (
|
|
114
|
-
b'{"status": 402, "message": "Payment Required", "price_usdc": "0.
|
|
115
|
-
b'"recipient_wallet": "
|
|
179
|
+
b'{"status": 402, "message": "Payment Required", "price_usdc": "0.0050", '
|
|
180
|
+
b'"recipient_wallet": "0xa592625adbceb8e025ac383f1a3fd8ebb6a63f90", '
|
|
116
181
|
b'"preview_data": {"sample": true}}'
|
|
117
182
|
)
|
|
118
183
|
|
|
119
184
|
import urllib.error
|
|
120
185
|
http_error = urllib.error.HTTPError(
|
|
121
|
-
url="https://grid402.
|
|
186
|
+
url="https://grid402.online/api/v1/forex",
|
|
122
187
|
code=402,
|
|
123
188
|
msg="Payment Required",
|
|
124
189
|
hdrs={}, # type: ignore
|
|
@@ -130,8 +195,8 @@ class TestGrid402SDK(unittest.TestCase):
|
|
|
130
195
|
client.get_forex()
|
|
131
196
|
|
|
132
197
|
err = ctx.exception
|
|
133
|
-
self.assertEqual(err.price_usdc, "0.
|
|
134
|
-
self.assertEqual(err.recipient, "
|
|
198
|
+
self.assertEqual(err.price_usdc, "0.0050")
|
|
199
|
+
self.assertEqual(err.recipient, "0xa592625adbceb8e025ac383f1a3fd8ebb6a63f90")
|
|
135
200
|
self.assertIsNotNone(err.preview_data)
|
|
136
201
|
self.assertTrue(err.preview_data.get("sample"))
|
|
137
202
|
|
|
@@ -145,14 +210,14 @@ class TestGrid402SDK(unittest.TestCase):
|
|
|
145
210
|
mock_wallet.transfer.return_value = mock_transfer
|
|
146
211
|
|
|
147
212
|
challenge_bytes = (
|
|
148
|
-
b'{"price_usdc": "0.
|
|
149
|
-
b'"recipient_wallet": "
|
|
213
|
+
b'{"price_usdc": "0.0200", '
|
|
214
|
+
b'"recipient_wallet": "0xa592625adbceb8e025ac383f1a3fd8ebb6a63f90"}'
|
|
150
215
|
)
|
|
151
216
|
success_bytes = b'{"razao_social": "BANCO DO BRASIL SA", "cnpj": "00000000000191"}'
|
|
152
217
|
|
|
153
218
|
import urllib.error
|
|
154
219
|
challenge_error = urllib.error.HTTPError(
|
|
155
|
-
url="https://grid402.
|
|
220
|
+
url="https://grid402.online/api/v1/cnpj",
|
|
156
221
|
code=402,
|
|
157
222
|
msg="Payment Required",
|
|
158
223
|
hdrs={}, # type: ignore
|
|
@@ -168,8 +233,8 @@ class TestGrid402SDK(unittest.TestCase):
|
|
|
168
233
|
res = provider.query_cnpj("00000000000191", wallet_provider=mock_wallet)
|
|
169
234
|
|
|
170
235
|
mock_wallet.transfer.assert_called_once_with(
|
|
171
|
-
to="
|
|
172
|
-
amount="0.
|
|
236
|
+
to="0xa592625adbceb8e025ac383f1a3fd8ebb6a63f90",
|
|
237
|
+
amount="0.0200",
|
|
173
238
|
asset_id="usdc",
|
|
174
239
|
)
|
|
175
240
|
self.assertEqual(res.get("razao_social"), "BANCO DO BRASIL SA")
|
|
@@ -199,6 +264,92 @@ class TestGrid402SDK(unittest.TestCase):
|
|
|
199
264
|
self.assertIn("/api/v1/indicators", calls[0][0][0].full_url)
|
|
200
265
|
self.assertIn("/api/v1/holidays?year=2026", calls[1][0][0].full_url)
|
|
201
266
|
|
|
267
|
+
def test_client_workdays(self) -> None:
|
|
268
|
+
"""Verifica chamada get_workdays no Grid402Client retornando WorkdaysResponse."""
|
|
269
|
+
client = Grid402Client(sandbox=True)
|
|
270
|
+
|
|
271
|
+
mock_resp = MagicMock()
|
|
272
|
+
mock_resp.read.return_value = (
|
|
273
|
+
b'{"status": "success", "service": "workdays", "mode": "projection", '
|
|
274
|
+
b'"convention": "ANBIMA D+0 exclusivo", "start_date": "2026-11-06", '
|
|
275
|
+
b'"target_date": "2026-11-13", "workdays": 5, "calendar_days": 7, '
|
|
276
|
+
b'"start_is_workday": true, "target_is_workday": true, "tariff_usdc": "0.0050"}'
|
|
277
|
+
)
|
|
278
|
+
mock_resp.__enter__.return_value = mock_resp
|
|
279
|
+
|
|
280
|
+
with patch("urllib.request.urlopen", return_value=mock_resp) as mock_urlopen:
|
|
281
|
+
res = client.get_workdays(start_date="2026-11-06", days=5)
|
|
282
|
+
self.assertIsInstance(res, WorkdaysResponse)
|
|
283
|
+
self.assertEqual(res.workdays, 5)
|
|
284
|
+
self.assertEqual(res.target_date, "2026-11-13")
|
|
285
|
+
self.assertEqual(res.get("service"), "workdays")
|
|
286
|
+
|
|
287
|
+
req_arg = mock_urlopen.call_args[0][0]
|
|
288
|
+
self.assertIn("/api/v1/workdays", req_arg.full_url)
|
|
289
|
+
self.assertIn("start_date=2026-11-06", req_arg.full_url)
|
|
290
|
+
self.assertIn("days=5", req_arg.full_url)
|
|
291
|
+
|
|
292
|
+
def test_hash_determinism(self) -> None:
|
|
293
|
+
"""Verifica se compute_data_hash e deterministico independente da ordem de chaves."""
|
|
294
|
+
obj_a = {"status": "success", "service": "workdays", "workdays": 5}
|
|
295
|
+
obj_b = {"workdays": 5, "service": "workdays", "status": "success"}
|
|
296
|
+
self.assertEqual(compute_data_hash(obj_a), compute_data_hash(obj_b))
|
|
297
|
+
self.assertTrue(compute_data_hash(obj_a).startswith("0x"))
|
|
298
|
+
|
|
299
|
+
def test_oracle_proof_verification_success(self) -> None:
|
|
300
|
+
"""Verifica validacao positiva de resposta autentica assinada pelo oraculo."""
|
|
301
|
+
client = Grid402Client()
|
|
302
|
+
data = {"status": "success", "service": "workdays", "workdays": 5}
|
|
303
|
+
signed = generate_signed_payload(data, is_sandbox=False)
|
|
304
|
+
|
|
305
|
+
res = client.verify_proof(signed)
|
|
306
|
+
self.assertTrue(res.valid)
|
|
307
|
+
self.assertEqual(res.oracle_address, GRID402_ORACLE_WALLET.lower())
|
|
308
|
+
self.assertFalse(res.sandbox)
|
|
309
|
+
|
|
310
|
+
def test_oracle_proof_tampered_payload(self) -> None:
|
|
311
|
+
"""Verifica rejeicao de payload adulterado acusando DataHashMismatch."""
|
|
312
|
+
client = Grid402Client()
|
|
313
|
+
data = {"status": "success", "service": "workdays", "workdays": 5}
|
|
314
|
+
signed = generate_signed_payload(data, is_sandbox=False)
|
|
315
|
+
|
|
316
|
+
signed["workdays"] = 6
|
|
317
|
+
|
|
318
|
+
res = client.verify_proof(signed)
|
|
319
|
+
self.assertFalse(res.valid)
|
|
320
|
+
self.assertEqual(res.error, "DataHashMismatch")
|
|
321
|
+
|
|
322
|
+
def test_oracle_proof_wrong_oracle_address(self) -> None:
|
|
323
|
+
"""Verifica rejeicao de carteira de oraculo divergente da esperada."""
|
|
324
|
+
client = Grid402Client()
|
|
325
|
+
data = {"status": "success", "service": "workdays", "workdays": 5}
|
|
326
|
+
signed = generate_signed_payload(data, is_sandbox=False)
|
|
327
|
+
|
|
328
|
+
res = client.verify_proof(signed, expected_oracle_address="0x000000000000000000000000000000000000dead")
|
|
329
|
+
self.assertFalse(res.valid)
|
|
330
|
+
self.assertEqual(res.error, "OracleAddressMismatch")
|
|
331
|
+
|
|
332
|
+
def test_oracle_proof_invalid_signature(self) -> None:
|
|
333
|
+
"""Verifica rejeicao de assinatura forjada ou corrompida."""
|
|
334
|
+
client = Grid402Client()
|
|
335
|
+
data = {"status": "success", "service": "workdays", "workdays": 5}
|
|
336
|
+
signed = generate_signed_payload(data, is_sandbox=False)
|
|
337
|
+
|
|
338
|
+
signed["_oracle_proof"]["signature"] = "0x1234567890abcdef"
|
|
339
|
+
|
|
340
|
+
res = client.verify_proof(signed)
|
|
341
|
+
self.assertFalse(res.valid)
|
|
342
|
+
|
|
343
|
+
def test_oracle_proof_sandbox_mode(self) -> None:
|
|
344
|
+
"""Verifica validacao de prova emitida em modo Sandbox."""
|
|
345
|
+
client = Grid402Client(sandbox=True)
|
|
346
|
+
data = {"status": "success", "service": "indicators", "selic": "10.75"}
|
|
347
|
+
signed = generate_signed_payload(data, is_sandbox=True)
|
|
348
|
+
|
|
349
|
+
res = client.verify_proof(signed)
|
|
350
|
+
self.assertTrue(res.valid)
|
|
351
|
+
self.assertTrue(res.sandbox)
|
|
352
|
+
|
|
202
353
|
|
|
203
354
|
if __name__ == "__main__":
|
|
204
355
|
unittest.main()
|
grid402-2.2.0/grid402/models.py
DELETED
|
@@ -1,119 +0,0 @@
|
|
|
1
|
-
"""
|
|
2
|
-
Modelos tipados Pydantic para entradas e saidas do Grid402.
|
|
3
|
-
"""
|
|
4
|
-
|
|
5
|
-
from typing import Any, Dict, Optional
|
|
6
|
-
from pydantic import BaseModel, Field
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
class CnpjInput(BaseModel):
|
|
10
|
-
"""Parametros para consulta cadastral de Pessoa Juridica na Receita Federal."""
|
|
11
|
-
cnpj: str = Field(
|
|
12
|
-
...,
|
|
13
|
-
description="Numero do CNPJ com 14 digitos numericos, com ou sem mascara de pontuacao.",
|
|
14
|
-
examples=["00.000.000/0001-91", "00000000000191"],
|
|
15
|
-
)
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
class CepInput(BaseModel):
|
|
19
|
-
"""Parametros para consulta de endereco postal e codigo IBGE por CEP."""
|
|
20
|
-
code: str = Field(
|
|
21
|
-
...,
|
|
22
|
-
description="Codigo de CEP brasileiro com 8 digitos numericos, com ou sem hifen.",
|
|
23
|
-
examples=["01310-100", "01310100"],
|
|
24
|
-
)
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
class DnsInput(BaseModel):
|
|
28
|
-
"""Parametros para resolucao DNS autoritativa."""
|
|
29
|
-
domain: str = Field(
|
|
30
|
-
...,
|
|
31
|
-
description="Nome de dominio da internet para resolucao de registros A, AAAA, MX, TXT, NS e CNAME.",
|
|
32
|
-
examples=["base.org", "ethereum.org"],
|
|
33
|
-
)
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
class SslInput(BaseModel):
|
|
37
|
-
"""Parametros para inspecao e auditoria de certificado TLS e SSL."""
|
|
38
|
-
host: str = Field(
|
|
39
|
-
...,
|
|
40
|
-
description="Hostname ou dominio para inspecao de certificado TLS na porta 443.",
|
|
41
|
-
examples=["base.org", "google.com"],
|
|
42
|
-
)
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
class AsnInput(BaseModel):
|
|
46
|
-
"""Parametros para consulta de BGP e numero ASN."""
|
|
47
|
-
ip: Optional[str] = Field(
|
|
48
|
-
None,
|
|
49
|
-
description="Endereco IPv4 ou IPv6 a consultar. Se omitido, inspeciona o IP publico requisitante.",
|
|
50
|
-
examples=["1.1.1.1", "8.8.8.8"],
|
|
51
|
-
)
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
class CryptoInput(BaseModel):
|
|
55
|
-
"""Parametros opcionais para cotacao spot de criptoativos."""
|
|
56
|
-
symbol: Optional[str] = Field(
|
|
57
|
-
None,
|
|
58
|
-
description="Simbolo opcional do criptoativo (ex: BTC, ETH, SOL, USDC, BASE).",
|
|
59
|
-
examples=["BTC", "ETH"],
|
|
60
|
-
)
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
class HolidaysInput(BaseModel):
|
|
64
|
-
"""Parametros opcionais para consulta de feriados nacionais e bancarios."""
|
|
65
|
-
year: Optional[int] = Field(
|
|
66
|
-
None,
|
|
67
|
-
description="Ano calendario de 4 digitos entre 1900 e 2100. Se omitido, utiliza o ano corrente.",
|
|
68
|
-
ge=1900,
|
|
69
|
-
le=2100,
|
|
70
|
-
examples=[2026],
|
|
71
|
-
)
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
class EconomicIndicators(BaseModel):
|
|
75
|
-
selic_target: float = Field(..., description="Taxa Selic meta anual em percentual.")
|
|
76
|
-
selic_daily: float = Field(..., description="Taxa Selic acumulada diaria anualizada.")
|
|
77
|
-
cdi_annual: float = Field(..., description="Taxa CDI anualizada em percentual.")
|
|
78
|
-
cdi_daily: float = Field(..., description="Taxa CDI diaria efetiva em percentual.")
|
|
79
|
-
ipca_12m: float = Field(..., description="IPCA acumulado nos ultimos 12 meses.")
|
|
80
|
-
ipca_monthly: float = Field(..., description="IPCA do ultimo mes fechado.")
|
|
81
|
-
reference_date: str = Field(..., description="Data de referencia dos indicadores diarios.")
|
|
82
|
-
ipca_reference_month: str = Field(..., description="Mes de referencia da divulgacao do IPCA.")
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
class IndicatorsResponse(BaseModel):
|
|
86
|
-
status: str = Field(..., description="Status da consulta.")
|
|
87
|
-
service: str = Field("indicators", description="Nome do micro-servico.")
|
|
88
|
-
timestamp: str = Field(..., description="Data e hora ISO 8601 da resposta.")
|
|
89
|
-
indicators: EconomicIndicators = Field(..., description="Conjunto de indicadores economicos.")
|
|
90
|
-
source: str = Field(..., description="Fontes oficiais primarias.")
|
|
91
|
-
cached: Optional[bool] = Field(None, description="Indica se os dados foram servidos do cache.")
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
class HolidayItem(BaseModel):
|
|
95
|
-
date: str = Field(..., description="Data do feriado no formato AAAA-MM-DD.")
|
|
96
|
-
name: str = Field(..., description="Nome oficial do feriado ou celebracao.")
|
|
97
|
-
type: str = Field(..., description="Tipo do feriado: national, banking ou religious.")
|
|
98
|
-
day_of_week: str = Field(..., description="Dia da semana correspondente em portugues.")
|
|
99
|
-
is_banking_holiday: bool = Field(..., description="Indica se nao ha expediente bancario ao publico.")
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
class HolidaysResponse(BaseModel):
|
|
103
|
-
status: str = Field(..., description="Status da consulta.")
|
|
104
|
-
service: str = Field("holidays", description="Nome do micro-servico.")
|
|
105
|
-
year: int = Field(..., description="Ano calendario consultado.")
|
|
106
|
-
total_holidays: int = Field(..., description="Contagem total de feriados cadastrados no ano.")
|
|
107
|
-
holidays: list[HolidayItem] = Field(..., description="Lista de feriados ordenada cronologicamente.")
|
|
108
|
-
source: str = Field(..., description="Fontes oficiais primarias.")
|
|
109
|
-
cached: Optional[bool] = Field(None, description="Indica se os dados foram servidos do cache.")
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
class SettlementInfo(BaseModel):
|
|
113
|
-
"""Informacoes de liquidacao on-chain de micropagamento x402."""
|
|
114
|
-
settled: bool = Field(True, description="Indica se o pagamento foi liquidado com sucesso.")
|
|
115
|
-
tx_hash: str = Field(..., description="Hash da transacao confirmada na rede Base.")
|
|
116
|
-
price_usdc: str = Field(..., description="Valor pago em USDC.")
|
|
117
|
-
network: str = Field("Base", description="Rede blockchain da liquidacao.")
|
|
118
|
-
token: str = Field("USDC", description="Token utilizado no pagamento.")
|
|
119
|
-
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|