text:
build okay locally, but fails in playground
I am trying to compile the Homework01.hs
The build locally on Linux passes when I do :l src/Week02/Homework1.hs
Prelude PlutusTx Ledger.Scripts> :l src/Week02/Homework1.hs
[1 of 1] Compiling Week02.Homework1 ( src/Week02/Homework1.hs, /home/xxx/plutus-pioneer-program/code/week02/dist-newstyle/build/x86_64-linux/ghc-8.10.4.20210212/plutus-pioneer-program-week02-0.1.0.0/build/Week02/Homework1.o )
Ok, one module loaded.
Prelude PlutusTx Ledger.Scripts Week02.Homework1>

But when pasting the code in playground, I see an error :

Is this a playground problem or am I doing something wrong in Haskell ?
Just fyi, it does compile successfully in playground with the skeleton code initially provided by Lars at github.
The error description in playground doesn't help.

Copy paste the whole file and just delete the line with
module Week02.Homework1 where

The playground does not need a module declaration (i guess it declares its own)

You need to remove the module export lines. That's not valid Plutus code but is useful for testing in a repl.


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?

source: Stack Exchange

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

sort: votes


text:
If metadata can be changed, how can the uniqueness of an NFT can be guaranteed?
Let's say, there's manufacturer that produces luxury watches, and he uses Cardano NFTs to track their authenticity. He embeds unique serial number of a watch into metadata of NFT.  One watch - one NFT, that is.
But a bad actor could:

buy the simplest but real watch along with an NFT from the manufacture
create a replica of the most expensive watch of the manufacturer
change the metadata of that NFT -- the serial number and photo of a watch, such that metadata would describe a replica
sell the replica along with the updated NFT which now embeds metadata which describes the expensive replica

What prevents this from being possible?

The uniqueness of an NFT comes from its minting policy, not the metadata. If you create a script that can only mint one token, then you know any token with that address as its currency symbol is unique, and thus non-fungible.
One possible solution to your problem is a smart contract that holds the proof-of-ownership NFT for you. When the watch maker manufactures a watch, they generate an NFT and engrave the currency symbol on that watch. They then add that NFT to the contract with your address as the owner datum. If you ever sell the watch, you can use the contract to change the "owner" datum to the new owner.

engrave the currency symbol on that watch. --> what currency symbol? There may be thousands of watches, and there're only a dozen or two currency symbols in the world.

Each token in Cardano has a currency symbol and a token name. The currency symbol is always the minting policy address for that token. For an NFT, that can only exist for a single token.

Also on-chain metadata can not be changed

@AliciaBasilio on-chain metadata can not be changed but data presented by comunity tools respect NFT metadata standard which will show updated metadata, but only in case minting policy is unlocked. If minting policy is locked and can't be used any more than users have a guarantee metadata won't change (as described in linked nft standard above)

@Mitchell Turner is right.
I want to add this. In Cardano you can mint NFTs using:

Native scripts: using this option you're the owner of the policy keys (files) to mint a NFT with that policy Id. Unless your keys are stolen, then nobody else could use them to mint a NFT using the same policy Id. That means, nobody can update the metadata of your NFTs.

Plutus scripts: using this option you can create any kind of validation in the minting policy, i.e. allowing to mint only from certain addresses. Although, so far (as I know) it's not possible to attach metadata to your NFTs using Plutus scripts, but you can create NFTs: currency symbols + token name

Regarding to these terms currency symbol, token name, policy id and asset name, please take a look on this: What are the differences between policyId & currencySymbol and assetName & tokenName?

I think you can just attach metadata and a script using the cli which allows for minting "true" NFTs that are based on unique UTxO consumption (no timelocks).
That way you can use plutus scripts + attach metadata.

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


text:
What is the purpose of the `valHash :: Ledger.ValidatorHash` function in the Plutus Pioneer Program's Week 2 homework?
The homework for Week 2 involves implementing validators for two Plutus contracts. Details are here.
Spoiler alert! This probably gives away the answer to Week 2's first homework problem:
-- ...

module Week02.Homework1 where

-- ...

-- This should validate if and only if the two Booleans in the redeemer are equal!
mkValidator :: () -> (Bool, Bool) -> ScriptContext -> Bool
mkValidator _ r _ = traceIfFalse "Invalid redeemer" $ fst r == snd r

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

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

validator :: Validator
validator = Scripts.validatorScript typedValidator

--
-- HERE!
--
-- This appears superfluous
--
valHash :: Ledger.ValidatorHash
valHash = undefined -- FIX ME!
--valHash = Scripts.validatorHash typedValidator

scrAddress :: Ledger.Address
scrAddress = scriptAddress validator

-- ...

mkSchemaDefinitions ''GiftSchema

mkKnownCurrencies []

As marked superfluous above...
My Plutus Playground simulations execute correctly whether this line is defined or not:
valHash = undefined -- FIX ME!

This is also true of the same function definition in the second homework assignment for Week 2.

Should one of the answers be marked as accepted?

the ValidatorHash represents the hash of the serialized Script of your smart contract.
you can think at the ValidatorHash as being the equivalent of PubKeyHash used for people's wallets, but for smart contracts.
it is not needed to deploy the smart contract since the serialized Script is needed for that and not its hash.
it is instead useful to use to check if a smart contract is signing a transaction.
just like in the minting policy that allows only one wallet to mint some tokens by checking the PubKeyHash to be correct. The same logic could be applied in order to only allow a smart contract to mint, but in this case you'll need the ValidatorHash since a smart contract can't have PubKeys.
N.B.
your code compiles even if valHash is defined as
valHash = undefined

thanks to the laziness of haskell
since you never need to use the valHash in this specific example, then you never evaluate it, then there is no reason not to compile

I think it's required only when deploying the smart contract on-chain and the redeemer provides the validator.

Sounds plausible. I'm hoping the question will get picked up for next week's Q/A. I'll mark it correct if confirmed.

The valHash expression was added when Lars was writing Gift.hs. He added it and then did some inspections on it and scrAddress in the REPL. This was done for demonstration purposes as those two expressions are related to each other and they are important to understand when writing smart contracts.
After inspecting it in the REPL, he could have deleted valHash as it doesn't serve any purpose in any of lecture 2's scripts.
The reason you see it in Homework1.hs and Homework2.hs is because all of the scripts during week 2 are based off of the original Gift.hs.

valHash seems to be used by a function on the off-chain code (mustPayToOtherScript inside the give function; I am looking at the Burn.hs file). Therefore, I believe it is working here as the script address itself (at the end, the script address is composed of the script hash if I am not mistaken). So, it uses valHash to pass the address of the script to the off-chain code so it knows with which script you are trying to create a transaction.

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.

Lars explains this in the week 2 video 2 lecture from 30:48 to 31:40 that "this is just boilerplate."  https://www.youtube.com/watch?v=xgnmMl-eIIM&list=PLNEK_Ejlx3x0mhPmOjPSHZPtTFpfJo3Nd&index=2  Basically, he's having you take a standard toolbox to a job that in this case needs only a screwdriver. You're bringing along the hammer and wrench and pliers because that is the standard package of how you would normally do things.

Answer could be improved by following [answer] and How to reference material written by others guidelines.

Answer is difficult to understand, especially if English is not your native language.  It should be just the facts.

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.

It is not needed here because the Datum is (). If you recall, the Datum is passed the hash of the script. In this example however, the valHash is significant since the example datum is simply ().

the validator hash is not related to the Datum; the Datum should represent the state of the smart contract and is updated with each transaction using the off-chain code; the validator hash is something fixed, in particoular is the hash of the serialized script


text:
How does Constraints.mustHashDatum work?
I'm trying to understand how Constraints.mustHashDatum works but I'm not able to figure out the purpose of this Constraint.
Any help would be great.

This is my beginner takeaway about Constraints.mustHashDatum after reading about TxContraints and TxConstraint and mustHashDatum at the Ledger.Constraints documentation link below.  I will also be interested in the responses so that I can know the answer too.
Here are my thoughts.  It seems like when we're creating a transaction, we can dictate that one of the constraints/requirements is just that there exist a Datum and a DatumHash, and that both must be supplied as part of transaction creation.  If one or both is not supplied, then the transaction won't be generated because the particular mustHashDatum constraint wouldn't be met. I think maybe the mustHashDatum constraint does this for us, since just creating that constraint requires that we provide both. Presumably, we might set this as a constraint to make sure that later code involving the transaction can use/check the Datum and the DatumHash.
Below are the excerpts from the documentation that seemed applicable.
https://playground.plutus.iohkdev.io/doc/haddock/plutus-ledger-constraints/html/Ledger-Constraints.html
Ledger.Constraints
This module defines TxConstraints, a list of constraints on transactions. To construct a value of TxConstraints use the mustPayToTheScript, mustSpendAtLeast, etc functions. Once we have a TxConstraints value it can be used both to generate a transaction that satisfies the constraints (off-chain, using mkTx) and to check whether a given pending transaction meets the constraints (on-chain, using checkScriptContext).
~~~~~
Constructors
TxConstraints
txConstraints :: [TxConstraint]
~~~~~
data TxConstraint
Constraints on transactions that want to spend script outputs
Constructors
MustSpendAtLeast Value
MustHashDatum DatumHash Datum
~~~~~
Defining constraints
{-# INLINABLE mustHashDatum #-}
mustHashDatum :: DatumHash -> Datum -> TxConstraints i o
mustHashDatum dvh = singleton . MustHashDatum dvh

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:
Are negative values valid quantities in native assets?
In Cardano's Alonzo CDDL (Concise Data Definition Language) specification, it seems that the value of an asset could be negative. Is it correct?
If the above assumption is correct, I am wondering how will the ledger work in the following scenario:
Alice has a native asset named "X" with negative quantity of -1000. Then, she send this asset X=-1000 to Bob, who has the same asset but a positive quantity of 2000. If this transaction is valid and successfully included in the blockchain, does it mean Bob will end up having only 1000 token X (2000-1000=1000) left?
It sounds weird that Alice could burn anybody's token by simply sending a negative quantity of tokens. If I have to guess an explanation for this scenario, it could be that Alice is granted with the power of "burning" by the token issuer, therefore she could burn anybody's token by sending negative values to their addresses. Therefore, token issuers should be extremely cautious about minting and issuing negative quantity tokens to any third party.
Update:
After taking a careful look at the ledger spec, the quantity of an asset can only be uint, specified as multiasset<uint> in this line. Only the minting amount could be negative, specified as multiasset in this line. This also verified Andy's answer below.

Official documentation unambiguously says about it:

The minting parameter is now called with a negative value, therefore destroying one token.

cardano-cli transaction build --mainnet --alonzo-era
                              --tx-in $txhash#$txix
                              --tx-out $address+$burnoutput
                              --mint="-1 $policyid.$tokenname"
                              --minting-script-file $script
                              --change-address $address
                              --invalid-hereafter $slot
                              --witness-override 2
                              --out-file burning.raw

One obvious thing about burning tokens is: an owner can't burn any token if there's nothing to burn.
cardano-cli transaction build-raw \
                        --fee $burnfee \
                        --tx-in $txhash#$txix \
                        --tx-out $address+$burnoutput+"9999998 $policyid.$tokenname1 + 9995000 $policyid.$tokenname2"  \
                        --mint="-5000 $policyid.$tokenname2" \
                        --minting-script-file policy/policy.script \
                        --out-file burning.raw

For more details, read this post please.

Thanks for the answer! After taking another careful look at the ledger spec, I found that the asset quantity should be an unsigned int, as specified here, which verifies your answer. I will update this information in the question as well.

The amount of an asset is allowed to be negative because, in the minting field of a transaction, burning tokens is defined as negative minting. This does not mean that you can send negative amounts to an address i.e. that a UTxO is allowed to contain a negative amount of assets. Allowing this would effectively mean that anybody could print tokens by sending a positive amount and simultaneously a negative amount such that in sum no token apparently would be minted. It is clear that this cannot be true.


text:
What's the equivalent to ownPubKey in the newer version of Plutus?
In lesson 5 that they use a built in function called ownPubKey to access the wallet pubKey in the transaction on the plutus playground.
This function seems to be non-existent in the newer versions of plutus what is a good replacement for this?

You should use ownPaymentPubKeyHash here is the source code.
It will work by just replacing ownPubKeyHash with ownPaymentPubKeyHash and return type PubKeyHash to PaymentPubKeyHash.

Here is: How to reference material written by others

Interesting, I haven't found one either. If you need the PubKey to compute the hash you can use ownPaymentPubKeyHash


text:
Child compilation failed
Hello Cardano community.
This question has been asked in the community and I would like to resurface it as I am having the same problem.
Ref: plutus-playground-client npm start error (MacOs Intel i7)
There is not a resolution yet for this post and I am wondering if anyone in the community has anything additional to add.
I received this same error and I've included the error log below.
Using
VM VirtualBox
NixOS
Any help you could provide would be much appreciated.
ERROR in Error: Child compilation failed:
Module not found: Error: Can't resolve '/home/sidney/plutus-apps/plutus-playgr  ound-client/undefined/static/index.html' in '/home/sidney/plutus-apps/plutus-p  layground-client'
ModuleNotFoundError: Module not found: Error: Can't resolve '/home/sidney/plut  us-apps/plutus-playground-client/undefined/static/index.html' in '/home/sidney  /plutus-apps/plutus-playground-client'

Compilation.js:1765
[plutus-playground-client]/[webpack]/lib/Compilation.js:1765:28

NormalModuleFactory.js:730
[plutus-playground-client]/[webpack]/lib/NormalModuleFactory.js:730:13

NormalModuleFactory.js:273
[plutus-playground-client]/[webpack]/lib/NormalModuleFactory.js:273:22

NormalModuleFactory.js:402
[plutus-playground-client]/[webpack]/lib/NormalModuleFactory.js:402:22

NormalModuleFactory.js:117
[plutus-playground-client]/[webpack]/lib/NormalModuleFactory.js:117:11

NormalModuleFactory.js:646
[plutus-playground-client]/[webpack]/lib/NormalModuleFactory.js:646:24

NormalModuleFactory.js:800
[plutus-playground-client]/[webpack]/lib/NormalModuleFactory.js:800:8

NormalModuleFactory.js:920
[plutus-playground-client]/[webpack]/lib/NormalModuleFactory.js:920:5

child-compiler.js:169
[plutus-playground-client]/[html-webpack-plugin]/lib/child-compiler.js:169:1    8

Compiler.js:536
[plutus-playground-client]/[webpack]/lib/Compiler.js:536:11

Compiler.js:1103
[plutus-playground-client]/[webpack]/lib/Compiler.js:1103:17

task_queues.js:95 processTicksAndRejections
internal/process/task_queues.js:95:5

1 ERROR in child compilations (Use 'stats.children: true' resp. '--stats-children' for more details)
webpack compiled with 2 errors and 1 warning
ℹ ｢wdm｣: Failed to compile.

Upvote the existing question.  Duplicate questions get closed & deleted.

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


text:
Error starting /plutus-apps client and connecting to localhost macOS
Incurred an error starting /plutus-apps client and connecting to localhost: user error, Interpreter Error, CompilationErrors
Short Error
  plutus-playground-server: user error (Error evaluating simulation:
  InterpreterError (CompilationErrors [CompilationError {filename =

Computer:

macOS Monterey (v12.1)
Macbook Pro 2015 Intel Quad Core i7

Steps:

Started nix-shell in plutus-playground-server, and successfully ran plutus-playground-server
In new terminal tab, ~/plutus-apps, nix-shell successfully ran
Updated dependancies sudo GC_DONT_GC=1 npm install -g npm
start client cd plutus-playground-client and npm run start (Error occurred here)

Full Error:
  plutus-playground-server: user error (Error evaluating simulation:
  InterpreterError (CompilationErrors [CompilationError {filename =
  "\n/private/tmp/web-ghc-work-16cc79e7d9a477a7/Main.hs", row = 2, column =
  1, text = [" error:","    Could not find module
  \8216Playground.Contract\8217","    Use -v (or `:set -v` in ghci) to see a
  list of the files searched for.","  |","2 | import Playground.Contract","
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^"]},CompilationError {filename =
  "/private/tmp/web-ghc-work-16cc79e7d9a477a7/Main.hs", row = 3, column = 1,
  text = [" error:","    Could not find module \8216Plutus.Contract\8217","
  Use -v (or `:set -v` in ghci) to see a list of the files searched for.","
 |","3 | import Plutus.Contract","  |
 ^^^^^^^^^^^^^^^^^^^^^^"]},CompilationError {filename = "/private/tmp/web-
 ghc-work-16cc79e7d9a477a7/Main.hs", row = 4, column = 1, text = [" error:","
 Could not find module \8216PlutusTx.Prelude\8217","    Use -v (or `:set -v`
 in ghci) to see a list of the files searched for.","  |","4 | import
 PlutusTx.Prelude","  | ^^^^^^^^^^^^^^^^^^^^^^^"]}]))

References

Unable to start /plutus-apps client application

When starting the client server on macOS use GC_DONT_GC=1 npm run start.
That is, include GC_DONT_GC=1 in front of the command npm run start.
Then, open a browser tab to http://localhost:8009/ and, using Brave Browser, Advance from warnings. (Not https, see note below).
Note: I had to update my Plutus-apps/plutus-playground-client/webpack.config.js file per prodineeritecht's recommendation to bi-pass the https proxy firewall.

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:
new type and JSON
Working on Week 2 Homework 1, I tried to define a new type DuBool. The following is the relevant portion of the code, with the more traditional version commented out immediately above each line that uses DuBool.
newtype DuBool = DuBool (Bool,Bool)
PlutusTx.unstableMakeIsData ''DuBool
--
--
{-# INLINABLE mkValidator #-}
-- This should validate if and only if the two Booleans in the redeemer are equal!
-- mkValidator :: () -> (Bool, Bool) -> ScriptContext -> Bool
mkValidator :: () -> DuBool -> ScriptContext -> Bool
-- mkValidator _ _ _ = True -- FIX ME!
-- mkValidator _ (a,b) _ = traceIfFalse "Bools no match" $ a == b
mkValidator _ (DuBool d) _
    | a==b = True
    | otherwise = traceIfFalse "Bools no match" $ False
  where (a,b) = d
--
--
data Typed
instance Scripts.ValidatorTypes Typed where
-- Implement the instance!
    type instance DatumType Typed = ()
--    type instance RedeemerType Typed = (Bool,Bool)
    type instance RedeemerType Typed = DuBool
--
--
typedValidator :: Scripts.TypedValidator Typed
-- typedValidator = undefined -- FIX ME!
typedValidator = Scripts.mkTypedValidator @Typed
    $$(PlutusTx.compile [|| mkValidator ||])
    $$(PlutusTx.compile [|| wrap ||])
  where
--    wrap = Scripts.wrapValidator @() @(Bool,Bool)
    wrap = Scripts.wrapValidator @() @DuBool

This does compile in the repl error-free, and does compile and run in the playground simulator, but failure occurs with evaluation when the grab validation step occurs in the simulator, with

, Slot 2: 00000000-0000-4000-8000-000000000000 {Wallet W7ce8}:
            Contract instance stopped with error: "WalletError (ValidationError (ScriptFailure (EvaluationError [\"PT1\"] \"CekEvaluationFailure\")))" ]

I went back and attempted to edit the "type GiftSchema =" section to use DuBool, as follows:
type GiftSchema =
            Endpoint "give" Integer
--      .\/ Endpoint "grab" (Bool, Bool)
        .\/ Endpoint "grab" DuBool

and then the grab definition...
-- grab :: forall w s e. AsContractError e => (Bool, Bool) -> Contract w s e ()
grab :: forall w s e. AsContractError e => DuBool -> Contract w s e ()

But now compilation in the repl fails (sorry that the color and alignment here does not match what I see in the repl).

Prelude Ledger.Scripts PlutusTx> :l src/Week02/Homework1c_jwb.hs
[1 of 1] Compiling Week02.Homework1 ( src/Week02/Homework1c_jwb.hs, /Users/jwb/plutus/plutus-pioneer-program/code/week02/dist-newstyle/build/x86_64-osx/ghc-8.10.4.20210212/plutus-pioneer-program-week02-0.1.0.0/build/Week02/Homework1.o )
src/Week02/Homework1c_jwb.hs:117:13: error:
• No instance for (aeson-1.5.6.0:Data.Aeson.Types.FromJSON.FromJSON
DuBool)
arising from a use of ‘endpoint’
• In the expression: endpoint @"grab" grab
In an equation for ‘grab'’: grab' = endpoint @"grab" grab
In an equation for ‘endpoints’:
endpoints
= awaitPromise (give' select grab') >> endpoints
where
give' = endpoint @"give" give
grab' = endpoint @"grab" grab
|
117 |     grab' = endpoint @"grab" grab
|             ^^^^^^^^^^^^^^^^^^^^^
src/Week02/Homework1c_jwb.hs:119:1: error:
• No instance for (Schema.ToSchema DuBool)
arising from a use of ‘Playground.Schema.endpointsToSchemas’
• In the expression:
Playground.Schema.endpointsToSchemas
@((./) (Endpoint "give" Integer) (Endpoint "grab" DuBool))
In an equation for ‘schemas’:
schemas
= Playground.Schema.endpointsToSchemas
@((./) (Endpoint "give" Integer) (Endpoint "grab" DuBool))
|
119 | mkSchemaDefinitions ''GiftSchema
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Failed, no modules loaded.
Prelude Ledger.Scripts PlutusTx>

It appears that the entire code as written (including what I am leaving out for brevity) can convert (Bool,Bool) to JSON, but not DuBool. I am wondering if there is a simple change, perhaps to the imports, {-# LANGUAGE ... #-}, instantiation, etc. that would incorporate this functionality?
Clearly this is not needed to "solve" homework 1 of week 2, but I do believe it is a valid programmatic approach that will be useful going forward. And I think I am very close. Thanks in advance!
=============================================================
Kurt Sys provided an extremely helpful partial answer. A few rounds of trial and error in the repl led me to this compiling and working-in-the-simulator solution. I've left a comment trail to help anyone else following along.

-- import           Playground.Contract  (printJson, printSchemas, ensureKnownCurrencies, stage)
import           Playground.Contract  (printJson, printSchemas, ensureKnownCurrencies, stage, Generic, FromJSON, ToJSON, ToSchema)
--
-- newtype DuBool = DuBool (Bool,Bool)
data DuBool = DuBool
  {
    b1 :: Bool
   ,b2 :: Bool
  } deriving (Generic, FromJSON, ToJSON, ToSchema)
PlutusTx.unstableMakeIsData ''DuBool
--
{-# INLINABLE mkValidator #-}
-- This should validate if and only if the two Booleans in the redeemer are equal!
-- mkValidator :: () -> (Bool, Bool) -> ScriptContext -> Bool
mkValidator :: () -> DuBool -> ScriptContext -> Bool
-- mkValidator _ _ _ = True -- FIX ME!
-- mkValidator _ (DuBool (a,b)) _ = traceIfFalse "Bools no match" $ a == b
-- mkValidator _ (a,b) _ = traceIfFalse "Bools no match" $ a == b
-- mkValidator _ (DuBool d) _
mkValidator _ (DuBool a b) _
    | a==b = True
    | otherwise = traceIfFalse "Bools no match" $ False
--  where (a,b) = d

Now I need to understand the difference between "data" and "newtype".

I believe this should be broken up into multiple questions given the guidelines in [ask] and [help/dont-ask]

For homework1, you don't need to define a new type. That's what's done in homework2 :). Now, for defining a new data type (which is what you want):
data DuBool = DuBool
  {
    b1 :: bool ,
    b2 :: bool
  }

adding some type classes (implementing functions of some type classes) to it:
data DuBool = DuBool
  {
    b1 :: bool ,
    b2 :: bool
  } deriving (Generic, FromJSON, ToJSON, ToSchema)

I think that should work fine.

VERY helpful. Thank you. See my edit to the original question. If you can somehow incorporate what I produced into your answer I will consider this "answered" but as it stands yours is incomplete. But still very helpful as it led me to the solution.

I swear on MyRedeemer that I had not looked at homework 2 until now : D

@XiTouch the answer should be accepted as it was sufficient to lead you to an answer and Kurt has spent the time and effort to understand your long question(s).  If a better answer is provided in future, it can be voted up higher than the current one.

A little too brief, would benefit from a little more "why" explanation


text:
Where does the `mustPayToTheScript` function gets the script address from?
On the plutus pioneer program, lesson 02, Lars shows the parameterized contracts and on the off-chain code he makes use of the mustPayToTheScript function to create the transaction. Different from other similar functions, this one doesn't take the hash of the script as an input. Therefore, how does it know what is the script address to use?

It doesn't need the script address in this case because later he uses:
ledgerTx <- submitTxConstraints typedValidator tx

where typedValidator is the script.

Why didn't you give the OP an upvote?

Yeah, good point. Done


text:
TransactionBuilder and add_from_inputs
Looking through the cardano-serialization-lib I see a TransactionBuilderConfig and a TransactionBuilder constructor that looks like it takes the Config and exposes add_from_inputs that maybe does the coinSelection that is in a separate module in projects like Nami.
I don't however see how that's exposed in the javascript. Am I missing and/or misunderstanding these things or how they could or should be used??

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

It should be right there just as you say. The add_inputs_from function on the TransactionBuilder takes the strategy as the second parameter.
So in Javascript if your using this (https://www.npmjs.com/package/@emurgo/cardano-serialization-lib-browser or https://www.npmjs.com/package/@emurgo/cardano-serialization-lib-nodejs), you can import from it the CoinSelectionStrategyCIP2 and pass a strategy to the tx builder like this:
txBuilder.add_inputs_from(utxos, CoinSelectionStrategyCIP2.LargestFirst)

The implementation of the strategies is here: https://github.com/Emurgo/cardano-serialization-lib/blob/6a8c67a0fdb2ac6d72132d9693b87a6734f3fed5/rust/src/tx_builder.rs#L329

Ok cool thanks I'll try it out maybe I was looking at it wrong


text:
What is the purpose of placing () at the end of the function declaration?
In week02 Iteration 3 there is a function that has (). What is the purpose of that? Is it so that the function can't be used maliciously?
mkValidator :: Data -> Data -> Data -> ()

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

I would also suggest you read this article -> [help/dont-ask]

It performs the same kind of utility as void in other programming languages.  It's a unit and is a way of saying that the function doesn't return any value.


text:
week 02 - Pioneer cohort 3: Failed to build lzma-0.0.0.3
I am on week 02 of the 3rd Pioneer Cohort.
I am working on a Mac Mojave; when I get to running
cabal repl
I get this error:
Failed to build lzma-0.0.0.3. The failure occurred during the configure step.
I tried many things, including:

apt install liblzma-dev
sudo apt-get install liblzma-dev

But apt-get does not work on Mac.
So I tried

brew install liblzma-dev ==> failed
/usr/local/bin/brew install liblzma-dev ==> failed
/usr/local/bin/brew install liblzma-dev libglade ==> failed

I still get the same error with cabal repl
I appreciate any suggestions.
Thank you,

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.

I wish I could comment, but I don't have that kind of reputation. Make sure you go through the setup to get nix properly installed, then do all your work through nix-shell. Specifically get your cache setup properly because it will download all the dependencies you need to run Plutus and its applications. Also, remember to checkout your plutus-apps repo to the correct tag as mentioned in a previous video Lars did before you do the nix-shell command. This has been floating around in a few places including here and in Discord. It helped me get setup on Catalina: https://github.com/renzwo/carda


text:
Can all redeemers in a transaction be retrieved at once?
In the case of multiple datums and redeemers provided in a transaction, I see that TxInfo contains all datum in txInfoData   :: [(DatumHash, Datum)] but not all redeemers are included.
    data TxInfo = TxInfo
    { txInfoInputs      :: [TxInInfo] -- ^ Transaction inputs
    , txInfoOutputs     :: [TxOut] -- ^ Transaction outputs
    , txInfoFee         :: Value -- ^ The fee paid by this transaction.
    , txInfoMint        :: Value -- ^ The 'Value' minted by this transaction.
    , txInfoDCert       :: [DCert] -- ^ Digests of certificates included in this transaction
    , txInfoWdrl        :: [(StakingCredential, Integer)] -- ^ Withdrawals
    , txInfoValidRange  :: POSIXTimeRange -- ^ The valid range for the transaction.
    , txInfoSignatories :: [PubKeyHash] -- ^ Signatures provided with the transaction, attested that they all signed the tx
    , txInfoData        :: [(DatumHash, Datum)]
    , txInfoId          :: TxId
    -- ^ Hash of the pending transaction (excluding witnesses)
    } deriving stock (Generic, Haskell.Show, Haskell.Eq)

Is it possible to retrieve all redeemers at once ?

This was Lars response to this question in the ppp Q&A on 25/Jan/22. Recording timestamp 0:43:17

You cant retrieve all redeemers at once,  You can only see your own
redeemer,
You are always in the context of validating your specific input,
There maybe one or more script inputs, but for each script input the
validator is run, and it gets the datum, redeemer and context.
The context is always more or less the same in each case except the
context also knows which inputs you are presently validating and you
get the datum and redeemer belonging to that input (the datum
belonging to the output you are consuming and the redeemer for the
input).
So I think you can only see the current redeemer, the one belonging to
the input you are currently validating.
I may be wrong but that's how I think how it is, not only you can't
retrieve them at once but you can't see them at all


text:
How can I configure Ale so it finds Plutus libraries?
I'm using nvim with Ale, no particular config other than:
Plug 'w0rp/ale'
let g:ale_sign_error = '●'
let g:ale_sign_warning = '●'

It looks like works out of the box for Haskell, but cannot find Plutus libraries:
$ nvim src/Week02/Gift.hs

:messages

Could not find module ‘Plutus.Contract’ Use -v (or `:set -v` in ghci) to see a list of the files searched for. |16 | import           Plutus.Contract | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Could not find module ‘PlutusTx’ Use -v (or `:set -v` in ghci) to see a list of the files searched for. |17 | import           PlutusTx            (Data (..)) | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Could not find module ‘PlutusTx’ Use -v (or `:set -v` in ghci) to see a list of the files searched for. |18 | import qualified PlutusTx | ^^^^^^^^^^^^^^^^^^^^^^^^^
Could not find module ‘PlutusTx.Builtins’ Use -v (or `:set -v` in ghci) to see a list of the files searched for. |19 | import qualified PlutusTx.Builtins   as Builtins | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Could not find module ‘PlutusTx.Prelude’ Use -v (or `:set -v` in ghci) to see a list of the files searched for. |20 | import           PlutusTx.Prelude    hiding (Semigroup(..), unless) | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Could not find module ‘Ledger’ Perhaps you meant Lexer (needs flag -package-key ghc-8.10.4.20210212) Use -v (or `:set -v` in ghci) to see a list of the files searched for. |21 | import           Ledger              hiding (singleton) | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
^^^^^^^^^^^^^^^
...

Any idea how to configure Ale so it finds Plutus libraries?

Does this answer your question? Vim setup of Lars

Not really, no reference to Ale at all in there.


text:
[Congestion ]Transaction submitted but never get processed
I have an issue on which I have been stuck for 4 days since the release of Sundaeswap and the congestion of the network.
I have my own node on the mainnet.
I have the same on the testnet and everything is working well on the testnet.
With the congestion of the network, I noticed that doing simple transfers from a wallet works well. (Maybe it's worth mentioning the wallet did not delegate to any pool)
Meaning the transaction gets processed and is visible on the various Cardano explorer after 10min.
However when I'm trying to have a transaction that is doing some minting. It gets signed and submitted, I have a transaction id, but after 12 hours, my wallet is still not updated with the potential minted tokens.
I know that my transaction got submitted , otherwise, I would not have had a transaction id or cardano-cli would have returned me an error.
Also, the exact same process on the testnet is working fine.
And the process was working well before the congestion of the network.
My guess is that the transaction is still stuck on the mempool.
But why do some other simple transfer transactions get through and not the one with minting ? I thought there was no prioritization on Cardano transaction?
Moreover, I saw some minting transactions still happening on the network, so what do the other node have that I'm missing to be able to mint?
Many thanks in advance for any documentation or tracks to explore.
Anselme

The fact that you have a transaction ID does not mean it was successfully submitted. The moment you create locally a transaction file, you already have a transaction ID for it, no matter if you submit it or not (even before you sign it). You can see the transaction ID with the command:
cardano-cli transaction txid --tx-body-file tx.raw

Are you using the --invalid-hereafter parameter when you create the transaction? Maybe you are giving it a too low validity period and it expires before being processed.
I created a few transactions in the last days and submitted them through my Daedalus, and they were all processed in a few minutes.

Many thanks for your answer @george-apex-stake-pool. Indeed you are right, I meant submitted because the command cardano-cli transaction submit --tx-file ... did not return me an error. I checked my here after, and it's talking the adding 10000 to the current slot (so transaction should be invalid after around 166 minutes which seems enough No ? ... However where you might be right, is about my policyscript where there is a time constraint of 5min... I will try to raise it to 15min (meaning the policy does not accept any minting after currentslot + 5*60 slots when the transaction is submitted.

So indeed, by extending my time constraint it worked. However I'm facing another issue. For the moment around 10 minutes happens between the transaction is submitted and the transaction get produced on a block. In the meantime, I cannot submit another transaction. Each time I have the following error: (ValueNotConserved)

You can submit other transactions if you consume other UTxOs. You cannot submit other transactions consuming the same UTxO.

Indeed, I forgot about that. Just out of curiosity, is there any way documentation on how cardano is keeping track of current pending utxos. Example:I have two wallets sync using two different nodesi could theoritically submit two transactions with the same utxos? Ultimately only one would get validated, but it's theoritcally possible right?

Yes, this is correct. But the network should be congested for this to work, otherwise the transaction from the first's node mempool will be quickly in the second's node mempool and you will not be able to submit the second transaction.

When the network is congested, your transaction can take some time before it gets processed within a block. Therefore, you need to make sure the --invalid-hereafter is sufficient.
In my case I put up to 15 minutes after the submission.
In the case where your transaction is minting, remember your policy script which could also have some time constraint. Therefore, make sure the slot is sufficient and also consider the potential delay before your transaction gets confirmed within a block

The parameter --invalid-hereafter is optional, you can skip it and the transaction will be valid forever.


text:
How can I derive the Staking address from a Payment address?
If someone provides me with a payment address, how can I derive the staking address from the payment address?
This can be useful for example when we want to sent rewards to the people in return for staking to a pool.

Good question, surprised you didn't get more votes.

This only works if it's an address embedding the payment and stake credential. You can use cardano-address address inspect locally. You could also use a tool like cardanoscan.io which when given an address to scan tells you the stake address associated as well.
Note that some addresses don't have stake addresses and other ones can have only pointers to stake registrations.

As Samuel said, the address in question must contain the staking part in the first place.
cardano-address uses IOG's implementation of bech32. Instead of using cardano-address you could also install bech32 instead and decode/encode the address.
$ addr=addr1qxkmuf2gqzsm5ejxm2amrwuq3pcc02cw6tttgsgqgafj46klskg5jjufdyf4znw8sjn37enwn5ge5l66qsx8srrpg3tq8du7us
$ echo $addr | ./bech32
01adbe254800a1ba6646dabbb1bb80887187ab0ed2d6b4410047532aeadf8591494b896913514dc784a71f666e9d119a7f5a040c780c614456

Now extract the last 57 bytes from the result as it is the staking address. Then you prefix that with the correct network tag (e0 for testnet and e1 for mainnet) and encode with bech32 to receive the staking address
$ echo "e1$(echo $addr | ./bech32 | tail -c 57)" | ./bech32 stake
stake1u9rfyvw5pkeherf56lzxjaqlpxs53fjghl4ft6w2x8wpnwchfeam3

On a side note, be aware of the existence of franken addresses. A constructed address which has the payment part of one wallet and the staking part of another. This way I could pretend I am the owner of the stake delegated to the pool.

Just for completeness, you can also use Haskell to decode the address into its components using a function like the one shown in the Plutus Pioneer Program.
tryReadStakeAddress :: String -> Maybe Plutus.StakingCredential
tryReadStakeAddress = show . Plutus.addressStakingCredential . tryReadAddress

tryReadAddress :: String -> Maybe Plutus.Address
tryReadAddress x = case deserialiseAddress AsAddressAny $ pack x of
    Nothing                                      -> Nothing
    Just (AddressByron _)                        -> Nothing
    Just (AddressShelley (ShelleyAddress _ p s)) -> Just Plutus.Address
        { Plutus.addressCredential        = credentialLedgerToPlutus p
        , Plutus.addressStakingCredential = stakeReferenceLedgerToPlutus s
        }

credentialLedgerToPlutus :: Ledger.Credential a StandardCrypto -> Plutus.Credential
credentialLedgerToPlutus (ScriptHashObj (ScriptHash h)) = Plutus.ScriptCredential $ Plutus.ValidatorHash $ toBuiltin $ hashToBytes h
credentialLedgerToPlutus (KeyHashObj (KeyHash h))       = Plutus.PubKeyCredential $ Plutus.PubKeyHash $ toBuiltin $ hashToBytes h

stakeReferenceLedgerToPlutus :: Ledger.StakeReference StandardCrypto -> Maybe Plutus.StakingCredential
stakeReferenceLedgerToPlutus (StakeRefBase x)                   = Just $ StakingHash $ credentialLedgerToPlutus x
stakeReferenceLedgerToPlutus (StakeRefPtr (Ptr (SlotNo x) y z)) = Just $ StakingPtr (fromIntegral x) (fromIntegral y) (fromIntegral z)
stakeReferenceLedgerToPlutus StakeRefNull                       = Nothing


text:
Why are community-wallets able to outperform the official solutions during the current "congestion"?
Can someone please explain the difference that led to some community-wallets beeing able to operate so much better during this congested period?
I have hours delay when using yoroi, but only 1-2 minutes delay when using ccvault for example.
I can not explain why the difference is so big.

They probably have a better queuing system for transactions when the tx cannot be submitted to the mempool immediately. It also could be yoroi receives a lot more transactions in general. There's a number of variables that could lead to a system having faster or slower adoption of transactions.

Thank you for clearing this up Sam :-)


text:
send token / asset by cardano-CLI
i am looking so long, but till now didnt find a complete answer about :
how to send a token / asset from cardano-cli.
can you please help me to go in details about build the transaction from the CLI ?

cardano-cli transaction build-raw \
cardano-cli transaction calculate-min-fee
cardano-cli transaction build-raw
cardano-cli transaction sign
cardano-cli transaction submit

is the steps correct in high Level?
can we go in details to write the commands?
thank you in advanced,
Thomas
theTokenSquare17

The tx-out of the build-raw command is the only thing that is different for sending assets. Instead of address+1000000 it will be address+"1000000 + 5 <policy id><<asset name>"

The only difference between building a regular ADA-only transaction and one that contains ADA + asset(s) is in the cardano-cli transaction build-raw step that follows the multi-asset syntax as discussed in the official cardano documentation
It would look something along the lines of:
cardano-cli transaction build-raw \
--tx-in <TX_ID> \
--fee <FEE> \
--tx-out <ADDRESS+LOVELACE+"NUMBER_OF_TOKEN(s) POLICYID" \
--out-file tx.raw

Note that in the --tx-out step, LOVELACE should be an integer value, and "NUMBER_OF_TOKEN(s) POLICYID" should all be a string.
The rest of the steps for caluclating min fees and signing/submitting should be the same.

thank you so much for the link,
it was exactly what i needed and yes, it is righ.
used it, tested and worked
cardano-cli transaction build-raw
--fee 0
--tx-in ${tx_in}
--tx-in ${my_tx_in}
--tx-out ${in_addr}+${amountToSendUser}+"1 ${myToken}"
--tx-out ${paymentAddr}+${amountToDonate}+"999 ${myToken}"
--invalid-hereafter $FINALTIP
--out-file tx.draft
fee=$(cardano-cli transaction calculate-min-fee
--tx-body-file tx.draft
--tx-in-count ${TXNS}
--tx-out-count 2
--witness-count 3
--mainnet
--protocol-params-file protocol.json
cardano-cli transaction build-raw
--fee ${fee}
--tx-in ${tx_in}
--tx-in ${my_tx_in}
--tx-out ${in_addr}+${amountToSendUser}+"1 ${myToken}"
--tx-out ${paymentAddr}+${amountToReturn}+"999 ${myToken}"
--invalid-hereafter $FINALTIP
--out-file tx.raw
cardano-cli transaction sign
--signing-key-file $paymentSignKeyPath
--tx-body-file tx.raw
--out-file tx.signed
--mainnet
cardano-cli transaction submit --tx-file tx.signed --mainnet


text:
Can blockchain viewers read the source code of a smart contract if they know its address?
I'm curious, is it possible to find the source code of the validation script of a smart contract (as well as other parts) that is already on the blockchain?
Or this code automatically picking up into the spending transaction that is referring to the smart contract address?
As I know, we need to provide the actual validation script in the spending transaction.
On the one hand it is a question of transparency, on the other hand of intellectual property.

Not exactly, the only part of the smart contract that actually lives on-chain is the script hash. Think of it as a compressed/hashed representation of how the real script (run off-chain) should work. These hashes are then used to create script addresses whose UTXOs can only be used as inputs for a new transaction if that transaction's script hash matches the hash at the script address.
In other words, script addresses act as guards for their UTXOs, and the only way to get past the guard (and thus use the UTXO as an input for your transaction) is to provide a proof that your transaction complies exactly with the logic set forth by the guard's author. The actual logic must therefore be performed in a local environment. There can be many ways to acquire the code itself, which the upcoming dApp certification program will help with.

In addition to what @nomad0 said, since one has to prove when consuming an UTxO at such an address what the "quard" is by appending the scripts logic to the transaction, from then on the logic is public. That is, since anyone can view that transaction, the appended script logic is also publicly viewable and verifiable. Note though that this logic is in some non human readable Plutus core form.

You can find the actual compiled Plutus Core bytecode on-chain. However, it is not human readable source code, but rather pre-processed / compiled haskell code.
As you mention, it is passed along as part of the transaction and it is "executed by nodes during transaction validation ‘live’ on the chain" (see https://docs.cardano.org/plutus/learn-about-plutus).
You can find examples of how the code appears on-chain on cardanoscan, eg here's a random recent example:
https://cardanoscan.io/transaction/68cfaf710b7267cd01b0b3d3e6889548a5776e653bdb44ae6a9512daa44bcbce?tab=contracts
Here's also some info on how those scripts can be created / exported for use in a tx:
https://plutus.readthedocs.io/en/latest/plutus/howtos/exporting-a-script.html

Yes. The contract bytecode is publicly available and executed on the blockchain. If you are able to decompile Plutus Core, you can re-create the source code.


text:
Received the transaction id but the transaction never happened
I used to work with Blockfrost API to submit my transactions. A few days ago, I ran into this problem in which my transactions were submitted successfully (The API returned me the transaction id without any error) but the transactions were never actually processed (When I looked for transactions in the Cardanoscan, nothing was found). I decided to submit my transactions on another node, and it did work fine for a couple of days, and now I have the same issue. Does anyone know where the problem might be?

The chain has been pretty congested since sundaeswap launched. It may take some time between transaction submission and inclusion into a block. If your TTL or --invalid-hereafter parameter is too short, the TX may be submitted to the mempool but be invalid by the time it is to be included in a block. Try setting the TTL to something like 10000+ and see if that helps.

Thanks! Would set TTL something very very high cause any problem?

None that I can think of off the top :)

@Foad You could omit the TTL entirely


text:
Can I control the amount spent by a plutus Script
I know that you can use collectFromScript to take all of the value from a script but is there a way to make it so you only take 1 ADA from a Script that holds 100 ADA?
Thank you

This question was asked again in more elaborate form a few hours later here: link.  Please edit questions rather than splintering them; that keeps our Stack Exchange concise and more useful.

Yes. You can just write a grab transaction where the whole 100ADA utxo gift is consumed by creating 2 utxo outputs: 1ADA for the grabber and 99ADA back to the script perhaps with a script update pointing to new output address.
If the 100ADA gifts are made up of smaller UTXOs then just choose from those.

How would I do this what functions in the Plutus library should I look up?

If you look at homework 2, what one can do I think is use the grab function. utxos in that function has a list of all utxos from address/ One can 1 ADA from that for the grabber then call the give function within grab to send the 99 ADA back to the script.This is all of course conceptual from me as I'm also just learning. I might try to play around with it and see if I can implement it.

No, it's a utxo system, so any inputs need a corresponding output. Now, the output could be to the script address itself depending on how the smart contract is written. The NFT auction from week 1 of Plutus pioneers showed how this is done for example.


text:
How to import root private key or account private key to cardano-wallet
I am playing around with cardano-wallet key derivation, and I have a mnemonic from which I've derived the root key, as well as account 0 public/private keys. Then, I imported a wallet using cardano-wallet using the account extended verification key running the following command:
cardano-wallet wallet create from-public-key <WALLET_NAME> <EXTENDED_KEY><CHAIN_CODE>
Once the wallet finished syncing, I found there was some tADA in a few of the first addresses. I am now trying to create a transaction using cardano-wallet to spend the tADA. I run:
cardano-wallet transaction create <WALLET_ID> --payment 1000000@<RECIEVING_ADDRESS>
However, it then prompts me for a passphrase which I never set up, seeing as all I did was import the account public key. I try entering 10 random characters and it tells: I couldn't find a root private key for the given wallet: <WALLET_ID>. However, this operation requires that I do have such a key. Either there's no such wallet, or I don't fully own it
Is there any way I can import the root private key or (even better) the account extended signing key so that cardano-wallet can handle transaction creation for me, or do I need to manually derive private keys for each address?

There's no endpoint to do this in the wallet. If you import an account public key, it's assumed you'll be generating and signing the tx offline and only using the wallet to get the utxos needed to do so. There's no technical reason the wallet couldn't allow importing an account private key, it just doesn't have that functionality developed. If it's something you need, I'd recommend opening an issue on the GH repository (or submit a PR if you have the Haskell expertise to add it).


text:
Week 2 - Homework - valid validator call true/true after invalid call true/false from same wallet doesn't go through
I managed to get the homework transactions to work as expected (happy), so far so good...
I also tried the following scenario which did not work.
Q1: Why doesn't it work?
Q2: How would it be possible to make it work!
wallet 1: give 20 Ada
wait 1
wallet 2: grab false/true
wait 1
wallet 2: grab true/true
wait 1
As expected, the first grab is not handled, as it evaluates false
But the second grab is also not handled ?
The logtrace shows:
Slot 3: 00000000-0000-4000-8000-000000000002 {Wallet Wc30e}:
No requests handled ]
Why isn't it possible for the same wallet to "correct" its previous mistake and try again with acceptible parameters ?

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.

Your scenario fails because the way off-chain code was implemented: Once on-chain grab validation fails, the off-chain caller grab fails and the execution finishes. Why? - Because off-chain code is not handling errors.
How to make it work? - Replace function endpoint with these 2 functions.
endpoints :: AsContractError e => Contract () GiftSchema e ()
endpoints = handleError handler (selectList [give', grab']) >> endpoints
  where
    give' = endpoint @"give" give
    grab' = endpoint @"grab" grab

handler :: AsContractError e => e -> Contract w s e ()
handler _ = logError @String "an error occurred"

Note: If I'm not wrong, in lecture 4 Lars talks about error handling in off-chain code.

Follow up question: suppose the above scenario played out on the MAINNET.  Say Wim's code was v1, kindofdev's improvement is v2.
Can the v2 code grab those 20 ADA 'locked' up by the v1 code ?
My guess: yes, as long as you don't change the validator code, because that determines the script address. Am I right?

Yes, that's correct. @wmoco_6725

Thanks @kindofdev, finally got time to execute it and your solution works!


text:
How does one count time within a smart contract
Imagine there is a bidding smart contract and i have a maximum time limit set for it. How would i count time within this smart contract in cardano ? Can i get the slotIds and use that as proxy count of time or is there any other way to read time within cardano blockchain ?

You can use either slots or regular time, see https://playground.plutus.iohkdev.io/doc/haddock/plutus-contract/html/Plutus-Contract.html#g:2


text:
How are values in UTXO's stored
Are values in UTXO's stored in a set manner for example if 50 Tokens with metadata and 50 tokens without metadata had the same Token Name and currency symbol and were to be handed out from a script 1 at a time would it be a 50% chance of getting a metadata Token or would it be based on a order in some way?

I think a misunderstanding here may lie in the fact that the metadata generally is attached to transactions and not directly to the tokens.
The way an NFT is connected to its metadata is by looking back at the minting transaction of a token (the transaction that created the token in the first place). And by doing so there is no problem in moving the tokens around freely without loosing track of their metadata. See more on how its currently done here: https://cips.cardano.org/cips/cip25/#motivation.
However, if your question is not related to NFTs, for other "fungible" tokens (technically similar, but with a quantity > 1) I believe you can create a scenario, in which you cannot trace each token back to the original minting transaction and thus there is no such hard connection between a token and the initial tx metadata. You could for example create 50 tokens in a tx with metadata and later create 50 more of the same token in a tx without metadata and mix them up (ie use both as inputs to a single tx) so you can no longer strictly separate them.

Thank you so much this was very benificial

Not entirely sure what you mean by the second part of your question. However, keep in mind that a UTXO is nothing more than the output of a previous transaction. This means that a single UTXO can contain an arbitrary amount of data (currently limited by the transaction size limit). It can be a combination of many different tokens, as well as metadata. The metadata is not necessarily token-specific, though it can be if that is its intended purpose.

Thank you for your response. What i meant by the second part of my question is are Tokens without "NFT" metadata differently by the The same token without metadata or would they be considered 1 of the same by a Plutus Script.

I’ve never seen anything about “metadata” in Plutus code. Relevant data is always attached to the datum in smart contracts afaik.


text:
How to handle tx dropped due to congested network?
Recently Cardano has come under heavy load. The consequences have been that some of our transactions which appear to have submitted successfully to the blockchain do not actually end up on the blockchain. By 'appear to' I mean we submit a transaction using the cardano-wallet api which returns a successful response.
For example:
  r = requests.post(f'http://{app.config["WALLET_API_URL"]}/v2/wallets/{app.config["WALLET_ID"]}/transactions', json=outbound_tx.body)

Now, sometimes when we manually follow up on these tx ids it turns out they never show up in cardano explorer. More directly, they never appear on chain. This never happened before the recent congestion so we assume some transactions are being dropped by the chain.
What is the best practice for following up on submitted transactions to ensure they have, in fact, posted to the chain?

The default TTL for transactions submitted via cardano-wallet is 7200 slots, or 2 hours. You can increase this by adding a --ttl <INTEGER> flag when you create the transaction on cardano-wallet. The best way to check if the transaction was included on-chain is to then check back on chain after the selected time has elapsed to see if it was included in a block. It shouldn't be too hard to automate this process either.
I expanded a bit in this post.


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:
How are datums retrieved from UTXOs by on-chain code?
How is Plutus on-chain code able to retrieve and decode datums from UTXOs of ScriptContext?
These datums are hardly found in cardano-db-sync or explorers anywhere?

Currently, only datum hashes are able to be a part of the UTXO, so you are only able to verify a datum value on chain. Retrieving the datum itself is therefore on off-chain process.
However CIP-32 is coming very soon (likely end of February/March) and will enable attaching the datum itself to a UTXO, rather than only the datum hash.


text:
What does "off-chain code lives in the wallet" mean?
That terminology was used in PPP3 lectures, but what does it mean?
The spending transaction should follow rules of the smart contract as was answered here Can blockchain viewers read the source code of a smart contract if they know its address?
The spender by default doesn't know the rules to form the spending transaction. Or his wallet can read the off-chain code of our smart contract somehow? The wallet actually has the whole copy of the blockchain and our smart contract inside also.
Because only the verification script (on-chain code) is hashed to provide the address (but probably we submit to the blockchain only on-chain code, I am not sure...)

I think that phrase can be a little misleading. Off-chain code will live anywhere close to where your end users will interact with your DApp. It is responsible for composing the correct transactions, so it does need to be aware of the contract specifications.
However, it does not need to be an actual wallet that runs the code to compose the transaction in the first place.
You can, for example, have a website or an app that is connected to your own backend server and when 1) a user interacts with it, 2) the server generates a valid transaction on-demand (incl. any scripts), 3) the transaction is then passed to the user's wallet only for signing (eg a browser extension) and 4) submitted to the network (either by the server or the wallet).

In the same question that you linked, I mentioned:

"The actual logic must therefore be performed in a local environment."

This is what it means to run off-chain code. Think about it this way: the on-chain part of a smart contract is a logical proof that a transaction was performed in a certain way, but the actual doing of that way is performed in your wallet (locally). It does not have to be in your wallet per say, but it can be if that is how your local environment is set up.
Even simpler: your computer does logic and generates a proof --> blockchain verifies said proof and if ok, validates the transaction.

Here are two threads that discuss the relationship between on-chain and off-chain code:
Where is stored off-chain code?
On-chain and off-chain for Plutus SCs

What does "off-chain code lives in the wallet" mean?

Off-chain code uses the context in your wallet, e.g. UTxOs and addresses, to construct a transaction that will be validated by the on-chain code and return any change back to your wallet.


text:
on multiple eUTxO and the validation proces
I have an in-depth question that needs good knowledge of the ledger rules.
I was thinking about how to program efficiently and design apps such that they are parallelizable, a good practice for achieving this is building modular and piece wise. While thinking about certain contracts that could validate in parallel I wondered how such transactions are build and specified for validation. This is not a canonical task and can be ambiguous for a validator. So a natural conclusion is that to preserve determinism one has to fully specify a transaction, some question on this specification.
Consider a transaction that tries to consume n eUTxO's of contract instance A and m of the contract instance B. Then this transaction has to have n+m datums that match the inputs.
Question 1: Do you specify in your transaction which datum corresponds to which input or does the validator node matches them by hashing your suggested datum? Also, if certain datums match, can you save on transaction size by appending the datum once and specifying the datum to each input?
Question 2: Do you append the contracts A and B multiple time (n+m times to be exact) to the transaction or just once for each occurrence? Again, the latter would save on transaction size.
Now there is also another integral part of consuming eUTxO's, namely their redeemers. Since each eUTxO generally have a different redeemer one also has to specify which redeemer is associated to which input.
Question 3: How is this association between redeemer en input specified in a transaction? And moreover, can this specification again be non-injective. That is, a redeemer can be appended once to the transaction but be associated to multiple inputs? This would again save on transaction size.
And lastly we have the outputs where we give each one a possible new datum. These new datums, how are the specified and can they be assigned in a non-injective way to save on transaction size?

Datums are stored in a hash map per transaction, so if a transaction uses the same datum multiple times, the datum is stored once and only the hashes are stored multiple times. The same goes for redeemers.
(I don't understand all the questions, but this is at least a partial answer. Feel free to add to this answer.)

Thank you Sjoerd, This clears things up about the whole "efficient handling of data" in a transaction of datums. Am I correct that you can extend this hash map idea for the redeemer and script as well?

@Fermat Indeed.

I don't have good knowledge of ledger rules, but I can refer to TxInfo data type in Plutus
data TxInfo = TxInfo
    { txInfoInputs          :: [TxInInfo] -- ^ Transaction inputs
    , txInfoReferenceInputs :: [TxInInfo] -- ^ Transaction reference inputs
    , txInfoOutputs         :: [TxOut] -- ^ Transaction outputs
    , txInfoFee             :: Value -- ^ The fee paid by this transaction.
    , txInfoMint            :: Value -- ^ The 'Value' minted by this transaction.
    , txInfoDCert           :: [DCert] -- ^ Digests of certificates included in this transaction
    , txInfoWdrl            :: Map StakingCredential Integer -- ^ Withdrawals
    , txInfoValidRange      :: POSIXTimeRange -- ^ The valid range for the transaction.
    , txInfoSignatories     :: [PubKeyHash] -- ^ Signatures provided with the transaction, attested that they all signed the tx
    , txInfoRedeemers       :: Map ScriptPurpose Redeemer
    , txInfoData            :: Map DatumHash Datum
    , txInfoId              :: TxId
    -- ^ Hash of the pending transaction (excluding witnesses)
    }

Here you can see that you need to provide Datum only once per each DatumHash, but for outputs, you need to provide a list [TxOut] with DatumHash in each list item. Redeemers should be provided for each UTxO you are trying to spend.
Regarding contracts, you need to attach script only once even if validating multiple UTxOs.
My answers are based on practical experience, so I may be wrong from Ledger perspective.


text:
Transactions without input addresses
I'm building a minting engine for a project and I found something strange today. One of the incoming transactions, which I pull from a Cardano Wallet (testnet) service has an input without an address. All the other transactions do have an input address. They're all transactions between two wallets I manage in ccVault, and always from wallet 1 to wallet 2.
So I'm wondering now, under which conditions does a transaction input not contain an address?
The transactions I'm talking about are the following.
Without input address (first try)
https://testnet.cardanoscan.io/transaction/44964910dee982af3f714a6e4f3e50670aa9f3ef90debced9b4785d6a28bc350
{
    ...
    "amount": {
        "quantity": 37023500,
        "unit": "lovelace"
    },
    "inputs": [
        {
            "id": "3c1c5b73ab66d18efa2540f59df345a702820833264519c69f9c79cbc07bce3c",
            "index": 1
        }
    ],
    ...
    "id": "44964910dee982af3f714a6e4f3e50670aa9f3ef90debced9b4785d6a28bc350",
    ...
}

With input address (second try)
https://testnet.cardanoscan.io/transaction/3f776bd594b43d6288bde265e5aa3aead414585ff664fef4736f0b42ce7db695
{
    ...
    "amount": {
        "quantity": 37023500,
        "unit": "lovelace"
    },
    "inputs": [
        {
            "amount": {
                "quantity": 683493813,
                "unit": "lovelace"
            },
            "address": "addr_test1qp608umcxnpuj869hu2an658pegt8rsgtu9kh9tmfy3kqcktz647sk9ds3hkrg888edxrgc708mfw2cncldqzzq7em4qzrctsk",
            "id": "44964910dee982af3f714a6e4f3e50670aa9f3ef90debced9b4785d6a28bc350",
            "assets": [],
            "index": 1
        }
    ],
    ...
    "id": "3f776bd594b43d6288bde265e5aa3aead414585ff664fef4736f0b42ce7db695",
    ...
}

UPDATE:
Just to clarify, they are both outgoing transactions from Wallet 1 to Wallet 2. Only the first one doesn't arrive with an input address, while the second one does:

I believe the issue boils down to the fact, that "the wallet does not maintain a complete ledger but only a subset narrowed down to the assets belonging
to the wallet" (see https://github.com/input-output-hk/cardano-wallet/issues/2434#issuecomment-757169360)
It should show the addresses and assets only for outgoing transactions according to the docs here https://input-output-hk.github.io/cardano-wallet/api/edge/#operation/getTransaction

assets and address are always present for outgoing transactions but
generally absent for incoming transactions. This information is
present on the Cardano explorer, but is not tracked by the wallet.

Not sure why it is actually showing for the other incoming transactions.
Anyhow that api is probably not the right tool for the job, but instead you need to use an explorer api like cardano-graphql or a service like Blockfrost, that will return the data through this endpoint: https://cardano-testnet.blockfrost.io/api/v0/txs/44964910dee982af3f714a6e4f3e50670aa9f3ef90debced9b4785d6a28bc350/utxos (see screenshot below)
There is a feature request for this though in cardano-wallet here:
https://github.com/input-output-hk/cardano-wallet/issues/2710
(And another related issue here: https://github.com/input-output-hk/cardano-wallet/issues/2617)

I'm not sure what you mean. They are both transactions initiated from Wallet 1 to Wallet 2. I've done about 100 payments in the same direction, except for this one (with input address addr_test1qphxhe0l6v6...), they all arrived with an input address in Wallet 2.

Sorry you're absolutely right. Was just seeing that one address ("addr_test1qp608umcxnpuj869hu2an658pegt8rsgtu9kh9tmfy3kqcktz647sk9ds3hkrg888edxrgc708mfw2cncldqzzq7em4qzrctsk") in the outputs of the first and as the input for the second transaction. But its change only in the first tx. So my guess is it still might be related to the issue above, but I'll take another look at it

When pulling the json you posted above, are you using the same walletId parameter in both cases? For this endpoint: https://localhost:8090/v2/wallets/{walletId}/transactions/{transactionId}

In any case maybe you could look at the "direction" attribute also in the response, as for "incoming" transactions there are just few cases that the address field should be populated: https://github.com/input-output-hk/cardano-wallet/issues/2617#issuecomment-821864615 and here https://github.com/input-output-hk/cardano-wallet/issues/2434#issuecomment-757169360

Okay did some editing on this one, hope this answer works better. Although I can't exactly tell yet what is causing the info to be missing from the cardano wallet api in this specific case (there's a few options), the solution should stay the same :)

When pulling the json you posted above, are you using the same walletId parameter in both cases? For this endpoint: localhost:8090/v2/wallets{walletId}/transactions/{transactionId}
Yes, and in both cases the address is missing for those transactions. I could use the change address, which is the last one in the outputs. That one seems to be always present. So far I can see, it is.
But you're probably right about it not being the right tool for the job. I've got a cardano-db-sync server as well, so I'll try pulling the required information for there.
Thanks for your answers!>


text:
Auction example: How does Bob know the redeemer of the UTXO sitting at the script address?
When Bob places a bid...

He places a transaction/bid that takes in his UTXO (for which he has the private key as he is the owner) and the UTXO sitting at the script address.,

It outputs a new UTXO to a script address and potentially other UTXOs to individual.

To do that Bob needs to provide the redeemer and the actual datum associated with the script.
Where does he get that information from?

Finding transactions
Bob (the person) doesn't have to necessarily know that there's an auction going in the blockchain, but he can launch a transaction and look for UTXOs of this type of contract. If the off-chain code finds these specific type of UTXOs, then he can fetch the datum associated to it, and therefore he can place a bid.
If you look in the EnglishAuction.hs file, line 334:
findAuction :: CurrencySymbol
            -> TokenName
            -> Contract w s Text (TxOutRef, ChainIndexTxOut, AuctionDatum)
findAuction cs tn = do
    utxos <- utxosAt $ scriptHashAddress auctionHash
    ...

This is the function responsible for this. This happens when bidding (line 277):
(oref, o, d@AuctionDatum{..}) <- findAuction bpCurrency bpToken
...

...or closing the auction (line 309), or with any other endpoint the contract opens to the public.
UTxOs, scripts and redeemers

Scripts are not "giving" different types of UTxOs, rather, scripts
are attached, linked to UTxOs.
UTxOs contain the hash of the
datum attached to them.
They are not stored in any database, the
blockchain is the "database" itself for these UTxOs, scripts, etc...

The Cardano node in charge of processing the transaction or the script will reach the UTxOs via the script address, or vice-versa, if needed, and then validate according to its logic, evaluate the script, and create new resulting UTxOs.
On the other hand, the script will know about the redeemer because the person who sends a transaction to the blockchain for this concrete script will attach it. The redeemer is the data the user provides to the smart contract.
References
You can learn more about datums and redeemers in the Cardano docs: Working with datums and redeemers.
Other interesting Cardano SE questions:

What exactly is a Redeemer?
What does it mean that a UTxO sits at script address?

Thanks for your answer! This generates more questions though... I understand different scripts give different types of UTXOs and have different script hashes. Are all the scripts public? This is the only way I can see for identifying specific types of UTXOs. When you say "fetch" you mean there is a database somewhere where the datum for each type of UTXO is stored? Also, say we are looking at a different example, not the Auction, how do I know the redeemer? Is it a completely off-chain process?

I've updated my answer, trying to explain more about scripts and redeemers.


text:
ConnectionError: There was a problem with the response body: Unexpected token T in JSON at position 0
I am having an issue with compiling any contracts on the local playground. It doesn't matter even when trying to compile the example contracts that are provided I keep getting this error. I have no idea what could be wrong, please help.

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.

Possibly the server part of the playground is not running properly.
It could either be it hasn't started correctly and needs another start attempt. Retry the steps here to start the plutus-playground-server https://docs.plutus-community.com/ (or if you're on a new mac, take a look here: https://github.com/renzwo/cardano-plutus-apps-install-m1). The server needs to be kept running in parallel in a separate window while using the playground.
Or I found a very old issue that suggests it could also be related to your disk being full: https://github.com/input-output-hk/plutus/issues/1243. So that might be worth checking also.


text:
Can GTK libraries used with Plutus?
Interested in GUI interfaces, is their restriction's in using GTK Haskell libraries with Plutus.
Am only starting on Journey so wanted general feedback that might help guide me down right path.

Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer.

Yes, I can't think of a reason why they won't work together.

Thank you Sjoerd, I will move forward to try with one of my small project Ideas.


text:
cabal repl error
When I run cabal repl in the week01 folder I get an error message that states the following
*/plutus-pioneer-program/code/week01/dist-newstyle:
    createDirectory: permission denied (Permission denied)

I am not sure how to resolve this error.  The command looks to create a directory but the build does not have permissions to create that directory.
Any help you can provide is appreciated.
Thank you

Can you please provide steps to reproduce this failure? Which Operating System, which architecture, which repo cloned, which ref, and which command invocations?

Thank you for your interest in help resolve this issue.

Operating System
VM VirtualBox running Ubuntu 20.04.3 LTS
Steps I take
Intiate nix-shell in the plutus-apps directory
Navigate to home/user/plutus-apps/plutus-pioneer-program/code/week01
or home/user/plutus-apps/plutus-pioneer-program/code/week02
At prompt enter: cabal repl
This is where I get the error message.

Do you have enough memory? Running all this stuff with require at least 8GB.

Yes, I believe I have about 12Gigs.  The problems seems to be tied to not having permissions to create files/directories during an installation.  When I run cabal repl, it throws an error protesting that cabal repl does not have permission to create directory dist-newstyle.


text:
cardano-wallet for pab-local-cluster
Does anyone have an example of how to execute the cardano-wallet CLI for the pab-local-cluster in plutus-apps (tag: v2022-01-17)?  I can get access to to the local wallet server APIs, but I need the cardano-wallet CLI so I can create new wallets.   I am running the local cluster as per "cabal exec plutus-pab-local-cluster" but do not see how to execute the cardano-wallet CLI that can connect with the local wallet server that is running.

Are you working using nix-shell? If you have Nix and call nix-shell first in plutus-apps dir, it will load shell where cardano-wallet CLI will be available, and you can cabal build/exec/etc from there also.
(also, you can create wallets using REST API as well)

Hi @MikhailLazarev, thanks for the repsonse.
Yes, I am using nix and when in the nix-shell, can access the cardano-wallet CLI, but it is not connected to the local cluster.
I've tried to add some params to cardano-wallet serve, but it is unable to connect to the node. The REST API works.
cardano-wallet serve --node-socket /run/user/1000/test-cluster3561/node/node.socket --testnet /run/user/1000/test-cluster5446/node/byron-genesis.json
[cardano-wallet.network:Warning:27] [2022-01-26 19:46:51.18 UTC] Couldn't connect to node (x19). Retrying in a bit.

FYI - I got the cadano-wallet CLI to work with the pab-local-cluster on ubuntu linux, I just setup a simple proxy as per below.
$ simpleproxy -L localhost:8090 -R localhost:46493

That's good. Can you explain about port 46493? in your answer.

This is the default port used for cardano wallet server with the local pab cluster.


text:
What mechanisms are in place encourage decentralization and to deter centralization of stake pools?
One of the core goals of any L1 cryptocurrency is to ensure decentralization of its consensus mechanism (proof-of-stake, proof-of-work, etc.).  For Cardano that is the number of independent Stake Pool Operators (SPOs)
What have the Cardano community and the Cardano protocol implemented to discourage the pool of SPOs from evolving into a large number of staking nodes operated by a few large SPOs?

Protocol Parameters
A few protocol parameters' sole purpose is to prevent over-centralization of stake. These include:

k (or nOpt) - a.k.a. the pool saturation limit. This disincentivizes over-delegation to any one pool by lowering total pool rewards after a high enough delegation. This limit is calculated by (Total circulating supply / k ), per pool. Increasing k thus encourages stake distribution across more pools. However, when this happens pool operators may "split" their pool into multiple pools. To combat this, we have the following parameter:

a0 - a.k.a. the pledge influence factor. This parameter dictates the effect an operator's pledge has on their pool's rewards (higher pledge = higher rewards). Currently, there is a linear relationship between pledge and pool rewards, but CIP-7 will soon change this to an n-curve to compensate for the unnecessary advantage it gives to pools with very high pledge (>5M).

Community and Active Participation
Apart from first-order incentive structures as outlined above, decentralization is also encouraged throughout the community at a pedagogical level. A combination of great documentation, peer-to-peer style learning, and a shared vision creates a kind of communal "ethos", in which decentralization is a high priority. For example, here is a great blog post by IOG's Chief Scientist Aggelos Kiayias outlining what all participants can do to help maintain healthy decentralization.
Additionally, there are many sub-communities within Cardano building on and addressing different problems, decentralization being one of them. For example, the Cardano Single Pool Alliance is a loose cohort of single SPO's who've committed to operating no more than one stake pool on the network. There is also the Cardano Bare Metal Alliance; SPO's committed to running their nodes on their own hardware (as opposed to cloud infrastructure) to prevent too much of the network from aggregating in large data centers.
Ultimately, it is education and awareness that goes furthest in promoting decentralization, because decentralization itself is much deeper topic than simply the distribution of block production. I expand on this further in this post.


text:
How can I determine how many staking nodes are run by an operator?
When selecting a Cardano Stake Pool for delegation, I have been relying on taking a look at their website and making a judgement call about whether they are are a sole operator with a single node.
Is there a way to determine if that is true or a good source that lists the stake pool operators by number of nodes?

You can't by the protocol. You're depending on each node being honest. This is because from the protocol perspective each pool is independent that a single owner owns. That being said, there are a few things you can check that are reported by the pool operator when they register the pool that can indicate related nodes.

Pool metadata. A lot of operations list same or similar metadata for each of their pools, for example 1PCT does this
Pool registered relays. You can be fairly certain that multiple pools using the same relay addresses registered by the pool are probably the same operator.
Pool rewards address. If multiple pools are sending their rewards to the same address, that would indicate they're owned by the same operator.

Additionally, you can take a look at the Cardano Single Pool Alliance here: https://singlepoolalliance.net/


text:
What is the fastest way of getting PolicyId from an Asset Fingerprint?
Is it possible to retrieve the policyId from an 'asset fingerprint' without any api request to an external source?

You can't, the fingerprint is the hash of the policy id and name concatenated. Cryptographic hashes can't be reversed.


text:
Question about funds in the "burned" example
On the "burned" example*, do those burnt tokens go back to being available from the reserve and to be rewarded back to circulation or are they locked and lost forever ?
If so, then is it correct to assume that poorly written smart contracts could potentially lock people's assets when a bug is found say... years down the road ?

(can't find the link now, sorry)

No, since the Redeemer can never succeed, those funds are locked in the script address forever and can never be redeemed.
Yes. This emphasizes the importance of audits of smart contracts before they're used on mainnet.

In addition to what @Samuel said. It is also wise to never send funds without a datum to a smart contract address. The ledger rules will not validate transactions that consume such UTxO's as scripts always expect an datum. This ledger implementation can change in the future, while a bad script that locks funds can not be fixed.


text:
What is a round trip problem? and why using Unstable functions could cause it? (unstableMakeIsData)
Lecture 2 of plutus-pioneer-program, introduces unstableMakeIsData
In the lecture it is advised to use the Stable version in production.
Lars explains that the Unstable version does not make any guarantee that different constructor numbers will be preserved for future versions of Plutus. He further adds that:

A newer version of plutus does it in a different way it would be incompatible and you would have round trip problems (??)

I understand the incompatibility issue, sure, but what exactly is a round trip problem in this context?

The round trip problem in programming is when you have 2 conversions functions (for example toJSON and fromJSON) that should be each others inverse but aren't. So you start with a value, then convert it but when you convert it back you don't get the value again.
So in this case: say you have created this datatype:
data MyType = Yes | No

unstableMakeIsData ''MyType

Then you convert the value Yes to a value of type Data using toBuiltinData:
yesAsData :: Data
yesAsData = toBuiltinData Yes

Later with a future version of Plutus you convert yesAsData back to a value of type MyType with fromBuiltinData yesAsData and you might get back No instead!

Well explained, thank you very much!


text:
When there are multiple liquidity pools for the same pair on SundaeSwap, which one is used for my trade?
Let's say we have two liquidity pools for token X and ADA (X/ADA)

pool 1 has 10 X and 10 ADA locked -> price is 1
pool 2 has 20 X and 10 ADA locked -> price is 2

What happens if I buy X/ADA now? In this situation, SundaeSwap shows the price of one of the pools, but it's not always the one with the better price (depending on if you buy or sell).
Could I order a buy and a sell and it would automatically buy for 1 ADA and sell for 2 ADA?
Example:
There are 2 pools for MIN/ADA:

I want to sell MIN for 0.3 ADA on the first pool. That seems to work:

But when I buy, I obviously would want the price of the second pool and buy 1 MIN for 0.27 ADA. But also here it shows the price of the first pool, which is more expensive.

Is this only a display issue and I would actually be able to buy 1 MIN for 0.27 ADA?

According to the CIO of SundaeSwap on Discord it's "picking the pool that gives you the best rate for your trade size". So in theory I believe, yes, it should only be a UI issue.
However, I have not confirmed this myself and the answer is from early December, so it might also be outdated.
https://discord.com/channels/830939534174453800/915669612350292038/917624514043600996


text:
Is it possible to decode smart contract code from a script hash?
Given a script address, is it possible to decode the Haskell/Plutus code of said script? How can you verify a script does what someone says it will do?

Somewhat but not completely I think. From one of the replies, I understand now the Plutus Core bytecode is on-chain, so this means it is possible to get the code of the smart contract if you can convert the bytecode back to Plutus / Haskell or some other language? So it's possible but just kind of hard / tedious?

Better as a comment on the original question/answer than to open a duplicate.  But this question has a better title.

On if it's possible to decode the Plutus code of a given contract, there's a possible duplicate of this question here: Can blockchain viewers read the source code of a smart contract if they know its address?.
In case that you want to verify that a compiled code sitting in the blockchain is what their creators claim to be (given that it comes from an open-source project), and you know the Plutus version they used and any other parameters needed, you could recompile the code and compare the resulting script hash with the hash on the blockchain, thus verifying the code is the same.
I'm afraid straight reading of source code from the blockchain right now is not possible. We can expect more tools and possibilities on reading contract's source code in the future since we are still in the "early days" of Cardano's smart contracts.

thanks for sharing that post, it definitely has helped my understanding. From my understanding of it, I guess it is possible to see the code of a smart contract but you have to convert it from Plutus Core bytecode to some other readable language?

Updated the answer with a small idea on comparing open code with the one on the chain.


text:
Why unstable functions?
What is the benefit of using unstable functions if those should not be used in production?
Can you name an example use case in favour of the unstable versions?

I think the best use case for unstableMakeIsData is for rapid prototyping. You can use it without having to know the target type's constructor. This also means you don't have to change the call to it every time you change the type while developing the contract.
Ultimately, once the type is more solidified, you'll want to use makeIsDataIndexed with an explicit mapping of the constructor. This is the more "strict" and safe way to do it for production.

MuesliSwap uses unstableMakeIsData in its validator too. Is there really a use case for makeIsDataIndexed ? (see: https://github.com/MuesliSwapTeam/muesliswap-cardano-contracts/blob/main/order-validator/src/Cardano/MuesliSwapOrderValidator/OrderValidator.hs)

That's really bad practice and ideally should be caught in code audit.