{
  "info": {
    "name": "iEXExchanger API v3",
    "description": "Check the API, verify HMAC v2, list exchange routes and request a quote. Use a test installation and a dedicated key.",
    "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
  },
  "auth": {
    "type": "noauth"
  },
  "protocolProfileBehavior": {
    "followRedirects": false,
    "strictSSL": true
  },
  "event": [
    {
      "listen": "prerequest",
      "script": {
        "type": "text/javascript",
        "exec": [
          "const utf8 = new TextEncoder();",
          "const toHex = (bytes) => Array.from(new Uint8Array(bytes), (byte) =>",
          "    byte.toString(16).padStart(2, '0')).join('');",
          "const encode = (part) => encodeURIComponent(part).replace(/[!'()*]/g,",
          "    (character) => '%' + character.charCodeAt(0).toString(16).toUpperCase());",
          "",
          "try {",
          "    const origin = pm.environment.get('EXCHANGER_API_ORIGIN');",
          "    const url = new URL(pm.variables.replaceIn(pm.request.url.toString()));",
          "    const method = pm.request.method.toUpperCase();",
          "    const allowed = new Set([",
          "        'GET /api/v3/ping',",
          "        'GET /api/v3/private/ping',",
          "        'GET /api/v3/private/exchange/routes',",
          "        'POST /api/v3/private/exchange/quotes',",
          "    ]);",
          "    if (url.protocol !== 'https:' || url.origin !== origin || url.username ||",
          "        url.password || url.hash || !allowed.has(method + ' ' + url.pathname)) {",
          "        throw new Error('Set the HTTPS exchanger origin and select a request from this collection.');",
          "    }",
          "",
          "    pm.request.headers.upsert({ key: 'Accept', value: 'application/json' });",
          "    if (url.pathname !== '/api/v3/ping') {",
          "        const token = pm.environment.get('EXCHANGER_API_TOKEN');",
          "        const secret = pm.environment.get('EXCHANGER_API_HMAC_SECRET');",
          "        if (!token || !secret) {",
          "            throw new Error('Set the local token and signing secret in the selected environment.');",
          "        }",
          "",
          "        const pairs = [];",
          "        const names = new Set();",
          "        for (const [name, value] of url.searchParams) {",
          "            if (!/^[A-Za-z][A-Za-z0-9_-]*(?:\\[[A-Za-z0-9_-]+\\])*$/.test(name) || names.has(name)) {",
          "                throw new Error('Use unique query parameters and explicit indexes for lists.');",
          "            }",
          "            names.add(name);",
          "            pairs.push(encode(name) + '=' + encode(value));",
          "        }",
          "",
          "        let body = '';",
          "        if (pm.request.body && pm.request.body.mode) {",
          "            if (pm.request.body.mode !== 'raw') {",
          "                throw new Error('This collection signs raw JSON bodies.');",
          "            }",
          "            body = pm.variables.replaceIn(pm.request.body.raw);",
          "            JSON.parse(body);",
          "            pm.request.body.update({ mode: 'raw', raw: body });",
          "            pm.request.headers.upsert({ key: 'Content-Type', value: 'application/json' });",
          "        }",
          "",
          "        const timestamp = String(Math.floor(Date.now() / 1000));",
          "        const nonce = toHex(crypto.getRandomValues(new Uint8Array(16)));",
          "        const idempotencyKey = pm.request.headers.get('Idempotency-Key') || '';",
          "        const bodyHash = toHex(await crypto.subtle.digest('SHA-256', utf8.encode(body)));",
          "        const canonical = ['v2', method, url.pathname, pairs.sort().join('&'),",
          "            bodyHash, timestamp, nonce, idempotencyKey.trim()].join('\\n');",
          "        const key = await crypto.subtle.importKey('raw', utf8.encode(secret),",
          "            { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);",
          "        const signature = toHex(await crypto.subtle.sign('HMAC', key, utf8.encode(canonical)));",
          "        const headers = {",
          "            Authorization: 'Bearer ' + token,",
          "            'X-Api-Signature-Version': 'v2',",
          "            'X-Api-Timestamp': timestamp,",
          "            'X-Api-Nonce': nonce,",
          "            'X-Api-Signature': 'sha256=' + signature,",
          "        };",
          "        for (const [header, value] of Object.entries(headers)) {",
          "            pm.request.headers.upsert({ key: header, value });",
          "        }",
          "    }",
          "} catch (error) {",
          "    pm.execution.skipRequest();",
          "    throw error;",
          "}"
        ]
      }
    },
    {
      "listen": "test",
      "script": {
        "type": "text/javascript",
        "exec": [
          "pm.test('HTTP 200 with a successful Exchanger API envelope', () => {",
          "    pm.response.to.have.status(200);",
          "    const payload = pm.response.json();",
          "    pm.expect(payload.state).to.eql(0);",
          "    const path = new URL(pm.variables.replaceIn(pm.request.url.toString())).pathname;",
          "    const resultType = path === '/api/v3/private/exchange/routes' ? 'array' : 'object';",
          "    pm.expect(payload.result).to.be.an(resultType);",
          "});"
        ]
      }
    }
  ],
  "item": [
    {
      "name": "Public ping",
      "request": {
        "method": "GET",
        "header": [],
        "url": "{{EXCHANGER_API_ORIGIN}}/api/v3/ping",
        "description": "Check the API address without credentials."
      }
    },
    {
      "name": "Signed ping",
      "request": {
        "method": "GET",
        "header": [],
        "url": "{{EXCHANGER_API_ORIGIN}}/api/v3/private/ping",
        "description": "Check the token and HMAC v2 without an extra scope."
      }
    },
    {
      "name": "List exchange routes",
      "request": {
        "method": "GET",
        "header": [],
        "url": "{{EXCHANGER_API_ORIGIN}}/api/v3/private/exchange/routes?per_page=5",
        "description": "Scope: public-api:exchange:routes:read. Copy a route ID from the response."
      }
    },
    {
      "name": "Request a quote",
      "request": {
        "method": "POST",
        "header": [],
        "url": "{{EXCHANGER_API_ORIGIN}}/api/v3/private/exchange/quotes",
        "description": "Scope: public-api:exchange:quotes:read. Uses EXCHANGER_ROUTE_ID and EXCHANGER_AMOUNT. Does not create an order.",
        "body": {
          "mode": "raw",
          "raw": "{\"route_id\": {{EXCHANGER_ROUTE_ID}}, \"amount\": \"{{EXCHANGER_AMOUNT}}\"}",
          "options": {
            "raw": {
              "language": "json"
            }
          }
        }
      }
    }
  ]
}
