user242: I ran into an error while trying to autobalance a transaction body:
module Foo.Offchain where
import Plutus.V1.Ledger.Scripts (MintingPolicy)
import Plutus.V1.Ledger.Address (Address)

import Hydra.Cardano.API
import Hydra.Prelude
import Test.Hydra.Prelude
import Cardano.Api.UTxO qualified as UTxO

import Foo.Onchain(fooPolicy)

userAddress :: Address ShelleyAddr
...

txFoo = do
  let policyScript = fromPlutusScript @PlutusScriptV2 
        $ getMintingPolicy fooPolicy
      policyId = PolicyId $ hashScript $ PlutusScript policyScript
      mintingWitness = BuildTxWith . Map.singleton policyId
        $ mkScriptWitness policyScript NoScriptDatumForMint (toScriptData ())
      mintingValue = valueFromList [(AssetId policyId "", 1)]
  ...
  pparams <- queryProtocolParameters networkId nodeSocket QueryTip
  systemStart <- querySystemStart networkId nodeSocket QueryTip
  eraHistory <- queryEraHistory networkId nodeSocket QueryTip
  stakePools <- queryStakePools networkId nodeSocket QueryTip
  utxoSet <- ...
  someUtxo <- ...
  someTxOut <- ...
  ...
  let unbalancedBody =
        TxBodyContent
          (withWitness <$> toList (UTxO.inputSet utxoSet))
          (TxInsCollateral [someUtxo])
          TxInsReferenceNone
          [someTxOut]
          TxTotalCollateralNone
          TxReturnCollateralNone
          (TxFeeExplicit 0)
          (TxValidityNoLowerBound, TxValidityNoUpperBound)
          TxMetadataNone
          TxAuxScriptsNone
          TxExtraKeyWitnessesNone
          (BuildTxWith $ Just pparams)
          TxWithdrawalsNone
          TxCertificatesNone
          TxUpdateProposalNone
          (TxMintValue mintingValue mintingWitness)
          TxScriptValidityNone
  let balancedBody = either (error . show) balancedTxBody $
        makeTransactionBodyAutoBalance
          BabbageEraInCardanoMode
          systemStart
          eraHistory
          pparams
          stakePools
          (UTxO.toApi utxoSet)
          preBody
          (ShelleyAddressInEra userAddress)
          Nothing

I got the following error:
TxBodyScriptExecutionError
  [ ( ScriptWitnessIndexMint 0
    , ScriptErrorEvaluationFailed
        (CekError An error has occurred:
           User error:
             The machine terminated because of an error, either from a built-in
             function or from an explicit use of 'error'.
           Caused by: (force headList [])
        )
        []
    )
  ]

The strange thing is that I still get this error even if I reduce fooPolicy
down to a trivial check that depends only the ScriptContext:
module Foo.Onchain where

import PlutusTx.Prelude
import Plutus.V1.Ledger.Api (BuiltinData(..), Data(..), MintingPolicy, ScriptContext, UnsafeFromData (unsafeFromBuiltinData), mkMintingPolicyScript)
import Plutus.V1.Ledger.Contexts (ScriptPurpose(..), scriptContextPurpose)
import PlutusTx qualified

{-# INLINEABLE fooPolicyValidator #-}
fooPolicyValidator :: BuiltinData -> BuiltinData -> ScriptContext -> Bool
fooPolicyValidator _ _ ctx =
  case scriptContextPurpose ctx of
    Minting _cSymbol ->
      traceIfTrue "Here" True
    _other ->
      traceIfTrue "There" True

fooPolicy :: MintingPolicy
fooPolicy =
  mkMintingPolicyScript $
    $$(PlutusTx.compile
      [||\y z -> checkBool 
        (fooPolicyValidator
          (BuiltinData (I 0))
          (BuiltinData (I 0)) 
          (unsafeFromBuiltinData z)
        )||])

{-# INLINEABLE checkBool #-}
checkBool :: Bool -> ()
checkBool True = ()
checkBool False = traceError "Check error"

How can it be possible to get an on-chain script execution error when all that my on-chain code does is look at the script context?

user242: The problem was that I was mixing on-chain code written in Plutus V1 with off-chain code that expects Plutus V2. In particular, the off-chain code utilities in the hydra-cardano-api library assume that all scripts are written in Plutus V2.
The strange error manifests because:

The Plutus V1 on-chain code compiles and serializes just fine.
The Plutus V2 off-chain code is happy to put the Plutus V1 compiled on-chain code into a transaction if you tag it as Plutus V2 code (i.e. fromPlutusScript @PlutusScriptV2)
When the Cardano node tries to validate your transaction, it fails at constructing the ScriptContext because of a mismatch between Plutus V1 and V2.
Unfortunately, when ScriptContext construction fails, the library is not able to give a more informative error than Caused by: (force headList []).

Solution: make sure that your on-chain code and off-chain code match on the Plutus version. For hydra-cardano-api, use Plutus V2 for all on-chain code.

242: <p>I ran into an error while trying to autobalance a transaction body:</p>
<pre class="lang-haskell prettyprint-override"><code>module Foo.Offchain where
import Plutus.V1.Ledger.Scripts (MintingPolicy)
import Plutus.V1.Ledger.Address (Address)

import Hydra.Cardano.API
import Hydra.Prelude
import Test.Hydra.Prelude
import Cardano.Api.UTxO qualified as UTxO

import Foo.Onchain(fooPolicy)

userAddress :: Address ShelleyAddr
...

txFoo = do
  let policyScript = fromPlutusScript @PlutusScriptV2 
        $ getMintingPolicy fooPolicy
      policyId = PolicyId $ hashScript $ PlutusScript policyScript
      mintingWitness = BuildTxWith . Map.singleton policyId
        $ mkScriptWitness policyScript NoScriptDatumForMint (toScriptData ())
      mintingValue = valueFromList [(AssetId policyId &quot;&quot;, 1)]
  ...
  pparams &lt;- queryProtocolParameters networkId nodeSocket QueryTip
  systemStart &lt;- querySystemStart networkId nodeSocket QueryTip
  eraHistory &lt;- queryEraHistory networkId nodeSocket QueryTip
  stakePools &lt;- queryStakePools networkId nodeSocket QueryTip
  utxoSet &lt;- ...
  someUtxo &lt;- ...
  someTxOut &lt;- ...
  ...
  let unbalancedBody =
        TxBodyContent
          (withWitness &lt;$&gt; toList (UTxO.inputSet utxoSet))
          (TxInsCollateral [someUtxo])
          TxInsReferenceNone
          [someTxOut]
          TxTotalCollateralNone
          TxReturnCollateralNone
          (TxFeeExplicit 0)
          (TxValidityNoLowerBound, TxValidityNoUpperBound)
          TxMetadataNone
          TxAuxScriptsNone
          TxExtraKeyWitnessesNone
          (BuildTxWith $ Just pparams)
          TxWithdrawalsNone
          TxCertificatesNone
          TxUpdateProposalNone
          (TxMintValue mintingValue mintingWitness)
          TxScriptValidityNone
  let balancedBody = either (error . show) balancedTxBody $
        makeTransactionBodyAutoBalance
          BabbageEraInCardanoMode
          systemStart
          eraHistory
          pparams
          stakePools
          (UTxO.toApi utxoSet)
          preBody
          (ShelleyAddressInEra userAddress)
          Nothing
</code></pre>
<p>I got the following error:</p>
<pre><code>TxBodyScriptExecutionError
  [ ( ScriptWitnessIndexMint 0
    , ScriptErrorEvaluationFailed
        (CekError An error has occurred:
           User error:
             The machine terminated because of an error, either from a built-in
             function or from an explicit use of 'error'.
           Caused by: (force headList [])
        )
        []
    )
  ]
</code></pre>
<p>The strange thing is that I still get this error even if I reduce <code>fooPolicy</code>
down to a trivial check that depends only the <code>ScriptContext</code>:</p>
<pre class="lang-haskell prettyprint-override"><code>module Foo.Onchain where

import PlutusTx.Prelude
import Plutus.V1.Ledger.Api (BuiltinData(..), Data(..), MintingPolicy, ScriptContext, UnsafeFromData (unsafeFromBuiltinData), mkMintingPolicyScript)
import Plutus.V1.Ledger.Contexts (ScriptPurpose(..), scriptContextPurpose)
import PlutusTx qualified

{-# INLINEABLE fooPolicyValidator #-}
fooPolicyValidator :: BuiltinData -&gt; BuiltinData -&gt; ScriptContext -&gt; Bool
fooPolicyValidator _ _ ctx =
  case scriptContextPurpose ctx of
    Minting _cSymbol -&gt;
      traceIfTrue &quot;Here&quot; True
    _other -&gt;
      traceIfTrue &quot;There&quot; True

fooPolicy :: MintingPolicy
fooPolicy =
  mkMintingPolicyScript $
    $$(PlutusTx.compile
      [||\y z -&gt; checkBool 
        (fooPolicyValidator
          (BuiltinData (I 0))
          (BuiltinData (I 0)) 
          (unsafeFromBuiltinData z)
        )||])

{-# INLINEABLE checkBool #-}
checkBool :: Bool -&gt; ()
checkBool True = ()
checkBool False = traceError &quot;Check error&quot;
</code></pre>
<p>How can it be possible to get an on-chain script execution error when all that my on-chain code does is look at the script context?</p>
 242: <p>The problem was that I was mixing on-chain code written in Plutus V1 with off-chain code that expects Plutus V2. In particular, the off-chain code utilities in the <code>hydra-cardano-api</code> library assume that all scripts are written in Plutus V2.</p>
<p>The strange error manifests because:</p>
<ul>
<li>The Plutus V1 on-chain code compiles and serializes just fine.</li>
<li>The Plutus V2 off-chain code is happy to put the Plutus V1 compiled on-chain code into a transaction if you tag it as Plutus V2 code (i.e. <code>fromPlutusScript @PlutusScriptV2</code>)</li>
<li>When the Cardano node tries to validate your transaction, it fails at constructing the ScriptContext because of a mismatch between Plutus V1 and V2.</li>
<li>Unfortunately, when ScriptContext construction fails, the library is not able to give a more informative error than <code>Caused by: (force headList [])</code>.</li>
</ul>
<p><strong>Solution:</strong> make sure that your on-chain code and off-chain code match on the Plutus version. For <code>hydra-cardano-api</code>, use Plutus V2 for all on-chain code.</p>
