@@ -144,39 +144,45 @@ export async function updateBalances(
144144 const BalanceModel = getStoreModel ( 'Balance' )
145145 const sequelize = getSequelize ( "Balance" )
146146
147- const promises : Array < Promise < unknown > > = [ ]
148-
149- if ( balancesToSaveWithOptimize . length > 0 ) {
150- promises . push (
151- optimizedBulkCreate ( "Balance" , balancesToSaveWithOptimize )
152- )
153- }
147+ const blockHeight = store . context . getHistoricalUnit ( )
154148
155149 if ( Object . keys ( currentBalancesMap ) . length > 0 ) {
156- promises . push (
157- BalanceModel . model . update (
158- {
159- __block_range : sequelize . fn (
160- "int8range" ,
161- sequelize . fn ( "lower" , sequelize . col ( "_block_range" ) ) ,
162- blockId ,
163- '[)'
164- ) ,
150+ // remove existing records of changes for this block
151+ // if they exist before saving records
152+ await BalanceModel . model . destroy ( {
153+ where : {
154+ // @ts -ignore
155+ last_updated_block_id : blockId ,
156+ } ,
157+ transaction : store . context . transaction ,
158+ } )
159+
160+ await BalanceModel . model . update (
161+ {
162+ __block_range : sequelize . fn (
163+ "int8range" ,
164+ sequelize . fn ( "lower" , sequelize . col ( "_block_range" ) ) ,
165+ blockId ,
166+ '[)'
167+ ) ,
168+ } ,
169+ {
170+ hooks : false ,
171+ where : {
172+ id : { [ Symbol . for ( "in" ) ] : Object . keys ( currentBalancesMap ) } ,
173+ __block_range : { [ Symbol . for ( "contains" ) ] : blockId } ,
165174 } ,
166- {
167- hooks : false ,
168- where : {
169- id : { [ Symbol . for ( "in" ) ] : Object . keys ( currentBalancesMap ) } ,
170- __block_range : { [ Symbol . for ( "contains" ) ] : blockId } ,
171- } ,
172- transaction : store . context . transaction ,
173- }
174- )
175+ transaction : store . context . transaction ,
176+ }
175177 )
176178 }
177179
178- if ( promises . length > 0 ) {
179- await Promise . all ( promises )
180+ if ( balancesToSaveWithOptimize . length > 0 ) {
181+ await optimizedBulkCreate ( "Balance" , balancesToSaveWithOptimize , ( doc ) => ( {
182+ ...doc ,
183+ __block_range : [ blockHeight , null ] ,
184+ } )
185+ )
180186 }
181187}
182188
0 commit comments