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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
// This file is part of Gear.

// Copyright (C) 2021-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/>.

use super::*;
use frame_support::traits::tokens::Balance as BalanceTrait;
use sp_runtime::{traits::Zero, RuntimeDebug};
use sp_std::marker::PhantomData;

mod error;
mod internal;
mod lockable;
mod negative_imbalance;
mod node;
mod positive_imbalance;
mod reservable;

#[cfg(test)]
mod property_tests;

pub use error::Error;
pub use internal::TreeImpl;
pub use lockable::{LockId, LockableTree};
pub use negative_imbalance::NegativeImbalance;
pub use node::{ChildrenRefs, GasNode, GasNodeId, NodeLock};
pub use positive_imbalance::PositiveImbalance;
pub use reservable::ReservableTree;

/// Simplified type for result of `GasTree::consume` call.
pub type ConsumeResultOf<T> = Result<
    Option<(
        <T as Tree>::NegativeImbalance,
        GasMultiplier<<T as Tree>::Funds, <T as Tree>::Balance>,
        <T as Tree>::ExternalOrigin,
    )>,
    <T as Tree>::Error,
>;

/// Simplified type for `GasTree::get_origin_node` call.
pub type OriginNodeDataOf<T> = (
    <T as Tree>::ExternalOrigin,
    GasMultiplier<<T as Tree>::Funds, <T as Tree>::Balance>,
    <T as Tree>::NodeId,
);

/// Abstraction for a chain of value items each piece of which has an attributed
/// owner and can be traced up to some root origin.
///
/// The definition is largely inspired by the `frame_support::traits::Currency`,
/// however, the intended use is very close to the UTxO based ledger model.
pub trait Tree {
    /// Type representing the external owner of a value (gas) item.
    type ExternalOrigin;

    /// Type that identifies a node of the tree.
    type NodeId: Clone;

    /// Type representing a quantity of value.
    type Balance: Clone;

    /// Type representing a quantity of token balance.
    type Funds: Clone;

    /// Types to denote a result of some unbalancing operation - that is
    /// operations that create inequality between the underlying value
    /// supply and some hypothetical "collateral" asset.

    /// `PositiveImbalance` indicates that some value has been added
    /// to circulation , i.e. total supply has increased.
    type PositiveImbalance: Imbalance<Balance = Self::Balance>;

    /// `NegativeImbalance` indicates that some value has been removed
    /// from circulation, i.e. total supply has decreased.
    type NegativeImbalance: Imbalance<Balance = Self::Balance>;

    type InternalError: Error;

    /// Error type
    type Error: From<Self::InternalError>;

    /// The total amount of value currently in circulation.
    fn total_supply() -> Self::Balance;

    /// Increase the total issuance of the underlying value by creating some
    /// `amount` of it and attributing it to the `origin`.
    ///
    /// The `key` identifies the created "bag" of value. In case the `key`
    /// already identifies some other piece of value an error is returned.
    fn create(
        origin: Self::ExternalOrigin,
        multiplier: GasMultiplier<Self::Funds, Self::Balance>,
        key: impl Into<Self::NodeId>,
        amount: Self::Balance,
    ) -> Result<Self::PositiveImbalance, Self::Error>;

    /// The id of node, external origin and funds multiplier for a key.
    ///
    /// Error occurs if the tree is invalidated (has "orphan" nodes), and the
    /// node identified by the `key` belongs to a subtree originating at
    /// such "orphan" node, or in case of inexistent key.
    fn get_origin_node(key: impl Into<Self::NodeId>)
        -> Result<OriginNodeDataOf<Self>, Self::Error>;

    /// The external origin for a key.
    ///
    /// See [`get_origin_node`](Self::get_origin_node) for details.
    fn get_external(key: impl Into<Self::NodeId>) -> Result<Self::ExternalOrigin, Self::Error> {
        Self::get_origin_node(key).map(|(external, _multiplier, _key)| external)
    }

    /// The funds multiplier for a key.
    ///
    /// See [`get_origin_node`](Self::get_origin_node) for details.
    fn get_funds_multiplier(
        key: impl Into<Self::NodeId>,
    ) -> Result<GasMultiplier<Self::Funds, Self::Balance>, Self::Error> {
        Self::get_origin_node(key).map(|(_external, multiplier, _key)| multiplier)
    }

    /// The id of external node for a key.
    ///
    /// See [`get_origin_node`](Self::get_origin_node) for details.
    fn get_origin_key(key: impl Into<Self::NodeId>) -> Result<Self::NodeId, Self::Error> {
        Self::get_origin_node(key).map(|(_external, _multiplier, key)| key)
    }

    /// Get value associated with given id and the key of an ancestor,
    /// that keeps this value.
    ///
    /// Error occurs if the tree is invalidated (has "orphan" nodes), and the
    /// node identified by the `key` belongs to a subtree originating at
    /// such "orphan" node, or in case of inexistent key.
    fn get_limit_node(
        key: impl Into<Self::NodeId>,
    ) -> Result<(Self::Balance, Self::NodeId), Self::Error>;

    /// Get value associated with given id and the key of an consumed ancestor,
    /// that keeps this value.
    ///
    /// Error occurs if the tree is invalidated (has "orphan" nodes), and the
    /// node identified by the `key` belongs to a subtree originating at
    /// such "orphan" node, or in case of inexistent key.
    fn get_limit_node_consumed(
        key: impl Into<Self::NodeId>,
    ) -> Result<(Self::Balance, Self::NodeId), Self::Error>;

    /// Get value associated with given id.
    ///
    /// See [`get_limit_node`](Self::get_limit_node) for details.
    fn get_limit(key: impl Into<Self::NodeId>) -> Result<Self::Balance, Self::Error> {
        Self::get_limit_node(key).map(|(balance, _key)| balance)
    }

    /// Get value associated with given id within consumed node.
    ///
    /// See [`get_limit_node_consumed`](Self::get_limit_node_consumed) for details.
    fn get_limit_consumed(key: impl Into<Self::NodeId>) -> Result<Self::Balance, Self::Error> {
        Self::get_limit_node_consumed(key).map(|(balance, _key)| balance)
    }

    /// Consume underlying value.
    ///
    /// If `key` does not identify any value or the value can't be fully
    /// consumed due to being a part of other value or itself having
    /// unconsumed parts, return `None`, else the corresponding
    /// piece of value is destroyed and imbalance is created.
    ///
    /// Error occurs if the tree is invalidated (has "orphan" nodes), and the
    /// node identified by the `key` belongs to a subtree originating at
    /// such "orphan" node, or in case of inexistent key.
    fn consume(key: impl Into<Self::NodeId>) -> ConsumeResultOf<Self>;

    /// Burn underlying value.
    ///
    /// This "spends" the specified amount of value thereby decreasing the
    /// overall supply of it. In case of a success, this indicates the
    /// entire value supply becomes over-collateralized,
    /// hence negative imbalance.
    fn spend(
        key: impl Into<Self::NodeId>,
        amount: Self::Balance,
    ) -> Result<Self::NegativeImbalance, Self::Error>;

    /// Split underlying value.
    ///
    /// If `key` does not identify any value or the `amount` exceeds what's
    /// locked under that key, an error is returned.
    ///
    /// This can't create imbalance as no value is burned or created.
    fn split_with_value(
        key: impl Into<Self::NodeId>,
        new_key: impl Into<Self::NodeId>,
        amount: Self::Balance,
    ) -> Result<(), Self::Error>;

    /// Split underlying value.
    ///
    /// If `key` does not identify any value an error is returned.
    ///
    /// This can't create imbalance as no value is burned or created.
    fn split(
        key: impl Into<Self::NodeId>,
        new_key: impl Into<Self::NodeId>,
    ) -> Result<(), Self::Error>;

    /// Cut underlying value to a reserved node.
    ///
    /// If `key` does not identify any value or the `amount` exceeds what's
    /// locked under that key, an error is returned.
    ///
    /// This can't create imbalance as no value is burned or created.
    fn cut(
        key: impl Into<Self::NodeId>,
        new_key: impl Into<Self::NodeId>,
        amount: Self::Balance,
    ) -> Result<(), Self::Error>;

    /// Creates deposit external node to be used as pre-defined gas node.
    fn create_deposit(
        key: impl Into<Self::NodeId>,
        new_key: impl Into<Self::NodeId>,
        amount: Self::Balance,
    ) -> Result<(), Self::Error>;

    /// Return bool, defining does node exist.
    fn exists(key: impl Into<Self::NodeId>) -> bool;

    /// Returns bool, defining does node exist and is external with deposit.
    fn exists_and_deposit(key: impl Into<Self::NodeId>) -> bool;

    /// Removes all values.
    fn clear();
}

/// Represents logic of centralized GasTree-algorithm.
pub trait Provider {
    /// Type representing the external owner of a value (gas) item.
    type ExternalOrigin;

    /// Type that identifies a tree node.
    type NodeId;

    /// Type representing a quantity of value.
    type Balance;

    /// Type representing a quantity of token balance.
    type Funds;

    /// Types to denote a result of some unbalancing operation - that is
    /// operations that create inequality between the underlying value
    /// supply and some hypothetical "collateral" asset.

    type InternalError: Error;

    /// Error type.
    type Error: From<Self::InternalError>;

    /// A ledger to account for gas creation and consumption.
    type GasTree: LockableTree<
            ExternalOrigin = Self::ExternalOrigin,
            NodeId = Self::NodeId,
            Balance = Self::Balance,
            Funds = Self::Funds,
            InternalError = Self::InternalError,
            Error = Self::Error,
        > + ReservableTree;

    /// Resets all related to gas provider storages.
    ///
    /// It's a temporary production solution to avoid DB migrations
    /// and would be available for test purposes only in the future.
    fn reset() {
        Self::GasTree::clear();
    }
}

/// Represents either added or removed value to/from total supply of the currency.
pub trait Imbalance {
    type Balance;

    /// Returns imbalance raw value.
    fn peek(&self) -> Self::Balance;

    /// Applies imbalance to some amount.
    fn apply_to(&self, amount: &mut Option<Self::Balance>) -> Result<(), ImbalanceError>;
}

/// Represents errors returned by via the [Imbalance] trait.
/// Indicates the imbalance value causes amount value overflowing
/// when applied to the latter.
#[derive(Debug, PartialEq)]
pub struct ImbalanceError;