text:
Errors with compiling when trying to install offchain-metadata-tools
Hello I am trying to install the offchain-metadata-tools library from IOHK and when using nix-build -A project I am getting this error below saying failed in linker phase when trying to connect to the Network.URI . I have been trying to troubleshoot it for the last day but I have had no luck. I am using an intel macbook pro with 16gb of RAM.
jmarzak-us-la:offchain-metadata-tools jmarzak$ GC_DONT_GC=1 nix-build -A project
trace: Using IOHK default nixpkgs
trace: WARNING: 8.10.2 is out of date, consider using 8.10.4.
trace: To make project.plan-nix for offchain-metadata-tools-src a fixed-output derivation but not materialized, set `plan-sha256` to the output of the 'calculateMaterializedSha' script in 'passthru'.
trace: To materialize project.plan-nix for offchain-metadata-tools-src entirely, pass a writable path as the `materialized` argument and run the 'updateMaterialized' script in 'passthru'.
trace: WARNING: 8.10.2 is out of date, consider using 8.10.4.
building '/nix/store/4hmcsf7dj3pb3v3w37wbm4pln42y0xpw-network-uri-lib-network-uri-2.6.4.1.drv'...
unpacking sources
unpacking source archive /nix/store/r4azmxsi3p5bjs81gvm2wvwxflap3x4s-network-uri-2.6.4.1.tar.gz
source root is network-uri-2.6.4.1
setting SOURCE_DATE_EPOCH to timestamp 1000000000 of file network-uri-2.6.4.1/tests/uri001.hs
patching sources
configuring
Configure flags:
--prefix=/nix/store/h2rcbnxmw08s6waqcclri9pnmrn5cg42-network-uri-lib-network-uri-2.6.4.1 lib:network-uri --package-db=clear --package-db=/nix/store/qxwbr7zgaar2ww1j21zlbsdq5chnnzvy-network-uri-lib-network-uri-2.6.4.1-config/lib/ghc-8.10.2/package.conf.d --exact-configuration --dependency=parsec=parsec-3.1.14.0-6iSWBB8iDTOE545kctTcd8 --dependency=th-compat=th-compat-0.1.1-LjxiD0nW4NUFjgNxm1UCB9 --dependency=rts=rts --dependency=ghc-heap=ghc-heap-8.10.2 --dependency=ghc-prim=ghc-prim-0.6.1 --dependency=integer-gmp=integer-gmp-1.0.3.0 --dependency=base=base-4.14.1.0 --dependency=deepseq=deepseq-1.4.4.0 --dependency=array=array-0.5.4.0 --dependency=ghc-boot-th=ghc-boot-th-8.10.2 --dependency=pretty=pretty-1.1.3.6 --dependency=template-haskell=template-haskell-2.16.0.0 --with-ghc=ghc --with-ghc-pkg=ghc-pkg --with-hsc2hs=hsc2hs --with-gcc=cc --with-ld=ld --with-ar=ar --with-strip=strip --disable-executable-stripping --disable-library-stripping --disable-library-profiling --disable-executable-profiling --enable-static --enable-shared --disable-coverage --enable-library-for-ghci
Configuring library for network-uri-2.6.4.1..
Warning: The flag --disable-executable-profiling is deprecated. Please use
--disable-profiling instead.
building
Preprocessing library for network-uri-2.6.4.1..
Building library for network-uri-2.6.4.1..
[1 of 3] Compiling Network.URI      ( Network/URI.hs, dist/build/Network/URI.o, dist/build/Network/URI.dyn_o )

Network/URI.hs:10:14: warning: [-Wtrustworthy-safe]
    ‘Network.URI’ is marked as Trustworthy but has been inferred as safe!
   |
10 | {-# LANGUAGE Trustworthy #-}
   |              ^^^^^^^^^^^
[2 of 3] Compiling Network.URI.Lens ( Network/URI/Lens.hs, dist/build/Network/URI/Lens.o, dist/build/Network/URI/Lens.dyn_o )
[3 of 3] Compiling Network.URI.Static ( Network/URI/Static.hs, dist/build/Network/URI/Static.o, dist/build/Network/URI/Static.dyn_o )
ld: warning: /nix/store/v0n14y5q17p050a81ih6w5d0szsncjmv-libiconv-osx-10.12.6/lib/libiconv.dylib, ignoring unexpected dylib file
ld: file not found: /usr/lib/system/libcache.dylib for architecture x86_64
clang-7: error: linker command failed with exit code 1 (use -v to see invocation)
`cc' failed in phase `Linker'. (Exit code: 1)
error: builder for '/nix/store/4hmcsf7dj3pb3v3w37wbm4pln42y0xpw-network-uri-lib-network-uri-2.6.4.1.drv' failed with exit code 1;
       last 10 log lines:
       >     ‘Network.URI’ is marked as Trustworthy but has been inferred as safe!
       >    |
       > 10 | {-# LANGUAGE Trustworthy #-}
       >    |              ^^^^^^^^^^^
       > [2 of 3] Compiling Network.URI.Lens ( Network/URI/Lens.hs, dist/build/Network/URI/Lens.o, dist/build/Network/URI/Lens.dyn_o )
       > [3 of 3] Compiling Network.URI.Static ( Network/URI/Static.hs, dist/build/Network/URI/Static.o, dist/build/Network/URI/Static.dyn_o )
       > ld: warning: /nix/store/v0n14y5q17p050a81ih6w5d0szsncjmv-libiconv-osx-10.12.6/lib/libiconv.dylib, ignoring unexpected dylib file
       > ld: file not found: /usr/lib/system/libcache.dylib for architecture x86_64
       > clang-7: error: linker command failed with exit code 1 (use -v to see invocation)
       > `cc' failed in phase `Linker'. (Exit code: 1)
       For full logs, run 'nix log /nix/store/4hmcsf7dj3pb3v3w37wbm4pln42y0xpw-network-uri-lib-network-uri-2.6.4.1.drv'.
error: 1 dependencies of derivation '/nix/store/q72i8ylgcspg7sj6gw54bkxxc7g5a089-cabal-install-exe-cabal-3.4.0.0.drv' failed to build
error: 1 dependencies of derivation '/nix/store/c5fwigx4wvpjkbcm8i6ki34zcaw4w8mq-offchain-metadata-tools-src-plan-to-nix-pkgs.drv' failed to build
(use '--show-trace' to show detailed location information)
jmarzak-us-la:offchain-metadata-tools jmarzak$

Welcome to Cardano SE! As a new user be sure to take the [Tour].

You are on BigSur or Monterey?


text:
nix installation issue on Fedora 35
I just ran sh <(curl -L https://nixos.org/nix/install) --daemon  to install nix via its installation instructions. I proceeded through the installation menu where it backs up your bashrc and other config files. y on sudo permissions, it installs and doesn't complain.
systemctl status systemctl status nix-daemon.service
daemon running with no issues. However when I execute nix-shell I get
nix-shell: /nix/store/jsp3h3wpzc842j0rz61m5ly71ak6qgdn-glibc-2.32-54/lib/libc.so.6: version GLIBC_2.33' not found (required by /usr/local/lib/libsodium.so.23)

When I execute nix-env --version same error.
I've uninstalled / reinstalled nix several times now and getting the same error. Checked Fedora 35 glibc version  ldd --version and get back 2.34
Any advice on getting nix-shell to execute properly in Fedora 35?

Welcome to Cardano SE! As a new user be sure to take the [Tour].

Where id you run nix-shell, in which folder?

Fixed. I had the Cardano node previously installed which involves compiling and installing libsodium. What I did was go into the libsodium folder and sudo make libsodium uninstall Then re-ran nix installation and now I get a nix-shell.

Welcome to Cardano SE! As a new user be sure to take the [Tour].

For me the make command failed and I had to go to /usr/local/lib, created a backup directory and moved all libsodium.* files to it. This removed that existing lib and nix installed fine.

I had the same issue. I noticed it happens when you had/have previously setup a Cardano node since that required setting up libsodium. The issue is with the LD_LIBRARY_PATH envronment variable added in the process.
To solve it I commented out that variable export in the ~/.bashrc file. You may need to restart the terminal for the change to take effect.

I went ahead and got ahold of a fedora 35 install. I was not able to install the --daemon version, due to fedoras SELinux enforcement. I did however manage to install nix in single user mode.
and nix-shell works.
$ nix-shell -p hello
these 42 paths will be fetched (61.29 MiB download, 281.92 MiB unpacked):
...
[nix-shell:~]$ hello
Hello, world!

[nix-shell:~]$

Sadly I'm getting the same error with single user mode installation.
sh <(curl -L https://nixos.org/nix/install) --no-daemon
copying Nix to /nix/store...........................................
/nix/store/azld8vfyqb4fx6bxdz28n3nw23nghf88-nix-2.5.1/bin/nix-store: /nix/store/jsp3h3wpzc842j0rz61m5ly71ak6qgdn-glibc-2.32-54/lib/libc.so.6: version `GLIBC_2.33' not found (required by /usr/local/lib/libsodium.so.23)
/tmp/nix-binary-tarball-unpack.PWdwdaEWRp/unpack/nix-2.5.1-x86_64-linux/install: unable to register valid paths

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
First time compiling sample Plutus code in local Plutus Playground failed. Can't figure out why
I've been a mainframe programmer my for decades.  Never developed on small server platforms. So the biggest challenge I'm having is dealing with the nerve wracking OS setup, Github cloning, server building, nix running craziness,  etc etc etc
These are the steps I accomplished leading up to my Failed Compile.
I followed The Plutus Playground Local Instance Instructions in the Plutus Env: Setup Starter Pack
1 Installed WSL (Ubuntu)   (couldn't get git to work until I did this.) Tried multiple thing. But only this worked.
then:

Download the plutus-apps repository: git clone https://github.com/input-output-hk/plutus-apps
COMPLETED

Go to the latest commit of the repository: git checkout 41149926c108c71831cfe8d244c83b0ee4bf5c8a
COMPLETED

At top of this repo, nix-build -A plutus-playground.server
COMPLETED

4 Enter nix-shell then:      This ran literally all day and finished at the $prompt
 COMPLETED
after nix-shell build stopped entered these two cmnds:
[nix-shell:~/plutus-apps]$ cd plutus-playground-client
[nix-shell:~/plutus-apps/plutus-playground-client]$ npm run start

 COMPLETED
I then navigated to localhost in browser which loaded the demo code to be compiled.
I hit the compile button , it displayed a Compilation Failed message and display the following errors in the Linux Command window:
 FAILED

"This ran literally all day and finished at the $prompt", did you add the IOG caches to your nix configuration? That could explain why it built so much.

No, I saw mention of that after the fact in the week #1 Exercises.

No, I saw mention of that after the fact in the week #1 Exercises.   I figured at some point I should go back and do that.  It def should've been in the Plutus Env: Setup Starter Pack  instructions, it would've saved me a lot of time.   I have no choice but to push through all the apps I don't know (Linux, Nix, Haskell etc and learn on the fly through trial and error.     Thanks man.

FYI, I answered another question that's similar but not the same here that shows some details of a new tool I created that's a little less convoluted. It uses the power of nix to abstract away a lot of the ugliness. https://cardano.stackexchange.com/a/6464/382

Notwithstanding the value/importance of cache issue pointed out by @angerman, the cause of the main question of your OP (i.e., the error on port 8080) appears to be that you started the client on 8009, but didn't show any steps for starting the server.
Open a second terminal session, enter the nix-shell, and start the server, and you should be set.

Thanks, this is great.  I see that I missed that step on the Setup Starter Pack.   Can I ask another quick question?       Cache setup says to update /etc/nix/nix.conf      Where is the /etc folder?   I haven't been able to locate it.   Do I have to create it?  If so what folder do I create it in.

You should find the necessary etc/ folder from your root directory.
In a terminal, you can do the following from anywhere to get there.
:~/plutus-apps$ cd /
bring you to this prompt...
:/$
that is your root dir/path (/) prompt
now;
:/$ ls
...and you should see something like this...
bin   dev  home  lib32  libx32      media  nix  proc  run   snap  sys  usr
boot  etc  lib   lib64  lost+found  mnt    opt  root  sbin  srv   tmp  var
Note the etc/ dir.
Now that you know where it is, from here just change to the etc/ directory.
If you need to make a nix folder, simply use the mkdir command.
I am not sure how comfortable you are in the bash shell. If you are, here is a handy concatenated line to mkdir and create a nix.conf file at the same time:
sudo mkdir folder && sudo touch $_/file.txt

or -> sudo mkdir etc/nix/ && sudo touch $_/nix.conf
I hope that helps you out with this. Good luck!

This my friend is excellent!!  Thank you so much

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
How to resolve the Following Error.?
Command failed: transaction build  Error:
The following scripts have execution failures:
the script for transaction input 1 (in the order of the TxIds) failed with:
The Plutus script evaluation failed: An error has occurred:  User error:
The provided Plutus code called 'error'.
Caused by: [ (force (builtin headList)) (con list (data) []) ]
Script debugging logs:

It appears you ended up calling head on an empty list []? That can not work as there is no element to take from an empty list. head only works on lists with at least one element, and fails for the empty list.


text:
nix doctor --verbose [FAIL] Multiple versions of nix found in PATH, on MacOS i7
After performing a git commit tag update on plutus-apps, I restarted my computer, and ran nix doctor --verbose and got the following FAIL
  [FAIL] Multiple versions of nix found in PATH:
    /nix/store/iq3ra93h9kxmnrw3zlxmqn8ng5w62dra-nix-2.5.1/bin
    /nix/store/j6fqvmsfhl4frzqn2f3bzhn8hr16j5q5-nix-2.5.1/bin

How do I correct this?

Updates on troubleshooting:

performed nix install sh <(curl -L https://nixos.org/nix/install) --daemon
read up on nix-store documentation
performed nix-store --delete /nix/store/j6fqvmsfhl4frzqn2f3bzhn8hr16j5q5-nix-2.5.1/bin to delete both instances, got "error: Cannot delete path /nix/store/... since it is still alive.  To find out why, use: nix-store --query --roots.

I may have created two profiles in /nix/var/nix/profiles/per-user/ as profile-link-1 and profile-link-2, potentially two different user environments.  I may have done something twice and nix made two different user env rather than overrride. See https://nixos.org/manual/nix/stable/introduction.html?highlight=%2Fnix%2Fvar%2Fnix%2Fprofiles%2Fper-user%2F#multi-user-support

I had success with just fully uninstalling nix.
However, uninstalling nix wasn't straight forward either (surprise!).  From my research, here are options that worked.
How to uninstall nix:

Script Github kintsugi/uninstall-nix-osx.sh

(hat tip to the tutorial https://github.com/renzwo/cardano-plutus-apps-install-m1/blob/main/README.md, see very bottom)
from terminal, cd to desktop (or whatever is easiest)
git clone https://gist.github.com/47e5e9f9d7c3a3a2f6004b6271365f8c.git
in terminal, sudo sh <drag-and-drop-file-here> or sudo sh </path/to/file/and_file_here>

OR

Manually follow Github Issue, How to remove nix #1402

I did this just as backup, #1 already worked, although there were some caution statements.

RESTART COMPUTER

In new tab, in ~/plutus-apps directory

nix doctor --verbose now all passes!

So far, the nix-build, nix-shell have worked too...

As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.


text:
Running week01 expressions in repl
I am new to haskell and I am trying to run a few expressions from the English Auction Contract in the repl.
So if I want to run ValidatorHash "f" from the second last line of the Contract in week01, how do I do it in the repl here [nix-shell:~/plutus-pioneer-program/code/week01]$ cabal repl?
What I tried
> import Ledger.ValidatorHash
> Ledger.ValidatorHash "f"
error: Couldn't match expected type ‘PlutusTx.Builtins.Internal.BuiltinByteString’
                  with actual type ‘[Char]’

then
> import PlutusTx.Builtins.Internal
> Ledger.ValidatorHash (BuiltinByteString "f")
error: Couldn't match expected type ‘bytestring-0.10.12.0:Data.ByteString.Internal.ByteString’
                  with actual type ‘[Char]’

then
> import Data.ByString as BS
error: Could not find module ‘Data.ByString’
    Perhaps you meant
      Data.ByteString (needs flag -package-key bytestring-0.10.12.0)
      Data.String (from base-4.14.1.0)

So do I really need to close this repl and figure out the way to open the repl with the flag?
Or is there something very obvious that I am missing?

Edit #1: added non-typo error for bytestring
> import Data.ByteString as BS
error: Could not load module ‘Data.ByteString’
    It is a member of the hidden package ‘bytestring-0.10.12.0’.
    Perhaps you need to add ‘bytestring’ to the build-depends in your .cabal file.

Looks like bytestring is hidden. Is it still possible to run ValidatorHash "f" using any other means?

Edit #2
My question was initially specific to find out the origin of 66 when using the token in week01 code as ValidatorHash "f" is taken from this statement in the contract myToken = KnownCurrency (ValidatorHash "f") "Token" (TokenName "T" :| []). But I was unable to evaluate it.

It was newbie mistake. There are these lines at the top
{-# LANGUAGE DataKinds                  #-}
{-# LANGUAGE DeriveAnyClass             #-}
{-# LANGUAGE DeriveGeneric              #-}
{-# LANGUAGE DerivingStrategies         #-}
{-# LANGUAGE FlexibleContexts           #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase                 #-}
{-# LANGUAGE MultiParamTypeClasses      #-}
{-# LANGUAGE NoImplicitPrelude          #-}
{-# LANGUAGE OverloadedStrings          #-}
{-# LANGUAGE RecordWildCards            #-}
{-# LANGUAGE ScopedTypeVariables        #-}
{-# LANGUAGE TemplateHaskell            #-}
{-# LANGUAGE TypeApplications           #-}
{-# LANGUAGE TypeFamilies               #-}
{-# LANGUAGE TypeOperators              #-}

I ran the following in the repl
:set -XDataKinds
:set -XDeriveAnyClass
:set -XDeriveGeneric
:set -XDerivingStrategies
:set -XFlexibleContexts
:set -XGeneralizedNewtypeDeriving
:set -XLambdaCase
:set -XMultiParamTypeClasses
:set -XNoImplicitPrelude
:set -XOverloadedStrings
:set -XRecordWildCards
:set -XScopedTypeVariables
:set -XTemplateHaskell
:set -XTypeApplications
:set -XTypeFamilies
:set -XTypeOperators

and then simply evaluated the expression and it worked!
> Ledger.ValidatorHash "f"
66

Somewhere you have a typo. "ByString" should be "ByteString".

thanks, I changed my final question to address it.

Perhaps you need to add ‘bytestring’ to the build-depends in your .cabal file.

Do you have a cabal file somewhere? If so, you need to add the bytestring package.

Instead of making bytestring work, can I just evaluate ValidatorHash "f"? Or do I need to setup some flags (like maybe :set -XTemplateHaskell)? I was successfully able to compile week01 so I was trying to run this expression in the repl.


text:
PPViewHashesDontMatch and UnspendableUTxONoDatumHash error on redeeming funds from week03 example
I am trying to redeem the funds from the smart contract into the second wallet without running cardano-node (following the instructions from here: https://www.youtube.com/watch?v=ABtffZPoUqU&list=PLNEK_Ejlx3x2zxcfoVGARFExzOHwXFCCL&index=11) but I get the following error (bcc is blockfrost's cardano-cli is taken from here https://github.com/blockfrost/blockfrost-cardano-cli):
$ bcc transaction submit -f tx.signed -t
 ›   Error: Command failed: transaction submit error
 ›   ShelleyTxValidationError ShelleyBasedEraAlonzo (ApplyTxError
 ›   [UtxowFailure (UnspendableUTxONoDatumHash (fromList [TxInCompact (TxId
 ›    {_unTxId = SafeHash
 ›   \"8583cadfd7a43be943b78b7756c9f02c7825f03dbc67d6dae24f6fb12080144e\"})
 ›    0])),UtxowFailure (PPViewHashesDontMatch (SJust (SafeHash
 ›   \"ca6319c1203911911d372c25297cb9d6606b515a9157a5e9d0a5bcec642efd34\"))
 ›    (SJust (SafeHash \"a0e5ad883f81c0808f38cfc635e2ede5f760fcb4cb83f8bdcf
 ›   f0491b1f50b30f\")))])

After pretty-printing this error for a bit I found the two errors mentioned in the question.
Here are the commands I used:
# give.sh (these commands ran fine)

cardano-cli transaction build-raw \
    --alonzo-era \
    --tx-in c2e2ef139d709c1bb8a0e50efbc9100c41ca34f91a9027823afbfcb45acd6d55#1 \
    --tx-out $(cat vesting.addr)+200000000 \
    --tx-out $(cat 01.addr)+789600000 \
    --fee 200000 \
    --tx-out-datum-hash-file unit.json \
    --out-file tx.body

cardano-cli transaction sign \
    --tx-body-file tx.body \
    --signing-key-file 01.skey \
    --testnet-magic 1097911063 \
    --out-file tx.signed

bcc transaction submit -f tx.signed -t

then
# grab.sh

cardano-cli transaction build-raw \
    --alonzo-era \
    --tx-in 8583cadfd7a43be943b78b7756c9f02c7825f03dbc67d6dae24f6fb12080144e#0 \
    --tx-in-script-file vesting.plutus \
    --tx-in-datum-file unit.json \
    --tx-in-redeemer-file unit.json \
    --tx-in-execution-units "(491845099,1197950)" \
    --tx-in-collateral c2e2ef139d709c1bb8a0e50efbc9100c41ca34f91a9027823afbfcb45acd6d55#0 \
    --required-signer-hash 6cc0729360da2e3592e516f261161140ae96455c12861dec958a4d86 \
    --tx-out $(cat 02.addr)+199400000 \
    --fee 600000 \
    --protocol-params-file protocol.json \
    --out-file tx.body

cardano-cli transaction sign \
    --tx-body-file tx.body \
    --signing-key-file 02.skey \
    --testnet-magic 1097911063 \
    --out-file tx.signed

bcc transaction submit -f tx.signed -t

To fix UnspendableUTxONoDatumHash I tried to hash the unit.json file using cardano-cli transaction hash-script-data --script-data-file unit.json > datum.hash but then the final command called this address 803a67b79578b8f24a15958a232b98aa2a40ec5e4d0e172e67336a235e51f328 as UnspendableUTxONoDatumHash.
To fix PPViewHashesDontMatch I tried searching for the hashes on the blockchain explorer but didn't find anything. In any case, I checked whether the beneficiary in Deploy.hs is set correctly but didn't find anything wrong there.

Edit #1
after fixing order of options I changed the build-raw command in give.sh to
cardano-cli transaction build-raw \
    --alonzo-era \
    --tx-in 079fa1b365b9a39a729968e3702f9a638f35cdcebdb1ea2ca5aeca4d32b20a0e#1 \
    --tx-out $(cat vesting.addr)+200000000 \
    --tx-out-datum-hash 923918e403bf43c34b4ef6b48eb2ee04babed17320d8d1b9ff9ad086e86f44ec \
    --tx-out $(cat 01.addr)+199200000 \
    --fee 200000 \
    --out-file tx.body

I get a different error
 ›   Error: Command failed: "transaction submit error
 ›   ShelleyTxValidationError ShelleyBasedEraAlonzo (ApplyTxError
 ›   [UtxowFailure (PPViewHashesDontMatch (SJust (SafeHash
 ›   \"ca6319c1203911911d372c25297cb9d6606b515a9157a5e9d0a5bcec642efd34\"))
 ›    (SJust (SafeHash \"a0e5ad883f81c0808f38cfc635e2ede5f760fcb4cb83f8bdcf
 ›   f0491b1f50b30f\"))),UtxowFailure (WrappedShelleyEraFailure
 ›   (UtxoFailure (UtxosFailure (ValidationTagMismatch (IsValid True)
 ›   (FailedUnexpectedly [PlutusFailure \"\\nThe 3 arg plutus script
 ›   (PlutusScript PlutusV1 ScriptHash
 ›   \\\"4d8aa3f72ac815edd554d1f3ecdc708ba0d9e52cd161f3b3a5640042\\\")
 ›   fails.\\nCekError An error has occurred:  User error:\\nThe provided
 ›   Plutus code called 'error'.\\nThe data is: Constr 0 []

Edit 2
Using the curl version of blockfrost transaction submit (https://docs.blockfrost.io/#tag/Cardano-Transactions/paths/~1tx~1submit/post) I get some more info
{
  "error": "Bad Request",
  "message": "\"transaction submit error ShelleyTxValidationError ShelleyBasedEraAlonzo (ApplyTxError
    [UtxowFailure
      (PPViewHashesDontMatch
        (SJust
          (SafeHash \\\"ca6319c1203911911d372c25297cb9d6606b515a9157a5e9d0a5bcec642efd34\\\"
          )
        )
        (SJust
          (SafeHash \\\"a0e5ad883f81c0808f38cfc635e2ede5f760fcb4cb83f8bdcff0491b1f50b30f\\\"
          )
        )
      ),
    UtxowFailure
      (WrappedShelleyEraFailure
        (UtxoFailure
          (UtxosFailure
            (ValidationTagMismatch (IsValid True)
              (FailedUnexpectedly
                [PlutusFailure \\\"\\\\nThe 3 arg plutus script
                  (PlutusScript PlutusV1 ScriptHash \\\\\\\"4d8aa3f72ac815edd554d1f3ecdc708ba0d9e52cd161f3b3a5640042\\\\\\\"
                  ) fails.\\\\n
                  CekError An error has occurred:  User error:\\\\n
                  The provided Plutus code called 'error'.\\\\n
                  The data is: Constr 0 []\\\\n
                  The redeemer is: Constr 0 []\\\\n
                  The context is:\\\\n
                  Purpose: Spending (TxOutRef
                    {txOutRefId = c3850544d66a0eef38326551c35807975c201f25787e8e9a379a306ee6f9c1f3, txOutRefIdx = 0
                    }
                  )\\\\n
                  TxInfo:\\\\n
                    TxId: d0aeeed88977e51047f7d455b5bac47f29c7ae70d9e5313bf504a35b3e56cd29\\\\n
                    Inputs: [ c3850544d66a0eef38326551c35807975c201f25787e8e9a379a306ee6f9c1f3!0
                      -> - Value (Map [(,Map [(\\\\\\\"\\\\\\\",200000000)])]) addressed to\\\\n
                      ScriptCredential: 4d8aa3f72ac815edd554d1f3ecdc708ba0d9e52cd161f3b3a5640042 (no staking credential) ]\\\\n
                    Outputs: [ - Value (Map [(,Map [(\\\\\\\"\\\\\\\",199400000)])]) addressed to\\\\n  ",
  "status_code": "400"
}

The PPViewHashesDontMatch error from Edit #2 is caused by protocol parameters file not having cost models field populated - this is a problem with blockfrost-cardano-cli not having access to cost models via Api resulting in script transactions failing.

Order of parameters is important!!!
From cardano-cli transaction build --help:
Usage: cardano-cli transaction build
            [ --byron-era
            | --shelley-era
            | --allegra-era
            | --mary-era
            | --alonzo-era
            ]
            [ --shelley-mode
            | --byron-mode [--epoch-slots NATURAL]
            | --cardano-mode [--epoch-slots NATURAL]
            ]
            (--mainnet | --testnet-magic NATURAL)
            [--script-valid | --script-invalid]
            [--witness-override WORD]
            (--tx-in TX-IN
              [--tx-in-script-file FILE
                [(--tx-in-datum-file FILE | --tx-in-datum-value JSON VALUE)
                  ( --tx-in-redeemer-file FILE
                  | --tx-in-redeemer-value JSON VALUE
                  )]])
            [--required-signer FILE]
            [--tx-in-collateral TX-IN]
            [--tx-out ADDRESS VALUE
              [ --tx-out-datum-hash HASH
              | --tx-out-datum-hash-file FILE
              | --tx-out-datum-hash-value JSON VALUE
              | --tx-out-datum-embed-file FILE
              | --tx-out-datum-embed-value JSON VALUE
              ]]
            --change-address ADDRESS
            [--mint VALUE
              (--mint-script-file FILE
                [--mint-redeemer-file FILE | --mint-redeemer-value JSON VALUE])]
            [--invalid-before SLOT]
            [--invalid-hereafter SLOT]
            [--certificate-file CERTIFICATEFILE
              [--certificate-script-file FILE
                [ --certificate-redeemer-file FILE
                | --certificate-redeemer-value JSON VALUE
                ]]]
            [--withdrawal WITHDRAWAL
              [--withdrawal-script-file FILE
                [ --withdrawal-redeemer-file FILE
                | --withdrawal-redeemer-value JSON VALUE
                ]]]
            [--json-metadata-no-schema | --json-metadata-detailed-schema]
            [--auxiliary-script-file FILE]
            [--metadata-json-file FILE | --metadata-cbor-file FILE]
            [--genesis FILE | --protocol-params-file FILE]
            [--update-proposal-file FILE]
            --out-file FILE

Pay closer attention to this part:
[--tx-out ADDRESS VALUE
              [ --tx-out-datum-hash HASH
              | --tx-out-datum-hash-file FILE
              | --tx-out-datum-hash-value JSON VALUE
              | --tx-out-datum-embed-file FILE
              | --tx-out-datum-embed-value JSON VALUE
              ]]

Notice how nested parameters are. I think you are basically attaching datum to --tx-out $(cat 01.addr)+789600000 and not transaction to the smartcontract!


text:
Running `cabal haddock` on a repo with plutus code errors
Aim: document a repo with plutus code using haddock.
Problem: Naively running cabal haddock has a problem that seems to be caused by plutus (on-chain) code.
For example, plutus-pioneer-program week03 runs in the repl with cabal repl, but cabal haddock errors as follows.
Haddock coverage:
GHC Core to PLC plugin: E043:Error: Reference to a name which is not a local, a builtin, or an external INLINABLE function: Variable Ledger.Typed.Scripts.Validators.wrapValidator
            No unfolding
Context: Compiling expr: Ledger.Typed.Scripts.Validators.wrapValidator
Context: Compiling expr: Ledger.Typed.Scripts.Validators.wrapValidator
                           @ Week03.Homework1.VestingDatum
Context: Compiling expr: Ledger.Typed.Scripts.Validators.wrapValidator
                           @ Week03.Homework1.VestingDatum @ ()
Context: Compiling expr: Ledger.Typed.Scripts.Validators.wrapValidator
                           @ Week03.Homework1.VestingDatum
                           @ ()
                           Week03.Homework1.$fUnsafeFromDataVestingDatum
Context: Compiling expr: Ledger.Typed.Scripts.Validators.wrapValidator
                           @ Week03.Homework1.VestingDatum
                           @ ()
                           Week03.Homework1.$fUnsafeFromDataVestingDatum
                           PlutusTx.IsData.Instances.$fUnsafeFromData()
Context: Compiling expr at "plutus-pioneer-program-week03-0.1.0.0-inplace:Week03.Homework1:(60,8)-(60,37)"
cabal: Failed to build documentation for
plutus-pioneer-program-week03-0.1.0.0.

Is there a straightforward way to build haddock docs for repos with plutus code?

Yes! Try cabal haddock -fplugin-opt Plutus.Tx.Plugin:defer-errors.
(From https://plutus-apps.readthedocs.io/en/latest/plutus/troubleshooting.html#plugin-errors)

Editing the cabal.project file as the link suggests gets cabal haddock working so I'm good. Passing cli arguments as suggested above or in the docs linked gives an error: cabal: Unrecognised target 'PlutusTx.Plugin:defer-errors'. Expected a module name, rather than 'defer-errors'.
I tried various perturbations such as Plutus.Tx...


text:
Diagnosing a POSIXTime discrepancy
My computer's date command is returning a timestamp wildly different from what testnet wants.
Using this formula,
> slotToEndPOSIXTime testnetConf 55047601
POSIXTime {getPOSIXTime = 1651015217999}

But on my computer
$date "%s"
1649413267

This is in seconds rather than millisecond, but what might account for the rest of the divergence?

Cadano timestamps are in UTC and your time is almost certainly local time.
Try setting the timezone:
TZ=UTC date "%s"

As you figured out, getPOSIXTime might be returning millseconds (or maybe even microseconds), whereas the date command is returning seconds.

My computer is set to UTC.
https://www.epochconverter.com/
says that 1651015217 is some weeks from now.
I'm guessing my issue is with some config somewhere, but I don't think I changed anything on my node ... or elsewhere...

The chain start time is set in the configuration.

Do you mean scZeroSlotTime? What should this number be? Neither the value in the example in the repo (1596059091000) , or the number in the linked SE page are close to the value that seems to work. I found no documentation that this number might be different on testnet to mainnet.

Yeah, I think that is it. Its the chain start time, so its usually set to current UTC time and then the chain is started.

Hmmm. Not sure I follow. What I ended up doing is in the other answer. I think there is something more fundamentally wrong in my setup. Maybe I'll find out when I move to mainnet

I'm not sure if this will be anyone else's problem or if i've done something uniquely strange. But here's what I did.

I had two issues with time
The first was with PAB config.
Finding a better estimate of the zero slot:
$ echo $(($(date +"%s") - $(cardano-cli query tip ${CARDANO_NODE_MAGIC} | jq '.slot')))
1594369215

This implies that my pab.yaml config needs to have
...
nodeServerConfig:
    ...
    scSlotZeroTime: 1594369215000
...

Note this number varies depending on how in sync the node is - but this seemed good enough. It is still weeks different from the example config. Very interested if anyone has an explanation for this.
The second issue was that mustValidateIn seems to have both an on-chain and off-chain interpretation which don't necessarily round-trip.
This is a bit of a pain when used in conjunction with the State Machine framework. Adding more stringent bounds in the off-chain code rectifies  this. Perhaps this problem is an artifact of the slot config above being slightly out.


text:
How many slots did Byron era (testnet) have?
I was wondering the number of slots the Byron era (testnet) had or the slot number when Byron finished.
The only info I've been able to find is systemStart": "2019-07-24T20:20:16Z" coming from testnet-shelley-genesis.json.
( Calculate timestamp from slot discusses about the same thing but with mainnet Byron. )
Any help would be great. Thanks in advance!

Should you have accepted the answer?

@gRebel right, done   ✅


text:
What's the difference between Ledger.CurrencySymbol and Plutus.V1.Ledger.Value.CurrencySymbol?
I'm a bit confused about CurrencySymbol type. In the documentation it appears twice in 2 modules: Plutus.V1.Ledger.Value (first image) and Ledger. (second image)
Are they the same type? When import each?
Thanks in advance!

If you look at the source of Ledger, you will see that it reexports CurrencySymbol from the Value module, so yes, they are the same:
module Ledger (
    module Export,
    AssetClass,
    CurrencySymbol,
    TokenName,
    Value,
    Ada
    ) where

import Ledger.Blockchain as Export
import Ledger.Index as Export
import Ledger.Orphans ()
-- We manually re-export 'Plutus.V1.Ledger.Scripts' so we can include some
-- extra instances
import Ledger.Address as Export
import Ledger.Contexts as Export
import Ledger.Crypto as Export
import Ledger.Scripts as Export
import Ledger.Tx as Export
import Ledger.Value as Export (noAdaValue)
import Plutus.V1.Ledger.Ada (Ada)
import Plutus.V1.Ledger.Interval as Export
import Plutus.V1.Ledger.Orphans ()
import Plutus.V1.Ledger.Slot as Export
import Plutus.V1.Ledger.Time as Export
import Plutus.V1.Ledger.TxId as Export
import Plutus.V1.Ledger.Value (AssetClass, CurrencySymbol, TokenName, Value)


text:
Is it possible to send funds to a scriptAddress using a lightweight wallet?
I would like that an user using Yoroi/Nami/etc could send funds to a script address which expected an empty datum: ().
EDIT (Pretty obvious, but the UTxO should be spendable later by a transaction)
I guess that this is possible using cardano-cli, however, could an user do that with a lightweight wallet at the time being?
Thanks in advance!

This answer will surely age fast.
At the time of writing both Nami V3.2.0 and Yoroi Nightly 4.11.501 allow you send to script address, but neither advertise any options of setting datums. Nami allows you to add a note, but that's just for the Tx metadata.
The transactions will succeed, and display in blockchain explorers such as cardanoscan. However the outputs will be stranded: no datum at a script address ==> stranded.
Interestingly, these seem to never make it into the chain-index db. Since they are unspendable this is sensible.
For the time being you'll need the Tx to be built using something like the cardano-serialization-lib or equivalent and handed over to the wallet.


text:
Empty TokenName Literal Overloading in Week05 Homework2
This doesn't work
mkPolicy oref () ctx = traceIfFalse "UTxO not consumed"   hasUTxO           &&
                       traceIfFalse "wrong amount minted" checkMintedAmount
  where
    info :: TxInfo
    info = scriptContextTxInfo ctx

    hasUTxO :: Bool
    hasUTxO = any (\i -> txInInfoOutRef i == oref) $ txInfoInputs info

    checkMintedAmount :: Bool
    checkMintedAmount = case flattenValue (txInfoMint info) of
        [(_, tn, amt)]  -> tn == "" && amt == 1
        _               -> False

and throws
GHC Core to PLC plugin: E042:Error: Unsupported feature: Type constructor: GHC.Prim.Char#
Context: Compiling type: GHC.Prim.Char#
Context: Compiling data constructor type: GHC.Types.C#
Context: Compiling type: GHC.Types.Char
Context: Compiling type: GHC.Base.String
Context: Compiling type: GHC.Base.String
                         -> Data.ByteString.Internal.ByteString
Context: Compiling definition of: Plutus.V1.Ledger.Value.$fIsStringTokenName1
Context: Compiling expr: Plutus.V1.Ledger.Value.$fIsStringTokenName1
Context: Compiling expr: Plutus.V1.Ledger.Value.$fIsStringTokenName1
                           ((GHC.Types.[] @ GHC.Types.Char)
                            `cast` (Sym (Nth:2
                                             (((<GHC.Base.String>_R
                                                ->_R Sym (PlutusTx.Builtins.Internal.N:BuiltinByteString[0]) ; Sym (Plutus.V1.Ledger.Value.N:TokenName[0])) ; Sym (Data.String.N:IsString[0]) <Plutus.V1.Ledger.Value.TokenName>_N) ; Data.String.N:IsString[0] <Plutus.V1.Ledger.Value.TokenName>_N))
                                    :: GHC.Types.Coercible GHC.Base.String GHC.Base.String))
... (a lot of lines skipped here)
Context: Compiling definition of: Week05.Homework2.mkPolicy
Context: Compiling expr: Week05.Homework2.mkPolicy
Context: Compiling expr: Week05.Homework2.mkPolicy oref'_axTu
Context: Compiling expr: PlutusTx.Base.$
                           @ (() -> Plutus.V1.Ledger.Contexts.ScriptContext -> GHC.Types.Bool)
                           @ Ledger.Typed.Scripts.MonetaryPolicies.WrappedMintingPolicyType
                           (Ledger.Typed.Scripts.MonetaryPolicies.wrapMintingPolicy
                              @ () PlutusTx.IsData.Instances.$fUnsafeFromData())
                           (Week05.Homework2.mkPolicy oref'_axTu)
Context: Compiling expr: \ (oref'_axTu :: Plutus.V1.Ledger.Tx.TxOutRef) ->
                           PlutusTx.Base.$
                             @ (() -> Plutus.V1.Ledger.Contexts.ScriptContext -> GHC.Types.Bool)
                             @ Ledger.Typed.Scripts.MonetaryPolicies.WrappedMintingPolicyType
                             (Ledger.Typed.Scripts.MonetaryPolicies.wrapMintingPolicy
                                @ () PlutusTx.IsData.Instances.$fUnsafeFromData())
                             (Week05.Homework2.mkPolicy oref'_axTu)
Context: Compiling expr at "plutus-pioneer-program-week05-0.1.0.0-inplace:Week05.Homework2:(55,8)-(55,85)"

but this works
mkPolicy oref () ctx = traceIfFalse "UTxO not consumed"   hasUTxO           &&
                       traceIfFalse "wrong amount minted" checkMintedAmount
  where
    info :: TxInfo
    info = scriptContextTxInfo ctx

    emptyToken :: TokenName
    emptyToken = TokenName ""

    hasUTxO :: Bool
    hasUTxO = any (\i -> txInInfoOutRef i == oref) $ txInfoInputs info

    checkMintedAmount :: Bool
    checkMintedAmount = case flattenValue (txInfoMint info) of
        [(_, tn, amt)]  -> tn == emptyToken && amt == 1
        _               -> False

I assumed that {-# LANGUAGE OverloadedStrings   #-} would work as TokenName is just a newtype for PlutusTx.Builtins.Internal.BuiltinByteString. From the repl
Prelude Week05.Homework2> :t Plutus.V1.Ledger.Value.TokenName
Plutus.V1.Ledger.Value.TokenName
  :: PlutusTx.Builtins.Internal.BuiltinByteString
     -> Plutus.V1.Ledger.Value.TokenName
Prelude Week05.Homework2> :i Plutus.V1.Ledger.Value.TokenName
type Plutus.V1.Ledger.Value.TokenName :: *
newtype Plutus.V1.Ledger.Value.TokenName
  = Plutus.V1.Ledger.Value.TokenName {Plutus.V1.Ledger.Value.unTokenName :: PlutusTx.Builtins.Internal.BuiltinByteString}
    -- Defined in `Plutus.V1.Ledger.Value'
instance Eq Plutus.V1.Ledger.Value.TokenName
  -- Defined in `Plutus.V1.Ledger.Value'
instance Ord Plutus.V1.Ledger.Value.TokenName
  -- Defined in `Plutus.V1.Ledger.Value'
instance Show Plutus.V1.Ledger.Value.TokenName
  -- Defined in `Plutus.V1.Ledger.Value'

Edit #1
On reading this doc I realised that maybe TokenName is not an instance of IsString. I tried to implement it using:
instance IsString TokenName where
        fromString = unTokenName

but I got this error
src/Week05/Homework2.hs:32:10: error:
    Duplicate instance declarations:
      instance IsString TokenName
        -- Defined at src/Week05/Homework2.hs:32:10
      instance IsString TokenName -- Defined in `Plutus.V1.Ledger.Value'
   |
32 | instance IsString TokenName where
   |          ^^^^^^^^^^^^^^^^^^

Edit #2
The complete Homework file is here.

In plutus docs I see that TokenName is an instance of IsString.  http://0.0.0.0:8002/haddock/plutus-ledger-api/html/Plutus-V1-Ledger-Value.html#t:TokenName

After digging into Plutus source, I think I've found why tn == "" crashes at runtime.
The problem might be that the instance of TokenName IsString doesn't use the INLINABLE pragma in the function fromString. Due to this, Plutus core crashes. (As a reminder, every function in order to compiles to Plutus core must have the INLINABLE pragma).
[source: Plutus.V1.Ledger.Value]
instance IsString TokenName where
    fromString = fromText . Text.pack

On other hand, for example traceIfFalse "UTxO not consumed" hasUTxO is resolved properly because the function fromString in IsString BuiltinString uses the INLINABLE mechanism.
[source: PlutusTx.Builtins.Class]
-- We can't put this in `Builtins.hs`, since that force `O0` deliberately, which prevents
-- the unfoldings from going in. So we just stick it here. Fiddly.
instance IsString BuiltinString where
    -- Try and make sure the dictionary selector goes away, it's simpler to match on
    -- the application of 'stringToBuiltinString'
    {-# INLINE fromString #-}
    -- See Note [noinline hack]
    fromString = Magic.noinline stringToBuiltinString

{-# INLINABLE stringToBuiltinString #-}
stringToBuiltinString :: Haskell.String -> BuiltinString
-- To explain why the obfuscatedId is here
-- See Note [noinline hack]
stringToBuiltinString str = obfuscatedId (BuiltinString $ pack str)

Why don't Plutus team use INLINABLE mechanism in the function fromString for TokenName? I don't know, it might be a bug.
EDIT 1
I've raised an issue on Plutus repo.
https://github.com/input-output-hk/plutus/issues/4404
EDIT 2
The issue is (see Plutus team's answer https://github.com/input-output-hk/plutus/issues/4404)

Unfortunately, due to the technical reasons plutus plugin doesn't
support OverloadedStrings with newtypes.

Notice the same thing happens with PubKeyHash (it's a newtype)

The problem is you don't have IsString in scope. If you add import Data.String should work. Here you can see it in the repl.

EDIT 1
( First part of the answer referred to how to bring into scope IsString for TokenName in the repl. )
Additionally, I've tried to compile your code with the imports and pragmas that you can see in the following code snippet and the result of compiling has been successful. Probably, you have something wrong with imports.
{-# LANGUAGE NoImplicitPrelude  #-}
{-# LANGUAGE OverloadedStrings  #-}

module Plutus.Contracts.Currency( mkPolicy ) where

import Ledger.Value ( flattenValue )
import Ledger.Contexts
    ( ScriptContext(scriptContextTxInfo),
      TxOutRef,
      TxInfo(txInfoInputs, txInfoMint),
      TxInInfo(txInInfoOutRef) )
import PlutusTx.Prelude
    ( Bool(False), Eq((==)), ($), (&&), any, traceIfFalse )

mkPolicy :: TxOutRef -> () -> ScriptContext -> Bool
mkPolicy oref () ctx = traceIfFalse "UTxO not consumed"   hasUTxO           &&
                       traceIfFalse "wrong amount minted" checkMintedAmount
  where
    info :: TxInfo
    info = scriptContextTxInfo ctx

    hasUTxO :: Bool
    hasUTxO = any (\i -> txInInfoOutRef i == oref) $ txInfoInputs info

    checkMintedAmount :: Bool
    checkMintedAmount = case flattenValue (txInfoMint info) of
        [(_, tn, amt)]  -> tn == "" && amt == 1
        _               -> False

But in week01 here there was no such import yet it still overloaded the string. Is there a special case for BuiltinByteString? I remember this because I didn't about the Overloaded String pragma ({-# LANGUAGE OverloadedStrings          #-}).

@Roofi, you are right, maybe for BuiltinByteString is different. Just curious, Does it work your code by importing Data.String?

Sorry, it doesn't.
At line 30 I changed
import           Data.String( IsString(..) )
to
import           Data.String and then tried the first code block in my question.
Also in my previous comment, I meant "didn't know about" instead of "didn't about".

@Roofi, I've just edited my answer. Please, take a look.

I think the code you provided may not raise that error as the error stems from the usage of wrapMintingPolicy. I inferred this by looking at the last line of the error block. I just edited my question to add a link to the complete code.

@Roofi, I've just added a new answer instead of  editing again my first question. (I think it will be more readable for the future)


text:
Where is the txValidRange default value set?
In lecture 3 of the Plutus Pioneer Program Vesting.hs, I noticed that the example vesting give/ grab endpoints work by waiting a number of slots after the deadline. The script then checks deadlineReached = contains (from $ deadline dat) $ txInfoValidRange info.
However, these docs for txInfoValidRange say that the default range is infinite. In the lecture video and in the playground, I don't see that we set the txInfoValidRange explicitly, so I assumed it was infinite, but that means a from range would never contain it.
I must be misunderstanding the linked documentation. At some point, the txValidRange must be getting set on the transactions submitted through the playground, otherwise, deadlineReached would always be false. I can't find where this default is being set though.
Is this set by Plutus clients? In this case, the Playground?
There is a related question here, but I understand the contains function. What I don't understand is how the txInfoValidRange is set.

This is the flow from Playground to the onchain validator:
Playground (grab) --> endpoints --> grab (offchain contract) --> validator (onchain).
txInfoValidRange is set by grab (offchain contract) in the following expression:
[line 115-117]
tx :: TxConstraints Void Void
tx = mconcat [Constraints.mustSpendScriptOutput oref unitRedeemer | oref <- orefs] <>
             Constraints.mustValidateIn (from now)

where Constraints.mustValidateIn (from now) specifically establishes that the transaction being built must validate from now to the eternity. If you don't set this Constraint, the default txInfoValidRange (all the time) will set.

Ahh, that was the gap in my understanding. The off chain code runs first and sets the TxInfo ValidRange. The validator run onchain and validates the transaction submitted by the offchain code.


text:
Documentation for filtering through the inputs of a Plutus Script
I Have 1000 utxo's sitting at a script address with unique datums is there documentation for a validator so that when collectFromScript is called it only pulls 1 utxo based on the user input matching with the datum of one of the utxo's sitting at the script?

Do you want to filter by datum in offchain code?

I want to filter by off-chain code preferably

Did my answer solve your doubt?

yes for sure thank you so much could another way to do this also be mustSpendScriptOutput

You can achieve the same thing in 2 steps: filter the map and then use mustSpendScriptOutput like in the following code snippet I've created for you: https://gist.github.com/kindofdev/47cf9e650fbd6a651e471a5e67462a9a
Don't forget up vote the answer ;)

In order to collect and filter by datum in offchain code you can use collectFromScriptFilter from Plutus.Contract. I've implemented a simple example showing the use case.
{-# LANGUAGE DataKinds           #-}
{-# LANGUAGE DerivingStrategies  #-}
{-# LANGUAGE DeriveAnyClass      #-}
{-# LANGUAGE DeriveGeneric       #-}
{-# LANGUAGE FlexibleContexts    #-}
{-# LANGUAGE NoImplicitPrelude   #-}
{-# LANGUAGE NumericUnderscores  #-}
{-# LANGUAGE OverloadedStrings   #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell     #-}
{-# LANGUAGE TypeApplications    #-}
{-# LANGUAGE TypeFamilies        #-}
{-# LANGUAGE TypeOperators       #-}
{-# LANGUAGE RecordWildCards     #-}

module Week05.OffchainFilterByDatumAndCollect where

import           Control.Monad        hiding (fmap)
import           Data.Aeson           (FromJSON, ToJSON)
import           Data.Text            (Text)
import           GHC.Generics         (Generic)
import           Plutus.Contract
import           Ledger               hiding (singleton)
import           Ledger.Ada           as Ada
import           Ledger.Constraints   as Constraints
import qualified Ledger.Typed.Scripts as Scripts
import           Plutus.Trace.Emulator  as Emulator
import qualified PlutusTx
import           PlutusTx.Prelude     hiding (Semigroup(..), unless)
import           Prelude              (IO, Semigroup (..), String, Show(..))
import qualified Prelude              as Haskell
import           Text.Printf          (printf)
import qualified Ledger.Tx            as Tx
import           Wallet.Emulator.Wallet ( knownWallet )

type Field1 = Integer
type Field2 = Integer

data MyParams = MyParams
    { mpField1 :: Field1
    , mpField2 :: Field2
    } deriving stock (Haskell.Eq, Haskell.Show, Generic)
      deriving anyclass (ToJSON, FromJSON)

data MyDatum = MyDatum
    { mdField1 :: Field1
    , myField2 :: Field2
    } deriving Show

PlutusTx.unstableMakeIsData ''MyDatum

{-# INLINABLE mkValidator #-}
mkValidator :: MyDatum -> () -> ScriptContext -> Bool
mkValidator _ _ _ = True

data Typed
instance Scripts.ValidatorTypes Typed where
    type instance DatumType Typed = MyDatum
    type instance RedeemerType Typed = ()

typedValidator :: Scripts.TypedValidator Typed
typedValidator = Scripts.mkTypedValidator @Typed
    $$(PlutusTx.compile [|| mkValidator ||])
    $$(PlutusTx.compile [|| wrap ||])
  where
    wrap = Scripts.wrapValidator @MyDatum @()

validator :: Validator
validator = Scripts.validatorScript typedValidator

valHash :: Ledger.ValidatorHash
valHash = Scripts.validatorHash typedValidator

scrAddress :: Ledger.Address
scrAddress = scriptAddress validator

type GiftSchema =
            Endpoint "give" (Integer, MyParams)
        .\/ Endpoint "grab" MyParams

give :: AsContractError e => (Integer, MyParams) -> Contract w s e ()
give (amount, MyParams{..}) = do
    let dat = MyDatum mpField1 mpField2
        lookups = Constraints.typedValidatorLookups typedValidator
        tx      = mustPayToTheScript dat $ Ada.lovelaceValueOf amount
    utx  <- mkTxConstraints lookups tx
    txid <- getCardanoTxId <$> submitUnbalancedTx (Constraints.adjustUnbalancedTx utx)
    void $ awaitTxConfirmed txid
    logInfo @String $ printf "made a gift of %d lovelace" amount

grab :: forall w s e. AsContractError e => MyParams -> Contract w s e ()
grab MyParams{..} = do
    utxos <- utxosAt scrAddress
    let dat     = MyDatum mpField1 mpField2
        flt _ ciTxOut = either id Ledger.datumHash (Tx._ciTxOutDatum ciTxOut) == Ledger.datumHash (Datum (PlutusTx.toBuiltinData dat))
        lookups = Constraints.unspentOutputs utxos <>
                  Constraints.typedValidatorLookups typedValidator
        tx      = collectFromScriptFilter flt utxos ()
    utx  <- mkTxConstraints lookups tx
    txid <- getCardanoTxId <$> submitUnbalancedTx (Constraints.adjustUnbalancedTx utx)
    void $ awaitTxConfirmed txid
    logInfo @String $ "collected gifts"

endpoints :: Contract () GiftSchema Text ()
endpoints = awaitPromise (give' `select` grab') >> endpoints
  where
    give' = endpoint @"give" give
    grab' = endpoint @"grab" grab

-- w1 gives 10 (datum1) + 20 (datum2)
-- w2 grab  10 (datum1)
-- script locks 20 (datum2)
test :: IO ()
test = runEmulatorTraceIO $ do
    let params1 = MyParams 1 1
        params2 = MyParams 2 2
    h1 <- activateContractWallet (knownWallet 1) endpoints
    h2 <- activateContractWallet (knownWallet 2) endpoints
    callEndpoint @"give" h1 (10_000_000, params1)
    void $ Emulator.waitNSlots 1
    callEndpoint @"give" h1 (20_000_000, params2)
    void $ Emulator.waitNSlots 1
    callEndpoint @"grab" h2 params1
    void $ Emulator.waitNSlots 1

In plutus-use-cases repo you can find more interesting examples:

https://github.com/input-output-hk/plutus-apps/blob/main/plutus-use-cases/src/Plutus/Contracts/Crowdfunding.hs

https://github.com/input-output-hk/plutus-apps/blob/main/plutus-use-cases/src/Plutus/Contracts/Escrow.hs


text:
cardano-cli not showing utxo but Testnet Blockchain Explorer does
I have requested funds via Faucet, twice in fact because the first one I thought the request didn't go through but when I run:
cardano-cli query utxo --address $(cat 01.addr) --testnet-magic 1097911063

I don't get the utxo output but only get a blank line for the hash and transactions. However when I look up the address in the Cardano Blockchain Explorer Testnet I can in fact verify I have 2000 ADA's in that address.
I wonder why this is or what I might have missed doing. Any help will be highly appreciated.

Is your local cardano-node fully updated?

Not sure. I've been running it but how do I know when the node is fully updated?

With : cardano-cli query tip --testnet-magic 1097911063 .
As result you should get: "syncProgress": "100.00"

I can confirm allowing the node to fully sync with the blockchain which incidentally took quite a bit of time fixed the issue. Once the sync was fully established the cardano-cli did output the relevant utxo info.


text:
funding a wallet
I've created a wallet with create-wallet.sh and loaded it with load-wallet.sh, and its balance is 0:
"balance":{"total":{"quantity":0,"unit":"lovelace"},"available":{"quantity":0,"unit":"lovelace"},"reward":{"quantity":0,"unit":"lovelace"}}

Lars says in the video that we can connect this wallet to Daedalus or Yoroi and then use the Faucet to fund the wallet. Is there a way to fund the wallet directly, without Daedalus or Yoroi? I have already used Faucet at a previous step, the balance of the address I have used is 999.656267 ADA and I should be able to connect the wallet to these funds.

You might do as follows:

create-wallet.sh (create a new wallet)

load-wallet.sh (load new wallet into wallet-backend)

Take id value from load-wallet.sh result.

Set WALLETID=id in your env.sh

. env.sh (source env.sh)

get_address.sh  (get the address of the new wallet)

Use send.sh (week03) in order to transfer funds from your funded address to your new address.

cardano-cli transaction build \
    --alonzo-era \
    --testnet-magic 1097911063 \
    --change-address <address_with_funds> \
    --tx-in <an_utxo_id_with_funds> \
    --tx-out "<your_new_address> <ada_to_tranfer> lovelace" \
    --out-file tx.body

cardano-cli transaction sign \
    --tx-body-file tx.body \
    --signing-key-file <skey_of_address_with_funds> \
    --testnet-magic 1097911063 \
    --out-file tx.signed

cardano-cli transaction submit \
    --testnet-magic 1097911063 \
    --tx-file tx.signed

Hope this will be useful.

$ ./sendWallet.sh
Estimated transaction fee: Lovelace 166953
Transaction successfully submitted.
That's great, it worked, balance is also updated.


text:
NFT minting using unique base64 encoded asset as input
Regarding the Week05 course material. It is recommended in the lecture on NFT minting policy that rather than rely on a deadline and constraint of 1 token per mint, that a unique input such as a UTxO be used, along with said 1 token constraint.
I was wondering, could an alternate unique input be a base64 (or other encoding scheme) of the actual NFT asset? Further, assuming this encoded string has been checked that it fits in the block size, could it be stored as datum somehow? (Though if I recall minting policies do not output datum, somebody please correct me if I am wrong.)

Creating an NFT using an tx hash (unspent) is exactly what the state machine thread token does.   You can see how by looking at the plutus source code for state machine below.  You can then use a forward minting policy hash and store it in the datum so each time a token is minted, the minting policy can ensures that no identical tokens are minted.
let mph = Scripts.forwardingMintingPolicyHash typedValidator

-- | Create a thread token. The thread token contains a reference to an unspent output of the wallet,
-- so it needs to used with 'mkStateMachine' immediately, and the machine must be initialised,
-- to prevent the output from getting spent in the mean time.
getThreadToken :: AsSMContractError e => Contract w schema e ThreadToken
getThreadToken = mapError (review _SMContractError) $ do
    txOutRef <- getUnspentOutput
    pure $ ThreadToken txOutRef (scriptCurrencySymbol (curPolicy txOutRef))

https://playground.plutus.iohkdev.io/doc/haddock/plutus-contract/html/src/Plutus.Contract.StateMachine.ThreadToken.html

By input, I assume you mean TokenName or CurrencySymbol.
CurrencySymbol is the hash of your script, so you cannot act on it. Having a particular TokenName does not solve the problem because the rules of the minting policy (whether it returns True or False given a context and a redeemer) determine if the token can be minted.
You can write:
mkPolicy :: TokenName -> () -> ScriptContext -> Bool
mkPolicy tn () ctx = traceIfFalse "wrong amount minted" checkMintedAmount
      where
    checkMintedAmount :: Bool
    checkMintedAmount = case flattenValue (txInfoMint . scriptContextInfo $ ctx) of
        [(_, tn', amt)] -> tn' == tn && amt == 1
        _               -> False

Deploying the contract with parameter 0x849720EF472980, if two people try to mint an amount of 1 (PutScriptHashHere, 0x849720EF472980), they will both succeed.
Putting deadlines will not solve the problem as the two can still both mint before the deadline.
The presence of a datum could solve the problem as you could have an Int which is incremented till it is one (or a Boolean).

As you mention it, there is none (although I did not understand exactly why there could not be).
If two minting transactions get to nodes at the same timeslot, both should succeed.

This isn't an answer, because I was wondering as well how to do the following, which may or may not be the same thing as you're asking how to do:
How do you prevent the same item (hash of a digitized item) from being tokenized into an NFT more than once when the script doesn't have access to the blockchain history?
Maybe it's possible to use the Statemachine feature to maintain a map of NFTs to item hashes, so it could track all the item hashes that have been minted with this policy?
I guess someone else could possibly make trivial changes to the policy's code just to change the script address, and then could mint a duplicate NFT of the same asset, but a statemachine could at least track assets for this one particular script.
This is all assuming a minting policy script can work with a statemachine, or a Datum.
Edit:
I noticed in this set of instructions for minting NFTs using the cardano-cli that metadata can be attached to the NFT. https://developers.cardano.org/docs/native-tokens/minting-nfts/
Meaning that it might be possible to add a datum value to the minted token somehow.
In order to check for duplicates across the whole BC, it might be necessary to use a third party NFT registry app.
Edit 2:
One thing that shows up in a later Plutus Pioneer lecture is using an NFT to verify that the correct oracles are being referenced. I think it's in the Uniswap code. The Uniswap operator mints an NFT as a kind of id, and the SC that runs the swap pools uses that NFT to make sure that only the operator can control the Dapp.
Using that idea, your contract could do something similar, making sure that no one else is running the same contract to make duplicates. This combined with some form of mapping to make sure no one duplicates the same asset on your contract, and registering with an NFT registry, might be a fairly solid way to ensure uniqueness of the assets being tokenized.
I could of course be missing something, I'm fairly new to this too.


text:
How to resolve npm build failure after running `GC_DONT_GC=1 npm start`?
MacOs Catalina 10.15.7 (Intel)
After facing issue here, I ran the command GC_DONT_GC=1 npm run start and it build some libraries, however failed with following error (plutus-playground-server was up and running):
79 silly inflate node_modules/@xtuc/ieee754
80 http fetch GET 200 https://registry.npmjs.org/@webassemblyjs%2fleb128 119ms (cache revalidated)
81 silly inflate node_modules/@xtuc/long
2686 error                         ^
2686 error ../src/libsass/src/ast.hpp:1616:14: note: use reference type 'const std::__1::basic_string<char> &' to prevent copying
2686 error         for (const auto denominator : denominators)
2686 error              ^~~~~~~~~~~~~~~~~~~~~~~~
2686 error                         &
2686 error 2 warnings generated.
2686 error In file included from ../src/binding.cpp:1:
2686 error In file included from ../../nan/nan.h:56:
2686 error In file included from /Users/CrosbyTop/Library/Caches/node-gyp/17.0.1/include/node/node.h:63:
2686 error In file included from /Users/CrosbyTop/Library/Caches/node-gyp/17.0.1/include/node/v8.h:25:
2686 error In file included from /Users/CrosbyTop/Library/Caches/node-gyp/17.0.1/include/node/v8-array-buffer.h:12:
2686 error In file included from /Users/CrosbyTop/Library/Caches/node-gyp/17.0.1/include/node/v8-local-handle.h:12:
2686 error /Users/CrosbyTop/Library/Caches/node-gyp/17.0.1/include/node/v8-internal.h:566:38: error: no template named 'remove_cv_t' in namespace 'std'; did you mean 'remove_cv'?
2686 error             !std::is_same<Data, std::remove_cv_t<T>>::value>::Perform(data);
2686 error                                 ~~~~~^~~~~~~~~~~
2686 error                                      remove_cv
2686 error /Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/type_traits:697:50: note: 'remove_cv' declared here
2686 error template <class _Tp> struct _LIBCPP_TEMPLATE_VIS remove_cv
2686 error                                                  ^
2686 error 1 error generated.
2686 error make: *** [Release/obj.target/binding/src/binding.o] Error 1
2686 error gyp ERR! build error
2686 error gyp ERR! stack Error: `make` failed with exit code: 2
2686 error gyp ERR! stack     at ChildProcess.onExit (/Users/CrosbyTop/projects/cardano/ppp3/plutus-apps/plutus-playground-client/node_modules/node-gyp/lib/build.js:194:23)
2686 error gyp ERR! stack     at ChildProcess.emit (node:events:390:28)
2686 error gyp ERR! stack     at Process.ChildProcess._handle.onexit (node:internal/child_process:290:12)
2686 error gyp ERR! System Darwin 19.6.0
2686 error gyp ERR! command "/usr/local/Cellar/node/17.0.1/bin/node" "/Users/CrosbyTop/projects/cardano/ppp3/plutus-apps/plutus-playground-client/node_modules/node-gyp/bin/node-gyp.js" "rebuild" "--verbose" "--libsass_ext=" "--libsass_cflags=" "--libsass_ldflags=" "--libsass_library="
2686 error gyp ERR! cwd /Users/CrosbyTop/projects/cardano/ppp3/plutus-apps/plutus-playground-client/node_modules/node-sass
2686 error gyp ERR! node -v v17.0.1
2686 error gyp ERR! node-gyp -v v7.1.2
2686 error gyp ERR! not ok
2686 error Build failed with error code: 1
2687 verbose exit 1

Welcome to Cardano SE! As a new user be sure to take the [Tour].

Actually, changing node-sass version to ^7.0.0 inside package-json helped me, however I am not sure it did not break any dependencies.
Node 17+ is not supported by node-sass ^5.

Welcome to Cardano SE! As a new user be sure to take the [Tour].


text:
"No unfolding" error in Visual Studio Code
I copied the Plutus starter template, Plutus Platform starter project, and created a file, BasicPlutusTx.hs (and added it under exposed-modules in the .cabal file).
Then I started copying over all the code from the introductory tutorial, Using Plutus Tx.
When I added the code,
functions :: CompiledCode Integer
functions = $$(compile [|| myProgram ||])

it caused Visual Studio Code to complain, giving an error at the top of the file:
Program error: GHC Core to PLC plugin: E043:Error: Reference to a name which is not a local, a builtin, or an external INLINABLE function: Variable PlutusTx.Builtins.addInteger
            No unfolding
Context: Compiling expr: PlutusTx.Builtins.addInteger
Context: Compiling expr: PlutusTx.Builtins.addInteger
                           (PlutusTx.Builtins.addInteger 1 1)
Context: Compiling expr: PlutusTx.Builtins.addInteger
                           (PlutusTx.Builtins.addInteger 1 1) (BasicPlutusTx.plusOne 1)
Context: Compiling definition of: BasicPlutusTx.myProgram
Context: Compiling expr: BasicPlutusTx.myProgram
Context: Compiling expr at "main:BasicPlutusTx:(76,16)-(76,41)"compile

However, cabal build still works.

If I recall correctly, this error can happen during the first evaluation, but will be gone during subsequent ones. This is due to unfolding not be available from the start, but only once the module has been compiled for the first time.

@angerman Am I running VSCode wrong? I'm starting nix-shell and then calling code from there

I see there's a flag in the project which enables the fix, but I don't see how or why VSCode would enable this flag

Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.


text:
nix-build not found inside nix-shell (Linux)
Every time I enter nix-shell, I need to execute the following command, otherwise nix-build and other nix-* commands are not found.
source /home/xxx/.nix-profile/etc/profile.d/nix.sh

I have added the following into file ~/.profile, but it does not seem to be working.
if [ -e /home/xxx/.nix-profile/etc/profile.d/nix.sh ]; then source /home/xxx/.nix-profile/etc/profile.d/nix.sh; fi # added by Nix installer

What's the reason for that? How can I get source /home/xxx/.nix-profile/etc/profile.d/nix.sh automatically when I run nix-shell?

Welcome to Cardano SE! As a new user be sure to take the [Tour].
Also, this seems to be a nix question rather than a Cardano question and it should not be on this site if that is the case.

This is fairly odd and should not happen. nix-shell would know how to set your profile. So what you are saying is it works in your regular shell, but fails in nix-shell. Can you please provide more info around the context? What system do you run on, ...?

Yes, context information is going to be essential to find the problem here. Perhaps the shell is overwritting the PATH a bit too aggresively. If you have a link or a relevant snippet from the shell.nix, please share

Thanks @nrdxp! I'm running on Ubuntu, I run shell.nix from plutus-apps, should I change the this file somehow?

Hi @gRebel, I had this problem when I run plutus-apps for plutus pioneer program.

If it is a generic nix problem, it shoudn't be here.  If nix is fine and the problem is with the plutus-apps package, then it might be relevant here is if it fits the [help/on-topic] on-topic criteria.

I had trouble getting the plutus playground environment to run properly until I followed the directions in this link https://docs.plutus-community.com/docs/setup/Ubuntu.html and first did the uninstall at the bottom of the page and did the re-install (as explained on the same page from the link provided above) for multiple-user. The multi-user version is recommended on the actual Nix website.  When I got to this line "Note If you will be working on the Plutus Pioneer Project, it will be necessary at this point to git checkout ... a specific commit to match the class materials. That commit hash is listed in the exercises week## directory in the cabal.project", I followed along with the tutorial listed below to compile the "English Auction" code from week01:  https://youtu.be/zPaDp4R9X7o?t=177  Your folders might vary from the instructors, so listen carefully to where you clone the repositories he mentions.

Thanks! I'm aware of the specific commit for the repo, like I said everything works after I do source /home/xxx/.nix-profile/etc/profile.d/nix.sh each time entering nix-shell. I believe the path environment somehow is overwritten incorrectly after nix-shell, but don't know where to change it.

Perhaps related, I think I must have installed Nix twice, or a build or shell, still learning, but I think I created two different profile-link-1 and profile-link-2 in the directory /nix/var/nix/profiles/per-user/.  When I do a nix doctor --verbose I was getting a multiple versions fail (https://cardano.stackexchange.com/questions/6648/nix-doctor-verbose-fail-multiple-versions-of-nix-found-in-path-on-macos-i7). Maybe someone smarter than me can help on how this happens, and if linked.

As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.


text:
Is there a way to set a trigger on Blockfrost to know when an asset has been moved?
With Blockfrost, I can easily query which assets belong to a staking address using /accounts/{stake_address}/addresses/assets. I would like to use this approach to allow users to associate their accounts with an ADA Handle. However, I don't see an easy way to check when the Handle has been moved to a different wallet (besides querying Blockfrost every x hours). Is there a better approach using Blockfrost? Should I look into hosting a node instead?

Using Tango (so not Blockfrost), this should be possible in two weeks. See here.

I don't think Blockfrost offers event based callbacks like that. You might want to look into tangocrypto, but as far as I can tell they also don't offer webhooks for this specific type of event: https://docs.tangocrypto.com/notify/notify/using-webhooks#types-of-wehooks
Maybe it's worth getting in touch with them as I think it could potentially be an interesting addition for their service.
The other option would be to set up a cardano node, as you said, and connect a db-sync (postgres) instance which you can query.

I contacted both Blockfrost and Tango about this feature, so hopefully at least one of them will consider adding it. In the meantime, looks like I'll be setting up a node and db-sync. Thanks for your help!


text:
What is the difference between "cabal build" and "cabal repl"?
What does "cabal repl" does and how it differentiates from "cabal build"?
the documentation says:

loads all of the modules of the target into GHCi as interpreted bytecode

But I dont fully understand when do I need to use that command

In our context of smart contracts, cabal build builds the executables needed for doing cabal run, which we use to build the Plutus validator.
cabal repl, in the other hand loads all the modules that are in your project into GHCi, which is ready to be used in interpreted code. In this context you can test your validator or your off-chain code in an interactive way, which is useful to test behavior of specific functions in your code.


text:
What is the correct way to compare DatumHash?
What is the correct way to compare DatumHash?
I imported the Eq function from PlutusTx
import PlutusTx.Prelude (Eq((==)))
...

checkDatumHash :: TxOut -> Bool
    checkDatumHash txOut = traceIfFalse "Incorrect datum" (own_dh == Just new_dh)
        where

            --d = Datum (PlutusTx.toBuiltinData nfts)
            --dh = fromJust (findDatumHash (Datum (PlutusTx.toBuiltinData nfts)) info)
            --new_d = findDatum dh info
            new_dt = nfts {p = r_prct, l = mk_prct}
            new_dh = datumHash (Datum (PlutusTx.toBuiltinData new_dt))
            own_dh =   txOutDatumHash txOut

It's fine to compare 2 Datum datas or PubKeyHash but I got unsupported feature error when compare 2 DatumHash data. (For above example, it's fine to compare: new_d == Just d)
GHC Core to PLC plugin: E042:Error: Unsupported feature: Kind: forall k. k -> *
Context: Compiling kind: forall k. k -> *
...

The error message may not show the direct issue, it points to my validator
typedBuyValidator :: [PubKeyHash] -> Scripts.TypedValidator Sale
typedBuyValidator [pkh1, pkh2] = Scripts.mkTypedValidator @Sale
    ($$(PlutusTx.compile [|| mkBuyValidator ||]) `PlutusTx.applyCode` PlutusTx.liftCode [pkh1, pkh2])
    $$(PlutusTx.compile [|| wrap ||])
  where
    wrap = Scripts.wrapValidator @DatumInfo @RedeemInfo

Why both DatumHash and PubKeyHash look very similar where both are wrapper of  PlutusTx.BuiltinByteString but issue happened only in DatumHash?
Another strange thing to me that I can compile the code using function findDatum from Ledger successfully where this also makes comparison of DatumHash inside.
findDatum :: DatumHash -> TxInfo -> Maybe Datum
findDatum dsh TxInfo{txInfoData} = snd <$> find f txInfoData
    where
        f (dsh', _) = dsh' == dsh

UPDATE:
I tested the comparision DatumHash by getting another own_dh1 to compare with own_dh and it compiled successfully:
checkDatumHash :: TxOut -> Bool
    checkDatumHash txOut = traceIfFalse "Incorrect datum" (own_dh == own_dh1)
        where

            --d = Datum (PlutusTx.toBuiltinData nfts)
            --dh = fromJust (findDatumHash (Datum (PlutusTx.toBuiltinData nfts)) info)
            --new_d = findDatum dh info
            new_dt = nfts {p = r_prct, l = mk_prct}
            new_dh = datumHash (Datum (PlutusTx.toBuiltinData new_dt))
            own_dh =   txOutDatumHash txOut
            own_dh1 =   txOutDatumHash txOut

Then I thought that maybe the problem may not relate to comparision but datumHash function which is hashing Datum to DatumHash was not allowed to run on Onchain code. Am I correct ?
new_dh = datumHash (Datum (PlutusTx.toBuiltinData new_dt))

Looked into plutus fw code, I found the function datumHash will eventually call to this function
-- NOT a builtin, only safe off-chain, hence the NOINLINE
{-# NOINLINE builtinDataToData #-}
-- | Convert a 'BuiltinData' into a 'PLC.Data'. Only works off-chain.
builtinDataToData :: BuiltinData -> PLC.Data
builtinDataToData (BuiltinData d) = d

I guess it's not possible to run datumHash in on-chain, this also caused my issue.


text:
Building a transaction on cardano-cli/api without running node?
Is there a way to build and sign transactions with the cardano-cli/api without running a node? I am trying to construct a transaction using the cli or api and submit it using blockfrost. It throws an error about the CARDANO_NODE_SOCKET_PATH since I am not running a node locally. Any help would be appreciated. I would prefer to avoid using the cardano-serialization-lib since I want all my offchain code to be in Haskell too.

You dont need a node at all to build or sign CLI transactions (i.e. assuming you're using cardano-cli transaction build-raw. The only point you might need to look up something from a live node is getting UTxOs to your address (and checking TTL), but atleast for latter you can also calculate current slot remotely (or use tip from your API provider).
As regards input UTxO , blockfrost as well as Koios both offer checking address utxos.

You could try building on/with parts of the plutus-apps repo.
It doesn't need a node.
However this is not its intended use case so it won't be without problems.
You'll probably have to write your own minAda function, your own balancer, and your own fee calculator. These are deemed the responsibility of the wallet - at present only the cardano-wallet is feature complete and integrated into plutus in that sense.
The cardano-wallet will not be happy if you don't point it at a node socket.

plutus-apps is pretty much abandoned https://github.com/input-output-hk/plutus-apps/commit/f4790acbf901cfd546ff57b7052b20f1addbd57b

I believe that error only comes up when you try to push a transaction
sounds like you've already constructed your transaction with cardano-cli - if not this is available via github, just grab the latest binary release from the cardano node repo, it'll include cardano-cli
at any rate, once you have your transaction built and signed it's just a matter of submitted it to the blockchain.
a couple of options, us a wallet like eternl, you can import your own transactions and use their nodes to push it, this is available under Send > Options > Import
alternatively you can use any of the publicly available cardano node apis


text:
Plutus: multiple-utxo withdraw fails, single-utxo withdraw succeeds
A beneficiary tries to withdraw the maximum amount from 2 utxo's of a smart contract in one transaction but that fails. If the beneficiary does it in two steps it succeeds.
Why does the first one fail?
Detail :
-------------------------------------------------------------------------
ben         | addr_test1v⋯qarpt4  | = 1101556208 |
            | - 714d2e⋯dea7cb#0   | +    1021470 | [ "ben"×1 ] Token
            | - 714d2e⋯dea7cb#1   | + 1100534738 |
-------------------------------------------------------------------------
tokencheck  | addr_test1w⋯hyha8n  | =   34000000 |
            | - 347def⋯58e2c7#0   | +   21000000 | {14e594⋯4816fa} Datum
            | - dca3bc⋯b80ae8#0   | +   13000000 | {14e594⋯4816fa} Datum

The beneficiary 'ben' tries to withdraw the maximum amount from smart contract 'tokencheck',
and in that transaction also includes his token 'ben' (62656e),  to fulfill a condition in the contract.
Ben tries to withdraw from both the utxo's of the contract (both have the same, correct datum) :
# total amount = 21000000 (contract) + 13000000 (contract) + 1021470 (ben token) - 966660 (fee) = 34054810

cardano-cli transaction build-raw
  --babbage-era
  --protocol-params-file protocol-parameters.json
  --tx-in "714d2e⋯dea7cb#0"                    # utxo with ben's token
  --tx-in "347def⋯58e2c7#0"                    # first utxo of contract
  --tx-in "dca3bc⋯b80ae8#0"                    # second utxo of contract
  --tx-in-datum-file datum.json
  --tx-in-redeemer-file redeemer.json
  --tx-in-script-file tokencheck.json
  --tx-in-collateral "714d2e⋯dea7cb#1"
  --required-signer ben.skey
  --tx-out "addr_test1v⋯qarpt4 + 34054810 + 1 2d99fb⋯63d3a1.62656e"
  --fee 966660
  --tx-in-execution-units '(3000000000,7000000)'
  --out-file tx_raw.json

This fails when submitting, with error message:
Command failed: transaction submit  Error: Error while submitting tx: ShelleyTxValidationError
ShelleyBasedEraBabbage (ApplyTxError
[UtxowFailure(
  FromAlonzoUtxowFail
    (MissingRedeemers [(Spending (TxIn (TxId {_unTxId = SafeHash "347def⋯58e2c7"}) (
        TxIx 0)),ScriptHash "5c2d3c⋯7d947b")])),
UtxowFailure (
  UtxoFailure (FromAlonzoUtxoFail (UtxosFailure (CollectErrors
    [NoRedeemer (Spending (TxIn (TxId {_unTxId = SafeHash "347def⋯58e2c7"}) (TxIx 0)))])))
    )
])

If Ben just withdraws using only ONE of the contract's utxo's, the transaction succeeds:
# total amount = 21000000 + 1021470 - 953284 = 21068186

cardano-cli transaction build-raw
  --babbage-era
  --protocol-params-file protocol-parameters.json
  --tx-in "714d2e⋯dea7cb#0"                    # utxo with ben's token
  --tx-in "347def⋯58e2c7#0"                    # one utxo of contract
  --tx-in-datum-file datum.json
  --tx-in-redeemer-file redeemer.json
  --tx-in-script-file tokencheck.json
  --tx-in-collateral "714d2e⋯dea7cb#1"
  --required-signer ben.skey
  --tx-out "addr_test1v⋯qarpt4 + 21068186 + 1 2d99fb⋯63d3a1.62656e"
  --fee 953284
  --tx-in-execution-units '(3000000000,7000000)'
  --out-file tx_raw.json

Transaction successfully submitted.

Question: why does the first transaction fail while the second succeeds?
Update
Here's the contract, it's written in Helios:
struct Datum {
    donor:        PubKeyHash
    beneficiary:  PubKeyHash
    policy:       MintingPolicyHash
}

func main(datum: Datum, ctx: ScriptContext) -> Bool {
    tx: Tx = ctx.tx;
    if (tx.is_signed_by(datum.donor)) {
        true
    } else {
        if ( tx.value_sent_to(datum.beneficiary).get(AssetClass::new(datum.policy, #62656e)) == 1) {
            true
        } else {
            print("computer says no"); false
        }
    }
}

Does contract only allows one input utxo that requires script to be consumed per transaction? Can you check or share the contract code too.

Contract added to the text above.
I don't think the problem is with the contract's code, because it would give a different error.

Yeah i see. Could it be due to build-raw requiring tx-in-script-file, datum redeemer for each input. I think it can be repeated and order matters. You can try that but not sure if it automatically uses same script, datum, redeemer for two inputs.

The solution is, as Nabin suggested, to repeat after each contract-utxo the datum/redeemer/script and execution units arguments as shown here:
cardano-cli transaction build-raw
  --babbage-era
  --protocol-params-file protocol-parameters.json
  --tx-in "344b8c⋯a3325e#0"                     # utxo with ben's token
  --tx-in "9b7697⋯dbb2e4#0"                     # contract utxo #1
  --tx-in-datum-file datum.json
  --tx-in-redeemer-file redeemer.json
  --tx-in-script-file tokencheck.json
  --tx-in-execution-units '(3000000000,7000000)'
  --tx-in "f44eee⋯db6906#0"                     # contract utxo #2
  --tx-in-datum-file datum.json
  --tx-in-redeemer-file redeemer.json
  --tx-in-script-file tokencheck.json
  --tx-in-execution-units '(3000000000,7000000)'
  --tx-in-collateral "344b8c⋯a3325e#1"
  --required-signer ben.skey
  --tx-out "addr_test1v⋯qarpt4 + 33323655 + 1 2d99fb⋯63d3a1.62656e"
  --fee 1697815
  --out-file tx_raw.json

Transaction successfully submitted.

Indeed: datum/redeemer and script need to be specified for each utxo separately


text:
Get public key into PubKeyHash and use it in mustBeSignedBy
A user provides me with his wallet pub key as BultinByteString (or Haskell string, fine either way). From that, I need to get the PubKeyHash, but I am not sure how to hash it or if I need to hash it at all.
Then, I need to use it in the PubKeyHash in Ledger.Constraints.MustBeSignedBy in my state machine. Kinda like that:
Constraints.mustBeSignedBy "35dedd2982a03cf39e7dce03c839994ffdec2ec6b04f1cf2d40e61a3"

or
Constraints.mustBeSignedBy PubKeyHash { getPubKeyHash = "35dedd2982a03cf39e7dce03c839994ffdec2ec6b04f1cf2d40e61a3" }

The problem is when I put some PubKeyHash in the constraint (like above), the compiler spits out 5000 long error starting with:
GHC Core to PLC plugin: E042:Error: Unsupported feature: Use of fromString on type other than builtin strings or bytestrings: Plutus.V1.Ledger.Crypto.PubKeyHash
Context: Compiling expr: Data.String.fromString
                           @ Plutus.V1.Ledger.Crypto.PubKeyHash
                           Plutus.V1.Ledger.Crypto.$fIsStringPubKeyHash
                           (GHC.CString.unpackCString#
                              "a2c20c77887ace1cd986193e4e75babd8993cfd56995cd5cfce609c2"#)

Can the string be translated into the PubKeyHash? Can it be somehow fixed? Is it me, or is it a Plutus bug?
Edit:
Tried new code:
Constraints.mustBeSignedBy $ pubKeyHash (PubKey {
                            getPubKey = LedgerBytes {
                                    getLedgerBytes = "35dedd2982a03cf39e7dce03c839994ffdec2ec6b04f1cf2d40e61a3"
                                }
                        })

Got new error:
 GHC Core to PLC plugin: E042:Error: Unsupported feature: Type constructor: GHC.Prim.Char#
Context: Compiling type: GHC.Prim.Char#
Context: Compiling data constructor type: GHC.Types.C#
Context: Compiling type: GHC.Types.Char
Context: Compiling type: GHC.Base.String
Context: Compiling type: GHC.Base.String
                         -> Plutus.V1.Ledger.Bytes.LedgerBytes
Context: Compiling definition of: Plutus.V1.Ledger.Bytes.$fIsStringLedgerBytes_$cfromString
Context: Compiling expr: Plutus.V1.Ledger.Bytes.$fIsStringLedgerBytes_$cfromString
Context: Compiling expr: Plutus.V1.Ledger.Bytes.$fIsStringLedgerBytes_$cfromString
...

Did you add OverloadedStrings pragma?

Yes, I do have that pragma at the beginning of my file. No other issues with strings occurred in my state machine contract.

It's an issue with Plutus core. Even though PubKeyHash is part of IsString type class, we can't use OverloadedStrings mechanism in on-chain code for certain types. Basically, the problem is this:

Unfortunately, due to the technical reasons plutus plugin doesn't
support OverloadedStrings with newtypes.

Please, check this issue.
https://github.com/input-output-hk/plutus/issues/4404
Same thing apply for PubKeyHash and LedgerBytes.
A solution might be to have a parameterized validator script with PubKeyHash. This way, you can build PubkeyHash offchain using OverloadedStrings and pass it to the validator.

Thank you! Parameterized validator script with PubKeyHash works like a charm. Indeed a fascinating issue.

@MartinDrozdík You’re welcome. glad to help!


text:
StateMachine - keep the same value for the next state
I work with the StateMachine library, and I need to transition from state to another where the stateValue of the State is exactly the same. The problem is that when I try to do the transition, I get an error that the user has insufficient funds pointing at the thread token. I presume that the stateValue of a State already includes the thread token, but it is added one more time or something like that. In summary, I have this (simplified):
{-# INLINABLE transition #-}
transition :: ContractParam -> State ContractDatum -> ContractRedeemer -> Maybe (TxConstraints Void Void, State ContractDatum)
transition cParam cState cRedeemer =
  ...

     -- This is simply what I need to transition to
     Just(mempty, State ("some updated datum") (stateValue cState))

  ...

To summarize, I need to keep the same stateValue into the next state but get insufficient funds error, so I presume I need something like (stateValue cState) - threadToken except the threadToken is not of type Value and I can not figure out, how to convert the thread token to Value or how to remove the thread token from stateValue so that I don't get the insufficient funds error.

Edit: The code snippet should work as is, but there was a bug. The newest plutus versions work.

Which version of plutus are you using? IIRC a problem like that was fixed in the last couple of months and maybe updating your dependencies to the latest plutus-apps (repository was split in two) might help already.

I am using an older plutus from time of plutus pioneer program #2. I am not sure what plutus version is that but I will try updating it.

Yes! Thank you, I updated to the latest plutus-starter project, and it is working as intended!


text:
What documentation works with handling utxos at the Plutus Script?
I am trying to make a Plutus smart contract which takes tokens locked to the contract and then on endpoint call (purchase) sends 1 to the caller and then the rest back to the contract. I cant find a distribution model for this I would assume you would have to create a new utxo out of the existing utxo and reduce it down into a single token on the script but I am very lost with this process.
I need help figuring this out so that I can create this send 1 token out of many script. A specific answer is what I'm looking for.
This is the code relevant to the problem, but it currently does not work.
purchaseUtxo :: ChainIndexTxOut
purchaseUtxo = case fromTxOut (scriptTxOut (Value.singleton (policyID contractInfo) (nameOfToken contractInfo) (1)) validate (Datum $ PlutusTx.toBuiltinData ()) )  of
    Nothing     ->  error ()
    Just x      ->  x

purchase ::  AsContractError e => PurchaseParams -> Contract w s e ()
purchase p=  do
    utxos <- fundsAtAddressGeq valAddress (Ada.lovelaceValueOf 1)
    let utxoMap = Map.singleton (TxOutRef (_citxTxId ChainIndexTx) 1) purchaseUtxo
        redeemer = ()
        pkh = ownPubKey
        tx       = Constraints.mustPayToTheScript () price <> collectFromScript utxoMap redeemer

    void (submitTxConstraintsSpending lootBox utxos tx)

And here is the error:

Compilation Error, Line 148, Column 54 (jump)

error:
• Couldn't match expected type ‘ChainIndexTx’
with actual type ‘TxId
-> Data.Set.Internal.Set TxIn
-> ChainIndexTxOutputs
-> SlotRange
-> Map DatumHash Datum
-> Map RedeemerHash Redeemer
-> Map ScriptHash Script
-> Maybe SomeCardanoApiTx
-> ChainIndexTx’
• Probable cause: ‘ChainIndexTx’ is applied to too few arguments
In the first argument of ‘_citxTxId’, namely ‘ChainIndexTx’
In the first argument of ‘TxOutRef’, namely
‘(_citxTxId ChainIndexTx)’
In the first argument of ‘Map.singleton’, namely
‘(TxOutRef (_citxTxId ChainIndexTx) 1)’
| 148 |     let utxoMap = Map.singleton (TxOutRef (_citxTxId ChainIndexTx) 1) purchaseUtxo
|                                                      ^^^^^^^^^^^^

on endpoint call sends 1 to the caller and then the rest back to the contract

Remember, the on-chain portion of a contract doesn't do anything actively, it only validates transactions. So a more accurate way to phrase this would be, "the script only validates transactions that spend 1 ADA and return the rest to the script."
I think everything you need to write a validator you could find in the auction code. Notice that it stores the current bid amount in the datum and that datum is attached to the actual UTxO with the value.
    ownOutput   :: TxOut
    outputDatum :: AuctionDatum
    (ownOutput, outputDatum) = case getContinuingOutputs ctx of
        [o] -> case txOutDatumHash o of
            Nothing   -> traceError "wrong output type"
            Just h -> case findDatum h info of
                Nothing        -> traceError "datum not found"
                Just (Datum d) ->  case PlutusTx.fromData d of
                    Just ad' -> (o, ad')
                    Nothing  -> traceError "error decoding data"
        _   -> traceError "expected exactly one continuing output"

    correctBidOutputDatum :: Bid -> Bool
    correctBidOutputDatum b = (adAuction outputDatum == auction)   &&
                              (adHighestBid outputDatum == Just b)

    correctBidOutputValue :: Integer -> Bool
    correctBidOutputValue amount =
        txOutValue ownOutput == tokenValue Plutus.<> Ada.lovelaceValueOf amount

If instead of the close endpoint, you have a take distributions endpoint, you could just do a similar check that the datum was updated and the value wasn't decremented by more than 1.
At that point, it is up to the caller to build a transaction in their own benefit. Again, the off-chain code in the above auction example could be adapted to build a transaction to claim distributions.

Thanks ill try this method

Did you have any luck?

yes I think I understand it better now thank you

On casual search I think what you need is Ledger.TxConstraint:
https://playground.plutus.iohkdev.io/doc/haddock/plutus-ledger-constraints/html/src/Ledger.Constraints.TxConstraints.html


text:
Is there any way to wrap a cardano native asset to eth?
I am looking for wrapping some native cardano tokens to the etherium network is there any way to achieve the same? Any help or urls will be very helpfull.

It can be done with Milkomeda C1 sidechain and Nomad bridge. See the Ethereum to Cardano walkthrough here: https://medium.com/@wingriderscom/how-to-transfer-erc20-assets-to-cardano-ba9c7b9b5a5

there is only limitted number of tokens are available if i want to wrap a token which is not in at thease list what i have to do for example a nft.

I am accepting the answer how ever there is no way to wrap many tokens out there nfts also a problem now.


text:
How to start building native tokens on ADA block chain
I saw this blog post from IOHK about building native tokens on ada network. In this particular post apart from command lines a web interface is being discussed but I can find a valid link on that particular post is there some one can give me a good direction in this?
The link which i have saw is below.
https://iohk.io/en/blog/posts/2021/02/18/building-native-tokens-on-cardano-for-pleasure-and-profit/
I have also saw this post as well. https://forum.cardano.org/t/cardano-gui-token-builder/80971/5 .
Atleast If a command line utility is available please share me some step by step instructions for the same.
Eagerly waiting to build token on ADA

Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.

Here are a few resources I found:
https://developers.cardano.org/docs/native-tokens/minting/
https://docs.cardano.org/native-tokens/getting-started
https://forum.cardano.org/t/an-introduction-to-minting-native-tokens-on-cardano/49734

I saw thease guides but i am looking for some web based UI i saw the mention for the same on IOHK blog but i was not able to detect any link that directs me to the mentioned UI. I am wondering is there something like that is available or not.

Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.


text:
Transactions without receiver_address
I am trying to figure out transactions without receiver address or same receiver and sender address .
What do these transactions mean ? I also see a deposit in the later part of the transaction. Can someone break the transactions down for me . Sharing some sample transaction hashes .
56e51e0766b072a94bfe6d02218ef39d25634c9493b0c93b2e1a1a7a0a3fc981
327ece1ac5cee03c3def2fd831aec1ec4c28a113a0ef0e87af1bf9e504f2b098
0fbeb9d4a30b8adf611669a9bdbda20c8a7cefa37bfb4e1ac1d374d19566c912
2cfd2cede25959b1493e7e438fde71f020675ab4b7dbfe3f4f4e6108d213b553

The first transaction looks like it is intended to "defragment" two utxos into one, no idea why...
The other transactions are stake pool registration transactions. The pool deposit of 500 Ada is being submitted in these transactions.
The Cardano Blockchain Explorer clearly mentions this 500 Ada as a deposit. View your second transaction here
In case you're wondering where the 500 Ada goes to, no... it doesn't go to the treasury... instead it seems to be recorded on the ledger itself as a deposit. This can be returned later on to the stake pool if and when it is deregistered. Read more here
To find out more about this process, refer to the corresponding documentation
Hope this helps!

Hey thank you for the info . This helps a lot .

if you found the answer useful, please consider upvoting the answer as useful and marking it as the solution.


text:
"'Inputs do not conform to this spec or are otherwise invalid.'" - extract balance from smart contract
I'm implementing a smart-contract in Plutus and I'm with a doubt. For example, Ethereum has some function only to owners, that enables to implement a withdraw of balance for only owner addresses.
I know, that in the script validator, I can put a clause that is true only with a specific public key hash. And I already implemented that. And it works... but only if I locked ADA or NFT through the smart contract itself. Imagine that I sent an NFT or ADA with the nami directly to the address... this way, I receive "'Inputs do not conform to this spec or are otherwise invalid.'". It is normal? There is a way to solve this? Or it is possible at least?
Thanks.

to my understanding, you created a new UTxO at the smart contract address just by sending a Value to it
the message you receive tells us there is something strange in the way you construct the "withdrawal" method
my intuition is that the method is trying to construct a transaction with a single UTxO form the Validator, while in this case, you have two of them
this might happen due to some particular TxConstraint you set
when you "deposit" through the smart contract you are spending the previous UTxO and creating a new one, by just sending funds you spend nothing and create a new one
to handle both cases the off-chain code should create a transaction with all the UTxO of the validator as input and the on-chain should check that all previous TxOut present at the validator address before the transaction where included (plus checking that at least 1 UTxO goes back to itself if you want to keep it "alive")

But for example, if the smart contract has only some ADA remaining, it is possible to withdraw? If I don't have a redeemer for that? I mean, it is possible to have a function in order to the owner can withdraw all?

with the redeemer you can set a specific one that only checks the public key hash, this way you enter god-modeù; without the redeemer it depends from the smart contract logic; you can still add something like if phk == owner_phk then True else -- smart contrac logic