"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.postSync = void 0;
const bignumber_js_1 = __importDefault(require("bignumber.js"));
/**
 * After each sync or scan, remove operations from the pending pools if necessary
 * Operations stay pending if and only if
 *  - they are confirmed, i.e. their hash appear in the operation list
 *  - they are not outdated, i.e. their sequence number is at least greater than the
 *    sequence number of the latest transaction
 * NOTE Compared to the default behaviour
 *  - pending operations of token accounts are cleaned up, so we don't see both pending and completed
 *    sub operations in the operation details drawer
 *  - pending operations are cleaned if their hash already belong to the completed operations, preventing
 *    undesired replacement (ex: optimistic operation for self token sending on EVM is incomplete, since
 *    it only contains the OUT sub operation)
 */
function postSync(initial, synced) {
    const lastOperation = synced.operations.find(op => ["OUT", "FEES"].includes(op.type));
    const latestSequence = lastOperation?.transactionSequenceNumber || new bignumber_js_1.default(-1);
    function isPending(account, op) {
        return (
        // Operation is not confirmed
        !account.operations.some(o => o.hash === op.hash) &&
            // Operation is not outdated
            op.transactionSequenceNumber !== undefined &&
            op.transactionSequenceNumber.gt(latestSequence));
    }
    const pendingOperations = initial.pendingOperations.length
        ? initial.pendingOperations.filter(op => isPending(synced, op))
        : [];
    const subAccounts = synced.subAccounts?.length
        ? synced.subAccounts.map(subAccount => ({
            ...subAccount,
            pendingOperations: subAccount.pendingOperations.filter(op => isPending(subAccount, op)),
        }))
        : [];
    return { ...synced, pendingOperations, subAccounts };
}
exports.postSync = postSync;
//# sourceMappingURL=postSync.js.map