grid402-mcp 1.9.0 → 2.0.1

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.
package/README.md CHANGED
@@ -1,16 +1,16 @@
1
1
  # grid402-mcp ⚡
2
2
 
3
- Servidor oficial do **Model Context Protocol (MCP)** para o **Grid402** — Hub de 23 Micro-Serviços de Dados Públicos Abertos e Utilitários de Rede (25 ferramentas MCP) com liquidação de micropagamentos x402 em USDC Multi-Chain (Base, Arbitrum, Polygon, Optimism, Ethereum e Solana SPL).
3
+ Servidor oficial do **Model Context Protocol (MCP)** para o **Grid402** — Hub de 25 Micro-Serviços de Dados Públicos Abertos e Utilitários de Rede (27 ferramentas MCP) com liquidação de micropagamentos x402 em USDC Multi-Chain (Base, Arbitrum, Polygon, Optimism, Ethereum e Solana SPL).
4
4
 
5
5
  Compatível nativamente com **Claude Desktop**, **Cursor**, **Smithery.ai**, **Glama**, **Coinbase AgentKit** e qualquer orquestrador compatível com a especificação MCP da Anthropic.
6
6
 
7
7
  ---
8
8
 
9
- ## 🛠️ Ferramentas Disponíveis (25 Tools)
9
+ ## 🛠️ Ferramentas Disponíveis (27 Tools)
10
10
 
11
11
  | Ferramenta | Descrição | Modalidade | Custo |
12
12
  |---|---|---|---|
13
- | `grid402_summary` | Resumo consolidado de saúde dos 23 serviços | Direto | Gratuito |
13
+ | `grid402_summary` | Resumo consolidado de saúde dos 25 serviços | Direto | Gratuito |
14
14
  | `grid402_forex` | Cotações em tempo real de USD, EUR e GBP para BRL | On-Demand | 0.0050 USDC (1 cr) |
15
15
  | `grid402_crypto` | Preços spot de BTC, ETH, SOL, USDC e BASE | On-Demand | 0.0050 USDC (1 cr) |
16
16
  | `grid402_dns` | Resolução autoritativa de DNS (A, AAAA, MX, TXT, NS, CNAME) | On-Demand | 0.0050 USDC (1 cr) |
@@ -32,6 +32,8 @@ Compatível nativamente com **Claude Desktop**, **Cursor**, **Smithery.ai**, **G
32
32
  | `grid402_ofac` | Triagem OFAC SDN / ONU e risco AML Web3 na Base Mainnet | On-Demand | 0.0200 USDC (4 cr) |
33
33
  | `grid402_notarize` | Carimbo do tempo criptográfico SHA-256 e prova de existência ECDSA | On-Demand | 0.0050 USDC (1 cr) |
34
34
  | `grid402_global_markets` | Calendário de bolsas (US/EU/UK/BR) e 30+ taxas de câmbio do BCE | On-Demand | 0.0050 USDC (1 cr) |
35
+ | `grid402_extract` | Extrator anti-SSRF de páginas web HTTP/HTTPS para Markdown limpo (LLMs e RAG) | On-Demand | 0.0050 USDC (1 cr) |
36
+ | `grid402_email_verify` | Auditoria Zero-PII de entregabilidade de e-mail B2B (RFC, MX, SPF, DMARC, disposable e score 0-100) | On-Demand | 0.0050 USDC (1 cr) |
35
37
  | `grid402_pass` | Emissão de Session Pass pré-pago (Starter 400 cr / Pro 1.000 cr / Fleet 6.000 cr) | Pré-Pago | 2 / 5 / 20 USDC |
36
38
  | `grid402_pass_balance` | Consulta de saldo, validade e Spend Controls de um Session Pass | Direto | Gratuito |
37
39
  | `grid402_verify` | Validação matemática de prova criptográfica de oráculo (_oracle_proof) secp256k1 | Direto | Gratuito |
@@ -72,18 +74,20 @@ Adicione ao seu arquivo de configuração (`claude_desktop_config.json`):
72
74
  "GRID402_ENDPOINT": "https://grid402.online",
73
75
  "GRID402_SANDBOX": "false",
74
76
  "GRID402_SESSION_PASS": "pass_g402_seu_passe_aqui_opcional",
75
- "GRID402_PRIVATE_KEY": "0xsua_chave_privada_base_aqui_opcional"
77
+ "GRID402_PAYMENT_NETWORK": "base",
78
+ "GRID402_PRIVATE_KEY": "0xsua_chave_privada_evm_opcional",
79
+ "GRID402_SOLANA_PRIVATE_KEY": "sua_chave_privada_solana_base58_opcional"
76
80
  }
77
81
  }
78
82
  }
79
83
  }
80
84
  ```
81
85
 
82
- > 💡 **Modo Sandbox Gratuito:** Você pode definir `"GRID402_SANDBOX": "true"` para testar todas as ferramentas sem gastar USDC nem configurar chave privada (limite de 5 consultas por hora por IP).
86
+ > 💡 **Modo Sandbox Gratuito:** Você pode definir `"GRID402_SANDBOX": "true"` para testar todas as ferramentas sem gastar USDC nem configurar chave privada (limite de 3 consultas por dia por IP).
83
87
  >
84
- > 💡 **Session Pass (Sem Chave Privada):** Se preferir não informar `GRID402_PRIVATE_KEY`, adquira um passe pré-pago em `https://grid402.online/#topup` e defina `"GRID402_SESSION_PASS": "pass_g402_..."` para execução em `<15ms`.
88
+ > 💡 **Session Pass (Sem Chave Privada):** Se preferir não informar `GRID402_PRIVATE_KEY`, adquira um passe pré-pago em `https://grid402.online/pass` e defina `"GRID402_SESSION_PASS": "pass_g402_..."` para execução em `<15ms`.
85
89
  >
86
- > 💡 **Nota de Segurança:** A variável `GRID402_PRIVATE_KEY` é opcional. Se informada, o servidor MCP realiza a transferência automática de USDC on-chain na Base a cada consulta paga. Se não informada ou sem saldo, o servidor retorna o desafio x402 com amostra de dados. A chave é processada estritamente na sua máquina local e nunca é enviada ao servidor do Grid402.
90
+ > 💡 **Auto-Payer Multi-Chain (Base, Polygon, Arbitrum e Solana):** O módulo `x402_payer.mjs` suporta liquidação automática Multi-Chain tanto para carteiras EVM (`GRID402_PRIVATE_KEY` em `base`, `polygon`, `arbitrum`, `optimism`, `ethereum`, com suporte a modo gasless EIP-3009 `GRID402_X402_GASLESS=true`) quanto para carteiras **Solana SPL USDC** (`GRID402_SOLANA_PRIVATE_KEY` em Base58 ou JSON array com `GRID402_PAYMENT_NETWORK=solana`, on-chain ou gasless PayAI SVM). As chaves são processadas estritamente na sua máquina local e nunca são enviadas ao servidor do Grid402.
87
91
 
88
92
  ---
89
93
 
package/index.mjs CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  /**
4
4
  * Grid402 Official Model Context Protocol (MCP) Server
5
- * Exposes 25 tools for real-time open data and M2M network utilities with Multi-Chain x402 USDC settlement.
5
+ * Exposes 27 tools for real-time open data and M2M network utilities with Multi-Chain x402 USDC settlement.
6
6
  */
7
7
 
8
8
  import { Server } from '@modelcontextprotocol/sdk/server/index.js';
@@ -11,16 +11,16 @@ import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprot
11
11
  import { MCP_TOOLS_DEFINITIONS, executeGrid402Request, DEFAULT_ENDPOINT } from './tools.mjs';
12
12
 
13
13
  export const GRID402_MCP_INSTRUCTIONS = [
14
- 'Grid402 is a verifiable public-data and network utility M2M oracle settled via HTTP x402 (USDC across Base, Arbitrum, Polygon, Optimism, Ethereum, and Solana SPL).',
15
- 'Tool selection: use free tools first (`grid402_summary` for 23-service health, `grid402_pass_balance` for prepaid pass quota/spend-controls, `grid402_verify` for offline-equivalent ECDSA secp256k1 proof verification). Prefer composite bundles (`grid402_domain_audit`, `grid402_kyb_audit`, `grid402_get_dossier_360`, `grid402_market_snapshot`) over multiple separate calls to reduce cost and latency.',
16
- 'Authentication and Payment modes: (1) Set `GRID402_SANDBOX=true` for free sandbox testing via `X-Payment: demo` (5 queries/hour per IP); (2) Set `GRID402_SESSION_PASS=pass_g402_...` for <15ms prepaid calls (`1 credit = 0.0050 USDC`, zero per-call gas); (3) Set `GRID402_PRIVATE_KEY` using a dedicated low-balance operational Base wallet for automatic on-chain settlement.',
14
+ 'Grid402 is a verifiable public-data and network utility M2M oracle settled via HTTP x402 (gasless PayAI exact on Base, Polygon, Arbitrum, and Solana; plus Optimism and Ethereum Session Pass top-ups).',
15
+ 'Tool selection: use free tools first (`grid402_summary` for 25-service health, `grid402_pass_balance` for prepaid pass quota/spend-controls, `grid402_verify` for offline-equivalent ECDSA secp256k1 proof verification). Prefer composite bundles (`grid402_domain_audit`, `grid402_kyb_audit`, `grid402_get_dossier_360`, `grid402_market_snapshot`) over multiple separate calls to reduce cost and latency, and use `grid402_extract` (URL-to-Markdown) or `grid402_email_verify` (Zero-PII MX/SPF/DMARC) for high-volume web and lead workflows.',
16
+ 'Authentication and Payment modes: (1) Set `GRID402_SANDBOX=true` for free sandbox testing via `X-Payment: demo` (3 queries/day per IP); (2) Set `GRID402_SESSION_PASS=pass_g402_...` for <15ms prepaid calls (`1 credit = 0.0050 USDC`, zero per-call gas); (3) Set `GRID402_PRIVATE_KEY` (EVM Base, Polygon, Arbitrum, Optimism, Ethereum) or `GRID402_SOLANA_PRIVATE_KEY` (Solana SPL USDC) plus optional `GRID402_PAYMENT_NETWORK=base|polygon|arbitrum|solana` for automatic Multi-Chain settlement.',
17
17
  'Spend controls and error handling: paid tools return `_oracle_proof` (ECDSA secp256k1) and `_meta` (upstream source and TTL). When HTTP 402 (`payment_required: true`) is returned without credentials, present the fee (`0.0050`–`0.0500` USDC) and free `preview` teaser instead of retrying blindly. Respect HTTP 429 (`PassDailyLimitExceeded`, `SandboxRateLimitExceeded`) and HTTP 403 (`PassEndpointNotAllowed`).',
18
18
  ].join(' ');
19
19
 
20
20
  const server = new Server(
21
21
  {
22
22
  name: 'grid402-mcp-server',
23
- version: '1.9.0',
23
+ version: '2.0.0',
24
24
  },
25
25
  {
26
26
  capabilities: {
@@ -111,6 +111,12 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
111
111
  case 'grid402_global_markets':
112
112
  service = 'global-markets';
113
113
  break;
114
+ case 'grid402_extract':
115
+ service = 'extract';
116
+ break;
117
+ case 'grid402_email_verify':
118
+ service = 'email-verify';
119
+ break;
114
120
  case 'grid402_pass':
115
121
  service = 'pass';
116
122
  break;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "grid402-mcp",
3
- "version": "1.9.0",
4
- "description": "Official Model Context Protocol (MCP) Server for Grid402 - The Verifiable Data and HTTP x402 Payment Layer for Autonomous AI Agents (25 MCP Tools: KYB 360 AI Dossier, Financial Markets, Compliance, Global LEI, OFAC AML, Network Audits) across Base, Arbitrum, Polygon, Optimism, Ethereum and Solana.",
3
+ "version": "2.0.1",
4
+ "description": "Official Model Context Protocol (MCP) Server for Grid402 - The Verifiable Data and HTTP x402 Payment Layer for Autonomous AI Agents (27 MCP Tools: Web-to-Markdown Extractor, Zero-PII Email Verifier, KYB 360 AI Dossier, Financial Markets, Compliance, Global LEI, OFAC AML, Network Audits) with Multi-Chain auto-payer and gasless PayAI x402 across Base, Polygon, Arbitrum and Solana.",
5
5
  "type": "module",
6
6
  "bin": {
7
7
  "grid402-mcp": "index.mjs"
@@ -29,6 +29,10 @@
29
29
  "ai-agents",
30
30
  "x402",
31
31
  "base",
32
+ "solana",
33
+ "polygon",
34
+ "arbitrum",
35
+ "multichain",
32
36
  "usdc",
33
37
  "forex",
34
38
  "crypto",
package/tools.mjs CHANGED
@@ -7,12 +7,12 @@ import { settleX402Payment } from './x402_payer.mjs';
7
7
  export const DEFAULT_ENDPOINT = process.env.GRID402_ENDPOINT || process.env.GRID402_API_URL || 'https://grid402.online';
8
8
 
9
9
  /**
10
- * Definições formais das 25 ferramentas no padrão MCP (23 micro-serviços + summary + pass_balance)
10
+ * Definições formais das 27 ferramentas no padrão MCP (25 micro-serviços + summary + pass_balance)
11
11
  */
12
12
  export const MCP_TOOLS_DEFINITIONS = [
13
13
  {
14
14
  name: 'grid402_summary',
15
- description: 'Consulta o resumo consolidado de saúde e disponibilidade dos 23 micro-serviços do Grid402 (gratuito, sem cobrança x402).',
15
+ description: 'Consulta o resumo consolidado de saúde e disponibilidade dos 25 micro-serviços do Grid402 (gratuito, sem cobrança x402).',
16
16
  inputSchema: {
17
17
  type: 'object',
18
18
  properties: {},
@@ -27,7 +27,7 @@ export const MCP_TOOLS_DEFINITIONS = [
27
27
  properties: {
28
28
  payment_tx_hash: {
29
29
  type: 'string',
30
- description: 'Hash opcional de transação na Base Mainnet comprovando o pagamento de 0.0050 USDC caso não utilize liquidação automática.',
30
+ description: 'Comprovante opcional de pagamento Multi-Chain USDC (Base, Polygon, Arbitrum ou Solana: 0x..., polygon:0x..., arbitrum:0x..., solana:<base58>, payload x402 base64 ou token pass_g402_...).',
31
31
  },
32
32
  },
33
33
  required: [],
@@ -41,7 +41,7 @@ export const MCP_TOOLS_DEFINITIONS = [
41
41
  properties: {
42
42
  payment_tx_hash: {
43
43
  type: 'string',
44
- description: 'Hash opcional de transação na Base Mainnet com 0.0050 USDC.',
44
+ description: 'Comprovante opcional de pagamento Multi-Chain USDC (Base, Polygon, Arbitrum ou Solana: 0x..., polygon:0x..., arbitrum:0x..., solana:<base58>, payload x402 base64 ou token pass_g402_...).',
45
45
  },
46
46
  },
47
47
  required: [],
@@ -59,7 +59,7 @@ export const MCP_TOOLS_DEFINITIONS = [
59
59
  },
60
60
  payment_tx_hash: {
61
61
  type: 'string',
62
- description: 'Hash opcional de transação na Base Mainnet com 0.0050 USDC.',
62
+ description: 'Comprovante opcional de pagamento Multi-Chain USDC (Base, Polygon, Arbitrum ou Solana: 0x..., polygon:0x..., arbitrum:0x..., solana:<base58>, payload x402 base64 ou token pass_g402_...).',
63
63
  },
64
64
  },
65
65
  required: ['domain'],
@@ -77,7 +77,7 @@ export const MCP_TOOLS_DEFINITIONS = [
77
77
  },
78
78
  payment_tx_hash: {
79
79
  type: 'string',
80
- description: 'Hash opcional de transação na Base Mainnet com 0.0050 USDC.',
80
+ description: 'Comprovante opcional de pagamento Multi-Chain USDC (Base, Polygon, Arbitrum ou Solana: 0x..., polygon:0x..., arbitrum:0x..., solana:<base58>, payload x402 base64 ou token pass_g402_...).',
81
81
  },
82
82
  },
83
83
  required: ['host'],
@@ -95,7 +95,7 @@ export const MCP_TOOLS_DEFINITIONS = [
95
95
  },
96
96
  payment_tx_hash: {
97
97
  type: 'string',
98
- description: 'Hash opcional de transação na Base Mainnet com 0.0050 USDC.',
98
+ description: 'Comprovante opcional de pagamento Multi-Chain USDC (Base, Polygon, Arbitrum ou Solana: 0x..., polygon:0x..., arbitrum:0x..., solana:<base58>, payload x402 base64 ou token pass_g402_...).',
99
99
  },
100
100
  },
101
101
  required: [],
@@ -113,7 +113,7 @@ export const MCP_TOOLS_DEFINITIONS = [
113
113
  },
114
114
  payment_tx_hash: {
115
115
  type: 'string',
116
- description: 'Hash opcional de transação na Base Mainnet com 0.0150 USDC.',
116
+ description: 'Comprovante opcional de pagamento Multi-Chain USDC (0.0150 USDC em Base, Polygon, Arbitrum ou Solana) ou token pass_g402_...',
117
117
  },
118
118
  },
119
119
  required: ['domain'],
@@ -131,7 +131,7 @@ export const MCP_TOOLS_DEFINITIONS = [
131
131
  },
132
132
  payment_tx_hash: {
133
133
  type: 'string',
134
- description: 'Hash opcional de transação na Base Mainnet com 0.0200 USDC.',
134
+ description: 'Comprovante opcional de pagamento Multi-Chain USDC (0.0200 USDC em Base, Polygon, Arbitrum ou Solana) ou token pass_g402_...',
135
135
  },
136
136
  },
137
137
  required: ['cnpj'],
@@ -149,7 +149,7 @@ export const MCP_TOOLS_DEFINITIONS = [
149
149
  },
150
150
  payment_tx_hash: {
151
151
  type: 'string',
152
- description: 'Hash opcional de transação na Base Mainnet com 0.0500 USDC ou token pass_g402_...',
152
+ description: 'Comprovante opcional de pagamento Multi-Chain USDC (0.0500 USDC em Base, Polygon, Arbitrum ou Solana) ou token pass_g402_...',
153
153
  },
154
154
  },
155
155
  required: ['cnpj'],
@@ -163,7 +163,7 @@ export const MCP_TOOLS_DEFINITIONS = [
163
163
  properties: {
164
164
  payment_tx_hash: {
165
165
  type: 'string',
166
- description: 'Hash opcional de transação na Base Mainnet com 0.0150 USDC.',
166
+ description: 'Comprovante opcional de pagamento Multi-Chain USDC (0.0150 USDC em Base, Polygon, Arbitrum ou Solana) ou token pass_g402_...',
167
167
  },
168
168
  },
169
169
  required: [],
@@ -181,7 +181,7 @@ export const MCP_TOOLS_DEFINITIONS = [
181
181
  },
182
182
  payment_tx_hash: {
183
183
  type: 'string',
184
- description: 'Hash opcional de transação na Base Mainnet com 0.0050 USDC.',
184
+ description: 'Comprovante opcional de pagamento Multi-Chain USDC (Base, Polygon, Arbitrum ou Solana: 0x..., polygon:0x..., arbitrum:0x..., solana:<base58>, payload x402 base64 ou token pass_g402_...).',
185
185
  },
186
186
  },
187
187
  required: ['code'],
@@ -199,7 +199,7 @@ export const MCP_TOOLS_DEFINITIONS = [
199
199
  },
200
200
  payment_tx_hash: {
201
201
  type: 'string',
202
- description: 'Hash opcional de transação na Base Mainnet com 0.0200 USDC.',
202
+ description: 'Comprovante opcional de pagamento Multi-Chain USDC (0.0200 USDC em Base, Polygon, Arbitrum ou Solana) ou token pass_g402_...',
203
203
  },
204
204
  },
205
205
  required: ['cnpj'],
@@ -213,7 +213,7 @@ export const MCP_TOOLS_DEFINITIONS = [
213
213
  properties: {
214
214
  payment_tx_hash: {
215
215
  type: 'string',
216
- description: 'Hash opcional de transação na Base Mainnet comprovando o pagamento de 0.0050 USDC caso não utilize liquidação automática.',
216
+ description: 'Comprovante opcional de pagamento Multi-Chain USDC (Base, Polygon, Arbitrum ou Solana: 0x..., polygon:0x..., arbitrum:0x..., solana:<base58>, payload x402 base64 ou token pass_g402_...).',
217
217
  },
218
218
  },
219
219
  required: [],
@@ -231,7 +231,7 @@ export const MCP_TOOLS_DEFINITIONS = [
231
231
  },
232
232
  payment_tx_hash: {
233
233
  type: 'string',
234
- description: 'Hash opcional de transação na Base Mainnet comprovando o pagamento de 0.0050 USDC caso não utilize liquidação automática.',
234
+ description: 'Comprovante opcional de pagamento Multi-Chain USDC (Base, Polygon, Arbitrum ou Solana: 0x..., polygon:0x..., arbitrum:0x..., solana:<base58>, payload x402 base64 ou token pass_g402_...).',
235
235
  },
236
236
  },
237
237
  required: [],
@@ -261,7 +261,7 @@ export const MCP_TOOLS_DEFINITIONS = [
261
261
  },
262
262
  payment_tx_hash: {
263
263
  type: 'string',
264
- description: 'Hash opcional de transacao na Base Mainnet comprovando o pagamento de 0.0050 USDC caso nao utilize liquidacao automatica.',
264
+ description: 'Comprovante opcional de pagamento Multi-Chain USDC (0.0050 USDC em Base, Polygon, Arbitrum ou Solana) ou token pass_g402_...',
265
265
  },
266
266
  },
267
267
  required: [],
@@ -321,7 +321,7 @@ export const MCP_TOOLS_DEFINITIONS = [
321
321
  },
322
322
  payment_tx_hash: {
323
323
  type: 'string',
324
- description: 'Hash opcional de transação na Base Mainnet com 0.0200 USDC.',
324
+ description: 'Comprovante opcional de pagamento Multi-Chain USDC (0.0200 USDC em Base, Polygon, Arbitrum ou Solana) ou token pass_g402_...',
325
325
  },
326
326
  },
327
327
  required: ['lei'],
@@ -339,7 +339,7 @@ export const MCP_TOOLS_DEFINITIONS = [
339
339
  },
340
340
  payment_tx_hash: {
341
341
  type: 'string',
342
- description: 'Hash opcional de transação na Base Mainnet com 0.0200 USDC.',
342
+ description: 'Comprovante opcional de pagamento Multi-Chain USDC (0.0200 USDC em Base, Polygon, Arbitrum ou Solana) ou token pass_g402_...',
343
343
  },
344
344
  },
345
345
  required: ['target'],
@@ -357,7 +357,7 @@ export const MCP_TOOLS_DEFINITIONS = [
357
357
  },
358
358
  payment_tx_hash: {
359
359
  type: 'string',
360
- description: 'Hash opcional de transação na Base Mainnet com 0.0050 USDC.',
360
+ description: 'Comprovante opcional de pagamento Multi-Chain USDC (Base, Polygon, Arbitrum ou Solana: 0x..., polygon:0x..., arbitrum:0x..., solana:<base58>, payload x402 base64 ou token pass_g402_...).',
361
361
  },
362
362
  },
363
363
  required: ['content'],
@@ -383,12 +383,52 @@ export const MCP_TOOLS_DEFINITIONS = [
383
383
  },
384
384
  payment_tx_hash: {
385
385
  type: 'string',
386
- description: 'Hash opcional de transação na Base Mainnet com 0.0050 USDC.',
386
+ description: 'Comprovante opcional de pagamento Multi-Chain USDC (Base, Polygon, Arbitrum ou Solana: 0x..., polygon:0x..., arbitrum:0x..., solana:<base58>, payload x402 base64 ou token pass_g402_...).',
387
387
  },
388
388
  },
389
389
  required: [],
390
390
  },
391
391
  },
392
+ {
393
+ name: 'grid402_extract',
394
+ description: 'Extrai páginas web públicas HTTP/HTTPS com proteção SSRF e devolve Markdown limpo pronto para LLMs e RAG, incluindo título, descrição e links absolutos (0.0050 USDC / 1 crédito).',
395
+ inputSchema: {
396
+ type: 'object',
397
+ properties: {
398
+ url: {
399
+ type: 'string',
400
+ description: 'URL pública HTTP ou HTTPS a ser extraída para Markdown limpo.',
401
+ },
402
+ max_chars: {
403
+ type: 'integer',
404
+ description: 'Limite opcional de caracteres no Markdown retornado (500 a 25000; padrão: 12000).',
405
+ },
406
+ payment_tx_hash: {
407
+ type: 'string',
408
+ description: 'Hash opcional de transação USDC ou token pass_g402_...',
409
+ },
410
+ },
411
+ required: ['url'],
412
+ },
413
+ },
414
+ {
415
+ name: 'grid402_email_verify',
416
+ description: 'Audita entregabilidade de e-mail B2B estritamente Zero-PII: sintaxe RFC, DNS MX, SPF, DMARC, detecção de domínio descartável (disposable), provedor gratuito e role-based (0.0050 USDC / 1 crédito).',
417
+ inputSchema: {
418
+ type: 'object',
419
+ properties: {
420
+ email: {
421
+ type: 'string',
422
+ description: 'Endereço de e-mail corporativo a auditar sem armazenamento em disco.',
423
+ },
424
+ payment_tx_hash: {
425
+ type: 'string',
426
+ description: 'Hash opcional de transação USDC ou token pass_g402_...',
427
+ },
428
+ },
429
+ required: ['email'],
430
+ },
431
+ },
392
432
  {
393
433
  name: 'grid402_pass',
394
434
  description: 'Emite um Session Pass pré-pago x402 (Starter 2 USDC = 400 créditos, Pro 5 USDC = 1.000 créditos, Fleet 20 USDC = 6.000 créditos; 1 crédito = 0.0050 USDC) ou consulta status via ?status=pass_g402_...',
@@ -401,7 +441,7 @@ export const MCP_TOOLS_DEFINITIONS = [
401
441
  },
402
442
  payment_tx_hash: {
403
443
  type: 'string',
404
- description: 'Hash opcional de transação na Base Mainnet para emissão de novo passe.',
444
+ description: 'Comprovante opcional de pagamento Multi-Chain USDC (Base, Polygon, Arbitrum, Optimism, Ethereum ou Solana) para emissão de novo passe.',
405
445
  },
406
446
  },
407
447
  required: [],
@@ -442,8 +482,14 @@ export const MCP_TOOLS_DEFINITIONS = [
442
482
  */
443
483
  export async function executeGrid402Request(service, params = {}, options = {}) {
444
484
  const endpoint = (options.endpoint || DEFAULT_ENDPOINT).replace(/\/$/, '');
445
- const privateKey = options.privateKey || process.env.GRID402_PRIVATE_KEY || null;
446
- const preferredRpc = options.rpcUrl || process.env.GRID402_BASE_RPC_URL || null;
485
+ const paymentNetwork = options.network || params.payment_network || process.env.GRID402_PAYMENT_NETWORK || null;
486
+ const solanaPrivateKey = options.solanaPrivateKey || process.env.GRID402_SOLANA_PRIVATE_KEY || null;
487
+ const privateKey = options.privateKey
488
+ || (String(paymentNetwork || '').toLowerCase() === 'solana' && solanaPrivateKey ? solanaPrivateKey : null)
489
+ || process.env.GRID402_PRIVATE_KEY
490
+ || solanaPrivateKey
491
+ || null;
492
+ const preferredRpc = options.rpcUrl || process.env.GRID402_RPC_URL || process.env.GRID402_BASE_RPC_URL || null;
447
493
 
448
494
  let path = '';
449
495
  const queryParams = new URLSearchParams();
@@ -546,6 +592,16 @@ export async function executeGrid402Request(service, params = {}, options = {})
546
592
  if (params.base) queryParams.set('base', params.base);
547
593
  if (params.date) queryParams.set('date', params.date);
548
594
  break;
595
+ case 'extract':
596
+ path = '/api/v1/extract';
597
+ if (params.url) queryParams.set('url', params.url);
598
+ if (params.max_chars !== undefined && params.max_chars !== null) queryParams.set('max_chars', String(params.max_chars));
599
+ break;
600
+ case 'email-verify':
601
+ case 'email_verify':
602
+ path = '/api/v1/email-verify';
603
+ if (params.email) queryParams.set('email', params.email);
604
+ break;
549
605
  case 'pass':
550
606
  path = '/api/v1/pass';
551
607
  if (params.status) queryParams.set('status', params.status);
@@ -570,7 +626,7 @@ export async function executeGrid402Request(service, params = {}, options = {})
570
626
  headers: {
571
627
  'Content-Type': 'application/json',
572
628
  'Accept': 'application/json',
573
- 'User-Agent': 'Grid402-MCP-Server/1.8',
629
+ 'User-Agent': 'Grid402-MCP-Server/2.0.0',
574
630
  },
575
631
  body: postPayload,
576
632
  });
@@ -582,7 +638,7 @@ export async function executeGrid402Request(service, params = {}, options = {})
582
638
 
583
639
  const headers = {
584
640
  'Accept': 'application/json',
585
- 'User-Agent': 'Grid402-MCP-Server/1.8',
641
+ 'User-Agent': 'Grid402-MCP-Server/2.0.0',
586
642
  };
587
643
 
588
644
  if (params.idempotency_key) {
@@ -608,13 +664,19 @@ export async function executeGrid402Request(service, params = {}, options = {})
608
664
  if (response.status === 402) {
609
665
  const challenge = await response.json();
610
666
 
611
- // Se temos uma chave privada configurada, tenta pagamento on-chain automático
667
+ // Se temos uma chave privada configurada (EVM ou Solana), tenta pagamento Multi-Chain automático
612
668
  if (privateKey) {
613
669
  try {
614
- const paymentResult = await settleX402Payment(challenge, privateKey, preferredRpc);
670
+ const paymentResult = await settleX402Payment(challenge, privateKey, preferredRpc, {
671
+ network: paymentNetwork,
672
+ gasless: options.gasless,
673
+ });
615
674
 
616
- // Refaz a requisição com o hash da transação confirmada na Base
617
- headers['X-Payment'] = paymentResult.txHash;
675
+ // Refaz a requisição com o comprovante Multi-Chain (Base, Polygon, Arbitrum ou Solana)
676
+ headers['X-Payment'] = paymentResult.paymentHeader || paymentResult.txHash;
677
+ if (paymentResult.network && paymentResult.network !== 'base') {
678
+ headers['X-Payment-Network'] = paymentResult.network;
679
+ }
618
680
  const retryResponse = await fetch(url, { headers });
619
681
 
620
682
  if (retryResponse.status === 200) {
@@ -622,8 +684,8 @@ export async function executeGrid402Request(service, params = {}, options = {})
622
684
  return {
623
685
  ...data,
624
686
  _x402_settlement: {
625
- status: 'CONFIRMED_ON_CHAIN',
626
- network: 'Base',
687
+ status: paymentResult.mode === 'x402_gasless' ? 'SETTLED_VIA_FACILITATOR' : 'CONFIRMED_ON_CHAIN',
688
+ network: paymentResult.networkName || 'Base',
627
689
  tx_hash: paymentResult.txHash,
628
690
  block_number: paymentResult.blockNumber,
629
691
  amount_usdc: paymentResult.amountUsdc,
@@ -642,9 +704,9 @@ export async function executeGrid402Request(service, params = {}, options = {})
642
704
  // Se não há chave privada ou session pass configurados, retorna o desafio de pagamento estruturado
643
705
  return {
644
706
  payment_required: true,
645
- message: 'Esta consulta requer micropagamento em USDC na rede Base via protocolo x402.',
707
+ message: 'Esta consulta requer micropagamento em USDC Multi-Chain (Base, Polygon, Arbitrum ou Solana) via protocolo x402.',
646
708
  challenge,
647
- instructions: 'Opções de acesso: (1) Teste grátis definindo GRID402_SANDBOX=true; (2) Use um passe pré-pago sem expor chave privada definindo GRID402_SESSION_PASS=pass_g402_...; (3) Para auto-liquidação on-chain x402, defina GRID402_PRIVATE_KEY.',
709
+ instructions: 'Opções de acesso: (1) Teste grátis definindo GRID402_SANDBOX=true; (2) Use um passe pré-pago sem expor chave privada definindo GRID402_SESSION_PASS=pass_g402_...; (3) Para auto-liquidação x402 Multi-Chain, defina GRID402_PRIVATE_KEY (EVM Base/Polygon/Arbitrum) ou GRID402_SOLANA_PRIVATE_KEY (Solana SPL USDC) e opcionalmente GRID402_PAYMENT_NETWORK=base|polygon|arbitrum|solana.',
648
710
  };
649
711
  }
650
712
 
package/x402_payer.mjs CHANGED
@@ -1,10 +1,16 @@
1
1
  /**
2
- * Grid402 MCP Server - Módulo de Liquidação x402 On-Chain (Base Mainnet)
3
- *
4
- * Permite pagamentos automáticos de US$ 0.0050 USDC via transferência ERC-20
5
- * quando uma chave privada é fornecida no ambiente do agente.
2
+ * Grid402 MCP Server - Módulo de Liquidação Automática x402 Multi-Chain
3
+ *
4
+ * Suporta pagamentos automáticos em USDC (6 casas decimais) em:
5
+ * - Base Mainnet (Chain ID 8453 / eip155:8453) — On-Chain ERC-20 e Gasless EIP-3009
6
+ * - Polygon PoS (Chain ID 137 / eip155:137) — On-Chain ERC-20 e Gasless EIP-3009
7
+ * - Arbitrum One (Chain ID 42161 / eip155:42161) — On-Chain ERC-20 e Gasless EIP-3009
8
+ * - Optimism (Chain ID 10 / eip155:10) — On-Chain ERC-20
9
+ * - Ethereum Mainnet (Chain ID 1 / eip155:1) — On-Chain ERC-20
10
+ * - Solana Mainnet (solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp) — On-Chain SPL USDC e Gasless PayAI SVM
6
11
  */
7
12
 
13
+ import crypto from 'node:crypto';
8
14
  import { ethers } from 'ethers';
9
15
 
10
16
  export const BASE_RPC_URLS = [
@@ -13,78 +19,753 @@ export const BASE_RPC_URLS = [
13
19
  'https://base.llamarpc.com',
14
20
  ];
15
21
 
22
+ export const SOLANA_RPC_URLS = [
23
+ 'https://api.mainnet-beta.solana.com',
24
+ 'https://solana-rpc.publicnode.com',
25
+ ];
26
+
16
27
  export const USDC_CONTRACT_BASE = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913'.toLowerCase();
28
+ export const USDC_MINT_SOLANA = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
17
29
  export const GRID402_RECIPIENT_WALLET = '0xa592625adbceb8e025ac383f1a3fd8ebb6a63f90'.toLowerCase();
30
+ export const GRID402_SOLANA_RECIPIENT_WALLET = 'CSgJyQTwehb3vF2vbsDMdUuBPdcuvx1vdEEhGvVCCF8C';
31
+ export const PAYAI_SOLANA_FEE_PAYER = 'CjNFTjvBhbJJd2B5ePPMHRLx1ELZpa8dwQgGL727eKww';
32
+ export const SOLANA_SPL_TOKEN_PROGRAM_ID = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA';
18
33
  export const REQUIRED_RAW_UNITS = 5000n; // 0.0050 USDC (6 casas decimais)
19
34
 
35
+ export const SUPPORTED_X402_NETWORKS = {
36
+ base: {
37
+ slug: 'base',
38
+ name: 'Base',
39
+ kind: 'evm',
40
+ chainId: 8453,
41
+ caip2: 'eip155:8453',
42
+ usdcContract: USDC_CONTRACT_BASE,
43
+ recipient: GRID402_RECIPIENT_WALLET,
44
+ rpcs: BASE_RPC_URLS,
45
+ eip3009: { name: 'USD Coin', version: '2' },
46
+ },
47
+ polygon: {
48
+ slug: 'polygon',
49
+ name: 'Polygon',
50
+ kind: 'evm',
51
+ chainId: 137,
52
+ caip2: 'eip155:137',
53
+ usdcContract: '0x3c499c542cef5e3811e1192ce70d8cc03d5c3359',
54
+ recipient: GRID402_RECIPIENT_WALLET,
55
+ rpcs: [
56
+ 'https://polygon-rpc.com',
57
+ 'https://1rpc.io/matic',
58
+ 'https://polygon-bor-rpc.publicnode.com',
59
+ ],
60
+ eip3009: { name: 'USD Coin', version: '2' },
61
+ },
62
+ arbitrum: {
63
+ slug: 'arbitrum',
64
+ name: 'Arbitrum',
65
+ kind: 'evm',
66
+ chainId: 42161,
67
+ caip2: 'eip155:42161',
68
+ usdcContract: '0xaf88d065e77c8cc2239327c5edb3a432268e5831',
69
+ recipient: GRID402_RECIPIENT_WALLET,
70
+ rpcs: [
71
+ 'https://arb1.arbitrum.io/rpc',
72
+ 'https://1rpc.io/arb',
73
+ 'https://arbitrum-one-rpc.publicnode.com',
74
+ ],
75
+ eip3009: { name: 'USD Coin', version: '2' },
76
+ },
77
+ optimism: {
78
+ slug: 'optimism',
79
+ name: 'Optimism',
80
+ kind: 'evm',
81
+ chainId: 10,
82
+ caip2: 'eip155:10',
83
+ usdcContract: '0x0b2c639c533813f4aa9d7837caf62653d097ff85',
84
+ recipient: GRID402_RECIPIENT_WALLET,
85
+ rpcs: [
86
+ 'https://mainnet.optimism.io',
87
+ 'https://1rpc.io/op',
88
+ 'https://optimism-rpc.publicnode.com',
89
+ ],
90
+ eip3009: null,
91
+ },
92
+ ethereum: {
93
+ slug: 'ethereum',
94
+ name: 'Ethereum',
95
+ kind: 'evm',
96
+ chainId: 1,
97
+ caip2: 'eip155:1',
98
+ usdcContract: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',
99
+ recipient: GRID402_RECIPIENT_WALLET,
100
+ rpcs: [
101
+ 'https://ethereum-rpc.publicnode.com',
102
+ 'https://1rpc.io/eth',
103
+ 'https://eth.llamarpc.com',
104
+ ],
105
+ eip3009: null,
106
+ },
107
+ solana: {
108
+ slug: 'solana',
109
+ name: 'Solana',
110
+ kind: 'svm',
111
+ chainId: null,
112
+ caip2: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',
113
+ usdcContract: USDC_MINT_SOLANA,
114
+ recipient: GRID402_SOLANA_RECIPIENT_WALLET,
115
+ feePayer: PAYAI_SOLANA_FEE_PAYER,
116
+ rpcs: SOLANA_RPC_URLS,
117
+ },
118
+ };
119
+
20
120
  const ERC20_ABI = [
21
121
  'function transfer(address to, uint256 amount) returns (bool)',
22
122
  'function balanceOf(address account) view returns (uint256)',
23
123
  ];
24
124
 
125
+ const BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
126
+ const BASE58_MAP = new Map([...BASE58_ALPHABET].map((ch, idx) => [ch, BigInt(idx)]));
127
+ const ED25519_PKCS8_PREFIX = Buffer.from('302e020100300506032b657004220420', 'hex');
128
+
25
129
  /**
26
- * Cria um provider com fallback resiliente para a Base Mainnet
130
+ * Codifica um Buffer/Uint8Array em Base58 (padrão Bitcoin/Solana).
27
131
  */
28
- export async function getBaseProvider(preferredRpc = null) {
29
- const rpcs = preferredRpc ? [preferredRpc, ...BASE_RPC_URLS] : BASE_RPC_URLS;
132
+ export function encodeBase58(bytes) {
133
+ const buf = Buffer.from(bytes);
134
+ if (buf.length === 0) return '';
135
+ let num = BigInt('0x' + buf.toString('hex'));
136
+ let out = '';
137
+ while (num > 0n) {
138
+ const rem = Number(num % 58n);
139
+ out = BASE58_ALPHABET[rem] + out;
140
+ num /= 58n;
141
+ }
142
+ for (let i = 0; i < buf.length && buf[i] === 0; i++) {
143
+ out = '1' + out;
144
+ }
145
+ return out;
146
+ }
147
+
148
+ /**
149
+ * Decodifica uma string Base58 para Buffer.
150
+ */
151
+ export function decodeBase58(str) {
152
+ if (typeof str !== 'string' || str.trim() === '') {
153
+ throw new Error('String Base58 vazia ou inválida.');
154
+ }
155
+ const clean = str.trim();
156
+ let num = 0n;
157
+ for (const ch of clean) {
158
+ const val = BASE58_MAP.get(ch);
159
+ if (val === undefined) {
160
+ throw new Error(`Caractere inválido em Base58: "${ch}"`);
161
+ }
162
+ num = num * 58n + val;
163
+ }
164
+ let hex = num === 0n ? '' : num.toString(16);
165
+ if (hex.length % 2 !== 0) hex = '0' + hex;
166
+ const rawBytes = hex ? Buffer.from(hex, 'hex') : Buffer.alloc(0);
167
+ let leadingZeros = 0;
168
+ for (let i = 0; i < clean.length && clean[i] === '1'; i++) {
169
+ leadingZeros++;
170
+ }
171
+ return Buffer.concat([Buffer.alloc(leadingZeros, 0), rawBytes]);
172
+ }
173
+
174
+ /**
175
+ * Normaliza o nome/CAIP-2/ChainID de uma rede para o slug canônico suportado.
176
+ */
177
+ export function normalizePaymentNetwork(networkRaw, privateKeyHint = null) {
178
+ const val = String(networkRaw || '').trim().toLowerCase();
179
+ if (val) {
180
+ if (['base', 'base-mainnet', 'eip155:8453', '8453'].includes(val)) return 'base';
181
+ if (['polygon', 'matic', 'pol', 'polygon-pos', 'eip155:137', '137'].includes(val)) return 'polygon';
182
+ if (['arbitrum', 'arb', 'arbitrum-one', 'arb1', 'eip155:42161', '42161'].includes(val)) return 'arbitrum';
183
+ if (['optimism', 'op', 'op-mainnet', 'eip155:10', '10'].includes(val)) return 'optimism';
184
+ if (['ethereum', 'eth', 'mainnet', 'eth-mainnet', 'eip155:1', '1'].includes(val)) return 'ethereum';
185
+ if (['solana', 'sol', 'solana-mainnet', 'solana:5eykt4usfv8p8njdtrepy1vzqkqzkvdp'].includes(val)) return 'solana';
186
+ throw new Error(`Rede de pagamento não suportada: "${networkRaw}". Redes suportadas: base, polygon, arbitrum, optimism, ethereum, solana.`);
187
+ }
188
+
189
+ // Auto-detecção pela chave privada quando a rede não é explícita
190
+ if (typeof privateKeyHint === 'string') {
191
+ const trimmed = privateKeyHint.trim();
192
+ if (trimmed.startsWith('[') && trimmed.endsWith(']')) {
193
+ return 'solana';
194
+ }
195
+ if (!trimmed.startsWith('0x') && /^[1-9A-HJ-NP-Za-km-z]{43,90}$/.test(trimmed)) {
196
+ return 'solana';
197
+ }
198
+ }
199
+ return 'base';
200
+ }
201
+
202
+ /**
203
+ * Faz o parse de uma chave privada Solana Ed25519 (Base58 64-byte keypair, Base58 32-byte seed,
204
+ * JSON array de 32/64 bytes ou seed hexadecimal de 64 chars) usando node:crypto nativo.
205
+ */
206
+ export function parseSolanaKeypair(rawKey) {
207
+ if (!rawKey || typeof rawKey !== 'string') {
208
+ throw new Error('Chave privada Solana inválida. Forneça keypair Base58 (64 bytes), seed Base58 (32 bytes) ou JSON array.');
209
+ }
210
+ const trimmed = rawKey.trim();
211
+ let keyBytes;
212
+
213
+ if (trimmed.startsWith('[') && trimmed.endsWith(']')) {
214
+ let arr;
215
+ try {
216
+ arr = JSON.parse(trimmed);
217
+ } catch {
218
+ throw new Error('Chave privada Solana inválida: JSON array malformado.');
219
+ }
220
+ if (!Array.isArray(arr) || (arr.length !== 64 && arr.length !== 32)) {
221
+ throw new Error('Chave privada Solana inválida: o JSON array deve conter 32 ou 64 bytes.');
222
+ }
223
+ keyBytes = Buffer.from(arr);
224
+ } else if (/^(?:0x)?[0-9a-fA-F]{64}$/.test(trimmed)) {
225
+ const cleanHex = trimmed.startsWith('0x') ? trimmed.slice(2) : trimmed;
226
+ keyBytes = Buffer.from(cleanHex, 'hex');
227
+ } else if (/^[1-9A-HJ-NP-Za-km-z]{43,90}$/.test(trimmed)) {
228
+ keyBytes = decodeBase58(trimmed);
229
+ } else {
230
+ throw new Error('Chave privada inválida. Para EVM use 0x + 64 hex; para Solana use Base58 (32/64 bytes) ou JSON array.');
231
+ }
232
+
233
+ if (keyBytes.length !== 32 && keyBytes.length !== 64) {
234
+ throw new Error(`Chave privada Solana com tamanho inválido (${keyBytes.length} bytes; esperado 32 ou 64 bytes).`);
235
+ }
236
+
237
+ const seed32 = keyBytes.subarray(0, 32);
238
+ const privateKeyObj = crypto.createPrivateKey({
239
+ key: Buffer.concat([ED25519_PKCS8_PREFIX, seed32]),
240
+ format: 'der',
241
+ type: 'pkcs8',
242
+ });
243
+ const spkiDer = crypto.createPublicKey(privateKeyObj).export({ format: 'der', type: 'spki' });
244
+ const publicKeyBytes = Buffer.from(spkiDer.subarray(spkiDer.length - 32));
245
+
246
+ if (keyBytes.length === 64) {
247
+ const embeddedPub = keyBytes.subarray(32, 64);
248
+ if (!embeddedPub.equals(publicKeyBytes)) {
249
+ throw new Error('Chave privada Solana inválida: a chave pública embutida nos últimos 32 bytes não corresponde à seed Ed25519.');
250
+ }
251
+ }
252
+
253
+ return {
254
+ seed: seed32,
255
+ publicKeyBytes,
256
+ publicKeyBase58: encodeBase58(publicKeyBytes),
257
+ privateKeyObject: privateKeyObj,
258
+ };
259
+ }
260
+
261
+ /**
262
+ * Codifica um inteiro no formato compact-u16 de transações Solana.
263
+ */
264
+ function encodeCompactU16(value) {
265
+ let rem = value;
266
+ const bytes = [];
267
+ while (true) {
268
+ let elem = rem & 0x7f;
269
+ rem >>= 7;
270
+ if (rem === 0) {
271
+ bytes.push(elem);
272
+ break;
273
+ }
274
+ elem |= 0x80;
275
+ bytes.push(elem);
276
+ }
277
+ return Buffer.from(bytes);
278
+ }
279
+
280
+ /**
281
+ * Constrói e assina uma transação Solana Legacy de transferência SPL USDC (`TransferChecked`, opcode 12).
282
+ *
283
+ * @param {object} params
284
+ * @param {string} params.privateKey Chave privada Solana (Base58 ou JSON array)
285
+ * @param {string} params.sourceTokenAccount Conta SPL USDC de origem (Base58)
286
+ * @param {string} params.destinationTokenAccount Conta SPL USDC de destino (Base58)
287
+ * @param {string} params.recentBlockhash Blockhash recente da Solana Mainnet (Base58)
288
+ * @param {bigint|number|string} [params.rawUnits] Quantidade bruta em 6 decimais (padrão 5000 = 0.0050 USDC)
289
+ * @param {string} [params.mint] Mint SPL USDC (padrão EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v)
290
+ * @param {string|null} [params.feePayer] Se informado e diferente da carteira pagadora, gera transação parcialmente assinada para o facilitador PayAI
291
+ */
292
+ export function buildSolanaSplTransferTransaction({
293
+ privateKey,
294
+ sourceTokenAccount,
295
+ destinationTokenAccount,
296
+ recentBlockhash,
297
+ rawUnits = REQUIRED_RAW_UNITS,
298
+ mint = USDC_MINT_SOLANA,
299
+ feePayer = null,
300
+ }) {
301
+ const keypair = parseSolanaKeypair(privateKey);
302
+ const ownerBytes = keypair.publicKeyBytes;
303
+ const sourceBytes = decodeBase58(sourceTokenAccount);
304
+ const destBytes = decodeBase58(destinationTokenAccount);
305
+ const mintBytes = decodeBase58(mint);
306
+ const tokenProgBytes = decodeBase58(SOLANA_SPL_TOKEN_PROGRAM_ID);
307
+ const blockhashBytes = decodeBase58(recentBlockhash);
308
+
309
+ for (const [label, buf] of [
310
+ ['sourceTokenAccount', sourceBytes],
311
+ ['destinationTokenAccount', destBytes],
312
+ ['mint', mintBytes],
313
+ ['recentBlockhash', blockhashBytes],
314
+ ]) {
315
+ if (buf.length !== 32) {
316
+ throw new Error(`Parâmetro Solana "${label}" inválido (${buf.length} bytes; esperado 32 bytes).`);
317
+ }
318
+ }
319
+
320
+ // Instruction data: TransferChecked (opcode 12) + uint64LE(amount) + uint8(decimals = 6)
321
+ const ixData = Buffer.alloc(10);
322
+ ixData.writeUInt8(12, 0);
323
+ ixData.writeBigUInt64LE(BigInt(rawUnits), 1);
324
+ ixData.writeUInt8(6, 9);
325
+
326
+ const hasSeparateFeePayer = Boolean(
327
+ feePayer && feePayer.trim() !== '' && feePayer.trim() !== keypair.publicKeyBase58
328
+ );
329
+
330
+ let header;
331
+ let accountKeys;
332
+ let programIdIndex;
333
+ let accountIndices;
334
+
335
+ if (hasSeparateFeePayer) {
336
+ const feePayerBytes = decodeBase58(feePayer);
337
+ if (feePayerBytes.length !== 32) {
338
+ throw new Error('feePayer Solana inválido.');
339
+ }
340
+ // 2 signers (0: feePayer writable, 1: owner readonly), 2 unsigned writable (2: source, 3: dest), 2 unsigned readonly (4: mint, 5: tokenProgram)
341
+ header = Buffer.from([2, 1, 2]);
342
+ accountKeys = [feePayerBytes, ownerBytes, sourceBytes, destBytes, mintBytes, tokenProgBytes];
343
+ programIdIndex = 5;
344
+ accountIndices = Buffer.from([2, 4, 3, 1]);
345
+ } else {
346
+ // 1 signer (0: owner writable), 2 unsigned writable (1: source, 2: dest), 2 unsigned readonly (3: mint, 4: tokenProgram)
347
+ header = Buffer.from([1, 0, 2]);
348
+ accountKeys = [ownerBytes, sourceBytes, destBytes, mintBytes, tokenProgBytes];
349
+ programIdIndex = 4;
350
+ accountIndices = Buffer.from([1, 3, 2, 0]);
351
+ }
352
+
353
+ const messageBytes = Buffer.concat([
354
+ header,
355
+ encodeCompactU16(accountKeys.length),
356
+ ...accountKeys,
357
+ blockhashBytes,
358
+ encodeCompactU16(1), // 1 instrução
359
+ Buffer.from([programIdIndex]),
360
+ encodeCompactU16(accountIndices.length),
361
+ accountIndices,
362
+ encodeCompactU16(ixData.length),
363
+ ixData,
364
+ ]);
365
+
366
+ const ownerSig = crypto.sign(null, messageBytes, keypair.privateKeyObject);
367
+ const signatures = hasSeparateFeePayer
368
+ ? [Buffer.alloc(64, 0), ownerSig]
369
+ : [ownerSig];
370
+
371
+ const serializedTx = Buffer.concat([
372
+ encodeCompactU16(signatures.length),
373
+ ...signatures,
374
+ messageBytes,
375
+ ]);
376
+
377
+ return {
378
+ transactionBase64: serializedTx.toString('base64'),
379
+ signatureBase58: encodeBase58(ownerSig),
380
+ from: keypair.publicKeyBase58,
381
+ feePayer: hasSeparateFeePayer ? feePayer.trim() : keypair.publicKeyBase58,
382
+ };
383
+ }
384
+
385
+ /**
386
+ * Constrói o payload gasless x402 v2 para Solana SVM (`PAYMENT-SIGNATURE` / `X-Payment` em base64).
387
+ */
388
+ export function buildSolanaX402PaymentPayload({
389
+ privateKey,
390
+ sourceTokenAccount,
391
+ destinationTokenAccount,
392
+ recentBlockhash,
393
+ rawUnits = REQUIRED_RAW_UNITS,
394
+ recipient = GRID402_SOLANA_RECIPIENT_WALLET,
395
+ mint = USDC_MINT_SOLANA,
396
+ feePayer = PAYAI_SOLANA_FEE_PAYER,
397
+ }) {
398
+ const built = buildSolanaSplTransferTransaction({
399
+ privateKey,
400
+ sourceTokenAccount,
401
+ destinationTokenAccount,
402
+ recentBlockhash,
403
+ rawUnits,
404
+ mint,
405
+ feePayer,
406
+ });
407
+
408
+ const payloadObj = {
409
+ x402Version: 2,
410
+ scheme: 'exact',
411
+ network: SUPPORTED_X402_NETWORKS.solana.caip2,
412
+ accepted: {
413
+ scheme: 'exact',
414
+ network: SUPPORTED_X402_NETWORKS.solana.caip2,
415
+ amount: String(BigInt(rawUnits)),
416
+ asset: mint,
417
+ payTo: recipient,
418
+ maxTimeoutSeconds: 300,
419
+ extra: { feePayer },
420
+ },
421
+ payload: {
422
+ transaction: built.transactionBase64,
423
+ },
424
+ };
425
+
426
+ return {
427
+ payloadBase64: Buffer.from(JSON.stringify(payloadObj), 'utf8').toString('base64'),
428
+ payload: payloadObj,
429
+ from: built.from,
430
+ to: recipient,
431
+ signatureBase58: built.signatureBase58,
432
+ };
433
+ }
434
+
435
+ /**
436
+ * Executa uma chamada JSON-RPC na Solana Mainnet com failover entre nós públicos.
437
+ */
438
+ export async function callSolanaRpc(method, params = [], preferredRpc = null) {
439
+ const rpcs = preferredRpc ? [preferredRpc, ...SOLANA_RPC_URLS] : SOLANA_RPC_URLS;
440
+ let lastError = null;
441
+
442
+ for (const rpc of rpcs) {
443
+ try {
444
+ const res = await fetch(rpc, {
445
+ method: 'POST',
446
+ headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
447
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),
448
+ });
449
+ if (!res.ok) {
450
+ lastError = new Error(`HTTP ${res.status} de ${rpc}`);
451
+ continue;
452
+ }
453
+ const data = await res.json();
454
+ if (data.error) {
455
+ throw new Error(data.error.message || JSON.stringify(data.error));
456
+ }
457
+ return data.result;
458
+ } catch (err) {
459
+ lastError = err;
460
+ }
461
+ }
462
+ throw new Error(`Falha ao comunicar com RPC da Solana Mainnet (${method}): ${lastError?.message || 'indisponível'}`);
463
+ }
464
+
465
+ /**
466
+ * Liquida um desafio x402 na Solana Mainnet (SPL USDC).
467
+ * Suporta modo gasless x402 v2 (`options.gasless = true`) ou envio direto on-chain (`solana:<signature>`).
468
+ */
469
+ export async function settleSolanaUsdcPayment(challenge, privateKey, preferredRpc = null, options = {}) {
470
+ const keypair = parseSolanaKeypair(privateKey);
471
+ const rawUnits = BigInt(challenge?.price_raw_units || REQUIRED_RAW_UNITS);
472
+ const formattedUsdc = (Number(rawUnits) / 1e6).toFixed(4);
473
+ const recipientOwner = challenge?.solana_recipient_wallet || GRID402_SOLANA_RECIPIENT_WALLET;
474
+ const mint = USDC_MINT_SOLANA;
475
+
476
+ // 1. Consulta conta SPL USDC do pagador e valida saldo
477
+ const senderAccounts = await callSolanaRpc(
478
+ 'getTokenAccountsByOwner',
479
+ [keypair.publicKeyBase58, { mint }, { encoding: 'jsonParsed' }],
480
+ preferredRpc
481
+ );
482
+ const senderEntry = senderAccounts?.value?.[0];
483
+ if (!senderEntry?.pubkey) {
484
+ throw new Error(`Conta SPL USDC não encontrada na carteira Solana ${keypair.publicKeyBase58}.`);
485
+ }
486
+ const senderBalanceRaw = BigInt(senderEntry?.account?.data?.parsed?.info?.tokenAmount?.amount || '0');
487
+ if (senderBalanceRaw < rawUnits) {
488
+ const currentFormatted = (Number(senderBalanceRaw) / 1e6).toFixed(6);
489
+ throw new Error(`Saldo insuficiente de SPL USDC na carteira Solana ${keypair.publicKeyBase58}. Requerido: ${formattedUsdc} USDC, Atual: ${currentFormatted} USDC.`);
490
+ }
491
+
492
+ // 2. Consulta conta SPL USDC oficial do recebedor Grid402
493
+ const recipientAccounts = await callSolanaRpc(
494
+ 'getTokenAccountsByOwner',
495
+ [recipientOwner, { mint }, { encoding: 'jsonParsed' }],
496
+ preferredRpc
497
+ );
498
+ const recipientTokenAccount = recipientAccounts?.value?.[0]?.pubkey;
499
+ if (!recipientTokenAccount) {
500
+ throw new Error(`Conta SPL USDC de destino não encontrada para ${recipientOwner}.`);
501
+ }
502
+
503
+ // 3. Obtém blockhash recente
504
+ const latestBlockhashRes = await callSolanaRpc(
505
+ 'getLatestBlockhash',
506
+ [{ commitment: 'confirmed' }],
507
+ preferredRpc
508
+ );
509
+ const recentBlockhash = latestBlockhashRes?.value?.blockhash;
510
+ if (!recentBlockhash) {
511
+ throw new Error('Não foi possível obter recentBlockhash da Solana Mainnet.');
512
+ }
513
+
514
+ // 4. Modo Gasless via Facilitador PayAI x402 v2
515
+ const useGasless = options.gasless === true || process.env.GRID402_X402_GASLESS === 'true';
516
+ if (useGasless) {
517
+ const x402Built = buildSolanaX402PaymentPayload({
518
+ privateKey,
519
+ sourceTokenAccount: senderEntry.pubkey,
520
+ destinationTokenAccount: recipientTokenAccount,
521
+ recentBlockhash,
522
+ rawUnits,
523
+ recipient: recipientOwner,
524
+ mint,
525
+ });
526
+ return {
527
+ txHash: x402Built.signatureBase58,
528
+ paymentHeader: x402Built.payloadBase64,
529
+ blockNumber: latestBlockhashRes?.context?.slot || null,
530
+ network: 'solana',
531
+ networkName: 'Solana',
532
+ mode: 'x402_gasless',
533
+ from: keypair.publicKeyBase58,
534
+ to: recipientOwner,
535
+ amountUsdc: formattedUsdc,
536
+ };
537
+ }
538
+
539
+ // 5. Modo On-Chain Direto (envia transação SPL USDC e retorna solana:<signature>)
540
+ const signedTx = buildSolanaSplTransferTransaction({
541
+ privateKey,
542
+ sourceTokenAccount: senderEntry.pubkey,
543
+ destinationTokenAccount: recipientTokenAccount,
544
+ recentBlockhash,
545
+ rawUnits,
546
+ mint,
547
+ feePayer: null,
548
+ });
549
+
550
+ const txSignature = await callSolanaRpc(
551
+ 'sendTransaction',
552
+ [signedTx.transactionBase64, { encoding: 'base64', preflightCommitment: 'confirmed' }],
553
+ preferredRpc
554
+ );
555
+
556
+ return {
557
+ txHash: txSignature,
558
+ paymentHeader: `solana:${txSignature}`,
559
+ blockNumber: latestBlockhashRes?.context?.slot || null,
560
+ network: 'solana',
561
+ networkName: 'Solana',
562
+ mode: 'onchain_transfer',
563
+ from: keypair.publicKeyBase58,
564
+ to: recipientOwner,
565
+ amountUsdc: formattedUsdc,
566
+ };
567
+ }
568
+
569
+ /**
570
+ * Cria um provider EVM com fallback resiliente para qualquer rede EVM suportada (Base, Polygon, Arbitrum, Optimism, Ethereum).
571
+ */
572
+ export async function getEvmProvider(networkSlug = 'base', preferredRpc = null) {
573
+ const net = SUPPORTED_X402_NETWORKS[networkSlug] || SUPPORTED_X402_NETWORKS.base;
574
+ const rpcs = preferredRpc ? [preferredRpc, ...net.rpcs] : net.rpcs;
30
575
  for (const rpc of rpcs) {
31
576
  try {
32
- const provider = new ethers.JsonRpcProvider(rpc, 8453, { staticNetwork: true });
577
+ const provider = new ethers.JsonRpcProvider(rpc, net.chainId, { staticNetwork: true });
33
578
  await provider.getBlockNumber();
34
579
  return provider;
35
580
  } catch {
36
581
  // Tenta próximo RPC
37
582
  }
38
583
  }
39
- throw new Error('Não foi possível conectar a nenhum nó RPC da Base Mainnet.');
584
+ throw new Error(`Não foi possível conectar a nenhum nó RPC da rede ${net.name} (Chain ID ${net.chainId}).`);
40
585
  }
41
586
 
42
587
  /**
43
- * Executa a transferência de 0.0050 USDC na Base para liquidar o desafio x402
44
- *
588
+ * Cria um provider com fallback resiliente para a Base Mainnet (retrocompatível).
589
+ */
590
+ export async function getBaseProvider(preferredRpc = null) {
591
+ return getEvmProvider('base', preferredRpc);
592
+ }
593
+
594
+ /**
595
+ * Gera um payload gasless EIP-3009 (`TransferWithAuthorization`) assinado offline para Base, Polygon ou Arbitrum.
596
+ */
597
+ export async function buildEip3009PaymentPayload(challenge, privateKey, networkSlug = 'base') {
598
+ const slug = normalizePaymentNetwork(networkSlug, privateKey);
599
+ const net = SUPPORTED_X402_NETWORKS[slug];
600
+ if (!net || net.kind !== 'evm' || !net.eip3009) {
601
+ throw new Error(`A rede "${networkSlug}" não suporta assinatura gasless EIP-3009. Use base, polygon ou arbitrum.`);
602
+ }
603
+ if (!privateKey || typeof privateKey !== 'string' || !/^0x[0-9a-fA-F]{64}$/.test(privateKey.trim())) {
604
+ throw new Error('Chave privada EVM inválida. Deve iniciar com 0x e conter 64 caracteres hexadecimais.');
605
+ }
606
+
607
+ const wallet = new ethers.Wallet(privateKey.trim());
608
+ const rawUnits = BigInt(challenge?.price_raw_units || REQUIRED_RAW_UNITS);
609
+ const recipient = ethers.getAddress(challenge?.recipient_wallet || net.recipient);
610
+ const verifyingContract = ethers.getAddress(net.usdcContract);
611
+ const nowSec = Math.floor(Date.now() / 1000);
612
+ const validAfter = 0;
613
+ const validBefore = nowSec + 300;
614
+ const nonce = '0x' + crypto.randomBytes(32).toString('hex');
615
+
616
+ const domain = {
617
+ name: net.eip3009.name,
618
+ version: net.eip3009.version,
619
+ chainId: net.chainId,
620
+ verifyingContract,
621
+ };
622
+
623
+ const types = {
624
+ TransferWithAuthorization: [
625
+ { name: 'from', type: 'address' },
626
+ { name: 'to', type: 'address' },
627
+ { name: 'value', type: 'uint256' },
628
+ { name: 'validAfter', type: 'uint256' },
629
+ { name: 'validBefore', type: 'uint256' },
630
+ { name: 'nonce', type: 'bytes32' },
631
+ ],
632
+ };
633
+
634
+ const authorization = {
635
+ from: wallet.address,
636
+ to: recipient,
637
+ value: rawUnits.toString(),
638
+ validAfter: String(validAfter),
639
+ validBefore: String(validBefore),
640
+ nonce,
641
+ };
642
+
643
+ const signature = await wallet.signTypedData(domain, types, authorization);
644
+
645
+ const payloadObj = {
646
+ x402Version: 2,
647
+ scheme: 'exact',
648
+ network: net.caip2,
649
+ accepted: {
650
+ scheme: 'exact',
651
+ network: net.caip2,
652
+ amount: rawUnits.toString(),
653
+ asset: net.usdcContract,
654
+ payTo: recipient.toLowerCase(),
655
+ maxTimeoutSeconds: 300,
656
+ extra: net.eip3009,
657
+ },
658
+ payload: {
659
+ signature,
660
+ authorization: {
661
+ from: wallet.address.toLowerCase(),
662
+ to: recipient.toLowerCase(),
663
+ value: rawUnits.toString(),
664
+ validAfter: String(validAfter),
665
+ validBefore: String(validBefore),
666
+ nonce,
667
+ },
668
+ },
669
+ };
670
+
671
+ return {
672
+ payloadBase64: Buffer.from(JSON.stringify(payloadObj), 'utf8').toString('base64'),
673
+ payload: payloadObj,
674
+ signature,
675
+ nonce,
676
+ from: wallet.address,
677
+ to: recipient.toLowerCase(),
678
+ network: net.slug,
679
+ networkName: net.name,
680
+ amountUsdc: (Number(rawUnits) / 1e6).toFixed(4),
681
+ };
682
+ }
683
+
684
+ /**
685
+ * Executa a liquidação automática do desafio x402 em USDC Multi-Chain:
686
+ * - Solana Mainnet (`solana`): SPL USDC on-chain (`solana:<signature>`) ou gasless PayAI SVM (`x402Version: 2`)
687
+ * - Base, Polygon, Arbitrum, Optimism e Ethereum: transferência ERC-20 on-chain ou gasless EIP-3009
688
+ *
45
689
  * @param {object} challenge Desafio retornado pelo Grid402 (HTTP 402)
46
- * @param {string} privateKey Chave privada hexadecimal da carteira pagadora
47
- * @param {string} [preferredRpc] URL opcional de RPC da Base
48
- * @returns {Promise<{ txHash: string, blockNumber: number }>}
690
+ * @param {string} privateKey Chave privada EVM (0x + 64 hex) ou Solana (Base58 / JSON array)
691
+ * @param {string|null} [preferredRpc] URL opcional de RPC customizado
692
+ * @param {object} [options] Opções adicionais ({ network: 'base'|'polygon'|'arbitrum'|'optimism'|'ethereum'|'solana', gasless: boolean })
693
+ * @returns {Promise<{ txHash: string, paymentHeader: string, blockNumber: number|null, network: string, networkName: string, from: string, to: string, amountUsdc: string }>}
49
694
  */
50
- export async function settleX402Payment(challenge, privateKey, preferredRpc = null) {
51
- if (!privateKey || typeof privateKey !== 'string' || !privateKey.startsWith('0x')) {
695
+ export async function settleX402Payment(challenge, privateKey, preferredRpc = null, options = {}) {
696
+ if (!privateKey || typeof privateKey !== 'string') {
697
+ throw new Error('Chave privada inválida. Deve iniciar com 0x (64 hex para EVM) ou ser uma chave Solana Base58/JSON válida.');
698
+ }
699
+
700
+ const requestedNetwork = options.network || process.env.GRID402_PAYMENT_NETWORK || null;
701
+ const networkSlug = normalizePaymentNetwork(requestedNetwork, privateKey);
702
+ const net = SUPPORTED_X402_NETWORKS[networkSlug];
703
+
704
+ if (net.kind === 'svm') {
705
+ return settleSolanaUsdcPayment(challenge, privateKey, preferredRpc, options);
706
+ }
707
+
708
+ const trimmedKey = privateKey.trim();
709
+ if (!trimmedKey.startsWith('0x') || !/^0x[0-9a-fA-F]{64}$/.test(trimmedKey)) {
52
710
  throw new Error('Chave privada inválida. Deve iniciar com 0x e conter 64 caracteres hexadecimais.');
53
711
  }
54
712
 
55
- const recipient = (challenge?.recipient_wallet || GRID402_RECIPIENT_WALLET).toLowerCase();
56
- const tokenContract = (challenge?.token_contract || USDC_CONTRACT_BASE).toLowerCase();
57
713
  const rawUnits = BigInt(challenge?.price_raw_units || REQUIRED_RAW_UNITS);
714
+ const formattedUsdc = (Number(rawUnits) / 1e6).toFixed(4);
715
+ const useGasless = options.gasless === true || process.env.GRID402_X402_GASLESS === 'true';
716
+
717
+ if (useGasless && net.eip3009) {
718
+ const eip3009 = await buildEip3009PaymentPayload(challenge, trimmedKey, networkSlug);
719
+ return {
720
+ txHash: eip3009.nonce,
721
+ paymentHeader: eip3009.payloadBase64,
722
+ blockNumber: null,
723
+ network: net.slug,
724
+ networkName: net.name,
725
+ mode: 'x402_gasless',
726
+ from: eip3009.from,
727
+ to: eip3009.to,
728
+ amountUsdc: formattedUsdc,
729
+ };
730
+ }
58
731
 
59
- const provider = await getBaseProvider(preferredRpc);
60
- const wallet = new ethers.Wallet(privateKey, provider);
732
+ const recipient = (challenge?.recipient_wallet || net.recipient).toLowerCase();
733
+ const tokenContract = (
734
+ networkSlug === 'base'
735
+ ? (challenge?.token_contract || net.usdcContract)
736
+ : net.usdcContract
737
+ ).toLowerCase();
61
738
 
62
- // Instancia contrato ERC-20 do USDC na Base
739
+ const provider = await getEvmProvider(networkSlug, preferredRpc);
740
+ const wallet = new ethers.Wallet(trimmedKey, provider);
63
741
  const usdc = new ethers.Contract(tokenContract, ERC20_ABI, wallet);
64
742
 
65
- // 1. Verifica saldo de USDC
743
+ // 1. Verifica saldo de USDC na rede selecionada
66
744
  try {
67
745
  const balance = await usdc.balanceOf(wallet.address);
68
746
  if (balance < rawUnits) {
69
- throw new Error(`Saldo insuficiente de USDC na carteira ${wallet.address}. Requerido: 0.0050 USDC, Atual: ${ethers.formatUnits(balance, 6)} USDC.`);
747
+ throw new Error(`Saldo insuficiente de USDC na rede ${net.name} (${wallet.address}). Requerido: ${formattedUsdc} USDC, Atual: ${ethers.formatUnits(balance, 6)} USDC.`);
70
748
  }
71
749
  } catch (err) {
72
750
  if (err.message.includes('Saldo insuficiente')) {
73
751
  throw err;
74
752
  }
75
- // Caso leitura falhe por RPC restrito, tenta envio direto
76
753
  }
77
754
 
78
- // 2. Envia transferência ERC-20
755
+ // 2. Envia transferência ERC-20 e aguarda confirmação
79
756
  const tx = await usdc.transfer(recipient, rawUnits);
80
757
  const receipt = await tx.wait(1);
758
+ const paymentHeader = networkSlug === 'base' ? receipt.hash : `${networkSlug}:${receipt.hash}`;
81
759
 
82
760
  return {
83
761
  txHash: receipt.hash,
762
+ paymentHeader,
84
763
  blockNumber: receipt.blockNumber,
764
+ network: net.slug,
765
+ networkName: net.name,
766
+ mode: 'onchain_transfer',
85
767
  from: wallet.address,
86
768
  to: recipient,
87
- amountUsdc: '0.0050',
769
+ amountUsdc: formattedUsdc,
88
770
  };
89
771
  }
90
-