Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 51 additions & 28 deletions contracts/FlowCallbackScheduler.cdc
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import "FungibleToken"
import "FlowToken"
import "FlowFees"
import "FlowStorageFees"
import "ViewResolver"

/// FlowCallbackScheduler enables smart contracts to schedule autonomous execution in the future.
///
Expand Down Expand Up @@ -120,7 +121,7 @@ access(all) contract FlowCallbackScheduler {
/// must be implemented by the resource that contains the logic to be executed by the callback.
/// An authorized capability to this resource is provided when scheduling a callback.
/// The callback scheduler uses this capability to execute the callback when its scheduled timestamp arrives.
access(all) resource interface CallbackHandler {
access(all) resource interface CallbackHandler: ViewResolver.Resolver {

/// Human readable name for the callback handler
access(all) let name: String
Expand Down Expand Up @@ -164,6 +165,9 @@ access(all) contract FlowCallbackScheduler {
self.id = id
self.timestamp = timestamp
}

// event emitted when the resource is destroyed
access(all) event ResourceDestroyed(id: UInt64 = self.id, timestamp: UFix64 = self.timestamp)
}

/// Estimated callback contains data for estimating callback scheduling.
Expand Down Expand Up @@ -203,6 +207,10 @@ access(all) contract FlowCallbackScheduler {
/// Capability to the logic that the callback will execute
access(contract) let handler: Capability<auth(Execute) &{CallbackHandler}>

/// Type identifier of the callback handler
access(all) let handlerTypeIdentifier: String
access(all) let handlerAddress: Address

/// Optional data that can be passed to the handler
access(contract) let data: AnyStruct?

Expand All @@ -221,14 +229,16 @@ access(all) contract FlowCallbackScheduler {
) {
self.id = id
self.handler = handler
self.scheduledTimestamp = scheduledTimestamp
self.data = data
self.priority = priority
self.executionEffort = executionEffort
self.fees = fees
self.status = Status.Scheduled
let handlerRef = handler.borrow()
?? panic("Invalid callback handler: Could not borrow a reference to the callback handler")
self.handlerAddress = handler.address
self.handlerTypeIdentifier = handlerRef.getType().identifier
self.scheduledTimestamp = scheduledTimestamp
self.name = handlerRef.name
self.description = handlerRef.description
}
Expand Down Expand Up @@ -1224,19 +1234,21 @@ access(all) contract FlowCallbackScheduler {
}

for callback in pendingCallbacks {
let callbackHandler = callback.handler.borrow()
?? panic("Invalid callback handler: Could not borrow a reference to the callback handler")

emit PendingExecution(
id: callback.id,
priority: callback.priority.rawValue,
executionEffort: callback.executionEffort,
fees: callback.fees,
callbackOwner: callback.handler.address,
callbackHandlerTypeIdentifier: callbackHandler.getType().identifier,
callbackName: callbackHandler.name,
callbackDescription: callbackHandler.description
)
// Only emit the pending execution event if the callback handler capability is borrowable
// This is to prevent a situation where the callback handler is not available
// In that case, the callback is no longer valid because it cannot be executed
if let callbackHandler = callback.handler.borrow() {
emit PendingExecution(
id: callback.id,
priority: callback.priority.rawValue,
executionEffort: callback.executionEffort,
fees: callback.fees,
callbackOwner: callback.handler.address,
callbackHandlerTypeIdentifier: callbackHandler.getType().identifier,
callbackName: callbackHandler.name,
callbackDescription: callbackHandler.description
)
}

// after pending execution event is emitted we set the callback as executed because we
// must rely on execution node to actually execute it. Execution of the callback is
Expand Down Expand Up @@ -1276,19 +1288,30 @@ access(all) contract FlowCallbackScheduler {
self.canceledCallbacks.remove(at: 0)
}

let callbackHandler = callback.handler.borrow()
?? panic("Invalid callback handler: Could not borrow a reference to the callback handler")

emit Canceled(
id: callback.id,
priority: callback.priority.rawValue,
feesReturned: refundedFees.balance,
feesDeducted: totalFees - refundedFees.balance,
callbackOwner: callback.handler.address,
callbackHandlerTypeIdentifier: callbackHandler.getType().identifier,
callbackName: callbackHandler.name,
callbackDescription: callbackHandler.description
)
if let callbackHandler = callback.handler.borrow() {
emit Canceled(
id: callback.id,
priority: callback.priority.rawValue,
feesReturned: refundedFees.balance,
feesDeducted: totalFees - refundedFees.balance,
callbackOwner: callback.handler.address,
callbackHandlerTypeIdentifier: callbackHandler.getType().identifier,
callbackName: callbackHandler.name,
callbackDescription: callbackHandler.description
)
} else {
// if the callback handler is not borrowable, emit a cancel event with empty values
emit Canceled(
id: callback.id,
priority: callback.priority.rawValue,
feesReturned: refundedFees.balance,
feesDeducted: totalFees - refundedFees.balance,
callbackOwner: 0x0000000000000000, // invalid address
callbackHandlerTypeIdentifier: "",
callbackName: "",
callbackDescription: ""
)
}

self.removeCallback(callback: callback)

Expand Down
132 changes: 132 additions & 0 deletions contracts/FlowCallbackUtils.cdc
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
import "FlowCallbackScheduler"
import "FlowToken"

access(all) contract FlowCallbackUtils {

/// Storage path for CallbackManager resources
access(all) let managerStoragePath: StoragePath

/// Public path for CallbackManager resources
access(all) let managerPublicPath: PublicPath

/// Entitlements
access(all) entitlement Owner

/// CallbackManager resource that stores ScheduledCallback resources in a dictionary
/// and provides convenience methods for scheduling and canceling callbacks
access(all) resource CallbackManager {
/// Dictionary storing scheduled callbacks by their ID
access(self) var scheduledCallbacks: @{UInt64: FlowCallbackScheduler.ScheduledCallback}

init() {
self.scheduledCallbacks <- {}
}

/// Schedule a callback and store it in the manager's dictionary
/// @param callback: A capability to a resource that implements the CallbackHandler interface
/// @param data: Optional data to pass to the callback when executed
/// @param timestamp: The timestamp when the callback should be executed
/// @param priority: The priority of the callback (High, Medium, or Low)
/// @param executionEffort: The execution effort for the callback
/// @param fees: A FlowToken vault containing sufficient fees
/// @return: The scheduled callback resource
access(Owner) fun schedule(
callback: Capability<auth(FlowCallbackScheduler.Execute) &{FlowCallbackScheduler.CallbackHandler}>,
data: AnyStruct?,
timestamp: UFix64,
priority: FlowCallbackScheduler.Priority,
executionEffort: UInt64,
fees: @FlowToken.Vault
) {
// Clean up any invalid callbacks before scheduling a new one
self.cleanup()

// Route to the main FlowCallbackScheduler
let scheduledCallback <- FlowCallbackScheduler.schedule(
callback: callback,
data: data,
timestamp: timestamp,
priority: priority,
executionEffort: executionEffort,
fees: <-fees
)

// Store the callback in our dictionary
self.scheduledCallbacks[scheduledCallback.id] <-! scheduledCallback
}

/// Cancel a scheduled callback by its ID
/// @param id: The ID of the callback to cancel
/// @return: A FlowToken vault containing the refunded fees
access(Owner) fun cancel(id: UInt64): @FlowToken.Vault {
// Remove the callback from our dictionary
let callback <- self.scheduledCallbacks.remove(key: id)
?? panic("Invalid ID: Callback with ID \(id) not found in manager")

// Cancel the callback through the main scheduler
let refundedFees <- FlowCallbackScheduler.cancel(callback: <-callback!)

return <-refundedFees
}

/// Clean up callbacks that are no longer valid (return nil or Unknown status)
/// This removes and destroys callbacks that have been executed, canceled, or are otherwise invalid
/// @return: The number of callbacks that were cleaned up
access(Owner) fun cleanup(): Int {
var cleanedUpCount = 0
var callbacksToRemove: [UInt64] = []

// First, identify callbacks that need to be removed
for id in self.scheduledCallbacks.keys {
let status = FlowCallbackScheduler.getStatus(id: id)
if status == nil || status == FlowCallbackScheduler.Status.Unknown {
callbacksToRemove.append(id)
}
}

// Then remove and destroy the identified callbacks
for id in callbacksToRemove {
if let callback <- self.scheduledCallbacks.remove(key: id) {
destroy callback
cleanedUpCount = cleanedUpCount + 1
}
}

return cleanedUpCount
}

/// Get callback data by its ID
/// @param id: The ID of the callback to retrieve
/// @return: The callback data from FlowCallbackScheduler, or nil if not found
access(all) fun getCallbackData(id: UInt64): FlowCallbackScheduler.CallbackData? {
return FlowCallbackScheduler.getCallbackData(id: id)
}

/// Get all callback IDs stored in the manager
/// @return: An array of all callback IDs
access(all) fun getCallbackIDs(): [UInt64] {
return self.scheduledCallbacks.keys
}

/// Get the status of a callback by its ID
/// @param id: The ID of the callback
/// @return: The status of the callback, or Status.Unknown if not found in manager
access(all) fun getCallbackStatus(id: UInt64): FlowCallbackScheduler.Status? {
if self.scheduledCallbacks.containsKey(id) {
return FlowCallbackScheduler.getStatus(id: id)
}
return FlowCallbackScheduler.Status.Unknown
}
}

/// Create a new CallbackManager instance
/// @return: A new CallbackManager resource
access(all) fun createCallbackManager(): @CallbackManager {
return <-create CallbackManager()
}

access(all) init() {
self.managerStoragePath = /storage/flowCallbackManager
self.managerPublicPath = /public/flowCallbackManager
}
}
43 changes: 26 additions & 17 deletions contracts/testContracts/TestFlowCallbackHandler.cdc
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import "FlowCallbackScheduler"
import "FlowCallbackUtils"
import "FlowToken"
import "FungibleToken"

// TestFlowCallbackHandler is a simplified test contract for testing CallbackScheduler
access(all) contract TestFlowCallbackHandler {
access(all) var scheduledCallbacks: @{UInt64: FlowCallbackScheduler.ScheduledCallback}
access(all) var succeededCallbacks: [UInt64]

access(all) let HandlerStoragePath: StoragePath
Expand All @@ -19,6 +19,14 @@ access(all) contract TestFlowCallbackHandler {
self.name = name
self.description = description
}

access(all) view fun getViews(): [Type] {
return []
}

access(all) fun resolveView(_ view: Type): AnyStruct? {
return nil
}

access(FlowCallbackScheduler.Execute)
fun executeCallback(id: UInt64, data: AnyStruct?) {
Expand All @@ -28,23 +36,24 @@ access(all) contract TestFlowCallbackHandler {
if dataString == "fail" {
panic("Callback \(id) failed")
} else if dataString == "cancel" {
let manager = TestFlowCallbackHandler.borrowManager()
// This should always fail because the callback can't cancel itself during execution
destroy <-TestFlowCallbackHandler.cancelCallback(id: id)
destroy <-manager.cancel(id: id)
} else {
// All other regular test cases should succeed
TestFlowCallbackHandler.succeededCallbacks.append(id)
}
} else if let dataCap = data as? Capability<auth(FlowCallbackScheduler.Execute) &{FlowCallbackScheduler.CallbackHandler}> {
// Testing scheduling a callback with a callback
let scheduledCallback <- FlowCallbackScheduler.schedule(
let manager = TestFlowCallbackHandler.borrowManager()
manager.schedule(
callback: dataCap,
data: "test data",
timestamp: getCurrentBlock().timestamp + 10.0,
priority: FlowCallbackScheduler.Priority.High,
executionEffort: UInt64(1000),
fees: <-TestFlowCallbackHandler.getFeeFromVault(amount: 1.0)
)
TestFlowCallbackHandler.addScheduledCallback(callback: <-scheduledCallback)
} else {
panic("TestFlowCallbackHandler.executeCallback: Invalid data type for callback with id \(id). Type is \(data.getType().identifier)")
}
Expand All @@ -55,22 +64,23 @@ access(all) contract TestFlowCallbackHandler {
return <- create Handler(name: "Test FlowCallbackHandler Resource", description: "Executes a variety of callbacks for different test cases")
}

access(all) fun addScheduledCallback(callback: @FlowCallbackScheduler.ScheduledCallback) {
let status = callback.status()
if status == nil {
panic("Invalid status for callback with id \(callback.id)")
}
self.scheduledCallbacks[callback.id] <-! callback
access(all) fun getSucceededCallbacks(): [UInt64] {
return self.succeededCallbacks
}

access(all) fun cancelCallback(id: UInt64): @FlowToken.Vault {
let callback <- self.scheduledCallbacks.remove(key: id)
?? panic("Invalid ID: \(id) callback not found")
return <-FlowCallbackScheduler.cancel(callback: <-callback!)
access(all) fun borrowManager(): auth(FlowCallbackUtils.Owner) &FlowCallbackUtils.CallbackManager {
return self.account.storage.borrow<auth(FlowCallbackUtils.Owner) &FlowCallbackUtils.CallbackManager>(from: FlowCallbackUtils.managerStoragePath)
?? panic("Callback manager not set")
}

access(all) fun getSucceededCallbacks(): [UInt64] {
return self.succeededCallbacks
access(all) fun getCallbackIDs(): [UInt64] {
let manager = self.borrowManager()
return manager.getCallbackIDs()
}

access(all) fun getCallbackStatus(id: UInt64): FlowCallbackScheduler.Status? {
let manager = self.borrowManager()
return manager.getCallbackStatus(id: id)
}

access(contract) fun getFeeFromVault(amount: UFix64): @FlowToken.Vault {
Expand All @@ -82,7 +92,6 @@ access(all) contract TestFlowCallbackHandler {
}

access(all) init() {
self.scheduledCallbacks <- {}
self.succeededCallbacks = []

self.HandlerStoragePath = /storage/testCallbackHandler
Expand Down
4 changes: 2 additions & 2 deletions flow.json
Original file line number Diff line number Diff line change
Expand Up @@ -172,8 +172,8 @@
"testing": "0000000000000001"
}
},
"TestFlowCallbackQueue": {
"source": "./contracts/testContracts/TestFlowCallbackQueue.cdc",
"FlowCallbackUtils": {
"source": "./contracts/FlowCallbackUtils.cdc",
"aliases": {
"emulator": "f8d6e0586b0a20c7",
"testing": "0000000000000001"
Expand Down
Loading
Loading