"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const api_1 = require("@polkadot/api");
const factory_1 = require("../../../../src/factory");
const chai_1 = require("../../../chai");
const config_1 = require("../../../config");
const src_1 = require("../../../../src");
describe("TokensAPI", () => {
    let api;
    let user1Account;
    let user2Account;
    let interBtcAPI;
    before(() => __awaiter(void 0, void 0, void 0, function* () {
        api = yield factory_1.createSubstrateAPI(config_1.PARACHAIN_ENDPOINT);
        const keyring = new api_1.Keyring({ type: "sr25519" });
        user1Account = keyring.addFromUri(config_1.USER_1_URI);
        user2Account = keyring.addFromUri(config_1.USER_2_URI);
        interBtcAPI = new src_1.DefaultInterBtcApi(api, "regtest", user1Account, config_1.ESPLORA_BASE_PATH);
    }));
    after(() => {
        return api.disconnect();
    });
    it("should subscribe to balance updates", () => __awaiter(void 0, void 0, void 0, function* () {
        for (const currency of [...src_1.CollateralCurrency]) {
            yield testBalanceSubscription(currency);
        }
    }));
    function testBalanceSubscription(currency) {
        return __awaiter(this, void 0, void 0, function* () {
            // Subscribe and receive two balance updates
            let updatedBalance = new src_1.ChainBalance(currency);
            let updatedAccount = "";
            function balanceUpdateCallback(account, newBalance) {
                updatedBalance = newBalance;
                updatedAccount = account;
            }
            const amountToUpdateUser2sAccountBy = src_1.newMonetaryAmount(10, currency, true);
            const user2BalanceBeforeTransfer = yield interBtcAPI.tokens.balance(currency, src_1.newAccountId(api, user2Account.address));
            const unsubscribe = yield interBtcAPI.tokens.subscribeToBalance(currency, user2Account.address, balanceUpdateCallback);
            // Send the first transfer, expect the callback to be called with correct values
            yield interBtcAPI.tokens.transfer(user2Account.address, amountToUpdateUser2sAccountBy);
            chai_1.assert.equal(updatedAccount, user2Account.address);
            const expectedUser2BalanceAfterFirstTransfer = new src_1.ChainBalance(currency, user2BalanceBeforeTransfer.free.add(amountToUpdateUser2sAccountBy).toBig(), user2BalanceBeforeTransfer.transferable.add(amountToUpdateUser2sAccountBy).toBig(), user2BalanceBeforeTransfer.reserved.toBig());
            chai_1.assert.equal(updatedBalance.toString(), expectedUser2BalanceAfterFirstTransfer.toString());
            // Send the second transfer, expect the callback to be called with correct values
            yield interBtcAPI.tokens.transfer(user2Account.address, amountToUpdateUser2sAccountBy);
            chai_1.assert.equal(updatedAccount, user2Account.address);
            const expectedUser2BalanceAfterSecondTransfer = new src_1.ChainBalance(currency, expectedUser2BalanceAfterFirstTransfer.free.add(amountToUpdateUser2sAccountBy).toBig(), expectedUser2BalanceAfterFirstTransfer.transferable.add(amountToUpdateUser2sAccountBy).toBig(), expectedUser2BalanceAfterFirstTransfer.reserved.toBig());
            chai_1.assert.equal(updatedBalance.toString(), expectedUser2BalanceAfterSecondTransfer.toString());
            // TODO: Commented out because it blocks release, fix.
            // Fails because it conflicts with the escrowAPI test:
            // Error: tokens.LiquidityRestrictions Failed because liquidity restrictions due to locking
            // if (currency.name === Interlay.name) {
            //     const currentBlockNumber = await interBtcAPI.system.getCurrentBlockNumber();
            //     const unlockHeightDiff = (await escrowAPI.getSpan()).toNumber();
            //     const amountToFreeze = newMonetaryAmount(600, currency as Currency<U>, true);
            //     await escrowAPI.createLock(
            //         amountToFreeze as unknown as MonetaryAmount<Currency<GovernanceUnit>, GovernanceUnit>,
            //         currentBlockNumber + unlockHeightDiff
            //     );
            //     const expectedUser2BalanceAfterEscrowLock = new ChainBalance<U>(
            //         currency,
            //         expectedUser2BalanceAfterSecondTransfer.free.toBig(),
            //         expectedUser2BalanceAfterSecondTransfer.transferable.sub(amountToFreeze).toBig(),
            //         expectedUser2BalanceAfterSecondTransfer.reserved.toBig()
            //     );
            //     assert.equal(updatedAccount, user2Account.address);
            //     assert.equal(updatedBalance.toString(), expectedUser2BalanceAfterEscrowLock.toString());
            // }
            unsubscribe();
        });
    }
});
//# sourceMappingURL=tokens.test.js.map