JavaScript

function encodeBatch(rawTxs) {
  if (rawTxs.length === 0 || rawTxs.length > 16) {
    throw new Error("batch must contain 1-16 transactions");
  }

  let total = 0;
  for (const tx of rawTxs) {
    if (tx.length < 66 || tx.length > 1232) {
      throw new Error(`invalid tx size: ${tx.length}`);
    }
    total += 2 + tx.length;
  }

  const out = Buffer.allocUnsafe(total);
  let off = 0;
  for (const tx of rawTxs) {
    out.writeUInt16BE(tx.length, off);
    off += 2;
    Buffer.from(tx).copy(out, off);
    off += tx.length;
  }
  return out;
}

async function sendBatch(endpoint, apiKey, rawTxs) {
  const body = encodeBatch(rawTxs);
  const res = await fetch(
    `${endpoint}/api/sendBatch?c=${apiKey}`,
    {
      method: "POST",
      headers: { "Content-Type": "application/octet-stream" },
      body,
    }
  );

  if (!res.ok) {
    const text = await res.text();
    throw new Error(`sendBatch failed (${res.status}): ${text}`);
  }
}

Last updated