"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.handleHederaTrustedFlow = void 0;
const errors_1 = require("@ledgerhq/errors");
const hw_bolos_1 = require("@ledgerhq/hw-bolos");
const ledger_cal_service_1 = __importDefault(require("@ledgerhq/ledger-cal-service"));
const ledger_trust_service_1 = __importDefault(require("@ledgerhq/ledger-trust-service"));
const live_env_1 = require("@ledgerhq/live-env");
function isPKIUnsupportedError(err) {
    return err instanceof errors_1.TransportStatusError && err.message.includes("0x6a81");
}
async function handleHederaTrustedFlow({ exchange, hederaAccount, deviceModelId, }) {
    const serviceEnv = (0, live_env_1.getEnv)("MOCK_EXCHANGE_TEST_CONFIG") ? "test" : "prod";
    const cert = await ledger_cal_service_1.default.getCertificate(deviceModelId, "trusted_name", "latest", {
        env: serviceEnv,
        signatureKind: serviceEnv,
    });
    try {
        await (0, hw_bolos_1.loadPKI)(exchange.transport, "TRUSTED_NAME", cert.descriptor, cert.signature);
    }
    catch (err) {
        if (isPKIUnsupportedError(err)) {
            throw new errors_1.LatestFirmwareVersionRequired("LatestFirmwareVersionRequired");
        }
    }
    const challenge = await exchange.getChallenge();
    const hexChallenge = challenge.toString(16);
    const trustServiceResult = await ledger_trust_service_1.default.hedera.getPublicKey(hederaAccount.freshAddress, hexChallenge);
    const signedDescriptorBuffer = Buffer.from(trustServiceResult.signedDescriptor, "hex");
    await exchange.sendTrustedDescriptor(signedDescriptorBuffer);
}
exports.handleHederaTrustedFlow = handleHederaTrustedFlow;
//# sourceMappingURL=exchange.js.map