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 = $price_per_minute;
    IF $amount_due < $contract.locked_nano {
        $amount_due = $contract.locked_nano;
    };
    LET $escrow_multiplier = 1;
    IF $operator.escrow > 5000 {
        $escrow_multiplier = 5;
    };
    IF $node_is_online {
        UPDATE $contract.id SET locked_nano -= $amount_due;
        UPDATE $operator.id SET locked_nano += $amount_due * $escrow_multiplier;
    } ELSE {
        LET $compensation = $amount_due * 5;
        IF $compensation > $operator.escrow {
            $compensation = $operator.escrow ;
        };
        UPDATE $operator.id SET escrow -= $compensation;
        UPDATE $contract.in SET balance += $compensation;
    };
    IF $amount_due == $contract.locked_nano {
        fn::delete_vm($contract.id);
    };
};

