@@ -45,7 +45,15 @@ func (fp *FeePlugin) LoadFees(ctx context.Context, task *asynq.Task) error {
4545 return fmt .Errorf ("failed to acquire semaphore: %w" , err )
4646 }
4747 defer sem .Release (1 )
48- err := fp .executeFeeLoading (ctx , feePolicy )
48+
49+ // Here we load any existing batches that are in draft state, or that may have been missed along the way.
50+ err := fp .loadExistingBatches (ctx , feePolicy )
51+ if err != nil {
52+ fp .logger .WithError (err ).WithField ("public_key" , feePolicy .PublicKey ).Error ("Failed to load existing batches" )
53+ }
54+
55+ // Here we create a new batch, later these jobs could run separately on different frequencies.
56+ err = fp .executeFeeLoading (ctx , feePolicy )
4957 if err != nil {
5058 fp .logger .WithError (err ).WithField ("public_key" , feePolicy .PublicKey ).Error ("Failed to execute fee loading" )
5159 }
@@ -60,6 +68,42 @@ func (fp *FeePlugin) LoadFees(ctx context.Context, task *asynq.Task) error {
6068 return nil
6169}
6270
71+ func (fp * FeePlugin ) loadExistingBatches (ctx context.Context , feePolicy vtypes.PluginPolicy ) error {
72+ batches , err := fp .verifierApi .GetDraftBatches (feePolicy .PublicKey )
73+ if err != nil {
74+ return fmt .Errorf ("failed to get fee batches: %w" , err )
75+ }
76+
77+ for _ , batch := range batches {
78+ batches , err := fp .db .GetFeeBatch (ctx , batch .BatchID )
79+ if err != nil {
80+ return err
81+ }
82+
83+ if len (batches ) == 0 {
84+ _ , err = fp .db .CreateFeeBatch (ctx , nil , types.FeeBatch {
85+ ID : uuid .New (),
86+ BatchID : batch .BatchID ,
87+ PublicKey : feePolicy .PublicKey ,
88+ Status : types .FeeBatchStateDraft ,
89+ TxHash : nil ,
90+ Amount : batch .Amount ,
91+ })
92+ if err != nil {
93+ return err
94+ }
95+ fp .logger .WithField ("public_key" , feePolicy .PublicKey ).WithField ("batch_id" , batch .BatchID ).Info ("Created draft batch" )
96+ } else {
97+ fp .logger .WithField ("public_key" , feePolicy .PublicKey ).WithField ("batch_id" , batch .BatchID ).Info ("Draft batch already exists" )
98+ }
99+ }
100+ if len (batches ) == 0 {
101+ fp .logger .WithField ("public_key" , feePolicy .PublicKey ).Info ("No draft batches found" )
102+ }
103+
104+ return nil
105+ }
106+
63107func (fp * FeePlugin ) executeFeeLoading (ctx context.Context , feePolicy vtypes.PluginPolicy ) error {
64108
65109 // Get list of fees from the verifier connected to the fee policy
@@ -86,5 +130,10 @@ func (fp *FeePlugin) executeFeeLoading(ctx context.Context, feePolicy vtypes.Plu
86130 Amount : uint64 (batch .Amount ),
87131 })
88132
89- return err
133+ if err != nil {
134+ return fmt .Errorf ("failed to create fee batch: %w" , err )
135+ }
136+
137+ fp .logger .WithField ("public_key" , feePolicy .PublicKey ).WithField ("batch_id" , batch .BatchID ).Info ("Created draft batch" )
138+ return nil
90139}
0 commit comments