// Witness-only hourly feed. Account active/owner keys are never needed here. import { readFileSync } from 'node:fs'; import { pathToFileURL } from 'node:url'; import { base58 } from '@scure/base'; import { sha256 } from '@noble/hashes/sha2.js'; import { bytesToHex, hexToBytes } from '@noble/hashes/utils.js'; import { getHivePublicKeyFromPrivateKey, signHiveDigest } from '../../src/lib/hive-keys.ts'; import { concatBytes, uintLE, varuint, packString, PIXAGRAM_CHAIN_ID, PIXAGRAM_RPC } from '../../src/lib/pixagram-protocol.ts'; import { hiveUsd, ownRatio, pixaInHive, ratioFor, stepped } from './feed-price.mjs'; export const BIG_MAC_SOURCE = 'https://raw.githubusercontent.com/TheEconomist/big-mac-data/master/output-data/big-mac-full-index.csv'; // A PIXA's price is what it trades for on Pixa Markets' pool (feed-price.mjs), from 27 November 2026. Until then it was a // fixed $0.12, an operator's reference set on 15 October 2026. Pixa Markets runs on this server. export const MARKET_URL = process.env.PIXA_MARKET_URL ?? 'http://127.0.0.1:8810'; export const HIVE_NODES = ['https://api.hive.blog', 'https://api.openhive.network', 'https://api.deathwing.me']; export function latestUsBigMac(csv, now = Date.now()) { // Economist CSV has quoted country names containing commas. const rows = csv.trim().split(/\r?\n/).map((line) => { const fields = []; let field = ''; let quoted = false; for (let i = 0; i < line.length; i++) { if (line[i] === '"') { if (quoted && line[i + 1] === '"') { field += '"'; i++; } else quoted = !quoted; } else if (line[i] === ',' && !quoted) { fields.push(field); field = ''; } else field += line[i]; } if (quoted) throw new Error('Malformed Big Mac CSV.'); fields.push(field); return fields; }); const header = rows.shift(); const index = (key) => { const n = header.indexOf(key); if (n < 0) throw new Error('Big Mac CSV schema changed.'); return n; }; const country = index('iso_a3'); const date = index('date'); const price = index('dollar_price'); const latest = rows.filter((r) => r[country] === 'USA').sort((a, b) => b[date].localeCompare(a[date]))[0]; const value = Number(latest?.[price]); const dateString = latest?.[date]; const timestamp = Date.parse(dateString); if (!dateString || !/^\d{4}-\d{2}-\d{2}$/.test(dateString) || !Number.isFinite(timestamp) || timestamp > now || now - timestamp > 370 * 86400000 || !Number.isFinite(value) || value < 1 || value > 30) throw new Error('Big Mac source is missing, stale, or outside the expected range.'); return { date: dateString, usd: value, source: BIG_MAC_SOURCE }; } export function packFeedAsset(value) { const match = /^(\d+)\.(\d{3}) (PIXA|PXS)$/.exec(value); if (!match) throw new Error('Invalid feed asset.'); const amount = BigInt(match[1]) * 1000n + BigInt(match[2]); if (amount <= 0n || amount > 9223372036854775807n) throw new Error('Invalid feed amount.'); const bytes = new Uint8Array(16); new DataView(bytes.buffer).setBigInt64(0, amount, true); bytes[8] = 3; bytes.set(new TextEncoder().encode(match[3]), 9); return bytes; } export function feedTransaction(identity, globals, ratio) { const price = { base: '1.000 PXS', quote: `${ratio.toFixed(3)} PIXA` }; const key = base58.decode(identity.publicKey.slice(3)).slice(0, 33); // The HF30 evaluator retains Hive's internal hbd_exchange_rate property name. const props = [['hbd_exchange_rate', bytesToHex(concatBytes(packFeedAsset(price.base), packFeedAsset(price.quote)))], ['key', bytesToHex(key)]]; const tx = { ref_block_num: globals.head_block_number & 65535, ref_block_prefix: new DataView(hexToBytes(globals.head_block_id).buffer).getUint32(4, true), expiration: new Date(Date.parse(globals.time + 'Z') + 180000).toISOString().slice(0, 19), operations: [['witness_set_properties', { owner: identity.account, props, extensions: [] }]], extensions: [], signatures: [] }; const unsigned = concatBytes(uintLE(tx.ref_block_num, 2), uintLE(tx.ref_block_prefix, 4), uintLE(Date.parse(tx.expiration + 'Z') / 1000, 4), varuint(1), varuint(42), packString(identity.account), varuint(props.length), ...props.flatMap(([name, hex]) => [packString(name), varuint(hex.length / 2), hexToBytes(hex)]), varuint(0), varuint(0)); return { tx, unsigned, price }; } export async function runFeed({ keyPath, previewAccount, broadcast = false, fetchImpl = fetch, market = MARKET_URL, hiveNodes = HIVE_NODES }) { /** Hive's median price of a HIVE, from the first of its public nodes that answers. */ async function hiveMedian() { for (const node of hiveNodes) { try { const response = await fetchImpl(node, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'condenser_api.get_current_median_history_price', params: [] }), signal: AbortSignal.timeout(15000) }); if (!response.ok) continue; const payload = await response.json(); if (payload?.result) return payload.result; } catch { // The next node. } } throw new Error('No Hive node gave its median price.'); } async function rpc(method, params = []) { const response = await fetchImpl(PIXAGRAM_RPC, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }), signal: AbortSignal.timeout(15000) }); if (!response.ok) throw new Error(`Feed RPC unavailable (${response.status}).`); const payload = await response.json(); // Omit RPC error data, transactions, and credentials from operator logs. if (payload.error) throw new Error(`Feed RPC rejected ${method} (${payload.error.code}).`); return payload.result; } if (previewAccount && (broadcast || keyPath)) throw new Error('Preview takes only a public witness name.'); const identity = previewAccount ? { account: previewAccount } : JSON.parse(readFileSync(keyPath, 'utf8')); const config = await rpc('condenser_api.get_config'); if (config.HIVE_CHAIN_ID !== PIXAGRAM_CHAIN_ID || config.HIVE_ADDRESS_PREFIX !== 'PIX' || !String(config.HIVE_BLOCKCHAIN_VERSION).startsWith('1.30.')) throw new Error('Unexpected Pixagram protocol.'); const witness = await rpc('condenser_api.get_witness_by_account', [identity.account]); if (!witness?.signing_key) throw new Error('No registered signing key for this witness.'); if (previewAccount) { identity.publicKey = witness.signing_key; } else { if (getHivePublicKeyFromPrivateKey(identity.privateKey, 'PIX') !== identity.publicKey) throw new Error('Witness key does not match its public key.'); if (witness.signing_key !== identity.publicKey) throw new Error('Dedicated key is not the registered witness signing key.'); } const source = await fetchImpl(BIG_MAC_SOURCE, { signal: AbortSignal.timeout(15000) }); if (!source.ok) throw new Error('Big Mac source unavailable.'); const csv = await source.text(); if (csv.length > 2000000) throw new Error('Big Mac source is too large.'); const bigMac = latestUsBigMac(csv); // A PIXA in dollars: what the pool really traded at (or its price, when too little did), times Hive's median price. const usdPerHive = hiveUsd(await hiveMedian()); const pools = await fetchImpl(`${market}/api/pools`, { signal: AbortSignal.timeout(15000) }); if (!pools.ok) throw new Error(`Pixa Markets unavailable (${pools.status}).`); const pixa = pixaInHive(await pools.json(), usdPerHive); const pixaUsd = pixa.hive * usdPerHive; const target = ratioFor(bigMac.usd, pixaUsd); // No more than a tenth from this witness's own last feed in one go. const last = ownRatio(witness); const ratio = stepped(last, target); const globals = await rpc('condenser_api.get_dynamic_global_properties'); if (Math.abs(Date.now() - Date.parse(globals.time + 'Z')) > 60000) throw new Error('Pixagram RPC is not caught up.'); const { tx, unsigned, price } = feedTransaction(identity, globals, ratio); const remoteHex = await rpc('condenser_api.get_transaction_hex', [tx]); if (remoteHex !== bytesToHex(concatBytes(unsigned, varuint(0)))) throw new Error('Feed serialization differs from the chain.'); const result = { account: identity.account, reference: { from: pixa.from, pool: 'WPIXA:SWAP.HIVE', pixaHive: Number(pixa.hive.toFixed(6)), hiveUsd: usdPerHive, pixaUsd: Number(pixaUsd.toFixed(6)), tradedUsd: Number(pixa.tradedUsd.toFixed(2)) }, target: Number(target.toFixed(3)), last: last === null ? null : Number(last.toFixed(3)), bigMac, price, serializationVerified: true }; if (!broadcast) return result; tx.signatures = [signHiveDigest(bytesToHex(sha256(concatBytes(hexToBytes(PIXAGRAM_CHAIN_ID), unsigned))), identity.privateKey)]; const authority = await rpc('condenser_api.verify_authority', [tx]); if (authority !== true && !authority?.valid) throw new Error('Witness feed signing authority was rejected.'); const published = await rpc('condenser_api.broadcast_transaction_synchronous', [tx]); return { ...result, transactionId: published.id, block: published.block_num, published: true }; } if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { const args = process.argv.slice(2); try { let options; if (args.includes('--preview')) { if (args.length !== 2 || args[0] !== '--preview' || !/^[a-z][a-z0-9.-]{2,15}$/.test(args[1])) { throw new Error('Usage: --preview WITNESS'); } options = { previewAccount: args[1], market: process.env.PIXA_MARKET_URL ?? 'https://pixa.markets' }; } else { const index = args.indexOf('--signing-key'); const keyPath = process.env.CREDENTIALS_DIRECTORY ? `${process.env.CREDENTIALS_DIRECTORY}/witness-key` : index >= 0 && args[index + 1]; if (!keyPath) throw new Error('Pass --preview WITNESS or --signing-key JSON.'); options = { keyPath, broadcast: args.includes('--broadcast') }; } console.log(JSON.stringify(await runFeed(options), null, options.previewAccount ? 2 : undefined)); } catch (error) { console.error(error.message); process.exitCode = 1; } }