"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 });
const anchor = __importStar(require("@coral-xyz/anchor"));
const anchor_1 = require("@coral-xyz/anchor");
const web3_js_1 = require("@solana/web3.js");
const chai_1 = require("chai");
const SvmSpoke_common_1 = require("./SvmSpoke.common");
const utils_1 = require("./utils");
const { provider, program, owner, initializeState, crossDomainAdmin, assertSE } = SvmSpoke_common_1.common;
describe("svm_spoke.ownership", () => {
    anchor.setProvider(provider);
    const nonOwner = web3_js_1.Keypair.generate();
    const newOwner = web3_js_1.Keypair.generate();
    const newCrossDomainAdmin = web3_js_1.Keypair.generate();
    let state;
    beforeEach(async () => {
        state = await initializeState();
    });
    it("Initializes state with provided initial state", async () => {
        const initialState = {
            initialNumberOfDeposits: new anchor_1.BN(5),
            chainId: new anchor_1.BN(420), // Set the chainId
            remoteDomain: new anchor_1.BN(11), // Set the remoteDomain
            crossDomainAdmin, // Use the existing crossDomainAdmin
            depositQuoteTimeBuffer: new anchor_1.BN(3600), // Set the depositQuoteTimeBuffer
            fillDeadlineBuffer: new anchor_1.BN(14400), // Set the fillDeadlineBuffer (4 hours)
        };
        // Initialize state with the provided initial state
        state = await initializeState(undefined, initialState);
        // Fetch the updated state
        const stateData = await program.account.state.fetch(state);
        // Assert other properties as needed
        Object.keys(initialState).forEach((key) => {
            const adjustedKey = key === "initialNumberOfDeposits" ? "numberOfDeposits" : key; // stored with diff key in state.
            assertSE(stateData[adjustedKey], initialState[key], `${key} should match`);
        });
    });
    it("Pauses and unpauses deposits", async () => {
        chai_1.assert.isFalse((await program.account.state.fetch(state)).pausedDeposits, "Deposits should not be paused");
        // Pause deposits as owner
        const pauseDepositsAccounts = { state, signer: owner, program: program.programId };
        await program.methods.pauseDeposits(true).accounts(pauseDepositsAccounts).rpc();
        await new Promise((resolve) => setTimeout(resolve, 500));
        // Fetch the updated state
        let stateAccountData = await program.account.state.fetch(state);
        chai_1.assert.isTrue(stateAccountData.pausedDeposits, "Deposits should be paused");
        // Verify the PausedDeposits event
        let events = await (0, utils_1.readProgramEvents)(provider.connection, program);
        let pausedDepositEvents = events.filter((event) => event.name === "pausedDeposits");
        chai_1.assert.isTrue(pausedDepositEvents[0].data.isPaused, "PausedDeposits event should indicate deposits are paused");
        // Unpause deposits as owner
        await program.methods.pauseDeposits(false).accounts(pauseDepositsAccounts).rpc();
        await new Promise((resolve) => setTimeout(resolve, 500));
        // Fetch the updated state
        stateAccountData = await program.account.state.fetch(state);
        chai_1.assert.isFalse(stateAccountData.pausedDeposits, "Deposits should not be paused");
        // Verify the PausedDeposits event
        events = await (0, utils_1.readProgramEvents)(provider.connection, program);
        pausedDepositEvents = events.filter((event) => event.name === "pausedDeposits");
        chai_1.assert.isFalse(pausedDepositEvents[0].data.isPaused, "PausedDeposits event should indicate deposits are unpaused");
        // Try to pause deposits as non-owner
        try {
            const pauseDepositsAccounts = { state, signer: nonOwner.publicKey, program: program.programId };
            await program.methods.pauseDeposits(true).accounts(pauseDepositsAccounts).signers([nonOwner]).rpc();
            chai_1.assert.fail("Non-owner should not be able to pause deposits");
        }
        catch (err) {
            chai_1.assert.include(err.toString(), "Only the owner can call this function!", "Expected owner check error");
        }
    });
    it("Pauses and unpauses fills", async () => {
        chai_1.assert.isFalse((await program.account.state.fetch(state)).pausedFills, "Fills should not be paused");
        // Pause fills as owner
        const pauseFillsAccounts = { state, signer: owner, program: program.programId };
        await program.methods.pauseFills(true).accounts(pauseFillsAccounts).rpc();
        await new Promise((resolve) => setTimeout(resolve, 500));
        // Fetch the updated state
        let stateAccountData = await program.account.state.fetch(state);
        chai_1.assert.isTrue(stateAccountData.pausedFills, "Fills should be paused");
        // Verify the PausedFills event
        let events = await (0, utils_1.readProgramEvents)(provider.connection, program);
        let pausedFillEvents = events.filter((event) => event.name === "pausedFills");
        chai_1.assert.isTrue(pausedFillEvents[0].data.isPaused, "PausedFills event should indicate fills are paused");
        // Unpause fills as owner
        await program.methods.pauseFills(false).accounts(pauseFillsAccounts).rpc();
        await new Promise((resolve) => setTimeout(resolve, 500));
        // Fetch the updated state
        stateAccountData = await program.account.state.fetch(state);
        chai_1.assert.isFalse(stateAccountData.pausedFills, "Fills should not be paused");
        // Verify the PausedFills event
        events = await (0, utils_1.readProgramEvents)(provider.connection, program);
        pausedFillEvents = events.filter((event) => event.name === "pausedFills");
        chai_1.assert.isFalse(pausedFillEvents[0].data.isPaused, "PausedFills event should indicate fills are unpaused");
        // Try to pause fills as non-owner
        try {
            const pauseFillsAccounts = { state, signer: nonOwner.publicKey, program: program.programId };
            await program.methods.pauseFills(true).accounts(pauseFillsAccounts).signers([nonOwner]).rpc();
            chai_1.assert.fail("Non-owner should not be able to pause fills");
        }
        catch (err) {
            chai_1.assert.include(err.toString(), "Only the owner can call this function!", "Expected owner check error");
        }
    });
    it("Transfers ownership", async () => {
        // Transfer ownership to newOwner
        const transferOwnershipAccounts = { state, signer: owner };
        await program.methods.transferOwnership(newOwner.publicKey).accounts(transferOwnershipAccounts).rpc();
        await new Promise((resolve) => setTimeout(resolve, 500));
        // Verify the new owner
        let stateAccountData = await program.account.state.fetch(state);
        chai_1.assert.equal(stateAccountData.owner.toString(), newOwner.publicKey.toString(), "Ownership should be transferred");
        // Try to transfer ownership as non-owner
        try {
            const transferOwnershipAccounts = { state, signer: nonOwner.publicKey };
            await program.methods
                .transferOwnership(nonOwner.publicKey)
                .accounts(transferOwnershipAccounts)
                .signers([nonOwner])
                .rpc();
            chai_1.assert.fail("Non-owner should not be able to transfer ownership");
        }
        catch (err) {
            chai_1.assert.include(err.toString(), "Only the owner can call this function!", "Expected owner check error");
        }
    });
    it("Sets cross-domain admin", async () => {
        // Set cross-domain admin as owner
        const setCrossDomainAdminAccounts = { state, signer: owner, program: program.programId };
        await program.methods
            .setCrossDomainAdmin(newCrossDomainAdmin.publicKey)
            .accounts(setCrossDomainAdminAccounts)
            .rpc();
        await new Promise((resolve) => setTimeout(resolve, 500));
        // Verify the new cross-domain admin
        let stateAccountData = await program.account.state.fetch(state);
        chai_1.assert.equal(stateAccountData.crossDomainAdmin.toString(), newCrossDomainAdmin.publicKey.toString(), "Cross-domain admin should be set");
        // Verify the SetXDomainAdmin event
        let events = await (0, utils_1.readProgramEvents)(provider.connection, program);
        let setXDomainAdminEvents = events.filter((event) => event.name === "setXDomainAdmin");
        chai_1.assert.equal(setXDomainAdminEvents[0].data.newAdmin.toString(), newCrossDomainAdmin.publicKey.toString(), "SetXDomainAdmin event should indicate the new admin");
        // Try to set cross-domain admin as non-owner
        try {
            const setCrossDomainAdminAccounts = { state, signer: nonOwner.publicKey, program: program.programId };
            await program.methods
                .setCrossDomainAdmin(nonOwner.publicKey)
                .accounts(setCrossDomainAdminAccounts)
                .signers([nonOwner])
                .rpc();
            chai_1.assert.fail("Non-owner should not be able to set cross-domain admin");
        }
        catch (err) {
            chai_1.assert.include(err.toString(), "Only the owner can call this function!", "Expected owner check error");
        }
    });
});
