Skip to content

API de Exchanges 📝

Introducción

La API de Exchanges es la superficie central de swaps de p3p. Úsala para descubrir qué se puede comerciar, obtener la mejor cotización a través de cada fuente de liquidez agregada, bloquear esa cotización en un swap on-chain y rastrearlo hasta completarse.

Todos los endpoints a continuación requieren un encabezado api-key de desarrollador. Regístrate como socio en p3p.xyz para obtener uno.

http
api-key: YOUR_P3P_API_KEY

Endpoints


1. Obtener Cadenas

GET /chains api-key requerida

Devuelve cada cadena actualmente habilitada en p3p.

bash
curl https://api.p3p.xyz/chains \
  -H "api-key: YOUR_P3P_API_KEY"
ts
const chains = await fetch("https://api.p3p.xyz/chains", {
  headers: { "api-key": "YOUR_P3P_API_KEY" },
}).then((r) => r.json());
json
{
  "status": 200,
  "message": "ok",
  "data": [
    {
      "id": 0,
      "key": "btc",
      "name": "Bitcoin",
      "display": "BTC Chain",
      "color": "#F7931A",
      "logo": "",
      "icon": "token:btc",
      "explorer": {
        "address": "https://mempool.space/address/%s",
        "tx": "https://mempool.space/tx/%s"
      },
      "website": "https://bitcoin.org",
      "vm": "BVM",
      "validation": [
        "^(1[1-9A-HJ-NP-Za-km-z]{25,34}|3[1-9A-HJ-NP-Za-km-z]{25,34}|bc1[qpzry9x8gf2tvdw0s3jn54khce6mua7l]{8,87})$"
      ],
      "defaults": ["btc"],
      "tags": ["bitcoin", "btc", "xbt", "satoshi"],
      "enabled": true
    },
    {
      "id": 1,
      "key": "eth",
      "name": "Ethereum",
      "display": "ETH Chain",
      "color": "#627EEA",
      "logo": "",
      "icon": "token:eth",
      "explorer": {
        "address": "https://etherscan.io/address/%s",
        "tx": "https://etherscan.io/tx/%s"
      },
      "website": "https://ethereum.org",
      "vm": "EVM",
      "validation": [
        "^(0x)[0-9A-Fa-f]{40}$"
      ],
      "defaults": ["eth", "usdt", "usdc", "dai"],
      "tags": ["ethereum", "eth", "eht", "vitalik"],
      "enabled": true
    }
  ]
}

2. Obtener Tokens

GET /tokens api-key requerida

Devuelve los tokens habilitados agrupados por cadena.

bash
curl https://api.p3p.xyz/tokens \
  -H "api-key: YOUR_P3P_API_KEY"
json
{
  "eth": [
    { "key": "eth", "name": "Ether", "symbol": "ETH", "decimals": 18, "rate": "3421.8", "address": "", "native": true, "enabled": true },
    { "key": "usdt", "name": "Tether", "symbol": "USDT", "decimals": 6, "rate": "1.0", "address": "0xdac17f958d2ee523a2206206994597c13d831ec7", "native": false, "enabled": true }
  ],
  "ton": [
    { "key": "ton", "name": "Toncoin", "symbol": "TON", "decimals": 9, "rate": "5.23", "address": "", "native": true, "enabled": true },
    { "key": "usdt", "name": "USDT (TON)", "symbol": "USDT", "decimals": 6, "rate": "1.0", "address": "EQCxE6mUtQJKFnGfaROTKOt1lZbDiiX1kCixRv7Nw2Id_sDs", "native": false, "enabled": true }
  ]
}

3. Obtener Tasas

GET /rates api-key requerida

Devuelve las tasas de mercado de referencia en vivo para cada activo soportado, obtenidas de oráculos on-chain.

bash
curl https://api.p3p.xyz/rates \
  -H "api-key: YOUR_P3P_API_KEY"
json
{
  "btc": 98234.56,
  "eth": 3421.8,
  "ton": 5.23,
  "usdt": 1.0,
  "usdc": 1.0,
  "sol": 142.35
}

4. Cotizar Tasa de Exchange

POST /exchange/rate api-key requerida

Agrega tasas de cada fuente de liquidez activa y devuelve la mejor (o todas).

Cuerpo

CampoTipoRequeridoDescripción
chain_fromstringClave de cadena origen
token_fromstringClave de token origen
amount_fromstringCantidad en unidades de visualización
chain_tostringClave de cadena destino
token_tostringClave de token destino
opts.bestbooleannoOrdenar por mejor tasa (predeterminado)
opts.fastestbooleannoOrdenar por tasa más rápida en vez de la mejor
opts.partner_idstringnoTu ID de socio o billetera registrada (gana ingresos)
bash
curl -X POST https://api.p3p.xyz/exchange/rate \
  -H "Content-Type: application/json" \
  -H "api-key: YOUR_P3P_API_KEY" \
  -d '{
    "chain_from": "eth",
    "token_from": "eth",
    "amount_from": "0.1",
    "chain_to": "ton",
    "token_to": "ton",
    "opts": { "best": true }
  }'
ts
const rate = await fetch("https://api.p3p.xyz/exchange/rate", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    "api-key": "YOUR_P3P_API_KEY",
  },
  body: JSON.stringify({
    chain_from: "eth",
    token_from: "eth",
    amount_from: "0.1",
    chain_to: "ton",
    token_to: "ton",
    opts: { best: true },
  }),
}).then((r) => r.json());
json
{
  "type": "crypto",
  "path_from": "eth.eth",
  "path_to": "ton.ton",
  "amount_from": "0.1",
  "amount_to": "342.18",
  "direction": "exact_input",
  "amount_from_unit": 0.1,
  "amount_to_unit": 342.18,
  "rate": "3421.8",
  "impact": "0.01",
  "duration": 90,
  "boosted": false
}

5. Crear Exchange

POST /exchange/create api-key requerida

Bloquea una tasa, crea un exchange y recibe una dirección de depósito.

Cuerpo

CampoTipoRequeridoDescripción
chain_fromstringClave de cadena origen
token_fromstringClave de token origen
amount_fromstringCantidad en unidades de visualización
chain_tostringClave de cadena destino
token_tostringClave de token destino
wallet_tostringDirección del destinatario en la cadena destino
wallet_refundstringnoDirección de reembolso si el swap no puede completarse
wallet_fromstringnoDirección origen del usuario (algunas cadenas la necesitan)
opts.bestbooleannoOrdenar por mejor tasa (predeterminado)
opts.fastestbooleannoOrdenar por tasa más rápida en vez de la mejor
opts.partner_idstringnoTu ID de socio o billetera registrada (gana ingresos)
bash
curl -X POST https://api.p3p.xyz/exchange/create \
  -H "Content-Type: application/json" \
  -H "api-key: YOUR_P3P_API_KEY" \
  -d '{
    "chain_from": "eth", "token_from": "eth", "amount_from": "0.1",
    "chain_to":   "ton", "token_to":   "ton",
    "wallet_to":     "UQAbc...XYZ",
    "wallet_refund": "0xRefund...address",
    "opts": { "partner_id": "P3_YOURPARTNERID" }
  }'
ts
const exchange = await fetch("https://api.p3p.xyz/exchange/create", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    "api-key": "YOUR_P3P_API_KEY",
  },
  body: JSON.stringify({
    chain_from: "eth",
    token_from: "eth",
    amount_from: "0.1",
    chain_to: "ton",
    token_to: "ton",
    wallet_to: "UQAbc...XYZ",
    wallet_refund: "0xRefund...address",
    opts: { partner_id: "P3_YOURPARTNERID" }, 
  }),
}).then((r) => r.json());
json
{
  "created_at": "2026-05-24T10:30:00Z",
  "id": "ex_8f4c2a...",
  "type": "crypto",
  "chain_from": "eth",
  "token_from": "eth",
  "amount_from": "0.1",
  "chain_to": "ton",
  "token_to": "ton",
  "amount_to": "342.18",
  "amount_to_unit": 342.18,
  "wallet_refund": "0xRefund...address",
  "wallet_from": "",
  "wallet_to": "UQAbc...XYZ",
  "deposit_address": "0xDepositAddressGeneratedForYou",
  "rate": "3421.8",
  "impact": "0.01",
  "duration": 90
}

Para exchanges de socios (al usar el header api-key): La respuesta devuelve hash en lugar de id:

json
{
  "created_at": "2026-05-24T10:30:00Z",
  "hash": "A7K2M9X5B3C1D8F4",
  "type": "crypto",
  "chain_from": "eth",
  "token_from": "eth",
  "amount_from": "0.1",
  "chain_to": "ton",
  "token_to": "ton",
  "amount_to": "342.18",
  "amount_to_unit": 342.18,
  "wallet_to": "UQAbc...XYZ",
  "deposit_address": "0xDepositAddressGeneratedForYou",
  "rate": "3421.8",
  "impact": "0.01",
  "duration": 90
}

Envía amount_from de token_from desde tu billetera a deposit_address para iniciar el swap. Rastrea el progreso con Verificar Estado de Exchange a continuación.

Los exchanges de socios son privados

Los exchanges de socios (identificados por hash) solo son accesibles pasando el hash como ID con tu header api-key. No pueden ser consultados por ID de transacción normal.

Ventana de depósito

El depósito debe coincidir exactamente con amount_from y llegar dentro de ~6 minutos. Después del timeout puedes reintentar con ?bump=true en el endpoint de estado.


6. Verificar Estado de Exchange

GET /check/:txId api-key requerida

Obtén el estado actual de un único exchange o factura.

QueryTipoDescripción
bumpbooleanSi true, reintenta un exchange estancado/con timeout
bash
curl https://api.p3p.xyz/check/ex_8f4c2a... \
  -H "api-key: YOUR_P3P_API_KEY"
json
{
  "id": "ex_8f4c2a...",
  "created_at": "2026-05-24T10:30:00Z",
  "status": "exchanging",
  "type": "internal",
  "invoice": false,
  "chain_from": "eth",
  "token_from": "eth",
  "amount_from": "0.1",
  "chain_to": "ton",
  "token_to": "ton",
  "amount_to": "342.18",
  "amount_to_unit": 342.18,
  "wallet_to": "UQAbc...XYZ",
  "deposit_address": "0xDepositAddressGeneratedForYou",
  "checkpoint": 3,
  "checkpoints": 5
}

Valores de estado

EstadoSignificado
newEsperando el depósito del usuario
depositedDepósito detectado, preparando el swap
processingSwap enviado a la fuente de liquidez, esperando confirmación
exchangingSwap confirmado, los fondos están siendo intercambiados
completeHecho — el destinatario ha recibido los fondos
timeoutVentana de depósito expirada; llama con ?bump=true para reiniciar y reintentar
errorEl exchange encontró un error; llama con ?bump=true para reintentar
expiredEl exchange ha expirado y ya no puede reintentarse

Reintento bump

Si un trade hace timeout (no se detectó depósito dentro de la ventana de depósito), llama al endpoint nuevamente con ?bump=true para resetear la ventana:

bash
curl "https://api.p3p.xyz/check/ex_8f4c2a...?bump=true" \
  -H "api-key: YOUR_P3P_API_KEY"

Exchanges de socios (creados con el header api-key) pueden consultarse pasando el hash como ID. Si hay un header api-key, el sistema automáticamente intenta hacer coincidir como hash primero:

bash
# Usando api-key de socio — busca por hash
curl https://api.p3p.xyz/check/A7K2M9X5B3C1D8F4 \
  -H "api-key: YOUR_PARTNER_API_KEY"
json
{
  "hash": "A7K2M9X5B3C1D8F4",
  "created_at": "2026-05-24T10:30:00Z",
  "status": "complete",
  "type": "internal",
  "invoice": false,
  "chain_from": "eth",
  "token_from": "eth",
  "amount_from": "0.1",
  "chain_to": "ton",
  "token_to": "ton",
  "amount_to": "342.18",
  "amount_to_unit": 342.18,
  "wallet_to": "UQAbc...XYZ",
  "deposit_address": "0xDepositAddressGeneratedForYou",
  "checkpoint": 5,
  "checkpoints": 5
}

Formato del hash

Por defecto, los hashes tienen 40 caracteres alfanuméricos (a-z, A-Z, 0-9). Los socios pueden personalizar el formato a través del Panel de Socios.


7. Verificar Múltiples Exchanges

POST /check api-key requerida

Verifica varios trades en una sola llamada.

Cuerpo

CampoTipoRequeridoDescripción
hashesstring[]Array de IDs de exchanges
bash
curl -X POST https://api.p3p.xyz/check \
  -H "Content-Type: application/json" \
  -H "api-key: YOUR_P3P_API_KEY" \
  -d '{ "hashes": ["ex_8f4c2a...", "ex_aa11bb..."] }'

Devuelve un array de objetos de estado de exchange minificados:

json
[
  {
    "hash": "ex_8f4c2a...",
    "status": "complete",
    "type": "crypto",
    "invoice": false,
    "chain_from": "eth",
    "token_from": "eth",
    "amount_from": "0.1",
    "chain_to": "ton",
    "token_to": "ton",
    "amount_to": "342.18",
    "checkpoint": 4,
    "checkpoints": 4
  },
  {
    "hash": "A7K2M9X5B3C1D8F4",
    "status": "exchanging",
    "type": "crypto",
    "invoice": false,
    "chain_from": "ton",
    "token_from": "usdt",
    "amount_from": "100",
    "chain_to": "eth",
    "token_to": "usdc",
    "amount_to": "99.5",
    "checkpoint": 2,
    "checkpoints": 4
  }
]