// Mytrade BIT Agent Network: signed calls from your own server (Node.js 18+). // BIT_KEY_ID and BIT_KEY_SECRET come from your secret store, never from the code. import { createHash, createHmac, randomBytes } from 'node:crypto'; const API = 'https://mytrade.kz/api/demand-network/v1'; const KEY_ID = process.env.BIT_KEY_ID!; const SECRET = process.env.BIT_KEY_SECRET!; async function signed(method: string, path: string, payload?: unknown) { const body = payload === undefined ? '' : JSON.stringify(payload); const ts = String(Math.floor(Date.now() / 1000)); const nonce = randomBytes(16).toString('hex'); const bodyHash = createHash('sha256').update(body).digest('hex'); const signature = createHmac('sha256', SECRET) .update([method, path, ts, nonce, bodyHash].join('\n')).digest('hex'); const response = await fetch(new URL(path, API).href, { method, body: body || undefined, headers: { Authorization: `DN-HMAC-SHA256 ${KEY_ID}`, 'X-DN-Timestamp': ts, 'X-DN-Nonce': nonce, 'X-DN-Signature': signature, 'Content-Type': 'application/json', 'Idempotency-Key': randomBytes(16).toString('hex'), }, }); return response.json(); } // 1. Check the key. The first successful call marks the platform as Connected. console.log(await signed('GET', '/api/demand-network/v1/me')); // 2. Only after the user agreed: prepare a Want request. The user reviews and sends it on Mytrade. // prepareWant({ query: 'chairs', quantity: '20', quantity_unit: 'pcs', country_code: 'KZ', language: 'en' }) export const prepareWant = (want: Record) => signed('POST', '/api/demand-network/v1/want-invites', want);