"use strict";
// SPDX-License-Identifier: Apache-2.0
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;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
require("../environmentMock");
const RPCTransactionAdapter_1 = require("../../../src/port/out/rpc/RPCTransactionAdapter");
const in_1 = require("../../../src/port/in");
const Injectable_1 = __importDefault(require("../../../src/core/injectable/Injectable"));
const MirrorNodeAdapter_1 = require("../../../src/port/out/mirror/MirrorNodeAdapter");
const ConnectRequest_1 = __importStar(require("../../../src/port/in/request/network/ConnectRequest"));
const ethers_1 = require("ethers");
const config_1 = require("../../config");
const SecurityRole_1 = require("../../../src/domain/context/security/SecurityRole");
const NetworkService_1 = __importDefault(require("../../../src/app/service/network/NetworkService"));
const RPCQueryAdapter_1 = require("../../../src/port/out/rpc/RPCQueryAdapter");
const RegulationType_1 = require("../../../src/domain/context/factory/RegulationType");
in_1.SDK.log = { level: "ERROR", transports: new in_1.LoggerTransports.Console() };
const decimals = 6;
const name = "TEST_SECURITY_TOKEN";
const symbol = "TEST";
const isin = "ABCDE123456Z";
const votingRight = true;
const informationRight = false;
const liquidationRight = true;
const subscriptionRight = false;
const conversionRight = true;
const redemptionRight = false;
const putRight = true;
const dividendRight = 1;
const currency = "0x345678";
const numberOfShares = 0;
const nominalValue = 1000;
const nominalValueDecimals = 3;
const regulationType = RegulationType_1.RegulationType.REG_D;
const regulationSubType = RegulationType_1.RegulationSubType.C_506;
const countries = "AF,HG,BN";
const info = "Anything";
const configId = "0x0000000000000000000000000000000000000000000000000000000000000000";
const configVersion = 1;
const mirrorNode = {
    name: "testmirrorNode",
    baseUrl: "https://testnet.mirrornode.hedera.com/api/v1/",
};
const rpcNode = {
    name: "testrpcNode",
    baseUrl: "http://127.0.0.1:7546/api",
};
describe("🧪 Role test", () => {
    let th;
    let ns;
    let mirrorNodeAdapter;
    let rpcQueryAdapter;
    let equity;
    const delay = async (seconds = 5) => {
        seconds = seconds * 1000;
        await new Promise((r) => setTimeout(r, seconds));
    };
    beforeAll(async () => {
        mirrorNodeAdapter = Injectable_1.default.resolve(MirrorNodeAdapter_1.MirrorNodeAdapter);
        mirrorNodeAdapter.set(mirrorNode);
        th = Injectable_1.default.resolve(RPCTransactionAdapter_1.RPCTransactionAdapter);
        ns = Injectable_1.default.resolve(NetworkService_1.default);
        rpcQueryAdapter = Injectable_1.default.resolve(RPCQueryAdapter_1.RPCQueryAdapter);
        rpcQueryAdapter.init();
        ns.environment = "testnet";
        ns.configuration = {
            factoryAddress: config_1.FACTORY_ADDRESS,
            resolverAddress: config_1.RESOLVER_ADDRESS,
        };
        ns.mirrorNode = mirrorNode;
        ns.rpcNode = rpcNode;
        await th.init(true);
        await th.register(undefined, true);
        const url = "http://127.0.0.1:7546";
        const customHttpProvider = new ethers_1.ethers.JsonRpcProvider(url);
        th.setSignerOrProvider(new ethers_1.Wallet(config_1.CLIENT_ACCOUNT_ECDSA.privateKey?.key ?? "", customHttpProvider));
        await in_1.Network.connect(new ConnectRequest_1.default({
            account: {
                accountId: config_1.CLIENT_ACCOUNT_ECDSA.id.toString(),
                privateKey: config_1.CLIENT_ACCOUNT_ECDSA.privateKey,
            },
            network: "testnet",
            wallet: ConnectRequest_1.SupportedWallets.METAMASK,
            mirrorNode: mirrorNode,
            rpcNode: rpcNode,
            debug: true,
        }));
        const requestST = new in_1.CreateEquityRequest({
            name: name,
            symbol: symbol,
            isin: isin,
            decimals: decimals,
            isWhiteList: false,
            erc20VotesActivated: false,
            isControllable: true,
            arePartitionsProtected: false,
            clearingActive: false,
            internalKycActivated: true,
            isMultiPartition: false,
            diamondOwnerAccount: config_1.CLIENT_ACCOUNT_ECDSA.id.toString(),
            votingRight: votingRight,
            informationRight: informationRight,
            liquidationRight: liquidationRight,
            subscriptionRight: subscriptionRight,
            conversionRight: conversionRight,
            redemptionRight: redemptionRight,
            putRight: putRight,
            dividendRight: dividendRight,
            currency: currency,
            numberOfShares: numberOfShares.toString(),
            nominalValue: nominalValue.toString(),
            nominalValueDecimals: nominalValueDecimals,
            regulationType: RegulationType_1.CastRegulationType.toNumber(regulationType),
            regulationSubType: RegulationType_1.CastRegulationSubType.toNumber(regulationSubType),
            isCountryControlListWhiteList: true,
            countries: countries,
            info: info,
            configId: configId,
            configVersion: configVersion,
        });
        equity = (await in_1.Equity.create(requestST)).security;
        await delay();
    }, 600_000);
    it("Grant and Revoke CONTROLLIST_ROLE role", async () => {
        expect((await in_1.Role.grantRole(new in_1.RoleRequest({
            securityId: equity.evmDiamondAddress,
            targetId: config_1.CLIENT_ACCOUNT_ECDSA_A.evmAddress.toString(),
            role: SecurityRole_1.SecurityRole._CONTROLLIST_ROLE,
        }))).payload).toBe(true);
        expect(await in_1.Role.hasRole(new in_1.RoleRequest({
            securityId: equity.evmDiamondAddress,
            targetId: config_1.CLIENT_ACCOUNT_ECDSA_A.evmAddress.toString(),
            role: SecurityRole_1.SecurityRole._CONTROLLIST_ROLE,
        }))).toBe(true);
        let roleCount = await in_1.Role.getRoleCountFor(new in_1.GetRoleCountForRequest({
            securityId: equity.evmDiamondAddress,
            targetId: config_1.CLIENT_ACCOUNT_ECDSA_A.evmAddress.toString(),
        }));
        let memberCount = await in_1.Role.getRoleMemberCount(new in_1.GetRoleMemberCountRequest({
            securityId: equity.evmDiamondAddress,
            role: SecurityRole_1.SecurityRole._CONTROLLIST_ROLE,
        }));
        expect(roleCount).toEqual(1);
        expect(memberCount).toEqual(1);
        let rolesFor = await in_1.Role.getRolesFor(new in_1.GetRolesForRequest({
            securityId: equity.evmDiamondAddress,
            targetId: config_1.CLIENT_ACCOUNT_ECDSA_A.evmAddress.toString(),
            start: 0,
            end: roleCount,
        }));
        let membersFor = await in_1.Role.getRoleMembers(new in_1.GetRoleMembersRequest({
            securityId: equity.evmDiamondAddress,
            role: SecurityRole_1.SecurityRole._CONTROLLIST_ROLE,
            start: 0,
            end: memberCount,
        }));
        expect(rolesFor.length).toEqual(1);
        expect(membersFor.length).toEqual(1);
        expect(rolesFor[0].toUpperCase()).toEqual(SecurityRole_1.SecurityRole._CONTROLLIST_ROLE.toUpperCase());
        expect(membersFor[0].toUpperCase()).toEqual(config_1.CLIENT_ACCOUNT_ECDSA_A.id.toString().toUpperCase());
        await in_1.Role.revokeRole(new in_1.RoleRequest({
            securityId: equity.evmDiamondAddress,
            targetId: config_1.CLIENT_ACCOUNT_ECDSA_A.evmAddress.toString(),
            role: SecurityRole_1.SecurityRole._CONTROLLIST_ROLE,
        }));
        roleCount = await in_1.Role.getRoleCountFor(new in_1.GetRoleCountForRequest({
            securityId: equity.evmDiamondAddress,
            targetId: config_1.CLIENT_ACCOUNT_ECDSA_A.evmAddress.toString(),
        }));
        memberCount = await in_1.Role.getRoleMemberCount(new in_1.GetRoleMemberCountRequest({
            securityId: equity.evmDiamondAddress,
            role: SecurityRole_1.SecurityRole._CONTROLLIST_ROLE,
        }));
        expect(roleCount).toEqual(0);
        expect(memberCount).toEqual(0);
        rolesFor = await in_1.Role.getRolesFor(new in_1.GetRolesForRequest({
            securityId: equity.evmDiamondAddress,
            targetId: config_1.CLIENT_ACCOUNT_ECDSA_A.evmAddress.toString(),
            start: 0,
            end: roleCount,
        }));
        membersFor = await in_1.Role.getRoleMembers(new in_1.GetRoleMembersRequest({
            securityId: equity.evmDiamondAddress,
            role: SecurityRole_1.SecurityRole._CONTROLLIST_ROLE,
            start: 0,
            end: memberCount,
        }));
        expect(rolesFor.length).toEqual(0);
        expect(membersFor.length).toEqual(0);
    }, 60000);
    it("grant all roles then revoke all roles using apply", async () => {
        expect((await in_1.Role.applyRoles(new in_1.ApplyRolesRequest({
            securityId: equity.evmDiamondAddress,
            targetId: config_1.CLIENT_ACCOUNT_ECDSA.evmAddress.toString(),
            roles: [
                SecurityRole_1.SecurityRole._CONTROLLIST_ROLE,
                SecurityRole_1.SecurityRole._ISSUER_ROLE,
                SecurityRole_1.SecurityRole._PAUSER_ROLE,
                SecurityRole_1.SecurityRole._CORPORATEACTIONS_ROLE,
            ],
            actives: [true, true, true, true],
        }))).payload).toBe(true);
        expect(await in_1.Role.hasRole(new in_1.RoleRequest({
            securityId: equity.evmDiamondAddress,
            targetId: config_1.CLIENT_ACCOUNT_ECDSA.evmAddress.toString(),
            role: SecurityRole_1.SecurityRole._CONTROLLIST_ROLE,
        }))).toBe(true);
        expect(await in_1.Role.hasRole(new in_1.RoleRequest({
            securityId: equity.evmDiamondAddress,
            targetId: config_1.CLIENT_ACCOUNT_ECDSA.evmAddress.toString(),
            role: SecurityRole_1.SecurityRole._ISSUER_ROLE,
        }))).toBe(true);
        expect(await in_1.Role.hasRole(new in_1.RoleRequest({
            securityId: equity.evmDiamondAddress,
            targetId: config_1.CLIENT_ACCOUNT_ECDSA.evmAddress.toString(),
            role: SecurityRole_1.SecurityRole._PAUSER_ROLE,
        }))).toBe(true);
        expect(await in_1.Role.hasRole(new in_1.RoleRequest({
            securityId: equity.evmDiamondAddress,
            targetId: config_1.CLIENT_ACCOUNT_ECDSA.evmAddress.toString(),
            role: SecurityRole_1.SecurityRole._CORPORATEACTIONS_ROLE,
        }))).toBe(true);
        expect((await in_1.Role.applyRoles(new in_1.ApplyRolesRequest({
            securityId: equity.evmDiamondAddress,
            targetId: config_1.CLIENT_ACCOUNT_ECDSA.evmAddress.toString(),
            roles: [
                SecurityRole_1.SecurityRole._CONTROLLIST_ROLE,
                SecurityRole_1.SecurityRole._ISSUER_ROLE,
                SecurityRole_1.SecurityRole._PAUSER_ROLE,
                SecurityRole_1.SecurityRole._CORPORATEACTIONS_ROLE,
            ],
            actives: [false, false, false, false],
        }))).payload).toBe(true);
        expect(await in_1.Role.hasRole(new in_1.RoleRequest({
            securityId: equity.evmDiamondAddress,
            targetId: config_1.CLIENT_ACCOUNT_ECDSA.evmAddress.toString(),
            role: SecurityRole_1.SecurityRole._CONTROLLIST_ROLE,
        }))).toBe(false);
        expect(await in_1.Role.hasRole(new in_1.RoleRequest({
            securityId: equity.evmDiamondAddress,
            targetId: config_1.CLIENT_ACCOUNT_ECDSA.evmAddress.toString(),
            role: SecurityRole_1.SecurityRole._ISSUER_ROLE,
        }))).toBe(false);
        expect(await in_1.Role.hasRole(new in_1.RoleRequest({
            securityId: equity.evmDiamondAddress,
            targetId: config_1.CLIENT_ACCOUNT_ECDSA.evmAddress.toString(),
            role: SecurityRole_1.SecurityRole._PAUSER_ROLE,
        }))).toBe(false);
        expect(await in_1.Role.hasRole(new in_1.RoleRequest({
            securityId: equity.evmDiamondAddress,
            targetId: config_1.CLIENT_ACCOUNT_ECDSA.evmAddress.toString(),
            role: SecurityRole_1.SecurityRole._CORPORATEACTIONS_ROLE,
        }))).toBe(false);
    }, 60000);
});
