"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
/**
 * Live demo of the trust-minimized x402 escrow channel over HTTP, testnet-10.
 *
 * A paid API gates requests with EscrowTabServer; a buyer's X402Client funds an
 * escrow, then pays per request with cumulative vouchers (no on-chain cost per
 * request). Finally the seller claims its earned funds with the latest voucher.
 *
 * Usage: SOMPI_NODE_URL=<node> node dist/demo-escrow.js
 */
const http = __importStar(require("node:http"));
const os = __importStar(require("node:os"));
const path = __importStar(require("node:path"));
const policy_1 = require("./policy");
const wallet_1 = require("./wallet");
const client_1 = require("./x402/client");
const escrow_1 = require("./x402/escrow");
const escrow_server_1 = require("./x402/escrow-server");
const NETWORK = process.env.SOMPI_NETWORK ?? "testnet-10";
const NODE = process.env.SOMPI_NODE_URL;
const PORT = 8650;
async function main() {
    const sellerWallet = new wallet_1.KaspaWallet({
        networkId: NETWORK,
        dataDir: path.join(os.homedir(), ".sompi", NETWORK, "demo-escrow-seller"),
        nodeUrl: NODE,
    });
    // Refund timeout: comfortably ahead of the current DAA so the demo's claims
    // happen well before clients could refund.
    const info = await (await sellerWallet.client()).getServerInfo();
    const refundTimeout = BigInt(info.virtualDaaScore) + 1000000n;
    const serverKey = (0, escrow_1.generateChannelKey)();
    const escrow = new escrow_server_1.EscrowTabServer({
        networkId: NETWORK,
        rpc: () => sellerWallet.client(),
        wallet: () => sellerWallet,
        serverPrivateHex: serverKey.privateKey,
        serverPublicHex: serverKey.publicKey,
        refundTimeout,
        minDepositSompi: 90000000n, // 0.9 KAS escrow (within the buyer's 1 KAS/tx policy)
        pricePerRequestSompi: 20000000n, // 0.2 KAS per request
        dataDir: path.join(os.homedir(), ".sompi", NETWORK, "demo-escrow-seller"),
        description: "sompi escrow demo: trust-minimized API",
    });
    let served = 0;
    const server = http.createServer(async (req, res) => {
        try {
            if (await escrow.gate(req, res))
                return;
            res.setHeader("content-type", "application/json");
            res.end(JSON.stringify({ result: `served request #${++served}`, daa: String(info.virtualDaaScore) }));
        }
        catch (e) {
            res.statusCode = 500;
            res.end(JSON.stringify({ error: String(e) }));
        }
    });
    await new Promise((r) => server.listen(PORT, r));
    console.log(`[seller] escrow-gated API on :${PORT} (0.2 KAS/request, 0.9 KAS escrow, refund@DAA ${refundTimeout})`);
    const buyerWallet = new wallet_1.KaspaWallet({ networkId: NETWORK, dataDir: path.join(os.homedir(), ".sompi", NETWORK), nodeUrl: NODE });
    const policy = new policy_1.PolicyEngine(path.join(os.homedir(), ".sompi", NETWORK));
    const client = new client_1.X402Client(buyerWallet, policy, path.join(os.homedir(), ".sompi", NETWORK, "demo-escrow-buyer"));
    console.log(`[buyer]  ${buyerWallet.address} — ${(0, wallet_1.formatKas)(await buyerWallet.balanceSompi())} KAS\n`);
    for (let i = 1; i <= 3; i++) {
        const t0 = Date.now();
        const r = await client.paidFetch(`http://127.0.0.1:${PORT}/api/data`);
        console.log(`request ${i} (${Date.now() - t0}ms): HTTP ${r.status} ${r.body}  [authorized ${r.authorizedSompi} sompi]`);
    }
    // Seller claims earned funds with the latest voucher (3 requests x 0.5 KAS = 1.5 KAS authorized).
    console.log("\n[seller] claiming earned funds with the latest voucher...");
    const claims = await escrow.claimAll(sellerWallet.address);
    for (const c of claims) {
        console.log(`         claimed ${(0, wallet_1.formatKas)(BigInt(c.amountSompi))} KAS from client ${c.clientPublic.slice(0, 12)}… txid ${c.txid}`);
    }
    server.close();
    await buyerWallet.disconnect();
    await sellerWallet.disconnect();
    process.exit(0);
}
main().catch((e) => {
    console.error("demo-escrow failed:", e);
    process.exit(1);
});
