1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
// This file is part of Gear.

// Copyright (C) 2024 Gear Technologies Inc.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0

// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

//! Implementation of HoldBound and HoldBound builder, specifcying cost of
//! holding data.

use super::ExtManager;
use crate::RESERVE_FOR;
use gear_common::{auxiliary::BlockNumber, scheduler::StorageType, LockId, MessageId};
use std::cmp::Ordering;

/// Hold bound, specifying cost of storage, expected block number for task to
/// create on it, deadlines and durations of holding.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct HoldBound {
    cost: u64,
    expected: BlockNumber,
    lock_id: Option<LockId>,
}

impl HoldBound {
    pub fn cost(&self) -> u64 {
        self.cost
    }

    pub fn expected(&self) -> BlockNumber {
        self.expected
    }

    pub fn lock_id(&self) -> Option<LockId> {
        self.lock_id
    }

    pub fn expected_duration(&self, manager: &ExtManager) -> BlockNumber {
        self.expected.saturating_sub(manager.block_height())
    }

    pub fn deadline(&self) -> BlockNumber {
        self.expected.saturating_add(RESERVE_FOR)
    }

    pub fn deadline_duration(&self, manager: &ExtManager) -> BlockNumber {
        self.deadline().saturating_sub(manager.block_height())
    }

    pub fn lock_amount(&self, manager: &ExtManager) -> u64 {
        let duration: u64 = self.deadline_duration(manager).into();
        duration.saturating_mul(self.cost())
    }
}

impl PartialOrd for HoldBound {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for HoldBound {
    fn cmp(&self, other: &Self) -> Ordering {
        self.expected.cmp(&other.expected)
    }
}

#[derive(Debug, Clone, Copy)]
pub struct HoldBoundBuilder {
    storage_type: StorageType,
    cost: u64,
}

impl HoldBoundBuilder {
    pub fn new(storage_type: StorageType) -> Self {
        Self {
            storage_type,
            cost: ExtManager::cost_by_storage_type(storage_type),
        }
    }

    pub fn at(self, expected: BlockNumber) -> HoldBound {
        HoldBound {
            cost: self.cost,
            expected,
            lock_id: self.storage_type.try_into().ok(),
        }
    }

    pub fn deadline(self, deadline: BlockNumber) -> HoldBound {
        let expected = deadline.saturating_sub(RESERVE_FOR);

        self.at(expected)
    }

    pub fn duration(self, manager: &ExtManager, duration: BlockNumber) -> HoldBound {
        let expected = manager.block_height().saturating_add(duration);

        self.at(expected)
    }

    pub fn maximum_for(self, manager: &ExtManager, gas: u64) -> HoldBound {
        let deadline_duration = gas
            .saturating_div(self.cost.max(1))
            // `saturated_into` conversion: try_into + unwrap_or(MAX)
            .try_into()
            .unwrap_or(u32::MAX);
        let deadline = manager.block_height().saturating_add(deadline_duration);

        self.deadline(deadline)
    }

    pub fn maximum_for_message(self, manager: &ExtManager, message_id: MessageId) -> HoldBound {
        let gas_limit = manager.gas_tree.get_limit(message_id).unwrap_or_else(|e| {
            let err_msg = format!(
                "HoldBoundBuilder::maximum_for_message: failed getting message gas limit. \
                Message id - {message_id}. Got error - {e:?}"
            );

            unreachable!("{err_msg}");
        });

        self.maximum_for(manager, gas_limit)
    }
}