text:
How to Look Up a Token Policy ID from The Smart Contract Validator
I have attached a token to the datum and sent it to the smart contract, now I need the validator to check that the token has a certain policy ID before it allows the contract to proceed.
How do I do that?

How did you attach the token to the datum? did you do something like <policy id>.<token name> as a BuiltinByteString ? I'm asking since the Datum is supposed to only have data

Please check the answer to my previous question. Someone told me to send along the token with the datum maybe attached isn't the right word but I don't know what would be.

You can use the following
info :: TxInfo
info = scriptContextTxInfo ctx

inputValue :: [Value]
inputValue = map (txOutValue . txInInfoResolved) (txInfoInputs info)

checkValueHasToken :: Value -> Bool
checkValueHasToken val = case flattenValue val of
        (pol, tn, amt) -> pol == knownPolicyID

checkInputHasToken :: Bool
checkInputHasToken = any checkValueHashToken inputValue


text:
ConstraintResolutionError
I'm getting the following error during the ledgerTx line of code
"ConstraintResolutionError (TxOutRefNotFound (TxOutRef {txOutRefId = 70d473b55eaac244c821a001fe153813249c22395cb55631f34eb149937d340a, txOutRefIdx = 1}))"
utxos <- utxosAt $ scriptAddress payValidator
let orefs = fst <$> Map.toList utxos
     change = _ciTxOutValue (snd (L.head (Map.toList utxos))) - (Ada.lovelaceValueOf bet)
     lookups = Constraints.typedValidatorLookups typedPayToScriptValidator
     tx = Constraints.mustSpendScriptOutput (last orefs) unitRedeemer <> Constraints.mustPayToTheScript bet change
ledgerTx <- submitTxConstraintsWith lookups tx
void $ awaitTxConfirmed $ getCardanoTxId ledgerTx

The issue was caused by the lookups. The combination of Constraints that resolved the issue is let lookups = Constraints.unspentOutputs utxos <> Constraints.typedValidatorLookups typedPayToScriptValidator <> Constraints.otherScript (Scripts.validatorScript typedPayToScriptValidator) I'm not sure exactly what these lookup constraints do and why they are necessary, but they fixed the ConstraintResolutionError

smacks self on forehead - I've been stuck on the exact same error. I couldn't figure out why it couldn't find a TxOutRef that I had just found a few lines earlier using utxosTxOutTxAt, but it's the lookups!
thanks!

source: Stack Exchange

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

sort: votes


text:
Send Given Amount of Tokens From Script to Wallet
Which TxConstraints i o method should I use to create a transaction where the script pays a specified amount to the wallet? The mustSpendScriptOutput is the only one I can find that sends tokens from the script to the wallet, but it sends all the tokens at a utxo. I am looking to send a specified amount, and the change is returned to the script.

UTxOs can only be consumed completely which means you will have to create a new output at the script address that receives the change that shall stay with the script which can be done via mustPayToTheScript <datum> <value>.

When I added that to the constraints the transaction failed. Is there a way I can post my code in multiple lines in a comment?

https://meta.stackexchange.com/questions/207842/how-to-easily-indent-multi-line-code

I'm getting a ConstraintResolutionError TxOutRefNotFound during the ledgerTx line of code
utxos <- utxosAt $ scriptAddress payValidator
let orefs = fst <$> Map.toList utxos
     change = _ciTxOutValue (snd (L.head (Map.toList utxos))) - (Ada.lovelaceValueOf bet)
     lookups = Constraints.typedValidatorLookups typedPayToScriptValidator
     tx = Constraints.mustSpendScriptOutput (last orefs) unitRedeemer <> Constraints.mustPayToTheScript bet change
ledgerTx <- submitTxConstraintsWith lookups tx
void $ awaitTxConfirmed $ getCardanoTxId ledgerTx

Looks like your TxOutRef is invalid and does not exist. Check your orefs

I needed to add Constraints.unspentOutputs utxos and Constraints.typedValidatorLookups myValidator to my lookups variable. Thanks for the help, I appreciate it.

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


text:
Is nix on an Intel Mac too problematic?
After too many errors I didn't know how to fix. I removed nix, even that was difficult. The nix blog show some progress in supporting M1 Macs but there are still problems. Has anyone succeeded with plutus projects with nix on an Intel Mac?

Please be more precise in what errors and problem you did encounter. This will make it easier to provide a good answer.

No, it is not. In fact I'm running the plutus-playground-server and plutus-playground-client on an x86_64-darwin machine with nix right now.

It should be fine - I got it running a day ago by following this guide which is for apple silicon (M1) macs : https://github.com/renzwo/cardano-plutus-apps-install-m1/blob/main/README.md
with 2 differences:

in step 3, when modifying nix.conf file, remove the "aarch64-darwin" string
later when you are starting plutus playground server and clients I did not need to prefix the commands with "GC_DONT_GC=1"

hope this helps.

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

Intel Macs should not be a problem.


text:
How to set plutus-apps NixOS options on Mac
This is the first time I've used nix. On plutus-apps readme, I changed nix.conf but I don't know how to do this step.
2.On NixOS, set the following NixOS options:
nix = {
binaryCaches          = [ "https://hydra.iohk.io" "https://iohk.cachix.org" ];
binaryCachePublicKeys = [ "hydra.iohk.io:f/Ea+s+dFdN+3Y/G+FDgSq+a5NEWhJGzdjvKNGv0/EQ=" "iohk.cachix.org-1:DpRUyj7h7V830dp/i6Nti+NEO2/nhblbov/8MW7Rqoo=" ];
};

If you're using an M1 Mac follow these instructions https://github.com/renzwo/cardano-plutus-apps-install-m1/blob/main/README.md
You should probably uninstall Nix first though (scroll to the bottom of that page to get a script for an easier uninstall)

I followed steps 4-6 in https://docs.plutus-community.com/docs/setup/MacOS.html and those worked for me (I have an Intel Mac - Big Sur). You could try them and see if they work for you. Those steps are:
Step 4. Edit the /etc/nix/nix.conf file:
nano /etc/nix/nix.conf
note, you will have to create that file if it doesn't exist
Step 5 - Add these lines to the file:
substituters = https://hydra.iohk.io https://iohk.cachix.org https://cache.nixos.org/
trusted-public-keys = hydra.iohk.io:f/Ea+s+dFdN+3Y/G+FDgSq+a5NEWhJGzdjvKNGv0/EQ= iohk.cachix.org-1:DpRUyj

Step 6 - Restart your computer - important that you do this

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


text:
cabal build Out of Memory Mac VS Code Docker
This is a follow up to my previous cabal build problem. I ran cabal update. Then cabal build was killed. I tried increasing Docker memory from 2GB to 3GB. My old Mac has 8GB, Activity Monitor peaked at 6.7GB
Completed ouroboros-network-framework-0.1.0.0 (lib)
cabal: Failed to build cardano-crypto-class-2.0.0 (which is required by
exe:plutus-starter-pab from plutus-starter-0.1.0.0 and
test:plutus-example-projects-test from plutus-starter-0.1.0.0). The build
process was killed (i.e. SIGKILL). The typical reason for this is that there
is not enough memory available (e.g. the OS killed a process using lots of
memory).
Failed to build iohk-monitoring-0.2.0.0 (which is required by
exe:plutus-starter-pab from plutus-starter-0.1.0.0 and
test:plutus-example-projects-test from plutus-starter-0.1.0.0). The build
process was killed (i.e. SIGKILL). The typical reason for this is that there
is not enough memory available (e.g. the OS killed a process using lots of
memory).

You will not be able to build this in less than 8G of RAM. Adding swap to make the total memory at least 8G may help.


text:
How do I get information from a contract?
How do you obtain information from a deployed contract? I know it is possible because I have seen a screenshot that showed detailed information about some of the interactions with a contract.
The specific contract is a DeFi that allows users to take out loans, and the screenshot showed the amount to be lent, the addresses involved, the loan interest...
How do you obtain that information?


text:
How to Make Sure A Contract Is Signed By a Certain Party?
I'm thinking about making a parameterised contract between two users. User A can be anyone i.e. any customer, But User B should always be the company. I want to make it so that the validator only validates if the Company signs the contract. How do I do this?
Also, How would both signatures be sent to the contract, without making it easy for somebody to fake the signature of the company?

So, at a high level, you can't make any restrictions on who can create a script, or submit datums to a script address. You can only put restrictions on who can "spend" datum utxos at the script address.
So, one solution is you specify a token that needs to be attached to the datum for it to be spent. That token's minting policy requires the minter to be User B.
User B can create an active instance of the script by submitting a datum attached to the token only she can create. This would essentially be the same as signing the contract, as User B would need to sign the tx that created that token.
The script will only allow User A and User B to spend that datum and make state changes if the "signing" token exists on the UTxO.

Note: You'd probably want to take care that the "signing" token can never be sent to a wallet, only to the script address. Otherwise it's essentially a blank check.

Your suggesting to have a locked policy and ensuring that a UTXO is present to sign the contract in the validator. This makes me want to ask what do you do if you want to update the SC how do you remove the token from it?

I don't think there is one correct answer. But you can't modify scripts ever. Script addresses are the hash of the code the validates it. So, if you modify the script, it will change the address.
That doesn't mean you can't make your SC upgradable. The upgrades will just cause it to use new scripts. Well designed SCs could be backwards compatible if participants want to interact with old scripts.
A script isn't the same thing as a SC. Multiple SCs can use the same script, and SCs can use many scripts and minting policies.

How do I attach the token UTXO to the Datdum?

All datums are attached to a UTxO. And UTxOs have a Value field that can include multiple native tokens.

Can you please send me a link on how to attach those tokens or let me know what I should be using to do it. Thanks This is the most helpful question I posted on here. Kinda sad I cant give you more upvotes,

Haha. Thanks. Don't worry about it. I can't tell you how to build your app, but here's an example of off-chain code combining multiple tokens into a single value:
https://github.com/input-output-hk/plutus-apps/blob/ea10bbfa3df3164f87c3687b6c4d99fc0310cf57/plutus-use-cases/src/Plutus/Contracts/Uniswap/OffChain.hs#L230

Thanks man that's perfect.


text:
What is this Pop Up Screen on Cardano Documentation?
When searching the docs it helps to use ctrl + F to find something fast, however, when I use it on the plutus docs I get a weird pop-up screen I'm not used to. (Image Below)
My Questions are:

What is this screen?
Why does it pop up?
Can It help me in any way / what use does it have?
Is there a way to stop it from poping up?

link to a page this has happened on: https://playground.plutus.iohkdev.io/doc/haddock/plutus-ledger-api/html/Plutus-V1-Ledger-Contexts.html

What is this screen?
that window comes by default with the haddock documentation
I think it should work as a quick "go-to" however for PlutusTx the links do never work (at least to my experience)
Why does it pop up?
by pressing Ctrl+F you are searching for some text in the DOM of the page
that window is located on top of the main content at the ```ħtml`` level so the search goes there first
Can It help me in any way / what use does it have?
It can give you a quick overview of what's on the page however the clicking on the Types usually doesn't work so it's not that useful
Is there a way to stop it from poping up?
not by the webpage functionalities but you can remove it from the page by running the following javascript code in the browser console

you can open the browser console by pressing F12 or  Ctrl+Shift+J or by the three dots on the top left of the browser searching for Developer tools

document.getElementById("synopsis").remove()

this will remove the window only for the current page, refreshing or re-access the page will have the window once again


text:
How to get the history of an NFT or NFT Series from blockfrost?
Hi is there a quick API call to get the transaction history of a specific NFT or collection of NFTs in BlockFrost?

Yes, there’s an endpoint for the asset transactions here:
https://docs.blockfrost.io/#tag/Cardano-Assets/paths/~1assets~1{asset}~1transactions/get
and also one for mint & burning history here:
https://docs.blockfrost.io/#tag/Cardano-Assets/paths/~1assets~1{asset}~1history/get

{asset}=nft asset id ?

Yes it’s the policy id combined with the hex encoded asset name, simply concatenated.
Example from the docs:
b0d07d45fe9514f80213f4020e5a61241458be626841cde717cb38a76e7574636f696e

is there a quick way to get the hex-encoded assetname?

You can just strip off the first 56 characters and you're left with the hex encoded asset name, eg using substring: asset.substring(56)

combination of the policy_id and hex encoded asset_name needs to be provided as an input parameter for this endpoint:
Blockfrost - Specific Asset


text:
How to Securely Serialise a Plutus Smart Contract Endpoint?
Assuming I made an arbitrary smart contract and want to serialise the endpoint after I have the validator hash and address hash, what should I do to ensure that the serialisation is as safe as possible?
are there steps I should follow to make minimum security guarantees or some software I can use to test it? How do I know that the serialisation is done correctly?

The current format of the question is a bit vague. Could you try to rephrase it? Are you trying to assert if you contract is safe to use from a design perspective? Or if the serialization does what it is meant to do?

Okay thanks for the input, I'll rewrite it when I'm on my laptop

before I can answer there is an important distinction that must be done
on-chain code can be serialized, off-chain code stays "off the chain" so there is nothing to serialize
so if you are searching for a way to serialize your off-chain code (which can be written in any language, from Haskell with the Contract monad to javascript thanks to the cardano-serialization-library) unfortunately there is nothing to do
serialize the on-chain code
from the chain point of view there is no difference between Validators and MintingPolicy(ies) and StakeValidator
all of them are Scripts for the chain, treated differently based on the ScriptPourpose of that transaction
so you first need to get the raw Script of your smart contract
you can do that with the following functions (all form Plutus.V1.Ledger.Api module)
unValidatorScript :: Validator -> Script
getMintingPolicy :: MintingPolicy -> Script
getStakeValidator :: StakeValidator -> Script

once you have your Script the process is always the same
Script has an instance of the Srialize typeclass which conviniently exposes the serialise function:
serialise :: forall a. Serialise a => a -> ByteString

then we need to strictly evaluate the byte-string and make sure the values do fit in shorts types, this can be done by concatenating the following two functions
import qualified Data.ByteString.Short          as SBS
import qualified Data.ByteString.Lazy           as LBS

-- LBS.toStrict :: ByteString -> ByteString
-- SBS.toShort :: ByteString -> ShortByteString
asStrictBS :: ByteString -> ShortByteString
asStrictBS = SBS.toShort . LBS.toStrict

then we have to specify how to interpret the ShortByteString we have:
-- PlutusScriptSerialized is a constrctor
PlutusScriptSerialized :: ShortByteString -> PlutusScript PlutusScriptV1

and finally get our Script into a file, which can be done thanks to the writeFileTextEnvelope from the Cardano.Api.SerialiseTextEnvelope module:
writeFileTextEnvelope :: forall a.
HasTextEnvelope a =>
FilePath
-> Maybe TextEnvelopeDescr -> a -> IO (Either (FileError ()) ())

I usually do all this whit the following utility funciutons:
getAndWriteScript :: ( willBeScript -> Ledger.Script ) -> FilePath -> willBeScript -> IO (Either (FileError ()) ())
getAndWriteScript getScript filePath =
--                          PlutusScript PlutusScriptV1 instance of HasTextEnvelope
    writeFileTextEnvelope @(PlutusScript PlutusScriptV1) filePath
    Nothing -- Maybe TextEnvelopeDescr ( Nothing => default )
    . PlutusScriptSerialised . SBS.toShort . LBS.toStrict . serialise . getScript

writeMintingPolicy :: FilePath -> Scripts.MintingPolicy -> IO (Either (FileError ()) ())
writeMintingPolicy = getAndWriteScript Ledger.getMintingPolicy

writeValidator :: FilePath -> Scripts.Validator -> IO (Either (FileError ()) ())
writeValidator = getAndWriteScript Ledger.unValidatorScript

Also have a look at https://playground.plutus.iohkdev.io/doc/haddock/plutus-ledger-api/html/Plutus-V2-Ledger-Api.html#v:validateScript. This functions checks if a SerializedScript is correctly serialized.


text:
How To Get Transaction Royalityies on Fungable Tokens
I want to make a fungible token (FT) that has a royalty attached (N%). The problem is UTxOs are purely passive so how can I get my N% of the transaction value on P2P transactions using code is law.
To clarify how do I ensure (using code) that every time my token is moved between people I get a cut.

This is not possible. Native Tokens are first class citizens on Cardano. They are not part of a smart contract that could enforce behavior like this but are assets in your wallet like ADA.
It's the same for NFTs, no one prevents you from sending a Cardano NFT directly to another wallet without paying the royalties that would apply on a marketplace.

To add to that, key witnessed address determines how the native assets located at that address are spend. So to enforce this you need to create "shared" pensioned address with a plutus script. Now the problem with this is that a wallet does not index this. This is something that we as a community have to solve with standards. An ECR20 contract does something similar, you have to import it into a wallet to keep track of funds. So it is possible but you have to invent the wheel.


text:
How to securely call Blockfrost or other API service from Smart Contract?
I just spent a few days trying to find a way to access account data from a smart contract using only plutus. Turns out IOG has yet to put that functionality in (at least that's how I understand it) but I no I can get info from the node and therefore from a service like blockfrost.
How do I get that data and have it update regularly until the contract validates?

You can't call API services directly from the smart contract, and this is not something that the "IOG has yet to put that functionality in";
the same behaviour is not possible in any other smart contract programming language for security reasons.
with that being said there are a few options you could use:
get the data from the off-chain (bad)
you could get the data from the Redeemer; so that the user is telling you the information you need.
this approach is bad because the user could send any redeemer to the script, and you have no way to check the information is true
as an example say you want to access the history of the past user transactions
the user can easily omit (or add) some transactions and you have no way to check that is true.
since ANYONE can write off-chain code to interact with the smart contract you cannot trust the input form the redeemer
Implement an Oracle
You could write a smart contract that keeps on a recognizable UTxO the data you need as Datum; then include that UTxO in the tx input of the smart contract you need the data for.
this way you access the data you need by reading any datum from the input.
now the trust is put only in the person that is able to update the oracle, and no longer in ANYONE in the world
the Plutus Pioneer Program, iteration #2, lesson 6 might help to have a better idea about Oracles

There are two points to note:

if you have access keys (such as the blockfrost project_id) you don't want to publish these.

you normally want to push the data into the contract by using the datum or pramterisation.

This means you might be well advised to put that processing on off-chain servers and figure out the input you want to send to the contract and proceed accordingly.

It is good to remember that all on-chain scripts are passive. This means that the do not compute anything, they validate only. A computer can query something, a validation process can only check whether something is done correctly.


text:
Whats the function to get the current time in Plutus?
Im using the time module in the ledger class to do some custom validation logic, but everything is done as intervals and I cant find the function that gets the current time. What is it?

each transaction on Cardano has a ttl (Time To Live) determined in the moment of transaction creation, it can't be submitted outside that interval, and even if the transaction is submited, other node would not reconize it

on cardano-cli the ttl defaults to ~2/~3 hours after the tx-body creation

and this information is reported in the ScriptContext from the Plutus.V1.Ledger.Contexts module, in particular yo need the TxInfos and from then the POSIXTimeRange you get form the txInfoValidRange function.
so starting from the ScriptContext your function would be somehting like:
getTTL :: ScritpContext -> POSIXTimeRange
getTTL = txInfoValidRange . scriptContextTxInfo

If you need to express logic valid before a specific time you should check for the upper limit of the interval to be before that timestamp
since POSIXTimeRange is just an alias for Interval POSIXTime
type POSIXTimeRange = Interval POSIXTime

you can check the Interval documentation for more
but you can get the upper limit of the interval like so
extractFiniteUpper :: Interval a -> Maybe a
extractFiniteUpper interval = case ivTo interval of
    UpperBound (Finite value) _isInclusive -> Just value
    _ -> Nothing


text:
Is there a Python Version of Cardano Node-CLI JavaScript Library?
I know JS, but I have other code written in python that I want to use in conjunction with the node. Is there a Python 3.xxxx SDK/Library/Module that will do everything the JS can?
Heres what is written about the JS Version: https://developers.cardano.org/docs/get-started/cardanocli-js

I know you are asking for a python library interacting with a node, but let me tell you there is a very comprehensive python library with which you don't need to run a node yourself.
You can find a list of it's features in the README https://github.com/cffls/pycardano/
For completeness, there are a few python libraries wrapping a cardano node and interacting with the cli. I haven't used any of those and I am not sure what features they support exactly, but here you go:

https://github.com/emesik/cardano-python
https://github.com/input-output-hk/cardano-clusterlib-py
https://gitlab.com/viper-staking/cardano-tools


text:
How To Explain Monterrey Expansion and Hard coded ADA values?
I have heard the term Monterrey Expansion used to talk about the ADA supply, but my understanding is that the total amount of ADA is fixed.
How can you have a hardcoded value for a upper bound on ADA and have an expanding supply of ADA at the same time?

Without repeating what's in the documentation already , monetary expansion refers to a percentage of ADA unlocked from reserves to distribute to treasury and stake rewards right before each epoch transition. It does not change the upper bound max-supply of ADA.


text:
How to specify the Cardano address for BlockFrost Transaction Endpoint?
Hi im trying to call this https://docs.blockfrost.io/#tag/Cardano-Addresses/paths/~1addresses~1{address}~1transactions/get from some code I wrote (images attached below) and get a None or Empty value returned.
I am using the receiving address from my wallet and am wondering if I'm using the wrong address? how should I find the right one?
Below is the output of some print statements I wrote:
endpoint:
addresses/addr1q8mw47vt7kf69ze5x92luhrxvk0p2vpd0emvhlg704u7cttdrr3j8j5k5yacga4ckv6lnx4p0la57q7nf24eszqk0r2q59elsd/transactions
Full Request:
https://cardano-mainnet.blockfrost.io/api/v0/addresses/addr1q8mw47vt7kf69ze5x92luhrxvk0p2vpd0emvhlg704u7cttdrr3j8j5k5yacga4ckv6lnx4p0la57q7nf24eszqk0r2q59elsd/transactions
Returned Value: None

Going by your question I will assume you are trying to get the transaction history of your wallet? The endpoint you are using requires an address previously associated with a transaction, and an unused receiving address won't return anything.
Your wallet consists of multiple UTxOs across multiple addresses, and that information is persisted locally by the wallet software so it's easy to obtain details like the transaction history. However in the context of statelessly querying Blockfrost you will have to retrieve all these addresses using the Account associated addresses
endpoint and then query the transactions per address. It might be a little easier using the Koios API because the resource takes an array of addresses but there is no easy way to achieve what you want at the moment.


text:
How to Access Secret Key Hash and PKH from a web wallet?
So I'm making a Dapp that uses the user's secret key to encrypt the data. It also allows another user to encrypt something else using their public key hash, but how do I get the key pairs from the web wallet integrated with my Dapp?

You can't directly access private keys of your users; those should reside safely in their wallet only.
There is, however, a way you can have their wallet use those keys to sign data that you pass over.
This is described in CIP 30: https://cips.cardano.org/cips/cip30/#apisigndataaddraddresspayloadbytespromisedatasignature
You call this function in the browser like so:
window.cardano.signData(Address, HexMsgToSign)

The wallet will then open a window showing the message and asking the user to sign, and return the signature.

You can't access the secret/private key of a wallet connected to your web site.


text:
How to have a contract on chain for extended periods of time?
In PPP Larz explains that there's a limit to how long a contract can remain on chain, what is that limit and how do I go about extending it?

Can you point to the source where Lars says this?

Just a guess, but you might be referring to the POSIX time <-> slot conversion, where Lars noted in week 3 (see notes here), that - if you require a definite upper bound for a slot interval - you should not place that upper bound too far into the future, because slot lengths could potentially change in the future, and cause your script to behave unexpectedly.
If so, I'm not sure if this is still important in the context of using txInfoValidRange in smart contracts though, since it seems to have changed from SlotRange to POSIXTimeRange (https://github.com/input-output-hk/plutus/blob/65fa7ce05a810947f565ac59b4d4e35b3cd5d1b3/plutus-ledger-api/src/PlutusLedgerApi/V1/Contexts.hs#L109 since this commit) - and so you probably don't need to care about this any longer.
In any case this is not related to how long your contract stays on chain, but only how one needs to consider working with time & slot length in certain scenarios.

Yeah it's changed a bit can i specify this to be something like 100 years from now?

In general if you're working with the POSIXTime: It's in milliseconds since 1970-01-01T00:00:00Z. So in 100 years it'll be around ~4812480000000. I think in general you can safely work with this in your scripts (but don't trust me on this :p).
However for the "txInfoValidRange" value: It's not set directly by you in posix time, but converted from slots under the hood and set by whoever created the transaction in the first place. I think it can also take any value up to infinity (open interval) - so yes, it can also be a valid tx in 100 years.


text:
What is a Semantics Model?
In the eUTxO research paper by IOHK, it mentioned that the eUTxO model is able to enable both expressive smart contracts and keep the simple semantic simplicity of the UTXO model.
But what does semantic simplicity mean?
As per request here is a link to the paper.

could you share the link to the paper for context?

Good call don't no why I didn't attach one. Sorry.

in theoretical computer science, "semantic" is meant to indicate a property of a language.
in particular, it describes the set of words/symbols that are disposed in a particular order to describe a well-formed program.
always in theoretical computer science, it is often introduced alongside the study of automata, in order to demonstrate the differences and limitations of various theoretical models.
in the paper you linked it is mentioned how the logic that we can run on protocols like Bitcoin could be expressed using a simple state machine, the simplest of automatas, which are easier to describe and write but less powerful than models such as a PDAs and Turing machines
so when it is said that the UTxO tends to produce a simpler semantic model from a purely practical point of view it can be seen as a way to express the complexity needed to describe a program.
A simpler semantic model doesn't necessarily mean that is less powerful, only that is easier to express. (whereas a less powerful semantic model is condition sufficient but not necessary for a simpler semantic model)


text:
Can I Use TraceIfFalse in deployment?
So I use traceIfFalse to test a lot of my smart contracts now I'm ready to deploy some of then and I want to know if this is for development only or if its fine to have a smart contract use this function when deployed to the chain?
Im using it in the validator of the contract.

it strictly depends on your needs and how your validator is supposed to work.
traces in general (trace, traceIfFalse, traceIfTrue, traceError) are known to be one of the causes of larger scripts.
so if your validator has to be used in pair with other data in a transaction it is essential it reduces the script size.
keep in mind that removing traces means you'll likely have a hard time understanding what is wrong if something goes wrong.
one possible solution to keep traces would be to use error codes ( as done for some errors that might happen when using builtin funcitonalities ) so that you can reduce the script size and have a clue of what's going on in your code.


text:
Can Queries To the Chain be made From Plutus Smart Contracts?
Considering that Plutus Smart Contracts have two parts (on chain and off chain) is there a way to make Queries to the Cardano Chain in the onchain part of the contract considering that the SC is actually already on the chain?
I want to be able to look up the transaction history of an address and check its balance.
I know I can do this via the Cardano Node, but considering that the contract must run on the node this should be possible how do I do it?

After reaching out to the Plutus-core team I got the answer and paraphrased it here.
They can but the functionality is quite limited right now, as the module is still under development. This means that it is likely unsafe for real applications.
I suggest waiting for the next stable update to plutus.
EDIT:
As per @kindofdev request, the module is the request module. I offered to help the team improve and build it out. Hope they agree. Anyone reading this is advised to urge them to let me build part of it.

Can you please pinpoint the module?

where's the proposal/issue?

The way I understood things from last Q&A session with Lars, no, you can't. You can only see the current transaction, not the history of an address.

This is incorrect the module call exist. See nest post, but its all in monads.


text:
What is the Address Gap Limit in Daedalus?
I saw another question posted about the gap limit, but I can't figure out what it is. Can you explain it, please?

Hierarchical Deterministic (HD) wallets allow for a very very large number of addresses/keys to be derived from a single master seed (mnemonic). However, it is computationally infeasible for wallet software like Daedalus to sync all the addresses, so it is limited by the address gap limit parameter.
By default, this limit is set to 20, so wallet software will check the first 20 addresses of a wallet (i.e. m/1852'/1815'/0'/0/0, m/1852'/1815'/0'/0/1, .... m/1852'/1815'/0'/0/19).
When an address containing UTXOs is found, it will sync another 20 addresses after the last address containing a UTXO. For example, if the highest used address is index number 17, then wallet software will query all addresses up to m/1852'/1815'/0'/0/37.
If you have UTXOs sitting at an address with a high index, you can either derive the key-pairs manually or set the gap limit to a higher number. Note: setting the gap limit too high can be strenuous for your computer depending on specs.

how can the gap limit be increased in daedalus? https://cardano.stackexchange.com/questions/7519/how-can-i-increase-the-address-gap-limit-in-daedalus


text:
I hear that Daedalus Is a Full Node Does That Mean I Can Set Up a DB Sync Server On Top of It?
The Daedalus wallet is said to be a full node wallet. Does that mean I can set up something similar to blockfrost on top of it? If so how?

Daedaldus consists of two processes, cardano-node and the wallet itself.
Yes, it is possible to connect a db-sync instance to the cardano-node.

How do you do this? Is there a youtube video I could follow or some docs?

I do not know of a YT video or any docs.
However, all you need is to find the cardano-node's socket file and then use the standard docs for db-sync to connect to that socket.


text:
How to Make a Successful CIP?
I am finding the current state of Plutus is not suitable for my purposes, as such I wish to make a CIP.
How do I make the CIP?
What should I do to optimise the CIP and maximise the chances of it being accepted?

So I managed to find a youtube Video by IOHK that describes everything in detail. This one video should be everything you need other than the GitHub repo it mentions.
IOHK Video: https://www.youtube.com/watch?v=q7U10EfqXJw
IOHK CIP Repo: https://github.com/cardano-foundation/CIPs

I have not gotten our CIP accepted (yet), but I suppose following the CIP process (CIP-1), being clear on the motivation, rationale, specification and rigorous in the overall analysis, plus laying out a plan should be a good start. From there, the CIP editors and others from the community would review & request clarifications.
There is even CIP-35 currently in flight, proposed by the plutus team  themselves, on how to evolve & propose changes to plutus in various dimensions!

To complete @Sebastian Nagel's answer, I would suggest to read CIP-0001 and in particular the section titled "How to champion a CIP beyond Draft / Progression to Active status".
Generally speaking, if you want a CIP to be accepted, it must obviously be well-written and contains sufficient details and justifications to be self-assessing. Yet, it must also demonstrate usefulness for the community and the best way to show this is to discuss the proposal (or the idea of it) in public forums upfront. Discussions also often happen on pull requests proposing new CIPs.
Finally, when a CIP refers to a protocol or an implementation change, it must be technically feasible, sound and secure. For Plutus, CIP-35 (tentatively) does already provides nice guidelines to drive this.


text:
How can you use Ledger.Constraints in the Validator?
Hi i have noticed that you can get the unspent UTxOs in an wallet address using the Ledger. Constraints module. I want to know can I use it the same in the mkValidator as in the Endpoints?
The general form of the question is can I query the CLI node inside the validator, and make custom validation logic using the received information?

Okay After some studying and testing on the playground the answer is a yes.
Whilst the Ledger.Constraints can not be taken as an input to the smart contract, it can be called from the validator part of the code, not just the Endpoints.
The exception is that if you have multiple smart contracts in a single Dapp the output of the first could be the input to the second. This would allow you to call Ledger.Constraints from the first contract and have the data readily available in the second.
You can use the Ledger.Contract module to query the chain, but it's limited and unstable. I am currently writing the CIP to fix this, so you may be able to do this easily and efficiently at the time of reading, but not writing.
Below is a link to a conversation with the plutus team on this topic: https://github.com/input-output-hk/plutus-apps/issues/339

In short: no.
Validator has three arguments:

datum, from the utxo considered
redemeer, supplied in the tx
script context, which is a collection of data about the tx.

Nothing else.
Any information the validator needs must be supplied somehow in the arguments.
Some Ledger.Constraints can be used in validator logic.
(Here)
These are used in some of the examples provided. For example
https://github.com/input-output-hk/plutus-apps/blob/13836ecf59649ca522471417b07fb095556eb981/plutus-use-cases/src/Plutus/Contracts/MultiSigStateMachine.hs#L225

Can i call the function to check the UTxOs at the address signing the transaction?

No. Not unless they are used in the Tx.


text:
How Do you generate the Cabal and Nix files for a new project?
I built the plutus-apps repo from iohk, and then made a different folder to orgenise my projects. I want to know how to have the nix files needed to make the environment generated in the new project folder and the same with the cabal files.
I have used cabal init but get the following output:

I don't really understand what this means nor can I figure out how to generate the files needed for nix-shell to work in this project.
Please help me figure out how to do this.
Thankyou.

Once inside the nix-shell, it assumes that the correct dependencies have already been loaded especially if you have built it on top of the newly cloned plutus-apps repo.  The nix files necessary are therefore already available for any new project that you would compile or run inside the nix shell.
In the Plutus Pioneer Program, there is an instruction to have to update (checkout) to the proper github commit tag of the plutus-apps repo that the current week's source codes is using.  Follow this intruction, then enter the nix shell.  Once inside the nix shell, you will be able to successfully compile and run the projects of the current week.
For a new project to work, there is an option to set a file as an executable in the cabal project file.  You may want to watch a part of the Plutus Pioneer Program - Iteration #3 Week #4 Lecture #2 video.  At time 09:55, Lars made an example on how to execute his source code using cabal run command, and he also explained afterwards the needed changes in the cabal project file if you want to use that command.

Thanks for the answer but i think it is answering the wrong question. The question is can I generate these files into a separate folder from a terminal command to upload them to GitHub along with my code for a new project.

@KryptoKing Okay, I was assuming that the files you want to generate are files of the nix shell, which in my opinion don't have to be specified as part of your new code, and therefore no need to include in Github upload.  I am not an expert in nix OS or shell, so I guess later somebody else knowledgeable might shed light about your intended result for your project.

Thanks for the help. I appreciate you trying to help me out. Can I ask why you don't believe they belong in the repo? Arnt they required to reproduce the effective env?

In Lars' lectures, we only clone the source files. I believe there are no nix files in his source repo.
I didn't encounter problems loading the PPP source files while inside the nix-shell,
and it successfully compiles and run. The nix-shell already managed the environment by referencing
the right plutus-apps and cabal files, thus, with the correct environment, you only need to clone
the source codes (and the cabal project file), no nix files needed just like what Lars did in his repo.


text:
Non-INLINABLE functions Error
I mark the function as inlinable but get the error that the function cannot be made inlinable. This does not appear to make sense as the function is known to be inlinable.

This was a problem with the Haskell compiler interfering with the code before it reached the Plutus compiler. The changes made in the Haskell compiler made it impossible to compile in Plutus.
This means the plugin doesn’t have access to implementation of the function, which it needs to be able to compile the function to Plutus Core. Some things you can do to fix it:
Make sure to add {-# INLINABLE functionname #-} to your function.
If there’s an extra $c in front of the function name in the error, GHC has generated a specialised version of your function, which prevents the plugin from accessing it. You can turn off specialisation with {-# OPTIONS_GHC -fno-specialise #-}
Other compiler options that can help:
{-# OPTIONS_GHC -fno-strictness #-}
{-# OPTIONS_GHC -fno-ignore-interface-pragmas #-}
{-# OPTIONS_GHC -fno-omit-interface-pragmas #-}
{-# OPTIONS_GHC -fobject-code #-}


text:
How to retrieve an addresses transaction history inside a plutus contract
I am trying to implement so logic to ensure smart contract (SC) validation upon certain conditions - which are derived from the end-users transaction history.
If I parameterise the SC and take the users address or public key hash (pkh) how can I look up the last N transactions to/sent from that address.
I need to be able to do this within the mkValidator logic.
Example:
mkValidator :: pkh -> () -> () -> () -> Bool
mkValidator pkh _ _ _
| pkh last transaction was to the specified user = True
| otherwise = False
I am attempting to make some free and opensource code for the community that tackle a fundamental problem in the Cardano protocol (i.e. it scales with the number of users) so I am attempting to stay away from blockfrost and other paid API services.

The current state of Plutus makes this impossible to do. Instead, you have to try and use a custom DB-sync server, and then construct the off-chain code in such a way that it passes the looked-up values to the Haskell program.
Note that you will have to use lifting to ensure that the values passed by the Haskell code, can configure the Plutus app.
The state of Plutus mentioned here is everything available on and before  Feb 22 2022.


text:
How To Optimise Daedalus Syncing?
So I started using my Daedalus Node as the node (instead of the direct build) for the cardano-cli, but it always takes forever to sync and I am wondering if I misconfigured something or if there's a better setup.
Can you please share your Daedalus optimisations/Configs?
Thanks

To help others with a similar issue, can you list for system specs and the time it has taken so far. It would be good to know your RAM size, SSD or HDD, and network speed via fast.com or similar.

As Erik mentioned, Daedalus is a full node and thus requires downloading the chain from peers and validating it locally on your machine. However, if you already have a trusted copy of the chain (either from previously syncing a full node or some other source), you can manually copy it into Daedalus' state directory. Doing this will speed things up because Daedalus will only have to validate the provided chain instead of downloading the whole thing from genesis. Of course, it will also have to download whatever is needed to extend the provided chain's tip to the current tip.
First, launch Daedalus, and click on Help > Daedalus Diagnostics. Under the "Core Info" section, the "Daedalus State Directory" specifies the filepath that Daedalus uses on your computer. In this directory should be a folder titled chain, containing 3 subdirectories: immutable, ledger, and volatile, as well as 2 files: lock and protocolMagicId.
Next, shutdown Daedalus, then replace the 5 assets in the chain folder with the other 5 found in your local copy of the chain (they should all have the same filenames as mentioned above). Also, make sure the chain folder and files have appropriate permissions (chmod 775 for chain).
Restart Daedalus and enjoy a faster sync!

Man your Daedalus knowledge is impressive you seem to be answering all my questions. A well-deserved upvote and tick.

Define "forever".
Sorry, but there are no tweaks to make it faster. If there were, they would be the default.
Please remember that Daedalus is a "full node". That means it downloads and stores the complete blockchain history, which on my full synced Linux machine uses disk store of 67 Gig for mainnet. I have not done a full sync with Daedalus recently, but I suspect it would be about 24 hours to sync.
There are however some thing that might help, like use a recent machine with at last 16G of RAM, use an SSD disk (which is faster than the older electro-mechanical ones, have a decent network connection.


text:
How to Run A DB Sync Server On Daedalus?
So I have been trying to do some fun things with Daedalus, and realised I should be able to query the node from it. This makes me wonder how to set up a limited database / querying system for my own needs out of Daedalus? Kinda like a smaller blockfrost.

The node by itself is stripped down of resources to keep active records of history, so the expectation that you could query node from Daedalus to have similar capability as cardano-db-sync (which maintains kinda everything from chain, as well as from ledger events, alongwith historical view). Thus, the resource requirements from dbsync are expected to be much more.
DB Sync v13 will allow you to stop querying ledger-state data which will shave off ~8-10GB (at the expense of not saving off-chain calcs coming from ledger-state). Instead if you're after creating small-scoped utility while not being able to spend much resources, you can look at projects below:

Ogmios / Kupo
Oura / Scrolls

Of course - the more you want to store and manage historically, higher the resources required will be

You can run cardano-db-sync, but be aware that is a rather heavy weight application that requires lots of RAM (ie 32 Gig) and will take about a week to sync.

32 GB will not be enough if you are also running cardano-node on the same machine. Or you will need to add a lot of swap...

Yeah looked at the repo this is not a viable option, for my computer and its over speced to train AI. That means I Have more Storage and RAM then most people.

@George-APEXStakePool I run a node and db-sync in a VM with 18 Gugabytes (16 was not enough).

@ErikdeCastroLopo If you run it long enough, you will see that one of them will eventually be killed with OOM error. It happened to me last week on a VM with 32 GM RAM. I upgraded it to 40 GB RAM and I also increased the swap (which was only 4 GB).


text:
How do you Connect ATALA to Plutus Smart Contracts
I think they use diffrent programming languages, but how can I use DID inside my Plutus contracts?

I do not have the answer for you but you are welcome to join the Atala PRISM Pioneer Program to find out how this can be done! https://atalaprism.io/app

In the current state of the two projects it is impossible to do so on the Plutus mainnet. The problem here is not that they use different languages (although that does make things a little trickier) its the fact that ATALA requires custom infrastructure (nodes) that do not currently exist in Plutus.


text:
How to Get Started with Cardano Native Script
What resources should you use to learn native script and in what order should you use them in?

You can find fairly extensive documentation on Cardano Native Script (aka Simple Script) here.
In short, you can define a JSON object with a simple set of rules known as scripts to validate operations around:

Payment (e.g. spending unspent transaction outputs, i.e. UTxOs at a payment address)
Staking (e.g. withdrawing rewards at a stake/reward address and delegation)
Minting (e.g. minting and burning of native assets under a policy)

Each script has a type defining different combinations of scripts required to validate an operation:

sig a signature witness of a key
after a point in time
before a point in time
atLeast M of N nested scripts
any of N nested scripts
all of N nested scripts

Given these script types, you can have fairly complex nested validation rules and order does not make a difference within the nested scripts.

Master branch no longer contain docs on that address. I found it on other branch: https://github.com/input-output-hk/cardano-node/blob/1.26.1-with-cardano-cli/doc/reference/simple-scripts.md


text:
How Will the Atala Plutus Integration Work?
I know that Atala prism will be used as the basis of Cardanos DiD but whenever I ask someone how it will work with Plutus, I end up hearing some new infrastructure needs to be built out.
My question is what is this infrastructure and how will it work with Plutus.


text:
How to build smart contract depending on trusted server for additional information
I am trying to build a smart contract that will need to rely on off-chain information from a trusted server in order to gather to the state of something which will impact on how the UTXO should be spent.
what is a strategy that i can use in order to have the on chain script make an some sort of http request to a trusted api server in order to get the status of something which can branch the decision of the on chain logic?
thanks for any suggestions.

Unfortunately, there is no way to make http calls from on-chain.
The only way to have off-chain information available on-chain is via transactions. Either the caller of the smart contract can bring the information with their transaction or the smart contract can reference data put on chain with previous transactions.
I'm guessing the latter is what you're looking for, what we call an "oracle". The data can be made available on the datum of some output (or "reference output") at another script address. You can make the updating of that data locked and only accessible by the "trusted" party's public key with a separate contract. Your smart contract can then reference the output that has the data on it.
There are additional ways you can customize this relationship, but that would be straying from your original question.
I hope that helps.


text:
Securing Stake Pool With Hardware Wallet
was looking at this project for securing cardano stake pool node with a hardware wallet (trezor specifically) https://github.com/vacuumlabs/cardano-hw-cli
just curious if anyone out there has used this to secure their node, was it possible to use the "hidden" wallets feature in trezor?
also i'm curious if if all the signing and certs could be done with the trezor or do you still need a air-gapped environment for protecting keys? or is trezor the "airgapped" environment now?

I started my pool before using a hardware wallet for the cold key was possible, so I did not test this. But I don't see any reason why using the hidden wallet feature wouldn't work.
You still need an airgapped environment for enhanced security (the cold key is the most important key), but it is less important when you have the cold key on a hardware wallet.

You do not secure your stake pool with your hardware wallet. What you are talking about is securing your pledge using your hardware wallet (with hidden wallet is ok). Then this hardware wallet is set as an owner on the stake pool.
Your airgapped stakepool keys are completely different. Those are used to set your pool information (margin, pledge, minFee, relays, metadata, etc..) and register owners. Those should remain airgapped for security.

You can also use the hardware wallet for the stake pool cold key. This is what the question is about. You cannot import the cold key of an existing stake pool in a hardware wallet, you need to create a new cold key (a new stake pool) for that.


text:
Cardano Node Compiler Error libsodium Fedora
for some reason i'm unable to compile cabal projects related to cardano projects on this system. not sure what could of changed recently as aside from recent system updates i haven't changed much. or anything at all for that matter related to haskell or cardano development.
I first noticed it when i was unable to build the atlas examples. however now i'm getting this error even when trying to compile the cardano-node/cli repo by running the cabal build all command.
❯ cabal build all
Warning: Requested index-state 2023-07-21T13:00:00Z is newer than
'cardano-haskell-packages'! Falling back to older state
(2023-07-21T12:48:43Z).
Resolving dependencies...
cabal: Could not resolve dependencies:
[__0] next goal: cardano-cli (user goal)
[__0] rejecting: cardano-cli-8.3.2.0, cardano-cli-8.3.1.0,
cardano-cli-8.3.0.0, cardano-cli-8.2.1, cardano-cli-8.2.0 (constraint from
user target requires ==8.1.2)
[__0] trying: cardano-cli-8.1.2
[__1] trying: ouroboros-consensus-protocol-0.5.0.4 (dependency of cardano-cli)
[__2] trying: cardano-crypto-tests-2.1.2.0 (dependency of
ouroboros-consensus-protocol)
[__3] next goal: cardano-crypto-praos (dependency of cardano-crypto-tests)
[__3] rejecting: cardano-crypto-praos-2.1.2.0, cardano-crypto-praos-2.1.1.2,
cardano-crypto-praos-2.1.1.1, cardano-crypto-praos-2.1.1.0,
cardano-crypto-praos-2.1.0.0, cardano-crypto-praos-2.0.0.1,
cardano-crypto-praos-2.0.0.0.1, cardano-crypto-praos-2.0.0 (conflict:
pkg-config package libsodium-any, not found in the pkg-config database)
[__3] fail (backjumping, conflict set: cardano-crypto-praos,
cardano-crypto-tests)
After searching the rest of the dependency tree exhaustively, these were the
goals I've had most trouble fulfilling: cardano-crypto-praos,
cardano-crypto-tests, ouroboros-consensus-protocol, cardano-cli
Try running with --minimize-conflict-set to improve the error message

versions of ghc / cabal and environment variables.
❯ ghc --version
The Glorious Glasgow Haskell Compilation System, version 8.10.7
❯ cabal --version
cabal-install version 3.6.2.1
compiled using version 3.6.2.0 of the Cabal library
❯ printenv | grep -i _path
LD_LIBRARY_PATH=/usr/local/lib
PKG_CONFIG_PATH=/usr/local/lib/pkgconfig
❯ pkg-config --list-all | grep -i libsodium
libsodium                      libsodium - A modern and easy-to-use crypto library
❯ tree /usr/local/lib
/usr/local/lib
├── libblst.a
├── libsecp256k1.a
├── libsecp256k1.la
├── libsecp256k1.so -> libsecp256k1.so.0.0.0
├── libsecp256k1.so.0 -> libsecp256k1.so.0.0.0
├── libsecp256k1.so.0.0.0
├── libsodium.a
├── libsodium.la
├── libsodium.so -> libsodium.so.23.3.0
├── libsodium.so.23 -> libsodium.so.23.3.0
├── libsodium.so.23.3.0
└── pkgconfig
    ├── libblst.pc
    ├── libsecp256k1.pc
    └── libsodium.pc

libsodium.pc
❯ cat /usr/local/lib/pkgconfig/libsodium.pc
prefix=/usr/local
exec_prefix=${prefix}
libdir=${exec_prefix}/lib
includedir=${prefix}/include

Name: libsodium
Version: 1.0.18
Description: A modern and easy-to-use crypto library

Libs: -L${libdir} -lsodium
Libs.private:  -pthread
Cflags: -I${includedir}

I am getting the same issue on nixOS.
libsodium is marked as broken in nixpkgs

Got it to compile successfully again. If you are using fedora 39 then you are going to be stuck using pkg-config version 1.9.5 (or at least that was the version i had at the time of this post) In the repos i wasn't able to downgrade or upgrade. so i went to the pkg-config repo where i was able to checkout the 2.0 tag and build, compile and install pkg-config. confirmed that the version was 2.0 and went back to the cardano-node repo and ran cabal build all and it is compiling successfully again. hope this is helpful to someone.


text:
Plutus Playground: error evaluating 'hello, world' example
When I try to evaluate the "Hello, world" example at https://playground.plutus.iohkdev.io/, I get the following error:
DecodingError: An error occurred while decoding a JSON value: Under 'EvaluationResult': At object key 'emulatorLog': Under 'Array': At array index 0: Under 'EmulatorTimeEvent': At object key '_eteEvent': Under 'EmulatorEvent'': At object key 'contents': Under 'ChainEvent': At object key 'contents': At array index 2: Under 'Tx': At object key 'txData': Expected value of type 'Object'.
Please try again or contact support for assistance.
Any idea?

it's a known issue: https://github.com/input-output-hk/plutus-apps/issues/195

since you have the answer you can post it as an answer to your own question here. Perfectly legitimate practice in Stack Exchange, and you get more rep :)

@MatthewCapps, thanks for a hint

This issue is reported at github.com/input-output-hk/plutus-apps/issues/195
Please have a look at Starter Pack (https://docs.google.com/document/d/13112LHG9vVvNUs40oZSqZ-DF6_yFiT_SJZ2NaEmjMM4) for the steps to set up a local instance of Plutus Playground.


text:
What are the types of data that are stored on the Cardano blockchain?
Is anything other than blocks which contain zero or more transactions, stored? Is e.g ledger state stored, is there anything special added at epoch boundaries?

Ledger state is not stored on the blockchain, but if you start with the correct initial ledger state and apply all blocks, in the correct sequence, from genesis to the current tip, you can recreate ledger state.
The things stored on the block chain include (may not be a complete list):

Blocks.
Transactions.
Stake pool registration certificates.
Stake pool parameter changes.
Stake address registrations certificates.
Staking delegation certificates (basically a special part of a transaction).
Proposals and voting for protocol parameters changes.

Things that are part of ledger state that is not stored on the blockchain (may also be incomplete):

The current UTxO state.
Current amount of ADA delegated to each stake pool.
Which stake address is currently delegated to each pool.
Rewards account balances for each stake address.
Current protocol parameters.

is there anything special added at epoch boundaries?

For the first Byron era there was an Epoch Boundary Block, but for all eras after that, there are no Epoch Boundary Blocks.

A follow-up question: given that Cardano is written in Haskell, is there an ADT somewhere that represents the single item that goes on the chain. Something like data Block = Txs ... | StakePoolAction ... | Proposal ...?

Unfortunately there is not a single type. The main complication is that all the types you mention are unique for each era (eg Byron, Shelley, Allegra, Mary, Alonzon, Babbage etc).  IMO this is an implementation detail that leaks out of cardano-api. For each era Block is a product type (ie a struct) with fields for transactions and all the other components. The current best way to access this is via cardano-api in the cardano-node repo.

I think this answer is partly wrong then: https://cardano.stackexchange.com/questions/1977/how-is-the-active-stake-of-a-stake-pool-calculated/1993#1993. It says "Data captured by the snapshot is stored on-chain as a part of the ledger state", for me that sentence implies that ledger state is stored on-chain as well.

Maybe its the other answer that is wrong. Some (but not all) parts of ledger state are available indirectly on chain. For instance, if you extract all the stake delegations from the chain, you can reconstruct the stake distribution for an epoch, but the stake distribution for an epoch is not directly stored on chain. The reward accounts for all stake addresses can be reconstructed by playing back the block chain, but the reward account balances are not on chain,

Also the full ledger state is HUGE . When stored on disk (db-sync actually does this) in a relatively compact form a single ledger state snapshot is about 2 gigaybtes in size. If that data was stored on chain, the chain would be significantly bigger than it is.

On the transaction you can store some (little metadata)
But a blockchain is not a distributed database.
usage of such feature is dependente on your use case.
Example:
I want to have in the blockchain all repair information of my car.
I'd attach to the transaction a hash that represents data on an "open database" so the record if changed no longer has the hash that was stored on chain.
then your car has its own wallet and anyone can see it's repair history...with confidence it's not faked


text:
Is there full list of Ouroboros mini-protocols that the node supports (preferably official and kept up to date)?
A paper from 2019 I found that describes mini-protocols: https://hydra.iohk.io/build/1070091/download/1/network.pdf. Have more protocols been added?

The network specs used for creation of that document (updated version from 2019) lives in ouroboros-network repository, and you can find the latest CI build of the document here

Following from the github repo, the main technical overview is in the "The Shelley Networking Protocol" pdf here: https://hydra.iohk.io/build/20405228/download/2/network-spec.pdf#chapter.3, and a lighter overview in the Cardano documentation here https://docs.cardano.org/explore-cardano/cardano-network/networking-protocol (need to scroll down, couldn't link to appropriate subsection)

Documentation link is dead.

It's here now https://input-output-hk.github.io/ouroboros-network/pdfs/network-spec/network-spec.pdf


text:
Why does staking happen with a delay?
In Cardano, AFAICU, at the beginning of an epoch a snapshot is taken of the end state of previous epoch to see who staked, how much and where. But it seems that that state is not used as for that current epoch but for the next one instead. Is there a particular reason for this?
E.g is it because to have time to calculate slot leaders and then let them know that they need to start producing blocks? Are there other reasons?
It seems somewhat counterintuitive that by the time one is "staking" the actual funds might be long gone, delegated to another pool or not staked at all. Though I understand that this doesn't break the system and that it's just a delay.

The stake distribution for epoch N is not used as the basis for the epoch N + 1 reward calculations because at the start of epoch N + 1 there may be a rollback that may rollback as far as later blocks of epoch N which would require a recalculation of the stake distribution.
However rollbacks are limited to a maximum of 2160 blocks, so the stake distribution for epoch N cannot be rolled back after 2160 blocks have been produced in epoch N + 1. It is therefore safe to use the epoch N stake distribution for the reward calculation for epoch N + 2.
Similarly rewards earned in epoch N + 2 are not distributed until epoch N + 4, again to avoid the possibility of a rollback.
Finally, rollbacks are part of the normal operation of a blockchain.


text:
What is a MIR certificate, what does MIR mean in general?
The acronym seems to mean "move instantaneous rewards" (link), but I can't find any good ELI5 explanation on what that means, when would I require a MIR certificate, etc.

"MIR" is not a particularly good name, but I can explain the history.
It started out standing for "move ITN rewards", where "ITN" stands for the "incentivized test net". The idea of the ITN was a test network whose rewards would end up on the main network after the launch of the Shelley phase. The MIR certificates were originally designed for exactly the purpose of transferring Lovelace from the reserves on mainnet to the participants of the ITN (and requiring authorization using the existing governance mechanisms).
It eventually became clear that this mechanism would be useful for more purposes than just the ITN rewards, such as paying out Catalyst winners from the treasury. So the acronym was re-imagined to stand for "move instantaneous rewards", since they transfer funds at the next epoch boundary.
An ELI5 explanation of MIR certificates is: MIR certificates require the authorization of the existing Cardano governance mechanism, and they result in the transfer of Lovelace from the reserves or the treasury to a collection of stake credentials. (They can also move Lovelace between the reserves and the treasury.)

Thank you, the back-story helps a lot! Somebody should write the "History of Cardano for developers" :)

Not sure about the exact purpose of MIR (move instantaneous rewards) certificate but it seems to be a specific type of transaction to allow for 'transferring funds between reserves and the treasury'.
My guess would be for funding things like Catalyst projects.
This link will tell you what instantaneous rewards are.


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:
What goes inside the block?
After going through lecture 1, where can I find out more information about what is stored in each block in blockchain ?
I am guessing that all the UTxOs and the script addresses will be there, as well as the (on-chain) plutus scripts themselves.
If the UTxOs are all in the blockchain, is it the user/wallet responsibility to safely maintain all the UTxOs that he owns ?
Thanks!

The UTxO set is not on the blockchain. Blocks contain transactions (including input UTxO references, output addresses, scripts, certificates (eg for delegation and other purposes) etc.
The UTxO set is an ephemeral data structure than can be built from the original genesis state and then apply blocks to it.

When, say, Alice sends money to Bob, how does Bob know which UTxO output belongs to him (so that he can consume that money) ? Is it the job of the wallet to scan through all new UTxOs that are generated in the blockchain, then compare this new UTxO with Bob's wallet -  and if it matches, add the new UTxO to Bob's wallet ? Is this a correct assumption ?

Yes, that is correct.


text:
Is Redeemer similar to <ScriptSig> in bitcoin context?
In the (e)UTxO model, discussed in the 1st lecture of PPP#3, I am trying to understand the differences between the UTxO model of Bitcoin and the (e)UTxO model of Cardano.
From what I understand, the "script" in Cardano is similar to the locking script (ScriptPubKey) used in Bitcoin, and "redeemer" is similar to the unlocking script (ScriptSig). The main difference being that Cardano script is Turing Complete. Is this a correct assumption ?
And what is the new "Datum" used in Cardano and how large is it ? I assume that "Datum" is stored "on-chain"?

One way to think of it is that:

The Datum is a piece of data that's attached to the UTXO by the producer,
The Redeemer is a piece of data that's provided by the consumer,
When the UTXO is consumed, the script is run with both the Datum and the Redeemer as arguments and it can thus verify its spent in the right context.

The Datum can be "arbitrarily" large subject to the Tx size limits. What's get stored in the UTXO is actually not the Datum itself but its hash. The spending transaction has to provide the actual Datum, of course matching the hashes stored in the UTXO.
I think your analogy is correct but I am not knowledgeable enough with Bitcoin to be sure.
HTH.

Thank you. Just found this thread which has lots of info : https://cardano.stackexchange.com/questions/471/what-exactly-is-a-redeemer?rq=1

It might help understand from where do these inputs of the functions come from:

the Redeemer is a piece of data constructed at the moment the user wants to interact with e smart contract, this piece of data is only available for the running transaction and is often used to allow the same smart contract to execute different logic based on the requested action of the user

the ScriptContext is passed by the node that is running the script, it passes transaction-related pieces of information such as who is giving the inputs and where those inputs are going (outputs), along with other transaction information such as the time the transaction is being executed

the Datum is what allows for the Turing completeness in the (e)UTxO model.
It is attached to an UtxO belonging to the smart contract, in particular, the Datum is often used to encode the state of the script and it can be useful to store variables that can change.
More in general the Datum allows the script to have some memory of the past of the script, and this is the reason the Datum makes Cardano smart contracts Turing complete


text:
Error when installing nix : the group 'nixbld' specified in 'build-users-group' does not exist
I am trying to install nix/plutus following the below instructions :
https://docs.plutus-community.com/docs/setup/Ubuntu.html
The first step to install curl when fine. I get below error when installing nix :
sh <(curl -L https://nixos.org/nix/install) --no-daemon
% Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
Dload  Upload   Total   Spent    Left  Speed
0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
100  4046  100  4046    0     0   8376      0 --:--:-- --:--:-- --:--:--  8376
downloading Nix 2.5.1 binary tarball for x86_64-linux from 'https://releases.nixos.org/nix/nix-2.5.1/nix-2.5.1-x86_64-linux.tar.xz' to '/tmp/nix-binary-tarball-unpack.4wSWtNaOSw'...
% Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
Dload  Upload   Total   Spent    Left  Speed
100 27.1M  100 27.1M    0     0  7549k      0  0:00:03  0:00:03 --:--:-- 7549k
Note: a multi-user installation is possible. See https://nixos.org/manual/nix/stable/installation/installing-binary.html#multi-user-installation
warning: installing Nix as root is not supported by this script!
performing a single-user installation of Nix...
copying Nix to /nix/store...........................................
warning: the group 'nixbld' specified in 'build-users-group' does not exist
warning: the group 'nixbld' specified in 'build-users-group' does not exist
installing 'nix-2.5.1'
error: the group 'nixbld' specified in 'build-users-group' does not exist
/tmp/nix-binary-tarball-unpack.4wSWtNaOSw/unpack/nix-2.5.1-x86_64-linux/install: unable to install Nix into your default profile
How can I can get past this ?
Thanks!

Don't run the installer as root! Run it as a normal user.

I always install as root. I get error with all the scripts. Except this one (multi-user):
sh <(curl -L https://nixos.org/nix/install) --daemon

I used the command:
sh <(curl -L https://nixos.org/nix/install)
(it seems to work)
I had to remove the:   --no-daemon  qualifier from the command I used previously


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:
ValidationError ValueContainsLessThanMinAda in Week02 Homework1.hs (cohort #3)
currently in the 3rd cohort and doing week 2 HW, specifically Homework1.hs. My code compiles, but when I run in the local playground and try the 'give' endpoint, I just keep getting 'Contract instance stopped with error: "WalletError (ValidationError (ValueContainsLessThanMinAda...' which from what I can find means I need to send a certain ADA value as a transaction fee along with the lovelace amount specified in 'give'.
This seems like an error in the playground or in the rest of the provided code for this homework as there is no option to do so. Can anyone confirm? Below is the scenario I'm running.

Here also is the error I'm getting:
Contract instance stopped with error: "WalletError (ValidationError (ValueContainsLessThanMinAda (Tx {txInputs = fromList [TxIn {txInRef = TxOutRef {txOutRefId = 6945becead343ee16a04848adee6d24bcf05129b355021411a0b65eca6e6624e, txOutRefIdx = 1}, txInType = Just ConsumePublicKeyAddress}], txCollateral = fromList [], txOutputs = [TxOut {txOutAddress = Address {addressCredential = PubKeyCredential a2c20c77887ace1cd986193e4e75babd8993cfd56995cd5cfce609c2, addressStakingCredential = Nothing}, txOutValue = Value (Map [(,Map [(\"\",99900000)])]), txOutDatumHash = Nothing},TxOut {txOutAddress = Address {addressCredential = ScriptCredential 847f43379bc66c74dcbe4b92912dd88a44eaa66cde36c55b9d082365, addressStakingCredential = Nothing}, txOutValue = Value (Map [(,Map [(\"\",100000)])]), txOutDatumHash = Just 923918e403bf43c34b4ef6b48eb2ee04babed17320d8d1b9ff9ad086e86f44ec}], txMint = Value (Map []), txFee = Value (Map []), txValidRange = Interval {ivFrom = LowerBound NegInf True, ivTo = UpperBound PosInf True}, txMintScripts = fromList [], txSignatures = fromList [(8d9de88fbf445b7f6c3875a14daba94caee2ffcbc9ac211c95aba0a2f5711853,5a77c67d8fa23cd9a1f2a3e496a323ce8ffd0468d99491e4b651ea6b385a34dc6dc9085d812cbb00ccb95bdc9946ad9c1d8cffae640ecb82c2bfdc1794c0d907)], txRedeemers = fromList [], txData = fromList [(923918e403bf43c34b4ef6b48eb2ee04babed17320d8d1b9ff9ad086e86f44ec,Datum {getDatum = Constr 0 []})]}) (TxOut {txOutAddress = Address {addressCredential = ScriptCredential 847f43379bc66c74dcbe4b92912dd88a44eaa66cde36c55b9d082365, addressStakingCredential = Nothing}, txOutValue = Value (Map [(,Map [(\"\",100000)])]), txOutDatumHash = Just 923918e403bf43c34b4ef6b48eb2ee04babed17320d8d1b9ff9ad086e86f44ec})))" ]

Edit to add: here's my code as well, the parts that I edited at least

There's a constraint that an UTXO must have at least 2 ADA (2.000.000 lovelaces).
I guess that because you are giving less than this value (100.000 lovelaces) you get that error.

Retried with 2 ADA, and it worked. One other thing I did though was do a 'cabal update' and 'cabal build' before starting the playground. I might have missed doing that when switching to week 2


text:
Cannot Get haskell-language-server running - duplicate symbol "sqlite3_fts3_may_be_corrupt"
hoping someone can help with this
So, I would like to get the haskell-language-server running, in the context of the plutus-pioneers-program, so that in VS Code I can Ctrl+Click and view type definitions, get IntelliSense suggestions, etc. It's my understanding that this is what the haskell-language-server does, correct me if I'm wrong.
I am currently on week 4 of cohort #3. After messing around for a while and getting errors, I decided to recreate a clean environment. I created a fresh Ubuntu VM, setup nix, and did the following steps:

clone plutus-apps repo
clone plutus-pioneer-program repo
consult week4 cabal.project to obtain plutus-apps commit ea1bfc6a49ee731c67ada3bfb326ee798001701a, and then checkout said commit in the plutus-apps repo.
run nix-shell in plutus-apps repo, wait for it to finish
within the launched nix shell from step 4, cd over to week04 in the plutus-pioneer-program repo, run haskell-language-server
haskell-language-server command eventually fails due to needing cabal-update to be run (this was printed in the output)
run cabal update, wait for it to finish
re-run haskell-language-server, it eventually fails with the below error:

GHC runtime linker: fatal error: I found a duplicate definition for symbol
   sqlite3_fts3_may_be_corrupt
whilst processing object file
   /nix/store/p2b0z9ajriig2krxkyn3n3wf1ph4bmzw-persistent-sqlite-lib-persistent-sqlite-2.13.0.4/lib/x86_64-linux-ghc-8.10.4.20210212/persistent-sqlite-2.13.0.4-B4U7gZMAoFwD1W7QEEZsue/HSpersistent-sqlite-2.13.0.4-B4U7gZMAoFwD1W7QEEZsue.o
The symbol was previously defined in
   /nix/store/b18hn2jh564d3f4hg5mpk639dh4cr45f-direct-sqlite-lib-direct-sqlite-2.3.26/lib/x86_64-linux-ghc-8.10.4.20210212/direct-sqlite-2.3.26-Gg0YVBPVrMk3LDxZxB2Bzf/HSdirect-sqlite-2.3.26-Gg0YVBPVrMk3LDxZxB2Bzf.o
This could be caused by:
   * Loading two different object files which export the same symbol
   * Specifying the same object file twice on the GHCi command line
   * An incorrect `package.conf' entry, causing some object to be
     loaded twice.
2022-02-13 15:46:37.022720678 [ThreadId 481] INFO hls:  File:     /home/ben/plutus-pioneer-program/code/week04/src/Week04/Vesting.hs
Hidden:   no
Range:    1:1-2:1
Source:   compiler
Severity: DsError
Message:
  loadObj
  "/nix/store/p2b0z9ajriig2krxkyn3n3wf1ph4bmzw-persistent-sqlite-lib-persistent-sqlite-2.13.0.4/lib/x86_64-linux-ghc-8.10.4.20210212/persistent-sqlite-2.13.0.4-B4U7gZMAoFwD1W7QEEZsue/HSpersistent-sqlite-2.13.0.4-B4U7gZMAoFwD1W7QEEZsue.o":
  failed
2022-02-13 15:46:37.023051069 [ThreadId 445] INFO hls:  finish: User TypeCheck (took 5.05s)
2022-02-13 15:46:37.044108638 [ThreadId 883] INFO hls:  finish: GetHie (took 0.02s)
2022-02-13 15:46:37.044666524 [ThreadId 906] INFO hls:  finish: GenerateCore (took 0.00s)
Files that failed:
 * /home/ben/plutus-pioneer-program/code/week04/src/Week04/Trace.hs
 * /home/ben/plutus-pioneer-program/code/week04/src/Week04/Vesting.hs

From Googling around, it seems the issue has to do with the {-# LANGUAGE DataKinds        #-} pragma in both those files, which is a core Haskell language extension. You can also see this from the error above, the Range: field talks about the first line of Vesting.hs, which is the DataKinds pragma. If this pragma is removed, the error goes away, however Vesting.hs and Trace.hs depend on it, and other errors are generated.
As best I can tell, there are somehow packages associated with this extension that either nix, cabal, or haskell-language-server have somehow duplicated. Or something. This is where my knowledge runs out.
Does anyone have any input here? How can this error be resolved?


text:
About Homework 4 - Getting PayParams through binding
This question is in the context of the homework for Lecture 4.
What is wrong with the following reasoning?
We know that payContract is type m (), where m stands for the monad Contract () PaySchema Text.  Therefore
payContract = do
    pp <- awaitPromise $ endpoint @"pay" return

must bind () to the variable pp.  Hence pp does not contain information about PayParams.
Obviously my argument is wrong, because ppLovelace pp does give you the payment amount.  But where exactly is the error in my logic?

Could you resolve your question with any of the answers here?

Obviously my argument is wrong, because ppLovelace pp does give you the payment amount.

Yes the argument is wrong because first of all the endpoint @"pay" return means it returns the value of @"pay" immediately so the side-effect which would be () is not reached. Also the function has a final call awaitPromise which returns a new monad with a different return value. Again the () is not seen by awaitPromise.
I hope I explained myself ok.

Here, the full payContract in Homework.hs.
payContract :: Contract () PaySchema Text ()
payContract = do
    pp <- awaitPromise $ endpoint @"pay" return
    let tx = mustPayToPubKey (ppRecipient pp) $ lovelaceValueOf $ ppLovelace pp
    void $ submitTx tx
    payContract

where  pp <- awaitPromise $ endpoint @"pay" return  is an intermediate computation which doesn't determine the type result of the function payContract. The type result of the function is given by the last expression in the function: payContract.
The type of awaitPromise $ endpoint @"pay" return is Contract () PaySchema PayParams. Therefore, pp is PayParams. But again, it's an intermediate computation.


text:
Allowing for a weaker on-chain constraint. Week 05 Homework 2
In HW 2 of Week 5, we need to write a script that mints a token with empty ByteString.  The minting policy code on the on-chain part (mkPolicy) could ensure that the token name is empty by defining
    checkMintedAmount :: Bool
    checkMintedAmount = case flattenValue (txInfoMint info) of
      [(_, tn, amt)] -> tn == (TokenName emptyByteString) && amt == 1
      _              -> False

I claim that that the weaker constraint
    checkMintedAmount :: Bool
    checkMintedAmount = case flattenValue (txInfoMint info) of
      [(_, _, amt)] -> amt == 1
      _             -> False

is good enough, since the off-chain part of the code will make sure that the token name is the empty string.  I ran the experiment and it seems to work.
Generalizing, it seems that the constraints on the on-chain script can be less stringent than the off-chain constraints if the transaction is going to be initiated by the wallet that owns the UTxO where the script resides.  Is this claim correct?

This question was answered by Lars during the Q&A.
In summary, you can't rely on an attacker using your offchain code. An attacker could write their own off chain code that uses a non empty Token name.
Perhaps if you are sure that you are the only person able to use the minting policy (eg you check that the transaction is signed by a specific user), you could make such assumptions.


text:
Homework for lecture # 5
How do I review the homework for lecture 5?  There is no folder 'lecture05' in https://github.com/input-output-hk/marlowe-pioneer-program/tree/main/code/src

Here is the homework for Lecture 5.


text:
Building Tx with cardano-api
Can anybody provide an example of building a simple Tx using just Haskell and Cardano-Api?
(I know that there are other great tools for building Tx's, but I'm curious about using Cardano-Api.)

Cardano faucet uses API directly to build it's transactions:
https://github.com/input-output-hk/cardano-faucet/blob/f1b83b4fe649c6dabffa483820f0d5ec47fb2633/cardano-faucet/src/Cardano/Faucet/TxUtils.hs#L25

Great example, thanks!

Sam's example is perfectly fine however we have another way to construct txs that may be more convenient via various lenses:
https://github.com/IntersectMBO/cardano-cli/blob/25a9cfd09052ce838dd08f6da3a22c24bc474a9d/cardano-cli/src/Cardano/CLI/EraBased/Run/Transaction.hs#L871
Then you can call makeTransactionBodyAutoBalance to create a balanced tx.

Great!  Thanks for the reference.


text:
How to deserialize Datum using Lucid
The following code allows me to query a Datum from the blockchain using Lucid and Blockfrost:
import { Blockfrost, Lucid } from "https://deno.land/x/lucid@0.10.7/mod.ts";

const lucid = await Lucid.new(
  new Blockfrost(
    "https://cardano-preview.blockfrost.io/api/v0",
    <your BLOCKFROST_API_KEY>
  ),
  "Preview"
);

const nft = "b7e0e70f653f23abc39d16f6f6be16fd72e3fe3030db9b16cecccf68524549545f5354415445";  // example

const utxo = await lucid.utxoByUnit(nft);
const datum = utxo.datum
console.log(datum);

The output to the console, for this example, is:
d8799f1903e819f80c1903e81903e8ff

My question now is, what command in Lucid allows me to deserialize this output?  I don't even know what kind of encoding I am dealing with (I suspect it is CBOR).
By the way, I know that the desired deserialization, for this example, should be:
{
   constructor: 0,
   fields: [
      {
         int: 1000
      },
      {
         int: 63500
      },
      {
         int: 1000
      },
      {
         int: 1000
      }
   ]
}

I figured out that the Lucid command that does the trick is Data.from.  First, in the original code, I need to add Data in the list of imports:
import { Blockfrost, Lucid, Data, } from "https://deno.land/x/lucid@0.10.7/mod.ts";

Then simply add:
const solution = Data.from(datum);
console.log(solution);

at the end of the original code.

Still it would be nice to know if it is indeed CBOR the encoding from which Data.from deserializes.


text:
Is Plutus off-chain code relevant for testing?
It was mentioned in lecture 1 that in this fourth cohort of the PPP we won't need to learn to write off-chain code in Plutus/Haskell. Nevertheless it appears that testing uses the emulator and it seems to me that Plutus off-chain code might be relevant for writing testing scenarios. Is this correct?  Would knowing about the "contract monad" be useful for writing tests?

From Lars' answer in the Q&A:

First of all, you can still use Haskell in Kuber to do the off-chain part.
As a side note, it is likely that GeniusYield will soon release a PAB replacement that is also a Haskell library.
If you want to write tests in emulator traces, you still need Plutus-Apps and understand the "contract monad".  But there are alternatives, like Plutus simple model developed by MLabs.
Plutus simple model is also a Haskell library and is the one used in this course (PPP fourth cohort).  It doesn't use the contract monad and is easier to use than emulator traces.  A forthcoming lecture on testing will use "Plutus simple model" (as do the tests in the homeworks).
Admittedly emulator traces are still quite nice, but it is unfortunate that you need all the theory behind the contract monad (and for this reason they will not be covered in this course).


text:
Understanding a datum declaration in typescript
At the bottom of this post are lines 52-68 of file lucid-vesting of week 4 (PPP fourth iteration).  I am having a hard time understanding line 60:
const dtm: Datum = Data.to<VestingDatum>(datum,VestingDatum);

Why are there two instances of VestingDatum?  It seems that the command to is converting datum to VestingDatum, but datum had already been declared to be of type VestingDatum.
// Creating a datum with a beneficiary and deadline
const datum: VestingDatum = {
    beneficiary: beneficiaryPKH,
    deadline: deadlinePosIx,
};

// An asynchronous function that sends an amount of Lovelace to the script with the above datum.
async function vestFunds(amount: bigint): Promise<TxHash> {
    const dtm: Datum = Data.to<VestingDatum>(datum,VestingDatum);
    const tx = await lucid
      .newTx()
      .payToContract(vestingAddress, { inline: dtm }, { lovelace: amount })
      .complete();
    const signedTx = await tx.sign().complete();
    const txHash = await signedTx.submit();
    return txHash
}

Lucid also has a minimal example for typed data here.
The function Data.to has the following signature (as seen from here):
/**
 * Convert PlutusData to Cbor encoded data.\
 * Or apply a shape and convert the provided data struct to Cbor encoded data.
 */
function to<T = Data>(data: T, shape?: Json): Datum | Redeemer {

Where the type Data which is a wrapper around your usual Plutus primitives (see this).
Lucid defines higher types here which correspond to their serialized version as one would expect.
Now seeing the definition of function to from Lucid's source code, you'll realize that it first wants to obtain this Data (this line) and then convert it for corresponding plutus types (the serialize function) in Cardano Multiplatform Library.
Now either you can play with so called raw/untyped datum (like in this example) in which case your T above will simply be that Data or you can play at a bit higher type level (like you would do when writing Plutus contracts) where lucid helps you get this T using Data.Static as seen here. The second parameter as you would understand by now, is not at type level and is for this - the shape of your structure. Also Json is essentially any type.


text:
Metadata Label Registry
Is there an official "label registry" for (transaction) metadata?
CIP 10 proposed such a registry, but I can not find it implemented anywhere.

There has been a lot of reorganization on the CIP website and for whatever reason a number of links seem to have been broken.
The registry as I understand it is this chunk of JSON in the CIP GitHub, permalinked below for convenience.

https://github.com/cardano-foundation/CIPs/blob/868ae58447c953cc6115b61064af6d5ad30edd87/CIP-0010/registry.json

My understanding is that new labels are added via pull-request to this repo.


text:
Is eUTxO a generalisation of UTxO
To me it sounds like UTxO is a very specific implementation of the more general eUTxO protocol. So could eUTxO be (in theory) be used to implement UTxO? Not that one would - but just to understand the distinction between the two.

You can think of regular Bitcoin-like UTXO's as a subset of all possible eUTXOs possible to construct on Cardano. Transactions that simply transfer ADA from one wallet to another (and nothing else) are examples of bitcoin-like UTXO's. eUTXO extends this core functionality by allowing one to attach arbitrary data and logic to each transaction, enabling complex lock-and-key mechanics that go way beyond simple public-private key transfers.
So to answer your question - yes; classic UTXO's are already implemented in Cardano and have been since genesis. UTXO's are to eUTXO's like squares are to rectangles.
Read more about the eUTXO model in the official Cardano Documentation


text:
Installing on WLS2 - error: experimental Nix feature 'nix-command' is disabled
I am completely green here. I'm following the instructions laid out in https://docs.plutus-community.com/docs/setup/WindowsWSL.html to setup my windows environment for cohort 3 of the pioneer program and having issues.  I've successfully completed steps 1-7 (in the link above), but when I do Step 8, which is ...
nix build -f default.nix plutus.haskell.packages.plutus-core.components.library
I get ...
error: experimental Nix feature 'nix-command' is disabled; use '--extra-experimental-features nix-command' to override
Where do I add that flag in the nix build command?
Thanks

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.

Previously there was another plutus repository, now they made an update with another name plutus-apps, the execution of the command must be updated so that it points to that reference of the plutus-apps project
nix --extra-experimental-features nix-command build -f default.nix plutus-apps.haskell.packages.plutus-core.components.library

This worked for my macOS Monterey 2015 Quad i7 setup.

I was a little bit on the tutorial and just started setting the environment. Sorry for that indeed.
I get the following error when i try to build plutus with nix command
error: getting status of /home/user/default.nix: no such file or directory
Thanks

Think I have resolved it.
nix --extra-experimental-features nix-command build -f default.nix plutus.haskell.packages.plutus-core.components.library


text:
Mongolia Course - Slides, Homework and Solutions
Does anyone know if we have access to the Mongolia course slides, homework and solutions? If so where can we find them? If not, please could they be made available? I think the homework exercises with solutions will be great practise for learning all the Haskell concepts as we follow the you tube videos.

Please note that the videos on github cover core content than the videos in YouTube

here
https://github.com/iohkedu/haskell-2020
videos, slides, homeworks and solutions
The videos here have way more content than in youtube


text:
Incorrect Pub Key from Wallet Emulator
I am getting incorrect pubkeys by running mockWalletPaymentPubKey $ knownWallet 1 and mockWalletPaymentPubKey $ knownWallet 2 (from here https://youtu.be/ae7U_yKIQ0Y?t=1390).
I checked that

I am in the correct directory
I imported the wallet emulator using import Wallet.Emulator
and the cabal build command ran successfully.

On restarting the repl, I get the same incorrect wallet pub keys.
Note: I was able to get the correct pub keys by looking at the transactions in the simulator.

mockWalletPaymentPubKey gives you the public key for a wallet.
For Vesting.hs, you need to use the public key hash.
Try mockWalletPaymentPubKeyHash $ knownWallet 1 instead.


text:
Unable to start /plutus-apps client application
Error is occurring for MacOS 12.1 Monterey. Please, let me know, if I should include additional details.
I am going through the step noted in this document in order to setup local Plutus app:  https://docs.google.com/document/d/15QR25eWgg587FTPnuf6Si_lpux-uFQsY_2Gj_4vf4lM/edit
Everything is going fine until the 6th step. The following is the error log I am getting:

> plutus-playground-client@1.0.0 start /Users/rnaydenov/Desktop/Plutus Pioneer/plutus-apps/plutus-playground-client
> plutus-playground-generate-purs && npm install && npm run install:spago && npm run build:webpack:dev

[Info] Running: (Nothing,PSGenerator {_outputDir = "generated"})
The following purescript packages are needed by the generated code:

  - plutus-playground-client
  - purescript-argonaut-codecs
  - purescript-either
  - purescript-enums
  - purescript-lists
  - purescript-maybe
  - purescript-newtype
  - purescript-ordered-collections
  - purescript-prelude
  - purescript-profunctor-lenses
  - purescript-tuples
  - web-common

Successfully created your PureScript modules!

Successfully created your servant API purescript functions!
Please make sure you have purescript-servant-support and purescript-bridge-json-helpers installed

plutus-playground-server: user error (Error evaluating simulation: InterpreterError (CompilationErrors [CompilationError {filename = "\n/private/tmp/web-ghc-work-95c26a6de2f74eb6/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-95c26a6de2f74eb6/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-95c26a6de2f74eb6/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","  | ^^^^^^^^^^^^^^^^^^^^^^^"]}]))
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! plutus-playground-client@1.0.0 start: `plutus-playground-generate-purs && npm install && npm run install:spago && npm run build:webpack:dev`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the plutus-playground-client@1.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm WARN Local package.json exists, but node_modules missing, did you mean to install?

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/rnaydenov/.npm/_logs/2022-01-12T22_40_06_274Z-debug.log

Fortunately, someone in the discord had this exact same problem.  I had suggested running nix-build, but that errored out.  Apparently the solution was to set this first, before running the command:
GC_DONT_GC=1

Here is the original message from the pioneers-lounge in the discord: https://discord.com/channels/826816523368005654/862912746847993887/930825351968473118

Thank you so much for the answer! GC_DONT_GC=1 npm start seemed to work .. now off to the next error (:
Also, for anyone trying to get this setup on Mac M1 I highly recommend this guide https://github.com/renzwo/cardano-plutus-apps-install-m1

Actually, for anyone that comes across this: if you manage to get the app running but stumble upon a compilation error of the sort 'Ledger not found', try stopping the client and server, exiting the nix-shell and running nix build -f default.nix plutus-apps.haskell.packages.plutus-pab.components.library in /plutus-apps.
According to the ReadMe in plutus-apps https://github.com/input-output-hk/plutus-apps this builds the Plutus PAB library required for the compilation.

This worked for me after "ERR check permissions missing write access", on masOS i7 Monterey.  sudo GC_DONT_GC=1 npm install -g npm .


text:
how to query the chain index tx endpoint?
The following curl is constructed via swagger that says it just needs the string, but this fails.
What am I doing wrong?
$curl -X 'POST' \
>   'http://localhost:9083/tx' \
>   -H 'accept: application/json;charset=utf-8' \
>   -H 'Content-Type: application/json;charset=utf-8' \
>   -d '"c42669c4818e04d732e77b9ed3efb22697ba4b1cd7540d2bab8c44f9a5e4fbb6"'
Error in $: parsing Plutus.V1.Ledger.TxId.TxId(TxId) failed, expected Object, but encountered String

I can pull out the tx data in sqlite3 so I think I've ruled out it being a bad id

The following substitution works
...
-d '{"getTxId" : "c42669c4818e04d732e77b9ed3efb22697ba4b1cd7540d2bab8c44f9a5e4fbb6"}'
...