@@ -176,16 +176,35 @@ func (d *MetadataStoreSqlite) SetTransaction(
176176 tmpTx .Metadata = tmpMetadata
177177 }
178178 collateralReturn := tx .CollateralReturn ()
179+ // For invalid transactions with collateral returns, fix indices via CBOR matching
180+ // since Produced() uses enumerated indices rather than real transaction indices
181+ var realIndexMap map [lcommon.Blake2b256 ]uint32
182+ if ! tx .IsValid () && collateralReturn != nil {
183+ realIndexMap = make (map [lcommon.Blake2b256 ]uint32 )
184+ for idx , out := range tx .Outputs () {
185+ if out != nil && idx <= int (^ uint32 (0 )) {
186+ // Hash CBOR for efficient map key
187+ outputHash := lcommon .NewBlake2b256 (out .Cbor ())
188+ //nolint:gosec // G115: idx bounds already checked above
189+ realIndexMap [outputHash ] = uint32 (idx )
190+ }
191+ }
192+ }
179193 for _ , utxo := range tx .Produced () {
180194 if collateralReturn != nil && utxo .Output == collateralReturn {
181- utxo := models .UtxoLedgerToModel (utxo , point .Slot )
182- tmpTx .CollateralReturn = & utxo
195+ m := models .UtxoLedgerToModel (utxo , point .Slot )
196+ // Fix collateral return index for invalid transactions
197+ if realIndexMap != nil && m .Cbor != nil {
198+ outputHash := lcommon .NewBlake2b256 (m .Cbor )
199+ if realIdx , ok := realIndexMap [outputHash ]; ok {
200+ m .OutputIdx = realIdx
201+ }
202+ }
203+ tmpTx .CollateralReturn = & m
183204 continue
184205 }
185- tmpTx .Outputs = append (
186- tmpTx .Outputs ,
187- models .UtxoLedgerToModel (utxo , point .Slot ),
188- )
206+ m := models .UtxoLedgerToModel (utxo , point .Slot )
207+ tmpTx .Outputs = append (tmpTx .Outputs , m )
189208 }
190209 result := txn .Clauses (clause.OnConflict {
191210 Columns : []clause.Column {{Name : "hash" }}, // unique txn hash
0 commit comments