-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDCAHandlerEVMV4.cdc
More file actions
273 lines (228 loc) · 11.2 KB
/
DCAHandlerEVMV4.cdc
File metadata and controls
273 lines (228 loc) · 11.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
import FlowTransactionScheduler from "FlowTransactionScheduler"
import FlowTransactionSchedulerUtils from "FlowTransactionSchedulerUtils"
import FlowToken from "FlowToken"
import FungibleToken from "FungibleToken"
import FlowFees from "FlowFees"
import FlowStorageFees from "FlowStorageFees"
import DCAServiceEVM from "DCAServiceEVM"
/// DCAHandlerEVMV4: Autonomous Scheduled Transaction Handler for EVM-Native DCA
///
/// This version follows the official scaffold pattern (CounterLoopTransactionHandler):
/// - Capabilities are passed IN the TransactionData struct (LoopConfig pattern)
/// - Handler does NOT store capabilities internally
/// - Uses Manager.scheduleByHandler() for autonomous rescheduling
///
/// Key Difference from V3:
/// V3 stored capabilities in the Handler resource and issued new caps each time.
/// V4 passes capabilities through TransactionData, allowing proper serialization
/// and retrieval via getControllers().
///
access(all) contract DCAHandlerEVMV4 {
// ============================================================
// Events
// ============================================================
access(all) event HandlerCreated(uuid: UInt64)
access(all) event ExecutionTriggered(planId: UInt64, success: Bool, nextScheduled: Bool)
access(all) event ExecutionSkipped(planId: UInt64, reason: String)
access(all) event NextExecutionScheduled(planId: UInt64, scheduledId: UInt64, timestamp: UFix64)
access(all) event NextExecutionSchedulingFailed(planId: UInt64, reason: String)
// ============================================================
// Storage Paths
// ============================================================
access(all) let HandlerStoragePath: StoragePath
access(all) let HandlerPublicPath: PublicPath
// ============================================================
// LoopConfig: Scheduling configuration passed in TransactionData
// ============================================================
/// Following the scaffold's LoopConfig pattern:
/// Capabilities are passed IN the data, not stored in handler.
access(all) struct LoopConfig {
/// Capability to the Manager for scheduling next transactions
access(all) let schedulerManagerCap: Capability<auth(FlowTransactionSchedulerUtils.Owner) &{FlowTransactionSchedulerUtils.Manager}>
/// Capability to withdraw FLOW for scheduling fees
access(all) let feeProviderCap: Capability<auth(FungibleToken.Withdraw) &FlowToken.Vault>
/// Transaction priority
access(all) let priority: FlowTransactionScheduler.Priority
/// Execution effort (compute limit)
access(all) let executionEffort: UInt64
init(
schedulerManagerCap: Capability<auth(FlowTransactionSchedulerUtils.Owner) &{FlowTransactionSchedulerUtils.Manager}>,
feeProviderCap: Capability<auth(FungibleToken.Withdraw) &FlowToken.Vault>,
priority: FlowTransactionScheduler.Priority,
executionEffort: UInt64
) {
self.schedulerManagerCap = schedulerManagerCap
self.feeProviderCap = feeProviderCap
self.priority = priority
self.executionEffort = executionEffort
}
}
// ============================================================
// TransactionData: Carries plan ID + LoopConfig for rescheduling
// ============================================================
access(all) struct TransactionData {
access(all) let planId: UInt64
access(all) let loopConfig: LoopConfig
init(planId: UInt64, loopConfig: LoopConfig) {
self.planId = planId
self.loopConfig = loopConfig
}
}
// ============================================================
// Handler Resource
// ============================================================
/// Handler resource that implements TransactionHandler interface.
/// Does NOT store capabilities - they come from TransactionData.
access(all) resource Handler: FlowTransactionScheduler.TransactionHandler {
/// Main execution entrypoint called by FlowTransactionScheduler
access(FlowTransactionScheduler.Execute)
fun executeTransaction(id: UInt64, data: AnyStruct?) {
// Parse transaction data
let txData = data as? TransactionData
if txData == nil {
log("DCAHandlerEVMV4: Invalid transaction data")
return
}
let planId = txData!.planId
let loopConfig = txData!.loopConfig
// Get plan details
let planOpt = DCAServiceEVM.getPlan(planId: planId)
if planOpt == nil {
emit ExecutionSkipped(planId: planId, reason: "Plan not found")
return
}
let plan = planOpt!
// Check if plan is active
if plan.getStatus() != DCAServiceEVM.PlanStatus.Active {
emit ExecutionSkipped(planId: planId, reason: "Plan not active")
return
}
// Execute the DCA plan via DCAServiceEVM
let success = DCAServiceEVM.executePlan(planId: planId)
// If successful and plan still active, schedule next execution
var nextScheduled = false
if success {
// Re-fetch plan to get updated nextExecutionTime
let updatedPlanOpt = DCAServiceEVM.getPlan(planId: planId)
if updatedPlanOpt != nil {
let updatedPlan = updatedPlanOpt!
// Only reschedule if plan is still active
if updatedPlan.getStatus() == DCAServiceEVM.PlanStatus.Active {
nextScheduled = self.scheduleNextExecution(
planId: planId,
nextExecutionTime: updatedPlan.nextExecutionTime,
loopConfig: loopConfig
)
}
}
}
emit ExecutionTriggered(planId: planId, success: success, nextScheduled: nextScheduled)
}
/// Schedule the next execution using capabilities from LoopConfig
access(self) fun scheduleNextExecution(
planId: UInt64,
nextExecutionTime: UFix64?,
loopConfig: LoopConfig
): Bool {
// Verify nextExecutionTime is provided
if nextExecutionTime == nil {
emit NextExecutionSchedulingFailed(planId: planId, reason: "Next execution time not set")
return false
}
// Prepare next transaction data (pass same loopConfig for chaining)
let nextTxData = TransactionData(planId: planId, loopConfig: loopConfig)
// Calculate fees manually (more reliable for Low priority than estimate())
// This pattern is from flow-dca repo which successfully uses Low priority
let baseFee = FlowFees.computeFees(
inclusionEffort: 1.0,
executionEffort: UFix64(loopConfig.executionEffort) / 100000000.0
)
// Scale by priority multiplier from scheduler config
let priorityMultipliers = FlowTransactionScheduler.getConfig().priorityFeeMultipliers
let scaledExecutionFee = baseFee * priorityMultipliers[loopConfig.priority]!
// Estimate storage fee (data is small, ~1KB)
let dataSizeMB = 0.001
let storageFee = FlowStorageFees.storageCapacityToFlow(dataSizeMB)
// Total fee with inclusion fee
let feeEstimate = scaledExecutionFee + storageFee + 0.00001
// Apply 5% buffer, cap at 10.0 FLOW
var feeWithBuffer = feeEstimate * 1.05
if feeWithBuffer > 10.0 {
feeWithBuffer = 10.0
}
// Borrow fee vault from capability
let feeVault = loopConfig.feeProviderCap.borrow()
if feeVault == nil {
emit NextExecutionSchedulingFailed(planId: planId, reason: "Could not borrow fee vault")
return false
}
// Check balance
if feeVault!.balance < feeWithBuffer {
emit NextExecutionSchedulingFailed(
planId: planId,
reason: "Insufficient fees. Required: ".concat(feeWithBuffer.toString()).concat(" Available: ").concat(feeVault!.balance.toString())
)
return false
}
// Withdraw fees
let fees <- feeVault!.withdraw(amount: feeWithBuffer)
// Borrow scheduler manager from capability
let schedulerManager = loopConfig.schedulerManagerCap.borrow()
if schedulerManager == nil {
// Return fees if we can't schedule
feeVault!.deposit(from: <-fees)
emit NextExecutionSchedulingFailed(planId: planId, reason: "Could not borrow scheduler manager")
return false
}
// Schedule next execution using Manager.scheduleByHandler()
// This is the key pattern from the scaffold
let scheduledId = schedulerManager!.scheduleByHandler(
handlerTypeIdentifier: self.getType().identifier,
handlerUUID: self.uuid,
data: nextTxData,
timestamp: nextExecutionTime!,
priority: loopConfig.priority,
executionEffort: loopConfig.executionEffort,
fees: <-fees as! @FlowToken.Vault
)
if scheduledId == 0 {
emit NextExecutionSchedulingFailed(planId: planId, reason: "scheduleByHandler returned 0")
return false
}
emit NextExecutionScheduled(planId: planId, scheduledId: scheduledId, timestamp: nextExecutionTime!)
return true
}
init() {
emit HandlerCreated(uuid: self.uuid)
}
}
// ============================================================
// Factory Functions
// ============================================================
access(all) fun createHandler(): @Handler {
return <- create Handler()
}
access(all) fun createLoopConfig(
schedulerManagerCap: Capability<auth(FlowTransactionSchedulerUtils.Owner) &{FlowTransactionSchedulerUtils.Manager}>,
feeProviderCap: Capability<auth(FungibleToken.Withdraw) &FlowToken.Vault>,
priority: FlowTransactionScheduler.Priority,
executionEffort: UInt64
): LoopConfig {
return LoopConfig(
schedulerManagerCap: schedulerManagerCap,
feeProviderCap: feeProviderCap,
priority: priority,
executionEffort: executionEffort
)
}
access(all) fun createTransactionData(planId: UInt64, loopConfig: LoopConfig): TransactionData {
return TransactionData(planId: planId, loopConfig: loopConfig)
}
// ============================================================
// Init
// ============================================================
init() {
self.HandlerStoragePath = /storage/DCAHandlerEVMV4
self.HandlerPublicPath = /public/DCAHandlerEVMV4
}
}