FOR $contract IN (select * from active_vm fetch out) {
    LET $operator = (select * from $contract.out.operator);
    LET $node_is_online = $contract.out.connected_at > $contract.out.disconnected_at;
    LET $price_per_minute = fn::vm_price_per_minute($contract.id);
    LET $amount_due = IF $price_per_minute > $contract.locked_nano {
        $contract.locked_nano
    } ELSE {
        $price_per_minute
    };
    LET $escrow_multiplier = IF $operator.escrow >= 5_000_000_000_000 { 5 } ELSE { 1 };
    IF $node_is_online {
        UPDATE $contract.id SET locked_nano -= $amount_due;
        UPDATE $operator.id SET balance += $amount_due * $escrow_multiplier;
    } ELSE {
        LET $compensation = IF $amount_due * 5 > $operator.escrow {
            $operator.escrow
        } ELSE {
            $amount_due * 5
        };
        UPDATE $operator.id SET escrow -= $compensation;
        UPDATE $contract.in SET balance += $compensation;
    };
    IF $amount_due >= $contract.locked_nano {
        fn::delete_vm($contract.id);
    };
};
