Smart Contract

FlowTransactionSchedulerBase

A.7d19efcd8e5b4a4a.FlowTransactionSchedulerBase

Valid From

140,587,918

Deployed

1w ago
Feb 16, 2026, 08:31:53 PM UTC

Dependents

9 imports
1import FungibleToken from 0xf233dcee88fe0abe
2import FlowToken from 0x1654653399040a61
3import FlowFees from 0xf919ee77447b7497
4import FlowStorageFees from 0xe467b9dd11fa00df
5import ViewResolver from 0x1d7e57aa55817448
6
7/// FlowTransactionScheduler enables smart contracts to schedule autonomous execution in the future.
8///
9/// This contract implements FLIP 330's scheduled transaction system, allowing contracts to "wake up" and execute
10/// logic at predefined times without external triggers. 
11///
12/// Scheduled transactions are prioritized (High/Medium/Low) with different execution guarantees and fee multipliers: 
13///   - High priority guarantees first-block execution,
14///   - Medium priority provides best-effort scheduling,
15///   - Low priority executes opportunistically when capacity allows after the time it was scheduled. 
16///
17/// The system uses time slots with execution effort limits to manage network resources,
18/// ensuring predictable performance while enabling novel autonomous blockchain patterns like recurring
19/// payments, automated arbitrage, and time-based contract logic.
20access(all) contract FlowTransactionSchedulerBase {
21
22    /// singleton instance used to store all scheduled transaction data
23    /// and route all scheduled transaction functionality
24    access(self) var sharedScheduler: Capability<auth(Cancel) &SharedScheduler>
25
26    /// storage path for the singleton scheduler resource
27    access(all) let storagePath: StoragePath
28
29    /// Enums
30
31    /// Priority
32    access(all) enum Priority: UInt8 {
33        access(all) case High
34        access(all) case Medium
35        access(all) case Low
36    }
37
38    /// Status
39    access(all) enum Status: UInt8 {
40        /// unknown statuses are used for handling historic scheduled transactions with null statuses
41        access(all) case Unknown
42        /// mutable status
43        access(all) case Scheduled
44        /// finalized statuses
45        access(all) case Executed
46        access(all) case Canceled
47    }
48
49    /// Events
50
51    /// Emitted when a transaction is scheduled
52    access(all) event Scheduled(
53        id: UInt64,
54        priority: UInt8,
55        timestamp: UFix64,
56        executionEffort: UInt64,
57        fees: UFix64,
58        transactionHandlerOwner: Address,
59        transactionHandlerTypeIdentifier: String,
60        transactionHandlerUUID: UInt64,
61        
62        // The public path of the transaction handler that can be used to resolve views
63        // DISCLAIMER: There is no guarantee that the public path is accurate
64        transactionHandlerPublicPath: PublicPath?
65    )
66
67    /// Emitted when a scheduled transaction's scheduled timestamp is reached and it is ready for execution
68    access(all) event PendingExecution(
69        id: UInt64,
70        priority: UInt8,
71        executionEffort: UInt64,
72        fees: UFix64,
73        transactionHandlerOwner: Address,
74        transactionHandlerTypeIdentifier: String
75    )
76
77    /// Emitted when a scheduled transaction is executed by the FVM
78    access(all) event Executed(
79        id: UInt64,
80        priority: UInt8,
81        executionEffort: UInt64,
82        transactionHandlerOwner: Address,
83        transactionHandlerTypeIdentifier: String,
84        transactionHandlerUUID: UInt64,
85
86        // The public path of the transaction handler that can be used to resolve views
87        // DISCLAIMER: There is no guarantee that the public path is accurate
88        transactionHandlerPublicPath: PublicPath?
89    )
90
91    /// Emitted when a scheduled transaction is canceled by the creator of the transaction
92    access(all) event Canceled(
93        id: UInt64,
94        priority: UInt8,
95        feesReturned: UFix64,
96        feesDeducted: UFix64,
97        transactionHandlerOwner: Address,
98        transactionHandlerTypeIdentifier: String
99    )
100
101    /// Emitted when a collection limit is reached
102    /// The limit that was reached is non-nil and is the limit that was reached
103    /// The other limit that was not reached is nil
104    access(all) event CollectionLimitReached(
105        collectionEffortLimit: UInt64?,
106        collectionTransactionsLimit: Int?
107    )
108
109    /// Emitted when the limit on the number of transactions that can be removed in process() is reached
110    access(all) event RemovalLimitReached()
111
112    // Emitted when one or more of the configuration details fields are updated
113    // Event listeners can listen to this and query the new configuration
114    // if they need to
115    access(all) event ConfigUpdated()
116
117    // Emitted when a critical issue is encountered
118    access(all) event CriticalIssue(message: String)
119
120    /// Entitlements
121    access(all) entitlement Execute
122    access(all) entitlement Process
123    access(all) entitlement Cancel
124    access(all) entitlement UpdateConfig
125
126    /// Interfaces
127
128    /// TransactionHandler is an interface that defines a single method executeTransaction that 
129    /// must be implemented by the resource that contains the logic to be executed by the scheduled transaction.
130    /// An authorized capability to this resource is provided when scheduling a transaction.
131    /// The transaction scheduler uses this capability to execute the transaction when its scheduled timestamp arrives.
132    access(all) resource interface TransactionHandler: ViewResolver.Resolver {
133
134        access(all) view fun getViews(): [Type] {
135            return []
136        }
137
138        access(all) fun resolveView(_ view: Type): AnyStruct? {
139            return nil
140        }
141
142        /// Executes the implemented transaction logic
143        ///
144        /// @param id: The id of the scheduled transaction (this can be useful for any internal tracking)
145        /// @param data: The data that was passed when the transaction was originally scheduled
146        /// that may be useful for the execution of the transaction logic
147        access(Execute) fun executeTransaction(id: UInt64, data: AnyStruct?)
148    }
149
150    /// Structs
151
152    /// ScheduledTransaction is the resource that the user receives after scheduling a transaction.
153    /// It allows them to get the status of their transaction and can be passed back
154    /// to the scheduler contract to cancel the transaction if it has not yet been executed. 
155    access(all) resource ScheduledTransaction {
156        access(all) let id: UInt64
157        access(all) let timestamp: UFix64
158        access(all) let handlerTypeIdentifier: String
159
160        access(all) view fun status(): Status? {
161            return FlowTransactionSchedulerBase.sharedScheduler.borrow()!.getStatus(id: self.id)
162        }
163
164        init(
165            id: UInt64, 
166            timestamp: UFix64,
167            handlerTypeIdentifier: String
168        ) {
169            self.id = id
170            self.timestamp = timestamp
171            self.handlerTypeIdentifier = handlerTypeIdentifier
172        }
173
174        // event emitted when the resource is destroyed
175        access(all) event ResourceDestroyed(id: UInt64 = self.id, timestamp: UFix64 = self.timestamp, handlerTypeIdentifier: String = self.handlerTypeIdentifier)
176    }
177
178    /// EstimatedScheduledTransaction contains data for estimating transaction scheduling.
179    access(all) struct EstimatedScheduledTransaction {
180        /// flowFee is the estimated fee in Flow for the transaction to be scheduled
181        access(all) let flowFee: UFix64?
182        /// timestamp is estimated timestamp that the transaction will be executed at
183        access(all) let timestamp: UFix64?
184        /// error is an optional error message if the transaction cannot be scheduled
185        access(all) let error: String?
186
187        access(contract) view init(flowFee: UFix64?, timestamp: UFix64?, error: String?) {
188            self.flowFee = flowFee
189            self.timestamp = timestamp
190            self.error = error
191        }
192    }
193
194    /// Transaction data is a representation of a scheduled transaction
195    /// It is the source of truth for an individual transaction and stores the
196    /// capability to the handler that contains the logic that will be executed by the transaction.
197    access(all) struct TransactionData {
198        access(all) let id: UInt64
199        access(all) let priority: Priority
200        access(all) let executionEffort: UInt64
201        access(all) var status: Status
202
203        /// Fee amount to pay for the transaction
204        access(all) let fees: UFix64
205
206        /// The timestamp that the transaction is scheduled for
207        /// For medium priority transactions, it may be different than the requested timestamp
208        /// For low priority transactions, it is the requested timestamp,
209        /// but the timestamp where the transaction is actually executed may be different
210        access(all) var scheduledTimestamp: UFix64
211
212        /// Capability to the logic that the transaction will execute
213        access(contract) let handler: Capability<auth(Execute) &{TransactionHandler}>
214
215        /// Type identifier of the transaction handler
216        access(all) let handlerTypeIdentifier: String
217        access(all) let handlerAddress: Address
218
219        /// Optional data that can be passed to the handler
220        /// This data is publicly accessible, so make sure it does not contain
221        /// any privileged information or functionality
222        access(contract) let data: AnyStruct?
223
224        access(contract) init(
225            id: UInt64,
226            handler: Capability<auth(Execute) &{TransactionHandler}>,
227            scheduledTimestamp: UFix64,
228            data: AnyStruct?,
229            priority: Priority,
230            executionEffort: UInt64,
231            fees: UFix64,
232        ) {
233            self.id = id
234            self.handler = handler
235            self.data = data
236            self.priority = priority
237            self.executionEffort = executionEffort
238            self.fees = fees
239            self.status = Status.Scheduled
240            let handlerRef = handler.borrow()
241                ?? panic("Invalid transaction handler: Could not borrow a reference to the transaction handler")
242            self.handlerAddress = handler.address
243            self.handlerTypeIdentifier = handlerRef.getType().identifier
244            self.scheduledTimestamp = scheduledTimestamp
245        }
246
247        /// setStatus updates the status of the transaction.
248        /// It panics if the transaction status is already finalized.
249        access(contract) fun setStatus(newStatus: Status) {
250            pre {
251                newStatus != Status.Unknown: "Invalid status: New status cannot be Unknown"
252                self.status != Status.Executed && self.status != Status.Canceled:
253                    "Invalid status: Transaction with id \(self.id) is already finalized"
254                newStatus == Status.Executed ? self.status == Status.Scheduled : true:
255                    "Invalid status: Transaction with id \(self.id) can only be set as Executed if it is Scheduled"
256                newStatus == Status.Canceled ? self.status == Status.Scheduled : true:
257                    "Invalid status: Transaction with id \(self.id) can only be set as Canceled if it is Scheduled"
258            }
259
260            self.status = newStatus
261        }
262
263        /// setScheduledTimestamp updates the scheduled timestamp of the transaction.
264        /// It panics if the transaction status is already finalized.
265        access(contract) fun setScheduledTimestamp(newTimestamp: UFix64) {
266            pre {
267                self.status != Status.Executed && self.status != Status.Canceled:
268                    "Invalid status: Transaction with id \(self.id) is already finalized"
269            }
270            self.scheduledTimestamp = newTimestamp
271        }
272
273        /// payAndRefundFees withdraws fees from the transaction based on the refund multiplier.
274        /// It deposits any leftover fees to the FlowFees vault to be used to pay node operator rewards
275        /// like any other transaction on the Flow network.
276        access(contract) fun payAndRefundFees(refundMultiplier: UFix64): @FlowToken.Vault {
277            pre {
278                refundMultiplier >= 0.0 && refundMultiplier <= 1.0:
279                    "Invalid refund multiplier: The multiplier must be between 0.0 and 1.0 but got \(refundMultiplier)"
280            }
281            if refundMultiplier == 0.0 {
282                FlowFees.deposit(from: <-FlowTransactionSchedulerBase.withdrawFees(amount: self.fees))
283                return <-FlowToken.createEmptyVault(vaultType: Type<@FlowToken.Vault>())
284            } else {
285                let amountToReturn = self.fees * refundMultiplier
286                let amountToKeep = self.fees - amountToReturn
287                let feesToReturn <- FlowTransactionSchedulerBase.withdrawFees(amount: amountToReturn)
288                FlowFees.deposit(from: <-FlowTransactionSchedulerBase.withdrawFees(amount: amountToKeep))
289                return <-feesToReturn
290            }
291        }
292
293        /// getData copies and returns the data field
294        access(all) view fun getData(): AnyStruct? {
295            return self.data
296        }
297
298        /// borrowHandler returns an un-entitled reference to the transaction handler
299        /// This allows users to query metadata views about the handler
300        /// @return: An un-entitled reference to the transaction handler
301        access(all) view fun borrowHandler(): &{TransactionHandler} {
302            return self.handler.borrow() as? &{TransactionHandler}
303                ?? panic("Invalid transaction handler: Could not borrow a reference to the transaction handler")
304        }
305    }
306
307    /// Struct interface representing all the base configuration details in the Scheduler contract
308    /// that is used for governing the protocol
309    /// This is an interface to allow for the configuration details to be updated in the future
310    access(all) struct interface SchedulerConfig {
311
312        /// maximum effort that can be used for any transaction
313        access(all) var maximumIndividualEffort: UInt64
314
315        /// minimum execution effort is the minimum effort that can be 
316        /// used for any transaction
317        access(all) var minimumExecutionEffort: UInt64
318
319        /// slot total effort limit is the maximum effort that can be 
320        /// cumulatively allocated to one timeslot by all priorities
321        access(all) var slotTotalEffortLimit: UInt64
322
323        /// slot shared effort limit is the maximum effort 
324        /// that can be allocated to high and medium priority 
325        /// transactions combined after their exclusive effort reserves have been filled
326        access(all) var slotSharedEffortLimit: UInt64
327
328        /// priority effort reserve is the amount of effort that is 
329        /// reserved exclusively for each priority
330        access(all) var priorityEffortReserve: {Priority: UInt64}
331
332        /// priority effort limit is the maximum cumulative effort per priority in a timeslot
333        access(all) var priorityEffortLimit: {Priority: UInt64}
334
335        /// max data size is the maximum data size that can be stored for a transaction
336        access(all) var maxDataSizeMB: UFix64
337
338        /// priority fee multipliers are values we use to calculate the added 
339        /// processing fee for each priority
340        access(all) var priorityFeeMultipliers: {Priority: UFix64}
341
342        /// refund multiplier is the portion of the fees that are refunded when any transaction is cancelled
343        access(all) var refundMultiplier: UFix64
344
345        /// canceledTransactionsLimit is the maximum number of canceled transactions
346        /// to keep in the canceledTransactions array
347        access(all) var canceledTransactionsLimit: UInt
348
349        /// collectionEffortLimit is the maximum effort that can be used for all transactions in a collection
350        access(all) var collectionEffortLimit: UInt64
351
352        /// collectionTransactionsLimit is the maximum number of transactions that can be processed in a collection
353        access(all) var collectionTransactionsLimit: Int
354
355        access(all) init(
356            maximumIndividualEffort: UInt64,
357            minimumExecutionEffort: UInt64,
358            slotSharedEffortLimit: UInt64,
359            priorityEffortReserve: {Priority: UInt64},
360            lowPriorityEffortLimit: UInt64,
361            maxDataSizeMB: UFix64,
362            priorityFeeMultipliers: {Priority: UFix64},
363            refundMultiplier: UFix64,
364            canceledTransactionsLimit: UInt,
365            collectionEffortLimit: UInt64,
366            collectionTransactionsLimit: Int,
367            txRemovalLimit: UInt
368        ) {
369            post {
370                self.refundMultiplier >= 0.0 && self.refundMultiplier <= 1.0:
371                    "Invalid refund multiplier: The multiplier must be between 0.0 and 1.0 but got \(refundMultiplier)"
372                self.priorityFeeMultipliers[Priority.Low]! >= 1.0:
373                    "Invalid priority fee multiplier: Low priority multiplier must be greater than or equal to 1.0 but got \(self.priorityFeeMultipliers[Priority.Low]!)"
374                self.priorityFeeMultipliers[Priority.Medium]! > self.priorityFeeMultipliers[Priority.Low]!:
375                    "Invalid priority fee multiplier: Medium priority multiplier must be greater than or equal to \(priorityFeeMultipliers[Priority.Low]!) but got \(priorityFeeMultipliers[Priority.Medium]!)"
376                self.priorityFeeMultipliers[Priority.High]! > self.priorityFeeMultipliers[Priority.Medium]!:
377                    "Invalid priority fee multiplier: High priority multiplier must be greater than or equal to \(priorityFeeMultipliers[Priority.Medium]!) but got \(priorityFeeMultipliers[Priority.High]!)"
378                self.priorityEffortLimit[Priority.High]! >= self.priorityEffortReserve[Priority.High]!:
379                    "Invalid priority effort limit: High priority effort limit must be greater than or equal to the priority effort reserve of \(priorityEffortReserve[Priority.High]!)"
380                self.priorityEffortLimit[Priority.Medium]! >= self.priorityEffortReserve[Priority.Medium]!:
381                    "Invalid priority effort limit: Medium priority effort limit must be greater than or equal to the priority effort reserve of \(priorityEffortReserve[Priority.Medium]!)"
382                self.priorityEffortLimit[Priority.Low]! >= self.priorityEffortReserve[Priority.Low]!:
383                    "Invalid priority effort limit: Low priority effort limit must be greater than or equal to the priority effort reserve of \(priorityEffortReserve[Priority.Low]!)"
384                self.priorityEffortReserve[Priority.Low]! == 0:
385                    "Invalid priority effort reserve: Low priority effort reserve must be 0"
386                self.collectionTransactionsLimit >= 0:
387                    "Invalid collection transactions limit: Collection transactions limit must be greater than or equal to 0 but got \(collectionTransactionsLimit)"
388                self.canceledTransactionsLimit >= 1:
389                    "Invalid canceled transactions limit: Canceled transactions limit must be greater than or equal to 1 but got \(canceledTransactionsLimit)"
390                self.collectionEffortLimit > self.slotTotalEffortLimit:
391                    "Invalid collection effort limit: Collection effort limit must be greater than \(self.slotTotalEffortLimit) but got \(self.collectionEffortLimit)"
392            }
393        }
394
395        access(all) view fun getTxRemovalLimit(): UInt
396    }
397
398    /// Concrete implementation of the SchedulerConfig interface
399    /// This struct is used to store the configuration details in the Scheduler contract
400    access(all) struct Config: SchedulerConfig {
401        access(all) var maximumIndividualEffort: UInt64
402        access(all) var minimumExecutionEffort: UInt64
403        access(all) var slotTotalEffortLimit: UInt64
404        access(all) var slotSharedEffortLimit: UInt64
405        access(all) var priorityEffortReserve: {Priority: UInt64}
406        access(all) var priorityEffortLimit: {Priority: UInt64}
407        access(all) var maxDataSizeMB: UFix64
408        access(all) var priorityFeeMultipliers: {Priority: UFix64}
409        access(all) var refundMultiplier: UFix64
410        access(all) var canceledTransactionsLimit: UInt
411        access(all) var collectionEffortLimit: UInt64
412        access(all) var collectionTransactionsLimit: Int
413
414        access(all) init(   
415            maximumIndividualEffort: UInt64,
416            minimumExecutionEffort: UInt64,
417            slotSharedEffortLimit: UInt64,
418            priorityEffortReserve: {Priority: UInt64},
419            lowPriorityEffortLimit: UInt64,
420            maxDataSizeMB: UFix64,
421            priorityFeeMultipliers: {Priority: UFix64},
422            refundMultiplier: UFix64,
423            canceledTransactionsLimit: UInt,
424            collectionEffortLimit: UInt64,
425            collectionTransactionsLimit: Int,
426            txRemovalLimit: UInt
427        ) {
428            self.maximumIndividualEffort = maximumIndividualEffort
429            self.minimumExecutionEffort = minimumExecutionEffort
430            self.slotTotalEffortLimit = slotSharedEffortLimit + priorityEffortReserve[Priority.High]! + priorityEffortReserve[Priority.Medium]!
431            self.slotSharedEffortLimit = slotSharedEffortLimit
432            self.priorityEffortReserve = priorityEffortReserve
433            self.priorityEffortLimit = {
434                Priority.High: priorityEffortReserve[Priority.High]! + slotSharedEffortLimit,
435                Priority.Medium: priorityEffortReserve[Priority.Medium]! + slotSharedEffortLimit,
436                Priority.Low: lowPriorityEffortLimit
437            }
438            self.maxDataSizeMB = maxDataSizeMB
439            self.priorityFeeMultipliers = priorityFeeMultipliers
440            self.refundMultiplier = refundMultiplier
441            self.canceledTransactionsLimit = canceledTransactionsLimit
442            self.collectionEffortLimit = collectionEffortLimit
443            self.collectionTransactionsLimit = collectionTransactionsLimit
444        }
445
446        access(all) view fun getTxRemovalLimit(): UInt {
447            return FlowTransactionSchedulerBase.account.storage.copy<UInt>(from: /storage/txRemovalLimit)
448                ?? 200
449        }
450    }
451
452
453    /// SortedTimestamps maintains timestamps sorted in ascending order for efficient processing
454    /// It encapsulates all operations related to maintaining and querying sorted timestamps
455    access(all) struct SortedTimestamps {
456        /// Internal sorted array of timestamps
457        access(self) var timestamps: [UFix64]
458
459        access(all) init() {
460            self.timestamps = []
461        }
462
463        /// Add a timestamp to the sorted array maintaining sorted order
464        access(all) fun add(timestamp: UFix64) {
465
466            var insertIndex = 0
467            for i, ts in self.timestamps {
468                if timestamp < ts {
469                    insertIndex = i
470                    break
471                } else if timestamp == ts {
472                    return
473                }
474                insertIndex = i + 1
475            }
476            self.timestamps.insert(at: insertIndex, timestamp)
477        }
478
479        /// Remove a timestamp from the sorted array
480        access(all) fun remove(timestamp: UFix64) {
481
482            let index = self.timestamps.firstIndex(of: timestamp)
483            if index != nil {
484                self.timestamps.remove(at: index!)
485            }
486        }
487
488        /// Get all timestamps that are in the past (less than or equal to current timestamp)
489        access(all) fun getBefore(current: UFix64): [UFix64] {
490            let pastTimestamps: [UFix64] = []
491            for timestamp in self.timestamps {
492                if timestamp <= current {
493                    pastTimestamps.append(timestamp)
494                } else {
495                    break  // No need to check further since array is sorted
496                }
497            }
498            return pastTimestamps
499        }
500
501        /// Check if there are any timestamps that need processing
502        /// Returns true if processing is needed, false for early exit
503        access(all) fun hasBefore(current: UFix64): Bool {
504            return self.timestamps.length > 0 && self.timestamps[0] <= current
505        }
506
507        /// Get the whole array of timestamps
508        access(all) fun getAll(): [UFix64] {
509            return self.timestamps
510        }
511    }
512
513    /// Resources
514
515    /// Shared scheduler is a resource that is used as a singleton in the scheduler contract and contains 
516    /// all the functionality to schedule, process and execute transactions as well as the internal state. 
517    access(all) resource SharedScheduler {
518        /// nextID contains the next transaction ID to be assigned
519        /// This the ID is monotonically increasing and is used to identify each transaction
520        access(contract) var nextID: UInt64
521
522        /// transactions is a map of transaction IDs to TransactionData structs
523        access(contract) var transactions: {UInt64: TransactionData}
524
525        /// slot queue is a map of timestamps to Priorities to transaction IDs and their execution efforts
526        access(contract) var slotQueue: {UFix64: {Priority: {UInt64: UInt64}}}
527
528        /// slot used effort is a map of timestamps map of priorities and 
529        /// efforts that has been used for the timeslot
530        access(contract) var slotUsedEffort: {UFix64: {Priority: UInt64}}
531
532        /// sorted timestamps manager for efficient processing
533        access(contract) var sortedTimestamps: SortedTimestamps
534    
535        /// canceled transactions keeps a record of canceled transaction IDs up to a canceledTransactionsLimit
536        access(contract) var canceledTransactions: [UInt64]
537
538        /// Struct that contains all the configuration details for the transaction scheduler protocol
539        /// Can be updated by the owner of the contract
540        access(contract) var config: {SchedulerConfig}
541
542        access(all) init() {
543            self.nextID = 1
544            self.canceledTransactions = [0 as UInt64]
545            
546            self.transactions = {}
547            self.slotUsedEffort = {}
548            self.slotQueue = {}
549            self.sortedTimestamps = SortedTimestamps()
550            
551            /* Default slot efforts and limits look like this:
552
553                Timestamp Slot (17.5kee)
554                ┌─────────────────────────┐
555                │ ┌─────────────┐         │ 
556                │ │ High Only   │         │ High: 15kee max
557                │ │   10kee     │         │ (10 exclusive + 5 shared)
558                │ └─────────────┘         │
559                | ┌───────────────┐       |
560                │ |  Shared Pool  │       |
561                | │ (High+Medium) │       |
562                | │     5kee     │       |
563                | └───────────────┘       |
564                │ ┌─────────────┐         │ Medium: 7.5kee max  
565                │ │ Medium Only │         │ (2.5 exclusive + 5 shared)
566                │ │   2.5kee      │         │
567                │ └─────────────┘         │
568                │ ┌─────────────────────┐ │ Low: 2.5kee max
569                │ │ Low (if space left) │ │ (execution time only)
570                │ │       2.5kee          │ │
571                │ └─────────────────────┘ │
572                └─────────────────────────┘
573            */
574
575            let sharedEffortLimit: UInt64 = 5_000
576            let highPriorityEffortReserve: UInt64 = 10_000
577            let mediumPriorityEffortReserve: UInt64 = 2_500
578
579            self.config = Config(
580                maximumIndividualEffort: 9999,
581                minimumExecutionEffort: 100,
582                slotSharedEffortLimit: sharedEffortLimit,
583                priorityEffortReserve: {
584                    Priority.High: highPriorityEffortReserve,
585                    Priority.Medium: mediumPriorityEffortReserve,
586                    Priority.Low: 0
587                },
588                lowPriorityEffortLimit: 2_500,
589                maxDataSizeMB: 0.001,
590                priorityFeeMultipliers: {
591                    Priority.High: 10.0,
592                    Priority.Medium: 5.0,
593                    Priority.Low: 2.0
594                },
595                refundMultiplier: 0.5,
596                canceledTransactionsLimit: 1000,
597                collectionEffortLimit: 500_000, // Maximum effort for all transactions in a collection
598                collectionTransactionsLimit: 150, // Maximum number of transactions in a collection
599                txRemovalLimit: 200
600            )
601        }
602
603        /// Gets a copy of the struct containing all the configuration details
604        /// of the Scheduler resource
605        access(contract) view fun getConfig(): {SchedulerConfig} {
606            return self.config
607        }
608
609        /// sets all the configuration details for the Scheduler resource
610        access(UpdateConfig) fun setConfig(newConfig: {SchedulerConfig}, txRemovalLimit: UInt) {
611            self.config = newConfig
612            FlowTransactionSchedulerBase.account.storage.load<UInt>(from: /storage/txRemovalLimit)
613            FlowTransactionSchedulerBase.account.storage.save(txRemovalLimit, to: /storage/txRemovalLimit)
614            emit ConfigUpdated()
615        }
616
617        /// getTransaction returns a copy of the specified transaction
618        access(contract) view fun getTransaction(id: UInt64): TransactionData? {
619            return self.transactions[id]
620        }
621
622        /// borrowTransaction borrows a reference to the specified transaction
623        access(contract) view fun borrowTransaction(id: UInt64): &TransactionData? {
624            return &self.transactions[id]
625        }
626
627        /// getCanceledTransactions returns a copy of the canceled transactions array
628        access(contract) view fun getCanceledTransactions(): [UInt64] {
629            return self.canceledTransactions
630        }
631
632        /// getTransactionsForTimeframe returns a dictionary of transactions scheduled within a specified time range,
633        /// organized by timestamp and priority with arrays of transaction IDs.
634        /// WARNING: If you provide a time range that is too large, the function will likely fail to complete
635        /// because the function will run out of gas. Keep the time range small.
636        ///
637        /// @param startTimestamp: The start timestamp (inclusive) for the time range
638        /// @param endTimestamp: The end timestamp (inclusive) for the time range
639        /// @return {UFix64: {Priority: [UInt64]}}: A dictionary mapping timestamps to priorities to arrays of transaction IDs
640        access(contract) fun getTransactionsForTimeframe(startTimestamp: UFix64, endTimestamp: UFix64): {UFix64: {UInt8: [UInt64]}} {
641            var transactionsInTimeframe: {UFix64: {UInt8: [UInt64]}} = {}
642            
643            // Validate input parameters
644            if startTimestamp > endTimestamp {
645                return transactionsInTimeframe
646            }
647            
648            // Get all timestamps that fall within the specified range
649            let allTimestampsBeforeEnd = self.sortedTimestamps.getBefore(current: endTimestamp)
650            
651            for timestamp in allTimestampsBeforeEnd {
652                // Check if this timestamp falls within our range
653                if timestamp < startTimestamp { continue }
654                
655                let transactionPriorities = self.slotQueue[timestamp] ?? {}
656                
657                var timestampTransactions: {UInt8: [UInt64]} = {}
658                
659                for priority in transactionPriorities.keys {
660                    let transactionIDs = transactionPriorities[priority] ?? {}
661                    var priorityTransactions: [UInt64] = []
662                        
663                    for id in transactionIDs.keys {
664                        priorityTransactions.append(id)
665                    }
666                        
667                    if priorityTransactions.length > 0 {
668                        timestampTransactions[priority.rawValue] = priorityTransactions
669                    }
670                }
671                
672                if timestampTransactions.keys.length > 0 {
673                    transactionsInTimeframe[timestamp] = timestampTransactions
674                }
675                
676            }
677            
678            return transactionsInTimeframe
679        }
680
681        /// calculate fee by converting execution effort to a fee in Flow tokens.
682        /// @param executionEffort: The execution effort of the transaction
683        /// @param priority: The priority of the transaction
684        /// @param dataSizeMB: The size of the data that was passed when the transaction was originally scheduled
685        /// @return UFix64: The fee in Flow tokens that is required to pay for the transaction
686        access(contract) fun calculateFee(executionEffort: UInt64, priority: Priority, dataSizeMB: UFix64): UFix64 {
687            // Use the official FlowFees calculation
688            let baseFee = FlowFees.computeFees(inclusionEffort: 1.0, executionEffort: UFix64(executionEffort)/100000000.0)
689            
690            // Scale the execution fee by the multiplier for the priority
691            let scaledExecutionFee = baseFee * self.config.priorityFeeMultipliers[priority]!
692
693            // Calculate the FLOW required to pay for storage of the transaction data
694            let storageFee = FlowStorageFees.storageCapacityToFlow(dataSizeMB)
695
696            // Add inclusion Flow fee for scheduled transactions
697            let inclusionFee = 0.00001
698
699            return scaledExecutionFee + storageFee + inclusionFee
700        }
701
702        /// getNextIDAndIncrement returns the next ID and increments the ID counter
703        access(self) fun getNextIDAndIncrement(): UInt64 {
704            let nextID = self.nextID
705            self.nextID = self.nextID + 1
706            return nextID
707        }
708
709        /// get status of the scheduled transaction
710        /// @param id: The ID of the transaction to get the status of
711        /// @return Status: The status of the transaction, if the transaction is not found Unknown is returned.
712        access(contract) view fun getStatus(id: UInt64): Status? {
713            // if the transaction ID is greater than the next ID, it is not scheduled yet and has never existed
714            if id == 0 as UInt64 || id >= self.nextID {
715                return nil
716            }
717
718            // This should always return Scheduled or Executed
719            if let tx = self.borrowTransaction(id: id) {
720                return tx.status
721            }
722
723            // if the transaction was canceled and it is still not pruned from 
724            // list return canceled status
725            if self.canceledTransactions.contains(id) {
726                return Status.Canceled
727            }
728
729            // if transaction ID is after first canceled ID it must be executed 
730            // otherwise it would have been canceled and part of this list
731            let firstCanceledID = self.canceledTransactions[0]
732            if id > firstCanceledID {
733                return Status.Executed
734            }
735
736            // the transaction list was pruned and the transaction status might be 
737            // either canceled or execute so we return unknown
738            return Status.Unknown
739        }
740
741        /// schedule is the primary entry point for scheduling a new transaction within the scheduler contract. 
742        /// If scheduling the transaction is not possible either due to invalid arguments or due to 
743        /// unavailable slots, the function panics. 
744        //
745        /// The schedule function accepts the following arguments:
746        /// @param: transaction: A capability to a resource in storage that implements the transaction handler 
747        ///    interface. This handler will be invoked at execution time and will receive the specified data payload.
748        /// @param: timestamp: Specifies the earliest block timestamp at which the transaction is eligible for execution 
749        ///    (Unix timestamp so fractional seconds values are ignored). It must be set in the future.
750        /// @param: priority: An enum value (`High`, `Medium`, or `Low`) that influences the scheduling behavior and determines 
751        ///    how soon after the timestamp the transaction will be executed.
752        /// @param: executionEffort: Defines the maximum computational resources allocated to the transaction. This also determines 
753        ///    the fee charged. Unused execution effort is not refunded.
754        /// @param: fees: A Vault resource containing sufficient funds to cover the required execution effort.
755        access(contract) fun schedule(
756            handlerCap: Capability<auth(Execute) &{TransactionHandler}>,
757            data: AnyStruct?,
758            timestamp: UFix64,
759            priority: Priority,
760            executionEffort: UInt64,
761            fees: @FlowToken.Vault
762        ): @ScheduledTransaction {
763
764            // Use the estimate function to validate inputs
765            let estimate = self.estimate(
766                data: data,
767                timestamp: timestamp,
768                priority: priority,
769                executionEffort: executionEffort
770            )
771
772            // Estimate returns an error for low priority transactions
773            // so need to check that the error is fine
774            // because low priority transactions are allowed in schedule
775            if estimate.error != nil && estimate.timestamp == nil {
776                panic(estimate.error!)
777            }
778
779            assert (
780                fees.balance >= estimate.flowFee!,
781                message: "Insufficient fees: The Fee balance of \(fees.balance) is not sufficient to pay the required amount of \(estimate.flowFee!) for execution of the transaction."
782            )
783
784            let transactionID = self.getNextIDAndIncrement()
785            let transactionData = TransactionData(
786                id: transactionID,
787                handler: handlerCap,
788                scheduledTimestamp: estimate.timestamp!,
789                data: data,
790                priority: priority,
791                executionEffort: executionEffort,
792                fees: fees.balance,
793            )
794
795            // Deposit the fees to the service account's vault
796            FlowTransactionSchedulerBase.depositFees(from: <-fees)
797
798            let handlerRef = handlerCap.borrow()
799                ?? panic("Invalid transaction handler: Could not borrow a reference to the transaction handler")
800
801            let handlerPublicPath = handlerRef.resolveView(Type<PublicPath>()) as? PublicPath
802
803            emit Scheduled(
804                id: transactionData.id,
805                priority: transactionData.priority.rawValue,
806                timestamp: transactionData.scheduledTimestamp,
807                executionEffort: transactionData.executionEffort,
808                fees: transactionData.fees,
809                transactionHandlerOwner: transactionData.handler.address,
810                transactionHandlerTypeIdentifier: transactionData.handlerTypeIdentifier,
811                transactionHandlerUUID: handlerRef.uuid,
812                transactionHandlerPublicPath: handlerPublicPath
813            )
814
815            // Add the transaction to the slot queue and update the internal state
816            self.addTransaction(slot: estimate.timestamp!, txData: transactionData)
817            
818            return <-create ScheduledTransaction(
819                id: transactionID, 
820                timestamp: estimate.timestamp!,
821                handlerTypeIdentifier: transactionData.handlerTypeIdentifier
822            )
823        }
824
825        /// The estimate function calculates the required fee in Flow and expected execution timestamp for 
826        /// a transaction based on the requested timestamp, priority, and execution effort. 
827        //
828        /// If the provided arguments are invalid or the transaction cannot be scheduled (e.g., due to 
829        /// insufficient computation effort or unavailable time slots) the estimate function
830        /// returns an EstimatedScheduledTransaction struct with a non-nil error message.
831        ///        
832        /// This helps developers ensure sufficient funding and preview the expected scheduling window, 
833        /// reducing the risk of unnecessary cancellations.
834        ///
835        /// @param data: The data that was passed when the transaction was originally scheduled
836        /// @param timestamp: The requested timestamp for the transaction
837        /// @param priority: The priority of the transaction
838        /// @param executionEffort: The execution effort of the transaction
839        /// @return EstimatedScheduledTransaction: A struct containing the estimated fee, timestamp, and error message
840        access(contract) fun estimate(
841            data: AnyStruct?,
842            timestamp: UFix64,
843            priority: Priority,
844            executionEffort: UInt64
845        ): EstimatedScheduledTransaction {
846            // Remove fractional values from the timestamp
847            let sanitizedTimestamp = UFix64(UInt64(timestamp))
848
849            if sanitizedTimestamp <= getCurrentBlock().timestamp {
850                return EstimatedScheduledTransaction(
851                            flowFee: nil,
852                            timestamp: nil,
853                            error: "Invalid timestamp: \(sanitizedTimestamp) is in the past, current timestamp: \(getCurrentBlock().timestamp)"
854                        )
855            }
856
857            if executionEffort > self.config.maximumIndividualEffort {
858                return EstimatedScheduledTransaction(
859                    flowFee: nil,
860                    timestamp: nil,
861                    error: "Invalid execution effort: \(executionEffort) is greater than the maximum transaction effort of \(self.config.maximumIndividualEffort)"
862                )
863            }
864
865            if executionEffort > self.config.priorityEffortLimit[priority]! {
866                return EstimatedScheduledTransaction(
867                            flowFee: nil,
868                            timestamp: nil,
869                            error: "Invalid execution effort: \(executionEffort) is greater than the priority's max effort of \(self.config.priorityEffortLimit[priority]!)"
870                        )
871            }
872
873            if executionEffort < self.config.minimumExecutionEffort {
874                return EstimatedScheduledTransaction(
875                            flowFee: nil,
876                            timestamp: nil,
877                            error: "Invalid execution effort: \(executionEffort) is less than the minimum execution effort of \(self.config.minimumExecutionEffort)"
878                        )
879            }
880
881            let dataSizeMB = FlowTransactionSchedulerBase.getSizeOfData(data)
882            if dataSizeMB > self.config.maxDataSizeMB {
883                return EstimatedScheduledTransaction(
884                    flowFee: nil,
885                    timestamp: nil,
886                    error: "Invalid data size: \(dataSizeMB) is greater than the maximum data size of \(self.config.maxDataSizeMB)MB"
887                )
888            }
889
890            let fee = self.calculateFee(executionEffort: executionEffort, priority: priority, dataSizeMB: dataSizeMB)
891
892            let scheduledTimestamp = self.calculateScheduledTimestamp(
893                timestamp: sanitizedTimestamp, 
894                priority: priority, 
895                executionEffort: executionEffort
896            )
897
898            if scheduledTimestamp == nil {
899                return EstimatedScheduledTransaction(
900                            flowFee: nil,
901                            timestamp: nil,
902                            error: "Invalid execution effort: \(executionEffort) is greater than the priority's available effort for the requested timestamp."
903                        )
904            }
905
906            if priority == Priority.Low {
907                return EstimatedScheduledTransaction(
908                            flowFee: fee,
909                            timestamp: scheduledTimestamp,
910                            error: "Invalid Priority: Cannot estimate for Low Priority transactions. They will be included in the first block with available space after their requested timestamp."
911                        )
912            }
913
914            return EstimatedScheduledTransaction(flowFee: fee, timestamp: scheduledTimestamp, error: nil)
915        }
916
917        /// calculateScheduledTimestamp calculates the timestamp at which a transaction 
918        /// can be scheduled. It takes into account the priority of the transaction and 
919        /// the execution effort.
920        /// - If the transaction is high priority, it returns the timestamp if there is enough 
921        ///    space or nil if there is no space left.
922        /// - If the transaction is medium or low priority and there is space left in the requested timestamp,
923        ///   it returns the requested timestamp. If there is not enough space, it finds the next timestamp with space.
924        ///
925        /// @param timestamp: The requested timestamp for the transaction
926        /// @param priority: The priority of the transaction
927        /// @param executionEffort: The execution effort of the transaction
928        /// @return UFix64?: The timestamp at which the transaction can be scheduled, or nil if there is no space left for a high priority transaction
929        access(contract) view fun calculateScheduledTimestamp(
930            timestamp: UFix64, 
931            priority: Priority, 
932            executionEffort: UInt64
933        ): UFix64? {
934
935            var timestampToSearch = timestamp
936
937            // If no available timestamps are found, this will eventually reach the gas limit and fail
938            // This is extremely unlikely
939            while true {
940
941                let used = self.slotUsedEffort[timestampToSearch]
942                // if nothing is scheduled at this timestamp, we can schedule at provided timestamp
943                if used == nil { 
944                    return timestampToSearch
945                }
946                
947                let available = self.getSlotAvailableEffort(timestamp: timestampToSearch, priority: priority)
948                // if theres enough space, we can tentatively schedule at provided timestamp
949                if executionEffort <= available {
950                    return timestampToSearch
951                }
952                
953                if priority == Priority.High {
954                    // high priority demands scheduling at exact timestamp or failing
955                    return nil
956                }
957
958                timestampToSearch = timestampToSearch + 1.0
959            }
960
961            // should never happen
962            return nil
963        }
964
965        /// slot available effort returns the amount of effort that is available for a given timestamp and priority.
966        access(contract) view fun getSlotAvailableEffort(timestamp: UFix64, priority: Priority): UInt64 {
967
968            // Remove fractional values from the timestamp
969            let sanitizedTimestamp = UFix64(UInt64(timestamp))
970
971            // Get the theoretical maximum allowed for the priority including shared
972            let priorityLimit = self.config.priorityEffortLimit[priority]!
973            
974            // If nothing has been claimed for the requested timestamp,
975            // return the full amount
976            if !self.slotUsedEffort.containsKey(sanitizedTimestamp) {
977                return priorityLimit
978            }
979
980            // Get the mapping of how much effort has been used
981            // for each priority for the timestamp
982            let slotPriorityEffortsUsed = self.slotUsedEffort[sanitizedTimestamp]!
983
984            // Get the exclusive reserves for each priority
985            let highReserve = self.config.priorityEffortReserve[Priority.High]!
986            let mediumReserve = self.config.priorityEffortReserve[Priority.Medium]!
987
988            // Get how much effort has been used for each priority
989            let highUsed = slotPriorityEffortsUsed[Priority.High] ?? 0
990            let mediumUsed = slotPriorityEffortsUsed[Priority.Medium] ?? 0
991
992            // If it is low priority, return whatever effort is remaining
993            // under the low priority effort limit, subtracting the currently used effort for low priority
994            if priority == Priority.Low {
995                let highPlusMediumUsed = highUsed + mediumUsed
996                let totalEffortRemaining = self.config.slotTotalEffortLimit.saturatingSubtract(highPlusMediumUsed)
997                let lowEffortRemaining = totalEffortRemaining < priorityLimit ? totalEffortRemaining : priorityLimit
998                let lowUsed = slotPriorityEffortsUsed[Priority.Low] ?? 0
999                return lowEffortRemaining.saturatingSubtract(lowUsed)
1000            }
1001            
1002            // Get how much shared effort has been used for each priority
1003            // Ensure the results are always zero or positive
1004            let highSharedUsed: UInt64 = highUsed.saturatingSubtract(highReserve)
1005            let mediumSharedUsed: UInt64 = mediumUsed.saturatingSubtract(mediumReserve)
1006
1007            // Get the theoretical total shared amount between priorities
1008            let totalShared = (self.config.slotTotalEffortLimit.saturatingSubtract(highReserve)).saturatingSubtract(mediumReserve)
1009
1010            // Get the amount of shared effort currently available
1011            let highPlusMediumSharedUsed = highSharedUsed + mediumSharedUsed
1012            // prevent underflow
1013            let sharedAvailable = totalShared.saturatingSubtract(highPlusMediumSharedUsed)
1014
1015            // we calculate available by calculating available shared effort and 
1016            // adding any unused reserves for that priority
1017            let reserve = self.config.priorityEffortReserve[priority]!
1018            let used = slotPriorityEffortsUsed[priority] ?? 0
1019            let unusedReserve: UInt64 = reserve.saturatingSubtract(used)
1020            let available = sharedAvailable + unusedReserve
1021            
1022            return available
1023        }
1024
1025         /// add transaction to the queue and updates all the internal state as well as emit an event
1026        access(self) fun addTransaction(slot: UFix64, txData: TransactionData) {
1027
1028            // If nothing is in the queue for this slot, initialize the slot
1029            if self.slotQueue[slot] == nil {
1030                self.slotQueue[slot] = {}
1031
1032                // This also means that the used effort record for this slot has not been initialized
1033                self.slotUsedEffort[slot] = {
1034                    Priority.High: 0,
1035                    Priority.Medium: 0,
1036                    Priority.Low: 0
1037                }
1038
1039                self.sortedTimestamps.add(timestamp: slot)
1040            }
1041
1042            // Add this transaction id to the slot
1043            let slotQueue = self.slotQueue[slot]!
1044            if let priorityQueue = slotQueue[txData.priority] {
1045                priorityQueue[txData.id] = txData.executionEffort
1046                slotQueue[txData.priority] = priorityQueue
1047            } else {
1048                slotQueue[txData.priority] = {
1049                    txData.id: txData.executionEffort
1050                }
1051            }
1052
1053            self.slotQueue[slot] = slotQueue
1054
1055            // Add the execution effort for this transaction to the total for the slot's priority
1056            let slotEfforts = self.slotUsedEffort[slot]!
1057            var newPriorityEffort = slotEfforts[txData.priority]! + txData.executionEffort
1058            slotEfforts[txData.priority] = newPriorityEffort
1059            var newTotalEffort: UInt64 = 0
1060            for priority in slotEfforts.keys {
1061                newTotalEffort = newTotalEffort.saturatingAdd(slotEfforts[priority]!)
1062            }
1063            self.slotUsedEffort[slot] = slotEfforts
1064            
1065            // Need to potentially reschedule low priority transactions to make room for the new transaction
1066            // Iterate through them and record which ones to reschedule until the total effort is less than the limit
1067            let lowTransactionsToReschedule: [UInt64] = []
1068            if newTotalEffort > self.config.slotTotalEffortLimit {
1069                let lowPriorityTransactions = slotQueue[Priority.Low]!
1070                for id in lowPriorityTransactions.keys {
1071                    if newTotalEffort <= self.config.slotTotalEffortLimit {
1072                        break
1073                    }
1074                    lowTransactionsToReschedule.append(id)
1075                    newTotalEffort = newTotalEffort.saturatingSubtract(lowPriorityTransactions[id]!)
1076                }
1077            }
1078
1079            // Store the transaction in the transactions map
1080            self.transactions[txData.id] = txData
1081
1082            // Reschedule low priority transactions if needed
1083            self.rescheduleLowPriorityTransactions(slot: slot, transactions: lowTransactionsToReschedule)
1084        }
1085
1086        /// rescheduleLowPriorityTransactions reschedules low priority transactions to make room for a new transaction
1087        /// @param slot: The slot that the transactions are currently scheduled at
1088        /// @param transactions: The transactions to reschedule
1089        access(self) fun rescheduleLowPriorityTransactions(slot: UFix64, transactions: [UInt64]) {
1090            for id in transactions {
1091                let tx = self.borrowTransaction(id: id)
1092                if tx == nil {
1093                    emit CriticalIssue(message: "Invalid ID: \(id) transaction not found while rescheduling low priority transactions")
1094                    continue
1095                }
1096
1097                if tx!.priority != Priority.Low {
1098                    emit CriticalIssue(message: "Invalid Priority: Cannot reschedule transaction with id \(id) because it is not low priority")
1099                    continue
1100                }
1101                
1102                if tx!.scheduledTimestamp != slot {
1103                    emit CriticalIssue(message: "Invalid Timestamp: Cannot reschedule transaction with id \(id) because it is not scheduled at the same slot as the new transaction")
1104                    continue
1105                }
1106
1107                let newTimestamp = self.calculateScheduledTimestamp(
1108                    timestamp: slot + 1.0,
1109                    priority: Priority.Low,
1110                    executionEffort: tx!.executionEffort
1111                )!
1112
1113                let effort = tx!.executionEffort
1114                let transactionData = self.removeTransaction(txData: tx!)
1115
1116                // Subtract the execution effort for this transaction from the slot's priority
1117                let slotEfforts = self.slotUsedEffort[slot]!
1118                slotEfforts[Priority.Low] = slotEfforts[Priority.Low]!.saturatingSubtract(effort)
1119                self.slotUsedEffort[slot] = slotEfforts
1120
1121                // Update the transaction's scheduled timestamp and add it back to the slot queue
1122                transactionData.setScheduledTimestamp(newTimestamp: newTimestamp)
1123                self.addTransaction(slot: newTimestamp, txData: transactionData)
1124            }
1125        }
1126
1127        /// remove the transaction from the slot queue.
1128        access(self) fun removeTransaction(txData: &TransactionData): TransactionData {
1129
1130            let transactionID = txData.id
1131            let slot = txData.scheduledTimestamp
1132            let transactionPriority = txData.priority
1133
1134            // remove transaction object
1135            let transactionObject = self.transactions.remove(key: transactionID)!
1136            
1137            // garbage collect slots 
1138            if let transactionQueue = self.slotQueue[slot] {
1139
1140                if let priorityQueue = transactionQueue[transactionPriority] {
1141                    priorityQueue[transactionID] = nil
1142                    if priorityQueue.keys.length == 0 {
1143                        transactionQueue.remove(key: transactionPriority)
1144                    } else {
1145                        transactionQueue[transactionPriority] = priorityQueue
1146                    }
1147
1148                    self.slotQueue[slot] = transactionQueue
1149                }
1150
1151                // if the slot is now empty remove it from the maps
1152                if transactionQueue.keys.length == 0 {
1153                    self.slotQueue.remove(key: slot)
1154                    self.slotUsedEffort.remove(key: slot)
1155
1156                    self.sortedTimestamps.remove(timestamp: slot)
1157                }
1158            }
1159
1160            return transactionObject
1161        }
1162
1163        /// pendingQueue creates a list of transactions that are ready for execution.
1164        /// For transaction to be ready for execution it must be scheduled.
1165        ///
1166        /// The queue is sorted by timestamp and then by priority (high, medium, low).
1167        /// The queue will contain transactions from all timestamps that are in the past.
1168        /// Low priority transactions will only be added if there is effort available in the slot.  
1169        /// The return value can be empty if there are no transactions ready for execution.
1170        access(Process) fun pendingQueue(): [&TransactionData] {
1171            let currentTimestamp = getCurrentBlock().timestamp
1172            var pendingTransactions: [&TransactionData] = []
1173
1174            // total effort across different timestamps guards collection being over the effort limit
1175            var collectionAvailableEffort = self.config.collectionEffortLimit
1176            var transactionsAvailableCount = self.config.collectionTransactionsLimit
1177
1178            // Collect past timestamps efficiently from sorted array
1179            let pastTimestamps = self.sortedTimestamps.getBefore(current: currentTimestamp)
1180
1181            for timestamp in pastTimestamps {
1182                let transactionPriorities = self.slotQueue[timestamp] ?? {}
1183                var high: [&TransactionData] = []
1184                var medium: [&TransactionData] = []
1185                var low: [&TransactionData] = []
1186
1187                for priority in transactionPriorities.keys {
1188                    let transactionIDs = transactionPriorities[priority] ?? {}
1189                    for id in transactionIDs.keys {
1190                        let tx = self.borrowTransaction(id: id)
1191                        if tx == nil {
1192                            emit CriticalIssue(message: "Invalid ID: \(id) transaction not found while preparing pending queue")
1193                            continue
1194                        }
1195                        
1196                        // Only add scheduled transactions to the queue
1197                        if tx!.status != Status.Scheduled {
1198                            continue
1199                        }
1200
1201                        // this is safeguard to prevent collection growing too large in case of block production slowdown
1202                        if tx!.executionEffort >= collectionAvailableEffort || transactionsAvailableCount == 0 {
1203                            emit CollectionLimitReached(
1204                                collectionEffortLimit: transactionsAvailableCount == 0 ? nil : self.config.collectionEffortLimit,
1205                                collectionTransactionsLimit: transactionsAvailableCount == 0 ? self.config.collectionTransactionsLimit : nil
1206                            )
1207                            break
1208                        }
1209
1210                        collectionAvailableEffort = collectionAvailableEffort.saturatingSubtract(tx!.executionEffort)
1211                        transactionsAvailableCount = transactionsAvailableCount - 1
1212                    
1213                        switch tx!.priority {
1214                            case Priority.High:
1215                                high.append(tx!)
1216                            case Priority.Medium:
1217                                medium.append(tx!)
1218                            case Priority.Low:
1219                                low.append(tx!)
1220                        }
1221                    }
1222                }
1223
1224                pendingTransactions = pendingTransactions
1225                    .concat(high)
1226                    .concat(medium)
1227                    .concat(low)
1228            }
1229
1230            return pendingTransactions
1231        }
1232
1233        /// removeExecutedTransactions removes all transactions that are marked as executed.
1234        access(self) fun removeExecutedTransactions(_ currentTimestamp: UFix64) {
1235            let pastTimestamps = self.sortedTimestamps.getBefore(current: currentTimestamp)
1236            var numRemoved = 0
1237            let removalLimit = self.config.getTxRemovalLimit()
1238
1239            for timestamp in pastTimestamps {
1240                let transactionPriorities = self.slotQueue[timestamp] ?? {}
1241                
1242                for priority in transactionPriorities.keys {
1243                    let transactionIDs = transactionPriorities[priority] ?? {}
1244                    for id in transactionIDs.keys {
1245
1246                        numRemoved = numRemoved + 1
1247
1248                        if UInt(numRemoved) >= removalLimit {
1249                            emit RemovalLimitReached()
1250                            return
1251                        }
1252
1253                        let tx = self.borrowTransaction(id: id)
1254                        if tx == nil {
1255                            emit CriticalIssue(message: "Invalid ID: \(id) transaction not found while removing executed transactions")
1256                            continue
1257                        }
1258
1259                        // Only remove executed transactions
1260                        if tx!.status != Status.Executed {
1261                            continue
1262                        }
1263
1264                        // charge the full fee for transaction execution
1265                        destroy tx!.payAndRefundFees(refundMultiplier: 0.0)
1266
1267                        self.removeTransaction(txData: tx!)
1268                    }
1269                }
1270            }
1271        }
1272
1273        /// process scheduled transactions and prepare them for execution. 
1274        ///
1275        /// First, it removes transactions that have already been executed. 
1276        /// Then, it iterates over past timestamps in the queue and processes the transactions that are 
1277        /// eligible for execution. It also emits an event for each transaction that is processed.
1278        ///
1279        /// This function is only called by the FVM to process transactions.
1280        access(Process) fun process() {
1281            let currentTimestamp = getCurrentBlock().timestamp
1282            // Early exit if no timestamps need processing
1283            if !self.sortedTimestamps.hasBefore(current: currentTimestamp) {
1284                return
1285            }
1286
1287            self.removeExecutedTransactions(currentTimestamp)
1288
1289            let pendingTransactions = self.pendingQueue()
1290
1291            for tx in pendingTransactions {
1292                // Only emit the pending execution event if the transaction handler capability is borrowable
1293                // This is to prevent a situation where the transaction handler is not available
1294                // In that case, the transaction is no longer valid because it cannot be executed
1295                if let transactionHandler = tx.handler.borrow() {
1296                    emit PendingExecution(
1297                        id: tx.id,
1298                        priority: tx.priority.rawValue,
1299                        executionEffort: tx.executionEffort,
1300                        fees: tx.fees,
1301                        transactionHandlerOwner: tx.handler.address,
1302                        transactionHandlerTypeIdentifier: transactionHandler.getType().identifier
1303                    )
1304                }
1305
1306                // after pending execution event is emitted we set the transaction as executed because we 
1307                // must rely on execution node to actually execute it. Execution of the transaction is 
1308                // done in a separate transaction that calls executeTransaction(id) function.
1309                // Executing the transaction can not update the status of transaction or any other shared state,
1310                // since that blocks concurrent transaction execution.
1311                // Therefore an optimistic update to executed is made here to avoid race condition.
1312                tx.setStatus(newStatus: Status.Executed)
1313            }
1314        }
1315
1316        /// cancel a scheduled transaction and return a portion of the fees that were paid.
1317        ///
1318        /// @param id: The ID of the transaction to cancel
1319        /// @return: The fees to be returned to the caller
1320        access(Cancel) fun cancel(id: UInt64): @FlowToken.Vault {
1321            let tx = self.borrowTransaction(id: id) ?? 
1322                panic("Invalid ID: \(id) transaction not found")
1323
1324            assert(
1325                tx.status == Status.Scheduled,
1326                message: "Transaction must be in a scheduled state in order to be canceled"
1327            )
1328            
1329            // Subtract the execution effort for this transaction from the slot's priority
1330            let slotEfforts = self.slotUsedEffort[tx.scheduledTimestamp]!
1331            slotEfforts[tx.priority] = slotEfforts[tx.priority]!.saturatingSubtract(tx.executionEffort)
1332            self.slotUsedEffort[tx.scheduledTimestamp] = slotEfforts
1333
1334            let totalFees = tx.fees
1335            let refundedFees <- tx.payAndRefundFees(refundMultiplier: self.config.refundMultiplier)
1336
1337            // if the transaction was canceled, add it to the canceled transactions array
1338            // maintain sorted order by inserting at the correct position
1339            var insertIndex = 0
1340            for i, canceledID in self.canceledTransactions {
1341                if id < canceledID {
1342                    insertIndex = i
1343                    break
1344                }
1345                insertIndex = i + 1
1346            }
1347            self.canceledTransactions.insert(at: insertIndex, id)
1348            
1349            // keep the array under the limit
1350            if UInt(self.canceledTransactions.length) > self.config.canceledTransactionsLimit {
1351                self.canceledTransactions.remove(at: 0)
1352            }
1353
1354            emit Canceled(
1355                id: tx.id,
1356                priority: tx.priority.rawValue,
1357                feesReturned: refundedFees.balance,
1358                feesDeducted: totalFees - refundedFees.balance,
1359                transactionHandlerOwner: tx.handler.address,
1360                transactionHandlerTypeIdentifier: tx.handlerTypeIdentifier
1361            )
1362
1363            self.removeTransaction(txData: tx)
1364            
1365            return <-refundedFees
1366        }
1367
1368        /// execute transaction is a system function that is called by FVM to execute a transaction by ID.
1369        /// The transaction must be found and in correct state or the function panics and this is a fatal error
1370        ///
1371        /// This function is only called by the FVM to execute transactions.
1372        /// WARNING: this function should not change any shared state, it will be run concurrently and it must not be blocking.
1373        access(Execute) fun executeTransaction(id: UInt64) {
1374            let tx = self.borrowTransaction(id: id) ?? 
1375                panic("Invalid ID: Transaction with id \(id) not found")
1376
1377            assert (
1378                tx.status == Status.Executed,
1379                message: "Invalid ID: Cannot execute transaction with id \(id) because it has incorrect status \(tx.status.rawValue)"
1380            )
1381
1382            let transactionHandler = tx.handler.borrow()
1383                ?? panic("Invalid transaction handler: Could not borrow a reference to the transaction handler")
1384
1385            let handlerPublicPath = transactionHandler.resolveView(Type<PublicPath>()) as? PublicPath
1386
1387            emit Executed(
1388                id: tx.id,
1389                priority: tx.priority.rawValue,
1390                executionEffort: tx.executionEffort,
1391                transactionHandlerOwner: tx.handler.address,
1392                transactionHandlerTypeIdentifier: transactionHandler.getType().identifier,
1393                transactionHandlerUUID: transactionHandler.uuid,
1394                transactionHandlerPublicPath: handlerPublicPath
1395
1396            )
1397            
1398            transactionHandler.executeTransaction(id: id, data: tx.getData())
1399        }
1400    }
1401    
1402    /// Deposit fees to this contract's account's vault
1403    access(contract) fun depositFees(from: @FlowToken.Vault) {
1404        let vaultRef = self.account.storage.borrow<&FlowToken.Vault>(from: /storage/flowTokenVault)
1405            ?? panic("Unable to borrow reference to the default token vault")
1406        vaultRef.deposit(from: <-from)
1407    }
1408
1409    /// Withdraw fees from this contract's account's vault
1410    access(contract) fun withdrawFees(amount: UFix64): @FlowToken.Vault {
1411        let vaultRef = self.account.storage.borrow<auth(FungibleToken.Withdraw) &FlowToken.Vault>(from: /storage/flowTokenVault)
1412            ?? panic("Unable to borrow reference to the default token vault")
1413            
1414        return <-vaultRef.withdraw(amount: amount) as! @FlowToken.Vault
1415    }
1416
1417    access(all) fun schedule(
1418        handlerCap: Capability<auth(Execute) &{TransactionHandler}>,
1419        data: AnyStruct?,
1420        timestamp: UFix64,
1421        priority: Priority,
1422        executionEffort: UInt64,
1423        fees: @FlowToken.Vault
1424    ): @ScheduledTransaction {
1425        return <-self.sharedScheduler.borrow()!.schedule(
1426            handlerCap: handlerCap, 
1427            data: data, 
1428            timestamp: timestamp, 
1429            priority: priority, 
1430            executionEffort: executionEffort, 
1431            fees: <-fees
1432        )
1433    }
1434
1435    access(all) fun estimate(
1436        data: AnyStruct?,
1437        timestamp: UFix64,
1438        priority: Priority,
1439        executionEffort: UInt64
1440    ): EstimatedScheduledTransaction {
1441        return self.sharedScheduler.borrow()!
1442            .estimate(
1443                data: data, 
1444                timestamp: timestamp, 
1445                priority: priority, 
1446                executionEffort: executionEffort,
1447            )
1448    }
1449
1450    access(all) fun cancel(scheduledTx: @ScheduledTransaction): @FlowToken.Vault {
1451        let id = scheduledTx.id
1452        destroy scheduledTx
1453        return <-self.sharedScheduler.borrow()!.cancel(id: id)
1454    }
1455
1456    /// getTransactionData returns the transaction data for a given ID
1457    /// This function can only get the data for a transaction that is currently scheduled or pending execution
1458    /// because finalized transaction metadata is not stored in the contract
1459    /// @param id: The ID of the transaction to get the data for
1460    /// @return: The transaction data for the given ID
1461    access(all) view fun getTransactionData(id: UInt64): TransactionData? {
1462        return self.sharedScheduler.borrow()!.getTransaction(id: id)
1463    }
1464
1465    /// borrowHandlerForID returns an un-entitled reference to the transaction handler for a given ID
1466    /// The handler reference can be used to resolve views to get info about the handler and see where it is stored
1467    /// @param id: The ID of the transaction to get the handler for
1468    /// @return: An un-entitled reference to the transaction handler for the given ID
1469    access(all) view fun borrowHandlerForID(_ id: UInt64): &{TransactionHandler}? {
1470        return self.getTransactionData(id: id)?.borrowHandler()
1471    }
1472
1473    /// getCanceledTransactions returns the IDs of the transactions that have been canceled
1474    /// @return: The IDs of the transactions that have been canceled
1475    access(all) view fun getCanceledTransactions(): [UInt64] {
1476        return self.sharedScheduler.borrow()!.getCanceledTransactions()
1477    }
1478
1479
1480    access(all) view fun getStatus(id: UInt64): Status? {
1481        return self.sharedScheduler.borrow()!.getStatus(id: id)
1482    }
1483
1484    /// getTransactionsForTimeframe returns the IDs of the transactions that are scheduled for a given timeframe
1485    /// @param startTimestamp: The start timestamp to get the IDs for
1486    /// @param endTimestamp: The end timestamp to get the IDs for
1487    /// @return: The IDs of the transactions that are scheduled for the given timeframe
1488    access(all) fun getTransactionsForTimeframe(startTimestamp: UFix64, endTimestamp: UFix64): {UFix64: {UInt8: [UInt64]}} {
1489        return self.sharedScheduler.borrow()!.getTransactionsForTimeframe(startTimestamp: startTimestamp, endTimestamp: endTimestamp)
1490    }
1491
1492    access(all) view fun getSlotAvailableEffort(timestamp: UFix64, priority: Priority): UInt64 {
1493        return self.sharedScheduler.borrow()!.getSlotAvailableEffort(timestamp: timestamp, priority: priority)
1494    }
1495
1496    access(all) fun getConfig(): {SchedulerConfig} {
1497        return self.sharedScheduler.borrow()!.getConfig()
1498    }
1499    
1500    /// getSizeOfData takes a transaction's data
1501    /// argument and stores it in the contract account's storage, 
1502    /// checking storage used before and after to see how large the data is in MB
1503    /// If data is nil, the function returns 0.0
1504    access(all) fun getSizeOfData(_ data: AnyStruct?): UFix64 {
1505        if data == nil {
1506            return 0.0
1507        } else {
1508            let type = data!.getType()
1509            if type.isSubtype(of: Type<Number>()) 
1510            || type.isSubtype(of: Type<Bool>()) 
1511            || type.isSubtype(of: Type<Address>())
1512            || type.isSubtype(of: Type<Character>())
1513            || type.isSubtype(of: Type<Capability>())
1514            {
1515                return 0.0
1516            }
1517        }
1518        let storagePath = /storage/dataTemp
1519        let storageUsedBefore = self.account.storage.used
1520        self.account.storage.save(data!, to: storagePath)
1521        let storageUsedAfter = self.account.storage.used
1522        self.account.storage.load<AnyStruct>(from: storagePath)
1523
1524        return FlowStorageFees.convertUInt64StorageBytesToUFix64Megabytes(storageUsedAfter.saturatingSubtract(storageUsedBefore))
1525    }
1526
1527    access(all) init() {
1528        self.storagePath = /storage/sharedScheduler
1529        let scheduler <- create SharedScheduler()
1530        let oldScheduler <- self.account.storage.load<@AnyResource>(from: self.storagePath)
1531        destroy oldScheduler
1532        self.account.storage.save(<-scheduler, to: self.storagePath)
1533        
1534        self.sharedScheduler = self.account.capabilities.storage
1535            .issue<auth(Cancel) &SharedScheduler>(self.storagePath)
1536    }
1537}