Skip to content

Commit 7eb9075

Browse files
Fix addAdaChange to never error
1 parent 7d6b461 commit 7eb9075

File tree

1 file changed

+17
-6
lines changed

1 file changed

+17
-6
lines changed

src/BotPlutusInterface/Balance.hs

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ import Data.Kind (Type)
2929
import Data.List ((\\))
3030
import Data.Map (Map)
3131
import Data.Map qualified as Map
32-
import Data.Maybe (fromJust, fromMaybe, mapMaybe)
32+
import Data.Maybe (fromMaybe, mapMaybe)
3333
import Data.Set (Set)
3434
import Data.Set qualified as Set
3535
import Data.Text (Text)
@@ -320,7 +320,7 @@ handleNonAdaChange changeAddr utxos tx =
320320
outputs =
321321
modifyFirst
322322
((==) changeAddr . Tx.txOutAddress)
323-
(maybe newOutput $ addValueToTxOut nonAdaChange)
323+
(Just . maybe newOutput (addValueToTxOut nonAdaChange))
324324
(txOutputs tx)
325325
in if isValueNat nonAdaChange
326326
then Right $ if Value.isZero nonAdaChange then tx else tx {txOutputs = outputs}
@@ -338,16 +338,27 @@ addAdaChange changeAddr change tx =
338338
{ txOutputs =
339339
modifyFirst
340340
((==) changeAddr . Tx.txOutAddress)
341-
(addValueToTxOut (Ada.lovelaceValueOf change) . fromJust)
341+
(fmap $ addValueToTxOut $ Ada.lovelaceValueOf change)
342342
(txOutputs tx)
343343
}
344344

345+
consJust :: forall (a :: Type). Maybe a -> [a] -> [a]
346+
consJust (Just x) = (x :)
347+
consJust _ = id
348+
345349
{- | Modifies the first element matching a predicate, or, if none found, call the modifier with Nothing
346350
Calling this function ensures the modifier will always be run once
347351
-}
348-
modifyFirst :: (a -> Bool) -> (Maybe a -> a) -> [a] -> [a]
349-
modifyFirst _ m [] = [m Nothing]
350-
modifyFirst p m (x : xs) = if p x then m (Just x) : xs else x : modifyFirst p m xs
352+
modifyFirst ::
353+
forall (a :: Type).
354+
-- | Predicate for value to update
355+
(a -> Bool) ->
356+
-- | Modifier, input Maybe representing existing value (or Nothing if missing), output value representing new value (or Nothing to remove)
357+
(Maybe a -> Maybe a) ->
358+
[a] ->
359+
[a]
360+
modifyFirst _ m [] = m Nothing `consJust` []
361+
modifyFirst p m (x : xs) = if p x then m (Just x) `consJust` xs else x : modifyFirst p m xs
351362

352363
addValueToTxOut :: Value -> TxOut -> TxOut
353364
addValueToTxOut val txOut = txOut {txOutValue = txOutValue txOut <> val}

0 commit comments

Comments
 (0)