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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
use crate::errors::{ApplicationError, RuntimeError};
use crate::internal_prelude::*;
use radix_blueprint_schema_init::{
    BlueprintCollectionSchema, BlueprintEventSchemaInit, BlueprintFunctionsSchemaInit, FieldSchema,
    FunctionSchemaInit, TypeRef,
};
use radix_blueprint_schema_init::{BlueprintSchemaInit, BlueprintStateSchemaInit};
use radix_common::constants::AuthAddresses;
use radix_engine_interface::api::{AttachedModuleId, ClientApi, FieldValue};
use radix_engine_interface::blueprints::package::{
    AuthConfig, BlueprintDefinitionInit, BlueprintType, FunctionAuth, MethodAuthTemplate,
    PackageDefinition,
};
use radix_native_sdk::modules::metadata::Metadata;
use radix_native_sdk::modules::role_assignment::RoleAssignment;
use radix_native_sdk::runtime::Runtime;

pub const TRANSACTION_TRACKER_BLUEPRINT: &str = "TransactionTracker";

pub const TRANSACTION_TRACKER_CREATE_IDENT: &str = "create";

pub const TRANSACTION_TRACKER_CREATE_EXPORT_NAME: &str = "create";

#[derive(Debug, Clone, ScryptoSbor)]
pub struct TransactionTrackerCreateInput {
    pub address_reservation: GlobalAddressReservation,
}

#[derive(Debug, Clone, ManifestSbor)]
pub struct TransactionTrackerCreateManifestInput {
    pub address_reservation: ManifestAddressReservation,
}

pub type TransactionTrackerCreateOutput = ComponentAddress;

pub struct TransactionTrackerNativePackage;

pub const PARTITION_RANGE_START: u8 = MAIN_BASE_PARTITION.0 + 1;
pub const PARTITION_RANGE_END: u8 = u8::MAX;
pub const EPOCHS_PER_PARTITION: u64 = 100;

impl TransactionTrackerNativePackage {
    pub fn definition() -> PackageDefinition {
        let mut aggregator = TypeAggregator::<ScryptoCustomTypeKind>::new();
        let key_type_id = aggregator.add_child_type_and_descendents::<Hash>();
        let value_type_id = aggregator.add_child_type_and_descendents::<TransactionStatus>();

        let mut collections: Vec<BlueprintCollectionSchema<TypeRef<LocalTypeId>>> = vec![];
        for _ in PARTITION_RANGE_START..=PARTITION_RANGE_END {
            collections.push(BlueprintCollectionSchema::KeyValueStore(
                BlueprintKeyValueSchema {
                    key: TypeRef::Static(key_type_id),
                    value: TypeRef::Static(value_type_id),
                    allow_ownership: false,
                },
            ))
        }

        let mut fields = Vec::new();
        fields.push(FieldSchema::static_field(
            aggregator.add_child_type_and_descendents::<TransactionTrackerSubstate>(),
        ));

        let mut functions = index_map_new();
        functions.insert(
            TRANSACTION_TRACKER_CREATE_IDENT.to_string(),
            FunctionSchemaInit {
                receiver: None,
                input: TypeRef::Static(
                    aggregator.add_child_type_and_descendents::<TransactionTrackerCreateInput>(),
                ),
                output: TypeRef::Static(
                    aggregator.add_child_type_and_descendents::<TransactionTrackerCreateOutput>(),
                ),
                export: TRANSACTION_TRACKER_CREATE_EXPORT_NAME.to_string(),
            },
        );

        let schema = generate_full_schema(aggregator);
        let blueprints = indexmap!(
            TRANSACTION_TRACKER_BLUEPRINT.to_string() => BlueprintDefinitionInit {
                blueprint_type: BlueprintType::default(),
                is_transient: false,
                dependencies: indexset!(
                ),
                feature_set: indexset!(),
                schema: BlueprintSchemaInit {
                    generics: vec![],
                    schema,
                    state: BlueprintStateSchemaInit {
                        fields,
                        collections,
                    },
                    events: BlueprintEventSchemaInit::default(),
                    types: BlueprintTypeSchemaInit::default(),
                    functions: BlueprintFunctionsSchemaInit {
                        functions,
                    },
                    hooks: BlueprintHooksInit::default(),
                },

                royalty_config: PackageRoyaltyConfig::default(),
                auth_config: AuthConfig {
                    function_auth: FunctionAuth::AccessRules(
                        indexmap!(
                            TRANSACTION_TRACKER_CREATE_IDENT.to_string() => rule!(require(AuthAddresses::system_role())),
                        )
                    ),
                    method_auth: MethodAuthTemplate::default(),
                },
            }
        );

        PackageDefinition { blueprints }
    }

    pub fn invoke_export<Y>(
        export_name: &str,
        input: &IndexedScryptoValue,
        api: &mut Y,
    ) -> Result<IndexedScryptoValue, RuntimeError>
    where
        Y: ClientApi<RuntimeError>,
    {
        match export_name {
            TRANSACTION_TRACKER_CREATE_EXPORT_NAME => {
                let input: TransactionTrackerCreateInput = input.as_typed().map_err(|e| {
                    RuntimeError::ApplicationError(ApplicationError::InputDecodeError(e))
                })?;

                let rtn = TransactionTrackerBlueprint::create(input.address_reservation, api)?;

                Ok(IndexedScryptoValue::from_typed(&rtn))
            }

            _ => Err(RuntimeError::ApplicationError(
                ApplicationError::ExportDoesNotExist(export_name.to_string()),
            )),
        }
    }
}

#[derive(Debug, Clone, ScryptoSbor)]
pub enum TransactionStatus {
    V1(TransactionStatusV1),
}

impl TransactionStatus {
    pub fn into_v1(self) -> TransactionStatusV1 {
        match self {
            TransactionStatus::V1(status) => status,
        }
    }
}

#[derive(Debug, Clone, ScryptoSbor)]
pub enum TransactionStatusV1 {
    CommittedSuccess,
    CommittedFailure,
    Cancelled,
}

pub type TransactionStatusSubstateContents = TransactionStatus;

#[derive(Debug, Clone, ScryptoSbor)]
pub enum TransactionTrackerSubstate {
    V1(TransactionTrackerSubstateV1),
}

impl TransactionTrackerSubstate {
    pub fn v1(&self) -> &TransactionTrackerSubstateV1 {
        match self {
            TransactionTrackerSubstate::V1(tracker) => tracker,
        }
    }

    pub fn into_v1(self) -> TransactionTrackerSubstateV1 {
        match self {
            TransactionTrackerSubstate::V1(tracker) => tracker,
        }
    }

    pub fn v1_mut(&mut self) -> &mut TransactionTrackerSubstateV1 {
        match self {
            TransactionTrackerSubstate::V1(tracker) => tracker,
        }
    }
}

#[derive(Debug, Clone, ScryptoSbor)]
pub struct TransactionTrackerSubstateV1 {
    pub start_epoch: u64,
    pub start_partition: u8,

    // parameters
    pub partition_range_start_inclusive: u8,
    pub partition_range_end_inclusive: u8,
    pub epochs_per_partition: u64,
}

impl TransactionTrackerSubstateV1 {
    pub fn partition_for_expiry_epoch(&self, epoch: Epoch) -> Option<u8> {
        let epoch = epoch.number();

        // Check if epoch is within range
        let num_partitions =
            self.partition_range_end_inclusive - self.partition_range_start_inclusive + 1;
        let max_epoch_exclusive =
            self.start_epoch + num_partitions as u64 * self.epochs_per_partition;
        if epoch < self.start_epoch || epoch >= max_epoch_exclusive {
            return None;
        }

        // Calculate the destination partition number
        let mut partition_number =
            self.start_partition as u64 + (epoch - self.start_epoch) / self.epochs_per_partition;
        if partition_number > self.partition_range_end_inclusive as u64 {
            partition_number -= num_partitions as u64;
        }

        assert!(partition_number >= self.partition_range_start_inclusive as u64);
        assert!(partition_number <= self.partition_range_end_inclusive as u64);

        Some(partition_number as u8)
    }

    /// This method will shift the start partition by 1, considering the partition range as a buffer.
    /// Protocol-specific implementation is within transaction executor.
    pub fn advance(&mut self) -> u8 {
        let old_start_partition = self.start_partition;
        self.start_epoch += self.epochs_per_partition;
        self.start_partition = if self.start_partition == self.partition_range_end_inclusive {
            self.partition_range_start_inclusive
        } else {
            self.start_partition + 1
        };
        old_start_partition
    }
}

pub struct TransactionTrackerBlueprint;

impl TransactionTrackerBlueprint {
    pub fn create<Y>(
        address_reservation: GlobalAddressReservation,
        api: &mut Y,
    ) -> Result<GlobalAddress, RuntimeError>
    where
        Y: ClientApi<RuntimeError>,
    {
        let current_epoch = Runtime::current_epoch(api)?;
        let intent_store = api.new_simple_object(
            TRANSACTION_TRACKER_BLUEPRINT,
            indexmap!(
                0u8 => FieldValue::new(&TransactionTrackerSubstate::V1(TransactionTrackerSubstateV1{
                    start_epoch: current_epoch.number(),
                    start_partition: PARTITION_RANGE_START,
                    partition_range_start_inclusive: PARTITION_RANGE_START,
                    partition_range_end_inclusive: PARTITION_RANGE_END,
                    epochs_per_partition: EPOCHS_PER_PARTITION,
                }))
            ),
        )?;
        let role_assignment = RoleAssignment::create(OwnerRole::None, indexmap!(), api)?.0;
        let metadata = Metadata::create(api)?;

        let address = api.globalize(
            intent_store,
            indexmap!(
                AttachedModuleId::RoleAssignment => role_assignment.0,
                AttachedModuleId::Metadata => metadata.0,
            ),
            Some(address_reservation),
        )?;
        Ok(address)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn calculate_coverage() {
        let covered_epochs = (EPOCHS_PER_PARTITION as f64
            * (PARTITION_RANGE_END as f64 - (PARTITION_RANGE_START as f64 - 1.0) - 1.0))
            .floor() as u64;
        let covered_days = covered_epochs
            * 5 // Targeted epoch duration: 5 mins
            / 60
            / 24;
        assert!(covered_epochs >= MAX_EPOCH_RANGE);
        assert_eq!(covered_days, 65);
    }

    #[test]
    fn test_partition_calculation() {
        let mut store = TransactionTrackerSubstate::V1(TransactionTrackerSubstateV1 {
            start_epoch: 256,
            start_partition: 70,
            partition_range_start_inclusive: PARTITION_RANGE_START,
            partition_range_end_inclusive: PARTITION_RANGE_END,
            epochs_per_partition: EPOCHS_PER_PARTITION,
        });
        let num_partitions = (PARTITION_RANGE_END - PARTITION_RANGE_START + 1) as u64;

        assert_eq!(store.v1().partition_for_expiry_epoch(Epoch::of(0)), None);
        assert_eq!(
            store.v1().partition_for_expiry_epoch(Epoch::of(256)),
            Some(70)
        );
        assert_eq!(
            store
                .v1()
                .partition_for_expiry_epoch(Epoch::of(256 + EPOCHS_PER_PARTITION - 1)),
            Some(70)
        );
        assert_eq!(
            store
                .v1()
                .partition_for_expiry_epoch(Epoch::of(256 + EPOCHS_PER_PARTITION)),
            Some(71)
        );
        assert_eq!(
            store.v1().partition_for_expiry_epoch(Epoch::of(
                256 + EPOCHS_PER_PARTITION * num_partitions - 1
            )),
            Some(69)
        );
        assert_eq!(
            store
                .v1()
                .partition_for_expiry_epoch(Epoch::of(256 + EPOCHS_PER_PARTITION * num_partitions)),
            None,
        );

        store.v1_mut().advance();
        assert_eq!(store.v1().start_epoch, 256 + EPOCHS_PER_PARTITION);
        assert_eq!(store.v1().start_partition, 71);
    }
}