Plutonomicon / cardano-transaction-lib

A Purescript library for building smart contract transactions on Cardano
https://plutonomicon.github.io/cardano-transaction-lib/
MIT License
93 stars 50 forks source link

Improve AlwaysSucceeds example #577

Closed klntsky closed 2 years ago

klntsky commented 2 years ago

countToZero is a boring way to ensure a tx passes. We can skip some of the waiting by checking utxos available at script address.

This code was suggested by Brian:

waitForTx :: Int -> ValidatorHash -> TransactionHash -> Contract () (Maybe TransactionInput)
waitForTx n vhash txid = do
  let scriptAddress = scriptHashAddress vhash
  UtxoM utxos <- fromMaybe (UtxoM Map.empty) <$> utxosAt scriptAddress
  case fst <$> find hasTransactionId (Map.toUnfoldable utxos :: Array (TransactionInput /\ TransactionOutput)) of
      Nothing ->
        if (n <= 0)
          then do
            pure Nothing
          else do
            logInfo' $ "No tx yet, waiting for: " <> show n <> " more seconds"
            (liftAff <<< delay <<< wrap) 1000.0
            waitForTx (n - 1) vhash txid
      Just txin -> do
        logInfo' $ "found tx:" <> show txid
        pure $ Just txin
  where
    hasTransactionId :: forall a. TransactionInput /\ a -> Boolean
    hasTransactionId (TransactionInput tx /\ _) =
      tx.transactionId == txid
ngua commented 2 years ago

Depending on on when https://github.com/mlabs-haskell/ogmios-datum-cache/pull/73 is complete, we could also use that to keep trying to query the transaction until success

ngua commented 2 years ago

Also, we should only be using find once ideally (or think of a better approach). It takes a long time since there are so many utxos locked at that script address

jy14898 commented 2 years ago

Implemented in https://github.com/Plutonomicon/cardano-transaction-lib/pull/761