"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 (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getMessages = exports.encodeMessageHeader = exports.decodeTokenMessengerMessageBody = exports.decodeMessageHeader = exports.decodeMessageSentData = void 0;
const anchor = __importStar(require("@coral-xyz/anchor"));
const superstruct_1 = require("superstruct");
const relayHashUtils_1 = require("./relayHashUtils");
// Index positions to decode Message Header from
// https://developers.circle.com/cctp/v1/message-format#cctp-v1-message-header
const HEADER_VERSION_INDEX = 0;
const SOURCE_DOMAIN_INDEX = 4;
const DESTINATION_DOMAIN_INDEX = 8;
const NONCE_INDEX = 12;
const HEADER_SENDER_INDEX = 20;
const HEADER_RECIPIENT_INDEX = 52;
const DESTINATION_CALLER_INDEX = 84;
const MESSAGE_BODY_INDEX = 116;
// Index positions to decode Message Body for TokenMessenger from
// https://developers.circle.com/cctp/v1/message-format#cctp-v1-message-body
const BODY_VERSION_INDEX = 0;
const BURN_TOKEN_INDEX = 4;
const MINT_RECIPIENT_INDEX = 36;
const AMOUNT_INDEX = 68;
const MESSAGE_SENDER_INDEX = 100;
/**
 * Decodes a CCTP message into a MessageHeader and TokenMessengerMessageBody.
 */
const decodeMessageSentData = (message) => {
    const messageHeader = (0, exports.decodeMessageHeader)(message);
    const messageBodyData = message.slice(MESSAGE_BODY_INDEX);
    const messageBody = (0, exports.decodeTokenMessengerMessageBody)(messageBodyData);
    return { ...messageHeader, messageBody };
};
exports.decodeMessageSentData = decodeMessageSentData;
/**
 * Decodes a CCTP message header.
 */
const decodeMessageHeader = (data) => {
    const version = data.readUInt32BE(HEADER_VERSION_INDEX);
    const sourceDomain = data.readUInt32BE(SOURCE_DOMAIN_INDEX);
    const destinationDomain = data.readUInt32BE(DESTINATION_DOMAIN_INDEX);
    const nonce = data.readBigUInt64BE(NONCE_INDEX);
    const sender = new anchor.web3.PublicKey(data.slice(HEADER_SENDER_INDEX, HEADER_SENDER_INDEX + 32));
    const recipient = new anchor.web3.PublicKey(data.slice(HEADER_RECIPIENT_INDEX, HEADER_RECIPIENT_INDEX + 32));
    const destinationCaller = new anchor.web3.PublicKey(data.slice(DESTINATION_CALLER_INDEX, DESTINATION_CALLER_INDEX + 32));
    const messageBody = data.slice(MESSAGE_BODY_INDEX);
    return {
        version,
        sourceDomain,
        destinationDomain,
        nonce,
        sender,
        recipient,
        destinationCaller,
        messageBody,
    };
};
exports.decodeMessageHeader = decodeMessageHeader;
/**
 * Decodes a TokenMessenger message body.
 */
const decodeTokenMessengerMessageBody = (data) => {
    const version = data.readUInt32BE(BODY_VERSION_INDEX);
    const burnToken = new anchor.web3.PublicKey(data.slice(BURN_TOKEN_INDEX, BURN_TOKEN_INDEX + 32));
    const mintRecipient = new anchor.web3.PublicKey(data.slice(MINT_RECIPIENT_INDEX, MINT_RECIPIENT_INDEX + 32));
    const amount = (0, relayHashUtils_1.readUInt256BE)(data.slice(AMOUNT_INDEX, AMOUNT_INDEX + 32));
    const messageSender = new anchor.web3.PublicKey(data.slice(MESSAGE_SENDER_INDEX, MESSAGE_SENDER_INDEX + 32));
    return { version, burnToken, mintRecipient, amount, messageSender };
};
exports.decodeTokenMessengerMessageBody = decodeTokenMessengerMessageBody;
/**
 * Encodes a MessageHeader into a Buffer.
 */
const encodeMessageHeader = (header) => {
    const message = Buffer.alloc(MESSAGE_BODY_INDEX + header.messageBody.length);
    message.writeUInt32BE(header.version, HEADER_VERSION_INDEX);
    message.writeUInt32BE(header.sourceDomain, SOURCE_DOMAIN_INDEX);
    message.writeUInt32BE(header.destinationDomain, DESTINATION_DOMAIN_INDEX);
    message.writeBigUInt64BE(header.nonce, NONCE_INDEX);
    header.sender.toBuffer().copy(message, HEADER_SENDER_INDEX);
    header.recipient.toBuffer().copy(message, HEADER_RECIPIENT_INDEX);
    header.destinationCaller.toBuffer().copy(message, DESTINATION_CALLER_INDEX);
    header.messageBody.copy(message, MESSAGE_BODY_INDEX);
    return message;
};
exports.encodeMessageHeader = encodeMessageHeader;
/**
 * Structure for the attestation response from the attestation service.
 */
const AttestationResponseStruct = (0, superstruct_1.object)({
    error: (0, superstruct_1.optional)((0, superstruct_1.string)()),
    messages: (0, superstruct_1.array)((0, superstruct_1.object)({
        attestation: (0, superstruct_1.string)(),
        message: (0, superstruct_1.string)(),
        eventNonce: (0, superstruct_1.string)(),
    })),
});
/**
 * Fetches attestation from attestation service given the txHash.
 */
const getMessages = async (txHash, srcDomain, irisApiUrl) => {
    console.log("Fetching attestations and messages for tx...", txHash);
    let attestationResponse = {};
    while (attestationResponse.error ||
        !attestationResponse.messages ||
        attestationResponse.messages?.[0]?.attestation === "PENDING") {
        const response = await fetch(`${irisApiUrl}/messages/${srcDomain}/${txHash}`);
        attestationResponse = await response.json();
        // Wait 2 seconds to avoid getting rate limited
        if (attestationResponse.error ||
            !attestationResponse.messages ||
            attestationResponse.messages?.[0]?.attestation === "PENDING") {
            await new Promise((r) => setTimeout(r, 2000));
        }
    }
    // Validate the response structure
    try {
        AttestationResponseStruct.assert(attestationResponse);
    }
    catch (error) {
        console.error("Invalid attestation response structure:", error);
        throw new Error("Invalid attestation response structure");
    }
    return attestationResponse;
};
exports.getMessages = getMessages;
