text:
Is type String truly equal to type [Char], and is Haskell truly "pure"?
One fundamental of Haskell is that a string is really a list of characters. Another fundamental is referential transparency, in that a pure function must always give the exact same result when given the same input.
However, these do not seem to be true in actual practice. For example, I created this function:
stringCharList :: String -> [Char] -> Bool
stringCharList a b
    | a==b = True
    | otherwise = False

if I enter (in the repl)
>stringCharList "hello" ['h','e','l','l','o']

I get back True, as expected. However, if I build this function, I get an error (shown below)
vowelz :: Char -> Bool
vowelz a
    | a `elem` vowels = True
    | otherwise = False
      where vowels = "aeiou"

JWB2.hs:38:22: error:
    • Ambiguous type variable ‘t0’ arising from the literal ‘"aeiou"’
      prevents the constraint ‘(Data.String.IsString
                                  (t0 Char))’ from being solved.
      Relevant bindings include
        vowels :: t0 Char (bound at JWB2.hs:38:13)
      Probable fix: use a type annotation to specify what ‘t0’ should be.
      These potential instances exist:
        instance (a ~ Char) => Data.String.IsString [a]
          -- Defined in ‘Data.String’
        ...plus two instances involving out-of-scope types
        (use -fprint-potential-instances to see them all)
    • In the expression: "aeiou"
      In an equation for ‘vowels’: vowels = "aeiou"
      In an equation for ‘vowelz’:
          vowelz a
            | a `elem` vowels = True
            | otherwise = False
            where
                vowels = "aeiou"
   |
38 |       where vowels = "aeiou"
   |                      ^^^^^^^

Either of these two alternatives resolves the error
vowelz :: Char -> Bool
vowelz a
    | a `elem` vowels = True
    | otherwise = False
      where vowels = "aeiou" :: String

-- OR.....

vowelz :: Char -> Bool
vowelz a
    | a `elem` vowels = True
    | otherwise = False
      where vowels = ['a','e','i','o','u']

I have tracked this down to the declaration of overloaded strings at the top of my experimental/learning hs file:
{-# LANGUAGE OverloadedStrings #-}

if this line is present, I observe the issues described above. If the line is removed, the issues go away and the observed behavior is as expected.
It seems to me that the OverloadedStrings declaration breaks both those fundamentals I listed at the start, which makes it hard to understand how Haskell can be considered "pure". It also suggests that if I want to make modular code that can be incorporated into other projects, I must account for the various hacks and kludges (and perhaps future, not-yet-invented hacks and kludges) or my pure function might break.
Can anyone help me wrap my brain around this?

Somewhere in the Haskell based libraries String is defined as a type alias as:
type String = [Char]

The problem with your function is that GHC is not able to determine the type of "aeiou". In this case you would need to add a type signature like this (untested but should work):
vowelz :: Char -> Bool
vowelz a
    | a `elem` vowels = True
    | otherwise = False
   where
     vowels :: String
     vowels = ['a','e','i','o','u']

Your solution is basically what I included in my question. The reason GHC is not able to determine the type is because of the OverloadedStrings language declaration. Without the OverloadedStrings and also without your solution, the code compiles just fine. My concern is around being forced to account for any arbitrary language modification when trying to write reusable code. My attitude is "if it compiles in a bare bones configuration, it should 'just work' in any configuration." Perhaps that is unrealistic, but then Haskell should not tout referential transparency.

The difference is that my solution includes a type signature for vowels which GHC can use to resolve uncertainty in the type of that value.
This has nothing to do with referential transparency and everything to do with automated type inference.

It sounds like the "best practice" is to not rely on type inference, and also to not assume that successfully compiled code is good enough. Thanks.

As someone who has been doing Haskell professionally I would say best practice is

All top level function should have type signatures (compiler checked documentation).
Other type signatures when compiler needs it or for documenation.

If code compiles (ie GHC can figure out the types) it is highly reliable.


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

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

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

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

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

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

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

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

source: Stack Exchange

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

sort: votes


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?

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


text:
How to PlutusTx.compile work with multiple arguments to mkPolicy
I'm on homework 5 of the pioneer program. If I check Signed.hs:
{-# INLINABLE mkPolicy #-}
mkPolicy :: PaymentPubKeyHash -> () -> ScriptContext -> Bool
mkPolicy pkh () ctx = txSignedBy (scriptContextTxInfo ctx) $ unPaymentPubKeyHash pkh

policy :: PaymentPubKeyHash -> Scripts.MintingPolicy
policy pkh = mkMintingPolicyScript $
    $$(PlutusTx.compile [|| Scripts.wrapMintingPolicy . mkPolicy ||])
    `PlutusTx.applyCode`
    PlutusTx.liftCode pkh

curSymbol :: PaymentPubKeyHash -> CurrencySymbol
curSymbol = scriptCurrencySymbol . policy

For some reason, this works, although mkPolicy has 3 arguments and while compiling, there's only 1. It seems that () -> ScriptContext is dropped while wrapping the script (which kind a makes sense). This results in only one argument, the PaymentPubKeyHash.
However, when I try Homework1, I need 2 arguments, so I try this:
mkPolicy :: PaymentPubKeyHash -> POSIXTime -> () -> ScriptContext -> Bool
mkPolicy pkh deadline () ctx =
   txSignedBy txInfo $ unPaymentPubKeyHash pkh &&
      to deadline `contains` txInfoValidRange txInfo
         where txInfo :: txInfo
               txInfo = scriptContextInfo ctx

policy :: PaymentPubKeyHash -> POSIXTime -> Scripts.MintingPolicy
policy pkh deadline = mkMintingPolicyScript $
   $$(PlutusTx.compile [|| Scripts.wrapMintingPolicy . mkPolicy ||])
   `PlutusTx.applyCode`
   PlutusTx.liftCode pkh
   `PlutusTx.applyCode`
   PlutusTx.liftCode deadline

curSymbol :: PaymentPubKeyHash -> POSIXTime -> CurrencySymbol
curSymbol pkh deadline = scriptCurrencySymbol . policy

I would expect the Scripts.wrapMintingPolicy again drops () -> ScriptContext while compiling, making it using the first two PaymentPubKeyHash -> POSIXTime. However, when I try to compile this, I get an error:
src/Week05/Homework1.hs:51:56: error:
    • Couldn't match type ‘()’ with ‘ScriptContext’
      Expected type: PaymentPubKeyHash
                     -> POSIXTime -> ScriptContext -> Bool
        Actual type: PaymentPubKeyHash
                     -> POSIXTime -> () -> ScriptContext -> Bool
    • Probable cause: ‘mkPolicy’ is applied to too few arguments
      In the second argument of ‘(.)’, namely ‘mkPolicy’
      In the Template Haskell quotation
        [|| Scripts.wrapMintingPolicy . mkPolicy ||]
      In the first argument of ‘PlutusTx.compile’, namely
        ‘[|| Scripts.wrapMintingPolicy . mkPolicy ||]’
   |
51 |    $$(PlutusTx.compile [|| Scripts.wrapMintingPolicy . mkPolicy ||])
   |                                                        ^^^^^^^^
Failed, no modules loaded.

So I've got the arguments wrong. I fail to understand why in the example of Signed.hs it works fine (1 argument to mkPolicy) and why it doesn't work fine in the case of 2 arguments.
What am I missing?
Thx.
== EDIT 14/02/2022
So, final solution, thanks to @Mihai Codescu
mkPolicy :: PaymentPubKeyHash -> POSIXTime -> () -> ScriptContext -> Bool
mkPolicy pkh deadline () ctx =
   txSignedBy txInfo (unPaymentPubKeyHash pkh) &&
      to deadline `contains` txInfoValidRange txInfo
         where txInfo :: TxInfo
               txInfo = scriptContextTxInfo ctx

policy :: PaymentPubKeyHash -> POSIXTime -> Scripts.MintingPolicy
policy pkh deadline = mkMintingPolicyScript $
   $$(PlutusTx.compile [|| mintingPolicyScript ||])
   `PlutusTx.applyCode`
   PlutusTx.liftCode pkh
   `PlutusTx.applyCode`
   PlutusTx.liftCode deadline
      where
         mintingPolicyScript :: PaymentPubKeyHash -> POSIXTime -> Scripts.WrappedMintingPolicyType
         mintingPolicyScript = \pkh' deadline' -> Scripts.wrapMintingPolicy $ mkPolicy pkh' deadline'

curSymbol :: PaymentPubKeyHash -> POSIXTime -> CurrencySymbol
curSymbol = \pkh' deadline' -> scriptCurrencySymbol (policy pkh' deadline')

We have wrapMintingPolicy :: UnsafeFromData r => (r -> ScriptContext -> Bool) -> WrappedMintingPolicyType.
In the first case, we can spell out the details like:
policy :: PaymentPubKeyHash -> Scripts.MintingPolicy
policy pkh = mkMintingPolicyScript $
    $$(PlutusTx.compile [|| \pkh' -> Scripts.wrapMintingPolicy $  mkPolicy pkh' ||])
    `PlutusTx.applyCode`
    PlutusTx.liftCode pkh

This means we partially apply mkPolicy and we get something that we can apply wrapMintingPolicy to.
In the second case we want to have:
policy :: PaymentPubKeyHash -> POSIXTime -> Scripts.MintingPolicy
policy pkh deadline = mkMintingPolicyScript $
    $$(PlutusTx.compile [|| \pkh' deadline' -> Scripts.wrapMintingPolicy $  mkPolicy pkh' deadline' ||])
    `PlutusTx.applyCode`
    PlutusTx.liftCode pkh
    `PlutusTx.applyCode`
    PlutusTx.liftCode deadline

Here we can't use composition anymore: wrapMintingPolicy :: y -> z and mkPolicy :: a -> b -> y.


text:
Yoroi and Ledger nano S seed phrase
I'm writting you today because I've a question about seed phrase. I'm a big fan of the cardano project (especially the vision) but sometimes I can be lost with the tech!
To make it simple, I have a Yoroi Wallet and a Ledger Nanos S. I've linked my ledger whith the Yoroi Wallet but it seems I have a seed from the ledger and a seed phrase from the yoroi wallet.
(I first created my yoroi account and then bought a ledger).
Do I need to keep them both or only my ledger seed phrase is okay now? 2 seed phrase is harder to manage for me.
I'm little bit lost so thank you in advance for your help,
Have a great day !

let me give you my case.
i had Y_yoroi wallet with 10K ADA with one Seed Phrase.
i bought L_ledger wallet, installed it and have my Ledger seed phrase (this moment i have 0 ADA here on this wallet).
i moved / sent my 10K ADA from Y_yoroi wallet to the L_ledger wallet.
this current moment the Y_yoroi wallet is empty with 0 ADA.
i can delete it and never use it again.
it is only your decision if you want to keep the Y_yoroi wallet.

and what i would recommend your to do in case you "Stake" your Y_yoroi wallet...
the case with 10K ADA, which is staked from Y_yoroi wallet

i moved 9.800 ADA from Y_yoroi to L_ledger wallet.
wait 10 days, so that the L_ledger to be staked (active stake) to the pool you staked with your 9.800 ADA. 200 ADA stayed in Y_yoroi wallet
the time the L_ledger wallet is staked with 9.800 ADA to the pool, i did withdrawal and unregisted / undelegated the Y_yoroi wallet.
wait for 10 days to receive back the 2 ADA from the deposit + the last rewards.
moved the last 200 ADA + 2ADA (deposit) + last rewards -> L_ledger wallet.

with this process, i think  is the best way not to loose rewards or any other ADA for the migration to the new wallet.
have a nice week,
Thomas
pool operator for TTS17

Thank you for your answer !
It truly helps me a lot but I'm not sure to understand perfectly. When you say you moved it into your ledger I don't visualize it. Ledger Live has no cardano wallet so where do you send it?
I'm asking myslef that maybe my ledger device (which is linked to yoroi) keeps my seed inside the device? It would be great because it means that It keeps it for me and I have only the seed phrase of the ledger to take care of.
At the end I would like to have only one seed phrase, use the security of ledger and continuing having staking rewards.

ok i though you have finished the whole installation properly.
let me text you something more

ok, check the whole process.

you Install Ledger Live and you connect your Ledger.
you move to the left bottom side, option "manager"
this moment you will be requested to connect your Ledger Nano X and give your PIN
there, you can find many Crypto. Install Cardano
Cardano will not be inserted in Ledger Live.
this moment you have to open Yoroi again
go to the main Page, where you find all your wallet, and "ADD NEW WALLET"
then you "CONNECT TO HARDWARE WALLET"
click on "CARDACO"
select "LEDGER HARDWARE WALLET"
select "STANDARD WALLET"
this moment you have to connect your Ledger NANO X device.
when you successfully import this "wallet", you will find a new wallet, which will be the Ledger wallet. - unfortunately, there is no Cardano in Ledger Live, but for my opinion is not a problem.
when you "add" this wallet, you are ready to find a "received" address and take the steps i mentioned in my previous answer.

i hope is clear my answer and can help you.
if you need more, dont hesitate to ask, i am happy to assist.
if that helps, dont forget to vote our answers :)
best regards
TTS17

Hi,
Thank you again for your answer and your pedagogy ! I was sleeping! It is awesome to have such space in the Cardano Ecosystem !
I'm still a little bit confused because I don't see the differences between the "new wallet" on Yoroi that I need to create.
It seems that I have done this instruction with my current Yoroi Wallet. This Wallet is called "Yoroi Ledger" and below this name I even have the logo of ledger and write "wallet ledger".
I installed Ledger Live on my ledger nano S months ago and Yesterday I just verified that I was on the latest version which is the case.

My ledger nano S is updated (I checked it yesterday on my computer with Ledger Live in the "manager") and I have only the Cardano app on it.
So, do I still need to open a new one or this current one is a "ledger wallet"?
It is not easy to distinguish the subtility between both so that's why I'm trying to put as much details as possible.
If I have to open a new one it is okay, my concern is about security (be sure that my ADA are on my cold wallet), staking (on Yoroi with a pool) and having 1 seed phrase (the seed phrase from ledger).
Thank you in advance it is so helpful !

sorry but with names i confuse a bit :)
each Hardware wallet, Ledger NANO X / S in your case, will have its own "object" in yoroi.
if you had so long a Ledger NANO S in yoroi, please keep it until you import the new one, and then if you want -> fund your ADA from NANO S to NANO X wallet.
but you need to import the NANO X to your yoroi.

my Friend,
please define what you want to do and then i am happy to assist you.

do you have / want to have only this 2 wallets? ledger S and Ledger X ?
do you have any other wallet?

please make more clear what you want to achieve

I only have 1 ledger which is is a Nano S (I can only install 3 applications on it) and I have only 1 Cardano wallet on yoroi.
I don't plan having a new ledger (I'm only in cardano) and I'm happy with juste one wallet on Yoroi.
I would like to have my Ada coins secured in my cold wallet (ledger nano S) and staking on Yoroi. Yoroi must just be a interface to visualize my coin but not to protect it.
This would allow me to have One seed phrase from Ledger which is easier for me to manage.

sorry but in the begin, in your main post, you said you have 1 seed phrase from yoroi wallet, and 1 seed phrase for the Ledger.
1 Ledger device gives you only one Seed Phrase for all your wallets for the different of coins you have. for that reason all the time i was giving you guide as i believed you have 2 wallets = 1 software wallet from yoroi, and 1 hardware Ledger wallet using it in yoroi. ------ if you had 2 wallets, for your question....i would keep the Ledger seed phrase , move all my ada to this wallet, and then wouldnt use my yoroi software wallet.

Thank you for your answer and for your time !
English is not my native language so maybe it caused this unclear information, I have a lack of vocabulary so It is hard to put details sometimes. I'm sorry !
So, it seems that all was good? My current wallet on Yoroi is a ledger wallet (it is what is written) so I have nothing to do?
I first opened the yoroi wallet and they gave me a seed phrase because it was a classic Yoroi wallet. And then, with my ledger S,  I linked it to my ledger so maybe the seed from Yoroi become useless? It should be in my ledger which store all the keys?

So my last question is what I do with the Yoroi Seed Phrase, should I keep it or it is useless because it is my ledger which is important now?

just to be safe, keep it.
but you need to understand what is for what.
i will ask you again, the seed phrase is for the software yoroi wallet? or for the Ledger wallet ?
till now, i dont understand if you have 2 wallets or one.


text:
Possible DApp infrastructure on Cardano. Interaction with users' wallets
I'm trying to build a possible DApp infrastructure on Cardano in my head.
We should write the validation script in Haskell. Also as I understand, it is suggested to use Haskell for the off-chain code that will generate/spend UTXOs.
Okay.
We have as called "endpoints" - special Monads that can connect real wallets to the DApp.
I guess these "endpoints" could be brought into the DApp frontend somehow.
Yes?
But I still cannot understand how to connect these "endpoints" to the real users' wallets? So far we have examples with test wallets.
And is it feasible to build all necessary off-chain parts in Haskell or nobody really does it? If not, how it is supposed to be done? I mean to be connected to the real users' wallets, build and submit or spend UTXOs?
Probably the PAB aims to solve this, but it is not ready yet.
What is the real state of the art now for me as a developer?
These posts are relevant, but it looks like no solution today:
How does DApp front-end integrate with user wallets?
How to connect wallet with my dapps using yoroi dapp connector.?
How does a Cardano DApp client authorize a payment?

Here is an example using the cardano-serialization-lib and ReactJs. I had a lot of the same questions until I decided to work through an example eventually created a gitrepo
Cardano-serialization-lib is the way to go if you want to write focus on Plutus On Chain code (and do as little as possible, or none Plutus off chain code)
https://github.com/dynamicstrategies/cardano-wallet-connector
A working demo is here:
https://dynamicstrategies.io/wconnector

The PAB's original main use case was to interact with Daedalus (see here). In this setup the PAB generates an unbalanced transaction that is passed to Daedalus for balancing and submission. The dApp infrastructure here would consist of (i) a frontend to accept user interaction, (ii) the PAB (including the chain index) for constructing the unbalanced transaction, and (iii) a Cardano node to which the PAB is connected. A list of the possible infrastructures can be found here: https://plutus-apps.readthedocs.io/en/latest/plutus/explanations/pab.html
With browser wallets the story is different. Browser wallets can't balance transactions as of early 2022. So, unfortunately, the current standard way to interact with them is to pass a balanced transaction to the browser wallet and have it sign it. To construct this balanced transaction there seem to be a multitude of ways currently deployed. Some use custom code that makes use of the available Cardano CLIs such as Cardano Wallet. A useful fork is apparently MELD.
I have written a high level, opinionated blog post on the current state of browser wallet integrations here.

Currently, many DApps construct unsigned transactions either directly from browser using Cardano-serialization-lib (it can compile to WASM) or from backend server using Cardano-serialization-lib, cardano-cli, or PAB. Once the unsigned transaction is created, its CBOR is sent to wallet for signing. Finally, the signature/witness are inserted back to the transaction so it become a signed transaction, which could then be submitted to the blockchain network either by the wallet itself or by backend server.
Here is a simple end-to-end working example that construct transactions using PyCardano and have user to sign transactions with Nami wallet.

The only way i have found is to do everything the PAB will do with Cardano Serialization Lib. You could do it with Cardano Cli etc... but UTXO model is not easy to implement in none of the above mentionated options. After all everything in the blockchain are just transactions... even smart contracts are just transaction with reedemers and datum and contracts in them. Any tool for generating transactions can in theory do the job. The only thing you need is a way to interact in a secure way with the user prvKeys, so that users  are in total control, only signing what the dApp asks to. This last option is already available with some light Wallets like Nami, CCVault... and i have read that even Yoroi.

Typhon Wallet Dapp connector takes away extra load of fetching UTXOs, building a transaction in your front-end application.
You just need to specify to which address you want to send ada/tokens to and work of building a transaction and submitting will be done by typhon wallet.
Below is an example code snippet,
const paymentTransactionResponse = await window.cardano.typhon.paymentTransaction({
  outputs: [
    {
      address:
        "addr_test1qz7jw975stagnvs00wsjny6y6gpazn86yvwcm2vy02j3up7mt68vuzvz4nzgs00x0shrgywvy674v6r2zcs8fxvvq27qfjq8np",
      amount: "6000000",
    },
  ],
});

More Examples, https://docs.typhonwallet.io/examples/paymentTransaction.html#sending-ada


text:
Unable to install Gloss on Mac M1
I just learning about Haskell and trying to create Haskell project with Cabal, but when I tried install Gloss, it always return an error
-- error
...
ghc: could not execute: opt
cabal: Failed to build OpenGLRaw-3.3.4.1 (which is required by
exe:bouncingball from bouncingball-0.1.0.0). See the build log above for
details.

-- project.cabal
build-depends:    base ^>=4.14.3.0, gloss

anyone can help how could I fix this issue?

I see you've also opened this, cabal issue. I'm afraid, this is really not a cardano question.


text:
PPP Q&A clarifying submitTxConstraintsWith parameters - lookups and tx
Can someone please explain the difference between the two sets of constraints supplied to submitTxConstraintsWith?
1st question:
The function takes two parameters, referred to as "lookups" and "tx" in the examples, which are both a set of constraints. So what differentiates the "lookup" constraints from the "tx"?  Another way to frame this is, what constraints go into "lookups" and what constraints go into "tx"?
2nd question:
Conceptually, what does the term "lookup" refer to?  What is being looked up?  The term is used throughout the documentation without any definition I can find.

"tx" constraints determine what goes into the transaction. "lookup" constraints determine which information is needed to validate the transaction, i.e. information from the blockchain or from the wallet.


text:
what is "WalletError (ValidationError (ScriptFailure (EvaluationError [\"PT5\"] \"CekEvaluationFailure\")))" when trying in playground?
I have Homework1 of week 5, and it works in the repl (meaning, the test gives the expected result). However, when I try the script in the playground (and remove the test - I don't think that makes a big difference, though, and I removed the line module ...), it's stuck on slot 1, at the bottom:
("txSignatures",Array []),("txValidRange",Object (fromList [("ivFrom",Array [Object (fromList [("tag",String "NegInf")]),Bool True]),("ivTo",Array [Object (fromList [("tag",String "PosInf")]),Bool True])]))])),("unBalancedTxUtxoIndex",Array []),("unBalancedTxValidityTimeRange",Object (fromList [("ivFrom",Array [Object (fromList [("tag",String "NegInf")]),Bool True]),("ivTo",Array [Object (fromList [("contents",Number 1.596059152999e12),("tag",String "Finite")]),Bool True])]))]))])),("mkTxLogTxConstraints",Object (fromList [("txConstraints",Array [Object (fromList [("contents",Array [String "aea02b83a8e055c06b768c2fcbf1101422b78405892b5027144ddb3b",String "d87980",Object (fromList [("unTokenName",String "ABC")]),Number 5.0]),("tag",String "MustMintValue")]),Object (fromList [("contents",Object (fromList [("ivFrom",Array [Object (fromList [("tag",String "NegInf")]),Bool True]),("ivTo",Array [Object (fromList [("contents",Number 1.596059152999e12),("tag",String "Finite")]),Bool True])])),("tag",String "MustValidateIn")])]),("txOwnInputs",Array []),("txOwnOutputs",Array [])]))])
, Slot 1: 00000000-0000-4000-8000-000000000000 {Wallet W872c}:
            Handled request:   Iteration 3 request ID 1
                               Response: "{\"contents\":1596059092999,\"tag\":\"CurrentTime
, Slot 1: 00000000-0000-4000-8000-000000000000 {Wallet W872c}:
            Current requests (1):   Iteration 4 request ID 1
                                    Request: "{\"contents\":{\"unBalancedTxRequiredSignatories\
, Slot 1: 00000000-0000-4000-8000-000000000000 {Wallet W872c}:
            Handled request:   Iteration 4 request ID 1
                               Response: "{\"contents\":{\"contents\":{\"contents\":{\"cont
, Slot 1: 00000000-0000-4000-8000-000000000000 {Wallet W872c}:
            Current requests (0):
, Slot 1: 00000000-0000-4000-8000-000000000000 {Wallet W872c}:
            Contract instance stopped with error: "WalletError (ValidationError (ScriptFailure (EvaluationError [\"PT5\"] \"CekEvaluationFailure\")))" ]

I don't really understand why the script fails in the playground, while it works perfectly fine in the repl. How to try out the same script in the repl?
Thanks!
== EDIT 15/02/2022
The code: https://gitlab.com/moment-4/courses/plutus-pioneer/plutus-pioneer-program/-/blob/week05/code/week05/src/Week05/Homework1.hs
The important lines (I think):
mkPolicy :: PaymentPubKeyHash -> POSIXTime -> () -> ScriptContext -> Bool
mkPolicy pkh deadline () ctx =
   txSignedBy txInfo (unPaymentPubKeyHash pkh) &&
      to deadline `contains` txInfoValidRange txInfo
         where txInfo :: TxInfo
               txInfo = scriptContextTxInfo ctx

policy :: PaymentPubKeyHash -> POSIXTime -> Scripts.MintingPolicy
policy pkh deadline = mkMintingPolicyScript $
   $$(PlutusTx.compile [|| mintingPolicyScript ||])
   `PlutusTx.applyCode`
   PlutusTx.liftCode pkh
   `PlutusTx.applyCode`
   PlutusTx.liftCode deadline
      where
         mintingPolicyScript :: PaymentPubKeyHash -> POSIXTime -> Scripts.WrappedMintingPolicyType
         mintingPolicyScript = \pkh' deadline' -> Scripts.wrapMintingPolicy $ mkPolicy pkh' deadline'

curSymbol :: PaymentPubKeyHash -> POSIXTime -> CurrencySymbol
curSymbol = \pkh' deadline' -> scriptCurrencySymbol (policy pkh' deadline')

Can you share your code?

yes, sure, see edit in my description. Thx.

I've reproduced exactly the same scenario in the tests (homework 1) over the playground with your code and it works as expected: first attempt mints and second one fails because deadline. Most probably the issue is related to your input. (deadline is posixtime, not slots)

deadline = 1596059191000 . I got it doing in the repl:
import Ledger.TimeSlot
import Data.Default
slotToBeginPOSIXTime def 100  -- slot 100

EDIT 1
After reading your comment the issue comes from this line in offchain code:
Constraints.mustValidateIn (to $ now + 60000)
because the tx doesn't pass the validRange pre-validation phase. If you play using a lower value you'll this in action.
As a side note, this is not a playground thing. You can test with Emulator Trace and won't be able to mint (probably with a different error message).
Hope this is useful.

Thx. When I use 100 slots (converted to POSIXTime), it works fine. When I use only 10 slots, it fails. So it seems the first transaction fails depending on the deadline. After bisecting, it seems that it only works if the deadline > POSIXTime of slot 61 (1596059152000) . Any idea why? Can it be because the deadline is already passed (time for compilation etc, but in that case, ~60 slots seems a lot)?

Do you mean 10 slots as deadline?

yes, exactly. 10 slots (converted to POSIXTime) - it only works if it's >61 slots (on my laptop), converted to POSIXTime

Yeah, that's it, thanks - and yes, extremely useful!! I forgot about that weird now + 60000. That was kind of a hacky solution to get it right - and hacky solutions result often in unexpected results.
Anyway, it all makes perfect sense now, great.


text:
How do I set txInfoValidRange on the testnet using cardano-cli
How does txInfoValidRange get set on the testnet?
I've been made aware that on the Plutus Playground
a piece of off-chain code:
"Constraints.mustValidateIn (from now)" will
set txInfoValidRange (works great).
I'm looking for the equivalent cardano-cli command
for "Constraints.mustValidateIn (from now)",
that will set the txInfoValidRange properly on
the testnet?

There are two options
--invalid-before SLOT    Time that transaction is valid from (in slots).
--invalid-hereafter SLOT Time that transaction is valid until (in slots).

In you example you would use --invalid-before $CURENT_TIME_SLOT

Thanks to both of you. --invalid-before SLOT worked perfectly!

I'd upvote both answers, but I only have an 11 reputation - need 15. I'll come back and do it when I get there. Thanks again!!!

@GaryAlexander Even so, I think you can mark one of those how the most useful.

At the time to build a transaction with cardano-cli using the command cardano-cli transaction build, you can use the input parameters --invalid-before SLOT or --invalid-hereafter SLOT where invalid-before refers to the time that transaction is valid from (in slots), and invalid-hereafter to the time that transaction is valid until (in slots).
Notice that if you don't set a valid range the default will be "all the time".

You can get this info using cardano-cli transaction build --help
An example of this would be the following command (shown by Lars in lecture 3). Check https://github.com/kindofdev/plutus-pioneer-program-iter3/blob/main/code/week03/testnet/grab.sh
cardano-cli transaction build \
    --alonzo-era \
    --testnet-magic 1097911063 \
    --change-address $(cat 02.addr) \
    --tx-in 18cbe6cadecd3f89b60e08e68e5e6c7d72d730aaa1ad21431590f7e6643438ef#1 \
    --tx-in-script-file vesting.plutus \
    --tx-in-datum-file unit.json \
    --tx-in-redeemer-file unit.json \
    --tx-in-collateral 18e93407ea137b6be63039fd3c564d4c5233e7eb7ce4ee845bc7df12c80e4df7#1 \
    --required-signer-hash c2ff616e11299d9094ce0a7eb5b7284b705147a822f4ffbd471f971a \
    --invalid-before 48866954 \
    --protocol-params-file protocol.json \
    --out-file tx.body

here the tx is invalid before slot 48866954. In plutus:
Constraints.mustValidateIn $ from $ slotToBeginPOSIXTime def 48866954
In your case you should use --invalid-before $CURRENT_TIME_SLOT
If you are wondering how to get a slot number for Cardano testnet given a posixtime, here you have a way to do it.
How to convert posixTime to slot number on Cardano Testnet


text:
Higher than needed transaction fees
Let's say I have a transaction that I manually altered to include transaction fees that are higher than the required amount of fees. The transaction is perfectly balanced and, apart from this, does not differ from a normal transaction. Is this transaction valid ? Or will it be refused by the blockchain nodes ?

Yes, as long as the all inputs match the outputs (minus the fee), and the fee is equal to or greater than the minimum fee as per the protocol parameters, it should be a valid transaction.


text:
Interpreter Error (error CallStack (from HasCallStack))
Im getting an interpreter error on the Plutus playground commit 3f84ea4fe3924cb7ee614da2b22c64c02c1177e6. I get it whenever I run the purchase endpoint.
This is the error
Main.hs: This must be replaced by the core-to-plc plugin during compilation: error CallStack (from HasCallStack): error, called at src/PlutusTx/Utils.hs:7:26 in plutus-tx-0.1.0.0-I9Dln998VX1LKsuzHCjcJz:PlutusTx.Utils

Do I need to upgrade versions or is there something wrong with my code?
    import           Control.Monad          hiding (fmap)
import           Data.Aeson             (ToJSON, FromJSON)
import           Data.Text              (Text)
import           Data.Void              (Void)
import           GHC.Generics           (Generic)
import           Data.Map              as Map hiding (foldl)
import           Plutus.Contract
import           Plutus.Contract        as Contract
import           Ledger.Address         as Add
import           Plutus.Trace.Emulator  as Emulator
import qualified PlutusTx
import           Ledger                 hiding (mint, singleton)
import           Ledger.Constraints     as Constraints
import qualified Ledger.Typed.Scripts   as Scripts
import           Ledger.Value           as Value
import           Playground.Contract    (printJson, printSchemas, ensureKnownCurrencies, stage, ToSchema)
import           Playground.TH          (mkKnownCurrencies, mkSchemaDefinitions)
import           Playground.Types       (KnownCurrency (..))
import           Prelude                (IO, Show (..), String)
import           Text.Printf            (printf)
import           Wallet.Emulator.Wallet
import           Wallet.Effects         as Effects
import qualified PlutusTx.Builtins      as Builtins
import           Plutus.V1.Ledger.Ada as Ada
import           Ledger.Tx              (scriptTxOut, ChainIndexTxOut)
import           Plutus.ChainIndex.Tx
import           Ledger.Blockchain
import           Playground.Contract
import           PlutusTx.Prelude     hiding (Semigroup(..), unless)
import           Prelude              (IO, Semigroup (..), String, Show(..))
import qualified Prelude              as Haskell
import           Cardano.Api hiding (Value, TxOut,Address)
import           Cardano.Api.Shelley hiding (Value, TxOut, Address)
import           Codec.Serialise hiding (encode)
import           Plutus.ChainIndex as Chain

minADA :: Value
minADA = Ada.lovelaceValueOf 2000000

price :: Value
price = Ada.lovelaceValueOf 12000000

data ContractInfo = ContractInfo
    { policyID :: !CurrencySymbol
    , walletOwner :: !PubKeyHash
    , nameOfToken :: !TokenName
    } deriving (Generic, ToJSON, FromJSON)

contractInfo = ContractInfo
    { policyID = "8b0dbdd6504ff8f129400ab3b21f12a52ffb09f0b3cff594cb5bb868"
    , walletOwner = "a2c20c77887ace1cd986193e4e75babd8993cfd56995cd5cfce609c2"
    , nameOfToken = "reward"
    }

--purchase portion of the contract
data LootBoxData
instance Scripts.ValidatorTypes LootBoxData where
    type instance RedeemerType LootBoxData = ()
    type instance DatumType LootBoxData = Integer

--Checks the validatorHash to make sure the LootBox has tokens to host the transaction
--If never changed by the end of the project use the builtins script validator
{-# INLINABLE mkValidator #-}
mkValidator :: Integer -> () -> ScriptContext -> Bool
mkValidator i x ctx = True

lootBox :: Scripts.TypedValidator LootBoxData
lootBox = Scripts.mkTypedValidator @LootBoxData
    $$(PlutusTx.compile [|| mkValidator ||])
    $$(PlutusTx.compile [|| wrap ||]) where
        wrap = Scripts.wrapValidator @Integer @()

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

validate :: Validator
validate = Scripts.validatorScript lootBox

valAddress :: Address
valAddress = Scripts.validatorAddress lootBox

--Start of minting portion of the smart contract

{-# INLINABLE mkPolicy #-}
mkPolicy :: PubKeyHash -> () -> ScriptContext -> Bool
mkPolicy pkh () ctx = txSignedBy (scriptContextTxInfo ctx) pkh

policy :: PubKeyHash -> Scripts.MintingPolicy
policy pkh = mkMintingPolicyScript $
    $$(PlutusTx.compile [|| Scripts.wrapMintingPolicy . mkPolicy||])
    `PlutusTx.applyCode`
    (PlutusTx.liftCode pkh)

--dont need
curSymbol :: PubKeyHash -> CurrencySymbol
curSymbol = scriptCurrencySymbol . policy

data MintParams = MintParams
    { mpAmount    :: !Integer
    } deriving (Generic, ToJSON, FromJSON, ToSchema)

PlutusTx.makeLift ''MintParams

--Start of endpoints
type SignedSchema =
    Endpoint "mint" MintParams
     .\/ Endpoint "lock" MintParams
     .\/ Endpoint "purchase" ()

mint :: AsContractError e => MintParams -> Contract w s e ()
mint mp = do
    ppkh <- Contract.ownPaymentPubKeyHash
    let pkh     = unPaymentPubKeyHash ppkh
        val     = Value.singleton (curSymbol pkh) (nameOfToken contractInfo) (mpAmount mp)
        lookups = Constraints.mintingPolicy $ policy (pkh)
        tx      = Constraints.mustMintValue val
    ledgerTx <- submitTxConstraintsWith @Void lookups tx
    void $ awaitTxConfirmed $ getCardanoTxId ledgerTx
    logInfo @String $ printf "forged %s" (show val)

lock :: MintParams -> Contract w SignedSchema Text ()
lock mp =  do
-- make a recusive function that allows for the creation of a 1000 utxos of diffrent datums from a wallet (cheap if implemented correctly)

    let v   = Value.singleton (policyID contractInfo) (nameOfToken contractInfo) (mpAmount mp) <> minADA
        tx  =   foldl
                (\acc i -> acc <> (Constraints.mustPayToTheScript (i) $ v))
                (TxConstraints [] [] [])
                [1..1000]

    void (submitTxConstraints lootBox tx)

purchase :: () -> Contract w SignedSchema Text ()
purchase _ =  do
    utxos <- utxosAt valAddress

    let outputs = Map.toList utxos
        r      = Redeemer $ PlutusTx.toBuiltinData ()
        (oref, o) = head outputs
        ppkh     = walletOwner contractInfo
        lookups = Constraints.unspentOutputs utxos <>
                  Constraints.otherScript validate
        tx      = mustPayToPubKey (Add.PaymentPubKeyHash ppkh) price <> mconcat [Constraints.mustSpendScriptOutput oref unitRedeemer ]
    ledgerTx <- submitTxConstraintsWith @Void lookups tx
    void $ awaitTxConfirmed $ getCardanoTxId ledgerTx
    logInfo @String $ "loot box used"

-- Sort through the Utxos so that it only collect the right one

endpoints :: Contract () SignedSchema Text ()
endpoints = awaitPromise (mint' `select` lock' `select` purchase') >> endpoints
  where
    mint' = endpoint @"mint" mint
    lock' = endpoint @"lock" lock
    purchase' = endpoint @"purchase" purchase

mkSchemaDefinitions ''SignedSchema

mkKnownCurrencies []

With tag: 62efdd2bfab3e076d40e07f8f4d7864a7f2ccc9  (week05) also fails.

I don't see the pragmas at the beginning of the module in your code...

After debugging your code I've found that the issue comes from lock contract which it's not minting nor transferring funds to the script. So when you try to purchase there's no utxo sitting at the script address. I guess that the weird error comes from this line:
(oref, o) = head outputs

takeaway 1: never use head because if the list is empty you'll get an exception
If in the purchase contract you check whether the list is not empty before continuing (like in purchase below), the weird error will disappear. However, the purchase is not going to work because there's nothing purchase.
purchase :: () -> Contract w SignedSchema Text ()
purchase _ =  do
    utxos <- utxosAt valAddress
    unless (Haskell.null utxos) $ do   -- HERE checks whether there's any utxo.
        let outputs = Map.toList utxos
            r      = Redeemer $ PlutusTx.toBuiltinData ()
            (oref, o) = head outputs
            ppkh     = walletOwner contractInfo
            lookups = Constraints.unspentOutputs utxos <>
                    Constraints.otherScript validate
            tx      = mustPayToPubKey (Add.PaymentPubKeyHash ppkh) price <> mconcat [Constraints.mustSpendScriptOutput oref unitRedeemer ]
        ledgerTx <- submitTxConstraintsWith @Void lookups tx
        void $ awaitTxConfirmed $ getCardanoTxId ledgerTx
        logInfo @String $ "loot box used"

You can check all of this reducing your scenario to only lock and then wait. You'll see no funds going to the script.
Ok, now the FIX.
Why doesn't lock contract work ? Basically, because it's uncompleted. You missed the lookups for the validator and the minting policy script, and also the constraint for mint values. (I think you copied-pasted from other thread (takeaway 2)). I've implemented the following code which locks funds properly.
lock :: MintParams -> Contract w SignedSchema Text ()
lock mp =  do
-- make a recusive function that allows for the creation of a 100 utxos of diffrent datums from a wallet (cheap if implemented correctly)
    pkh <- unPaymentPubKeyHash <$> Contract.ownPaymentPubKeyHash
    let n            = 10  -- If you need 100 you must use a custom configuration different to the default one (1000 ADAS per wallet)
        symbol       = curSymbol pkh
        tn           = nameOfToken contractInfo
        tokenPerUtxo = Value.singleton symbol tn (mpAmount mp)
        adaPerUtxo   = minADA
        valuePerUtxo = tokenPerUtxo <> adaPerUtxo
        tx           = foldl
                         (\acc i -> acc <> Constraints.mustPayToTheScript i valuePerUtxo)
                         (TxConstraints [] [] [])
                         [1..(Haskell.fromIntegral n)]
                    <> Constraints.mustMintValue (mconcat (Haskell.replicate n tokenPerUtxo ))
        lookups = Constraints.typedValidatorLookups lootBox
                <> Constraints.mintingPolicy (policy pkh)

Your code might have more issues (I haven't tested the full workflow), but at least now you can lock funds in the script address, and hopefully you'll be able to purchase. Good luck!
As a side note if I were you, I'd use traces (Emulator.Trace) with different scenarios instead of the playground. Errors are more meaningful and you'll debug the code faster (takeaway 3).
Hope this will be useful.


text:
Command failed: query utxo Error: This query cannot be used for the Byron era
When I am trying below command.
cardano-cli query utxo --address $(cat payment.addr) --testnet-magic 1097911063

I am getting this error.
Command failed: query utxo  Error: This query cannot be used for the Byron era

What I have to do now?

What are the contents of the payment.addr? Does it contain a Byron or a Shelley address?

$(cat payment.addr) zsh: command not found: addr_test1vp465rg9nm7x3th67nfsccuav25ffvjk3wr5upk57k3ec9gadwcjp  This is what i am getting

How do i know whether it is a shelly or byron?

Ok, that is a Shelley era address. You might try adding --shelley-mode or --cardano-mode to the command line.

cardano-cli: encodeFailure: local state query: using acquire without a Point must be conditional on negotiating v8 of the node-to-client protocol CallStack (from HasCallStack):   error, called at src/Ouroboros/Network/Protocol/LocalStateQuery/Codec.hs:80:7 in ouroboros-network-0.1.0.0-a6337e1ec691134555c3c4cba8800a5d3d08f8812cda7fdf6590dc6bf33ac964:Ouroboros.Network.Protocol.LocalStateQuery.Codec%   I am getting this now after adding shelly-mode

Try --cardano-mode instead.

I am getting this error now Command failed: query utxo  Error: This query cannot be used for the Byron era for --cardano-mode

I got it working using cardano-mode but the wallet is showing me zer balance . cardano-cli query utxo --address $(cat payment.addr) --testnet-magic 1097911063 --cardano-mode
                           TxHash                                 TxIx        Amount --------------------------------------------------------------------------------------

I had the same problem, but i found these posts (https://forum.cardano.org/t/testnet-tutorial-querry-utxo-error/45249 + https://forum.cardano.org/t/command-failed-query-utxo-error-this-query-cannot-be-used-for-the-byron-era/55606) with basically the same instruction: Just wait till the node is fully synced !. I did that, and 1 hour later the query command passed.
Hope it helps.

It can take 6hr to 2days for node to sync. So don't panic wait for an hour
You can monitor the progress of sync using this command
cardano-cli query tip --mainnet
Check the syncProgress param in the generated json


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

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

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

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


text:
My wallet showing nothing in it
Explorer showing me this.
https://explorer.cardano-testnet.iohkdev.io/en/address.html?address=addr_test1vp465rg9nm7x3th67nfsccuav25ffvjk3wr5upk57k3ec9gadwcjp
But if i check my wallet balance directly from the shell it is showing me nothing in it.
cardano-cli query utxo --address addr_test1vp465rg9nm7x3th67nfsccuav25ffvjk3wr5upk57k3ec9gadwcjp --testnet-magic 1097911063 --cardano-mode
                           TxHash                                 TxIx        Amount

Is the node fully synced? The CLI will show zero balance if the transaction that created the paid to that added has not been downloaded yet.

How do i know if the node is fully synced or not? I can see that this is going on eb4cde7e343e83820321069f5df4b3dbf705feef741f19270a2b56404f43aa3a at slot 44463043 [dk-Latit:cardano.node.ChainDB:Notice:142] [2022-02-15 08:02:03.05 UTC] Chain extended, new tip: b1c0fe52e6fac43668ac485dd922b57d160ee999a0d4e327a105d6a4422098df at slot 44463323 [dk-Latit:cardano.node.ChainDB:Notice:142] [2022-02-15 08:02:04.34 UTC] Chain extended, new tip: 4ff762c7491523fadf6406ca66325f8ac43f000f444ed07f8656156149e4da78 at slot 44463606 [dk-Latit:cardano.node.ChainDB:Notic

Use the cardano-cli query tip command to check if the node is synced, a syncProgress with the percentage value will appear there.
You will need your node to be synced to at least 4 days ago (Epoch 186, Block 3312024), when your transaction in the testnet took place. Otherwise it could be that what you are seeing is the status of your wallet in an older point in time.

This is what i am getting cardano-cli query tip syncProgress Invalid argument syncProgress'
Usage: cardano-cli query tip
[ --shelley-mode
| --byron-mode [--epoch-slots NATURAL]
| --cardano-mode [--epoch-slots NATURAL]
]
(--mainnet | --testnet-magic NATURAL)
[--out-file FILE]
Get the node's current tip (slot no, hash, block no)`

You don't have to run cardano-cli query tip syncProgress, only cardano-cli query tip. The syncProgresswill be part of the output in your terminal.

cardano-cli query tip --cardano-mode --testnet-magic 1097911063  This is what worked


text:
Working with BuiltinByteString
I tried to create a few modification on the NFT minting contract from week 5 of the plutus pioneer program.
I wanted to be able to mint a few tokens at once. My policy should require that the token names start with "ABC" + Integer where the integer is less than 100.
Here is my attempt:
{-# INLINABLE mkPolicy #-}
mkPolicy :: TxOutRef -> () -> ScriptContext -> Bool
mkPolicy oref () ctx = traceIfFalse "UTxO not consumed"   hasUTxO           &&
                          traceIfFalse "wrong amount minted" checkMintedAmount
  where
    info :: TxInfo
    info = scriptContextTxInfo ctx

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

    flattenVal :: [(CurrencySymbol, TokenName, Integer)]
    flattenVal = flattenValue (txInfoMint info)

    -- Check that TokenName is of the form ABC1 .. ABC99
    checkTokenName :: TokenName ->  Bool
    checkTokenName tn = isPrefixOf "ABC" (show tn) &&
                        isJust (readMaybe (post tn) :: Maybe Integer) &&
                        (read (post tn) :: Integer) < 100
        where
            post tn' = drop 3 $ show tn'

    checkMintedAmount :: Bool
    checkMintedAmount = all (\(_, tn', amt') -> checkTokenName tn' && amt' == 1) flattenVal

Unfortunately this gives a horrible run time error which would be too long to paste here, so I'll just paste the first few lines:
GHC Core to PLC plugin: E042:Error: Unsupported feature: Int: use Integer instead
Context: Compiling type: GHC.Types.Int
Context: Compiling type: GHC.Types.Int -> a -> GHC.Show.ShowS
Context: Compiling data constructor type: GHC.Show.C:Show
Context: Compiling type: GHC.Show.Show a
Context: Compiling expr: \ ($dShow_a14Ch [Occ=Once*] :: GHC.Show.Show a)
                           (tn' [Occ=Once*] :: a) ->
                           let {
                             n :: GHC.Types.Int
                             [LclId,
                              Unf=Unf{Src=<vanilla>, TopLvl=False, Value=True, ConLike=True,
                                      WorkFree=True, Expandable=True, Guidance=IF_ARGS [] 10 20}]
                             n = GHC.Types.I# 3# } in
                           letrec {
                             unsafeDrop [Occ=LoopBreaker]
                               :: forall a1. GHC.Types.Int -> [a1] -> [a1]
                             [LclId,
                              Arity=2,
                              Unf=Unf{Src=<vanilla>, TopLvl=False, Value=True, ConLike=True,
                                      WorkFree=True, Expandable=True, Guidance=IF_ARGS [20 30] 91 10}]
                             unsafeDrop
                               = \ (@ a1)
                                   (ds [Occ=Once!] :: GHC.Types.Int)
                                   (ds1 [Occ=Once!] :: [a1]) ->
                                   case ds of { GHC.Types.I# ipv ->
                                   case ds1 of {
                                     [] -> GHC.Types.[] @ a1;
                                     : _ [Occ=Dead] ipv2 [Occ=Once*] ->
                                       case ipv of {
                                         __DEFAULT ->
                                           unsafeDrop @ a1 (GHC.Types.I# (GHC.Prim.-# ipv 1#)) ipv2;
                                         1# -> ipv2
                                       }
                                   }
                                   }; } in
                           case GHC.Classes.leInt n (GHC.Types.I# 0#) of {
                             GHC.Types.False ->
                               unsafeDrop @ GHC.Types.Char n (GHC.Show.show @ a $dShow_a14Ch tn');
                             GHC.Types.True -> GHC.Show.show @ a $dShow_a14Ch tn'
                           }

I saw similar discussion on discord about trying to compare the token name to an empty string. Is this somehow related?
I though the above would work because I'm explicitly doing show on the BuiltinByteString
Any idea what I'm doing wrong?
Update
Someone pointed out that the compile is failing due to my onchain code not containing inlinable functions.
I think the prefix check should be doable using takeByteString and dropByteString. I'm still trying to figure out how would I check the integer part of the name? I can't find anything equivalent to ReadMaybe.
Update 2
I'm inching closer to a solution based on the feedback in the comments and in the Q&A that happened on 15 Feb
Here is the updated attempt to use only inlinable functions
    -- Check that TokenName is of the form ABC1 .. ABC99
    checkTokenName :: TokenName ->  Bool
    checkTokenName tn = lengthOfByteString bs > 3
                        && checkInt tokNum
        where
            bs = unTokenName tn
            tokNum = sliceByteString 3 2 bs
            tokNumLen = lengthOfByteString tokNum
            checkInt bs' = all (\i -> Builtins.greaterThanInteger i 47 && Builtins.lessThanInteger i 58)
                            -- Seems this list comprehension causes issues
                            [indexByteString bs' i | i <- [0..tokNumLen]]

Update 3
I tried the advise of Sjoerd Visscher, but unfortunately I get the same type of error if I use any function with recursion or a pattern matching.
For example
    checkTokenName :: TokenName ->  Bool
    checkTokenName tn = lengthOfByteString bs > 3
                        && checkInt tokNum tokNumLen
        where
            bs = unTokenName tn
            tokNum = sliceByteString 3 2 bs
            tokNumLen = lengthOfByteString tokNum
            checkInt _ 0 = True
            checkInt bs' i =  True && checkInt bs' (i-1)

Results in:
GHC Core to PLC plugin: E042:Error: Unsupported feature: Use of Haskell Integer equality, possibly via the Haskell Eq typeclass
Context: Compiling expr: GHC.Integer.Type.eqInteger#
Context: Compiling expr: GHC.Integer.Type.eqInteger# ds_d12x1
Context: Compiling expr: GHC.Integer.Type.eqInteger# ds_d12x1 0
Context: Compiling expr: case GHC.Integer.Type.eqInteger# ds_d12x1 0
                         of wild [Occ=Once]
                         { __DEFAULT ->
                         GHC.Prim.tagToEnum# @ GHC.Types.Bool wild
                         }
...

It seems that only a function with no pattern matching or recursion works here.
    checkTokenName :: TokenName ->  Bool
    checkTokenName tn = lengthOfByteString bs > 3
                        && lengthOfByteString bs < 6
                        && checkInt tokNum tokNumLen
        where
            bs = unTokenName tn
            tokNum = sliceByteString 3 2 bs
            tokNumLen = lengthOfByteString tokNum
            isNum i = Builtins.greaterThanInteger i 47 && Builtins.lessThanInteger i 58
            checkInt :: BuiltinByteString -> Integer -> Bool
            -- No recursion or pattern matching !?!?
            checkInt bs' len = (len == 1 && isNum (indexByteString bs' 0)) ||
                               (len == 2 && isNum (indexByteString bs' 0) &&
                                            isNum (indexByteString bs' 1))

Lars gave you the answer in the Q&A if you couldn't attend. Please, check here:
https://zoom.us/rec/share/B60Bu76Ub-lSnZjOqep-_Wpo1mtgoPrMvNXIdSazQeXnGykloxjScCqxg758ITXt.I153inPX-AlAftnC

Is Update 2 working? If not, could you paste the error you get?

@SjoerdVisscher Sorry, I didn't make it very obvious. Update 2 is not working. I added a comment above the list comprehension that causes an issue.  I believe it's the same error as before about not using inlinable types. I'll try update the question when I'm back at my home computer.

You can't use the [0..tokNumLen] syntax, that translates to a function from the Enum class from base which is not inlinable.
You could try something like this:
-- Check that TokenName is of the form ABC1 .. ABC99
    checkTokenName :: TokenName ->  Bool
    checkTokenName tn = lengthOfByteString bs > 3
                        && checkInt tokNum tokNumLen
        where
            bs = unTokenName tn
            tokNum = sliceByteString 3 2 bs
            tokNumLen = lengthOfByteString tokNum
            isNum i = Builtins.greaterThanInteger i 47 && Builtins.lessThanInteger i 58
            checkInt bs' 0 = True
            checkInt bs' i = isNum (indexByteString bs' (i - 1)) && checkInt bs' (i - 1)

Unfortunately it seems any attempt to use recursion results in the same error.


text:
How long will it takes a cardano node to fully sync?
I have startted my cardano node with this command.
cardano-node run \
--config $HOME/cardano/testnet-config.json \
--database-path $HOME/cardano/db/ \
--socket-path $HOME/cardano/db/node.socket \
--host-addr 127.0.0.1 \
--port 1337 \
--topology $HOME/cardano/testnet-topology.json

Now what i can see in my terminal is this.
dk-Latit:cardano.node.ChainDB:Notice:142] [2022-02-15 08:42:59.71 UTC] Chain extended, new tip: 4ec48842a96990c32bcc0bb3fa99037d12c70228df6a57bec7e273c9fb5789f8 at slot 45502922
[dk-Latit:cardano.node.ChainDB:Notice:142] [2022-02-15 08:43:01.05 UTC] Chain extended, new tip: 001df73cc6c3f531d4bb304ec579ccf4323811aa9f2404865684fa65554c3bfd at slot 45503205
[dk-Latit:cardano.node.ChainDB:Notice:142] [2022-02-15 08:43:03.18 UTC] Chain extended, new tip: 601a92bdbbc85fd99b8108780419b9716ce74379ad39dffed21d8753cc3d067f at slot 45503277
[dk-Latit:cardano.node.ChainDB:Notice:142] [2022-02-15 08:43:04.53 UTC] Chain extended, new tip: ffe4eeeb00529dbf0b031f6822c33dc3c93c68c02c22b01f709c2f3cf6cd7e44 at slot 45503504
[dk-Latit:cardano.node.ChainDB:Notice:1

How long am i supposed to see this? Is there any way to check whether the node is fully synced or not or what percentage its got synced?

When you accept an answer, you should also up-vote it.  ;-)  Let's build this community.

Testnet should sync within a couple of hours. Mainnet will be longer (I have not done this recently so I do not know).
There is a cardano-cli query tip command. eg:
CARDANO_NODE_SOCKET_PATH=state-node-mainnet/node.socket ./cardano-cli query tip --cardano-mode --mainnet
{
    "epoch": 321,
    "hash": "561310c715bff5d8a8f310e55e3ceb5b9116a058aaf716e3ab930bc120c6e47e",
    "slot": 53350023,
    "block": 6884753,
    "era": "Alonzo",
    "syncProgress": "100.00"
}

As of early 2022, I would expect about two days.

is that same for testnet as well?

for testnet, it typically takes 4-6 hours depending upon your internet connection.

It took about half a day to a day, from my personal experience in early 2022. But I think it varies depending on internet connection and the computer.
Make sure your machine is not resource-starved. I.e. check that you have enough RAM as you sync. While cardano-node does not require a super powerful computer, any computer process would struggle to get any work done if there are not enough resources ;)


text:
Plutus script execution at every end of epoch
I would like to develop a Plutus script that executes each time an epoch ends.
What's the best way to achieve this behaviour?

As mentioned by Jey earlier, blockchains and smart contracts remain latent until triggered by a user submitted transaction.
One way you could pull this off is that you could use the cardano-cli application to create, sign and submit a transaction which executed the plutus script at the end of every epoch. You can find out more about cardano-cli and plutus scripts here and a simple sample here
UPDATE: I realized that I missed out explaining how this could be done by creating an javascript bot which submits this kind of transaction near the end of the epoch automatically.
You can use the cardanocli-js javascript library to achieve this... here's a basic sample, but you can pretty much do any kind of action that the cardano-cli can do, in a programmatic submission.
Hope this helps!

This is exactly what I learned at the Plutus Pioneer Program but I just needed to be sure I was understanding it correctly. Thank you very much for your clarification!

Scripts are executed as part of a transaction validation. That means: no transaction -> no script execution. The blockchain has no mechanism of timed or automatic script execution. What you can do is to implement transaction submission at every new epoch in your off-chain code.


text:
How to embed smart contract in website
I am creating a dapp website and which will reward it's users on completing different tasks. I have to create cardano native tokens. My question is that how can I send, lock and burn native tokens from my website

Many projects are using these:

Dapp Connector Wallet
Cardano Serialization Lib
Plutus smart contract

Example: https://github.com/Berry-Pool/spacebudz
https://github.com/Emurgo/cardano-serialization-lib

I've written an example precisely for these sort of questions
https://github.com/dynamicstrategies/cardano-wallet-connector


text:
Create address from public/private keypair without external tools/apis
I am starting development with Cardano. I have created a Hierarchal Deterministic Wallet with both Bitcoin and Ethereum, so I am familiar with much of the terminology. I am trying to create a Cardano wallet, exclusive from cardano-node and wallet, instead using Blockfrost API. However, after deriving a keypair through ED25519, I am not sure the next steps. Bitcoin had a lot of documentation on how an address is created from the key, so it was fairly simple. I cannot find much on Cardano. Cardano states that...
The addresses are a blake2b-256 hash of the relevant verifying/public keys concatenated with some metadata that can be stored on the Cardano blockchain.
Im not sure what "some" metadata is, or how to even go about creating an address. Also I am hoping to create a testnet address if that matters. Thanks!

Here is an example of how to generate the public/private keys using the cardano-serialization-lib
https://github.com/Emurgo/cardano-serialization-lib/blob/master/doc/getting-started/generating-keys.md
You can install this lib in ReactJs, or similar and generate the keys
Alterantively I have a few examples of how to do this and a few other fucntions here:
https://github.com/dynamicstrategies/cardano-wallet-functions

Cardano uses a similar BIP-32/39/44 structure as bitcoin and ethereum, so you can use the same mnemonic seed phrase to derive your HD keys as you do on the other blockchains.
To do so manually, I'd recommend installing the cardano-wallet software - it comes with all the tools necessary for deriving all key types (most notably. cardano-address and bech32. Refer to the official cardano-wallet documentation for instructions on how to derive the keys/manage addresses, or, when installed, just run cardano-wallet --help for brief descriptions of all the commands.
To be clear: cardano-address is the low level module that gives you fine control over public/private key derivation, and cardano-cli can then used to construct individual addresses (including staking addresses). Alternatively, you can use cardano-wallet to construct entire sets of addresses, and have their UTXOs automatically managed for you.


text:
What is the Cardano's equivalent to the Ethereum's EVM?
What is Cardano's smart contract engine called?
Smart contract language:
Solidity (Ethereum) => Plutus (Cardano) Simple enough, I get this.

Smart contract "engine":
EVM (Ethereum) => ??? (Cardano) EUTXO? Plutus? PAB?

There is no Cardano equivalent to the EVM because code execution on Cardano is mostly an off-chain process.
In short, "smart contracts" is a bit of a misnomer because of how very different programmability is achieved in UTXO vs Accounts based distributed systems. In short:

In accounts, smart contracts are programs that are authorized to autonomously initiate state changes when specific conditions (on-chain) are met. In a way these programs have their own agency, making it easy to create a very precise dependency cascade (if X then Y then Z, then e.t.c.). As such, Ethereum itself is akin to a shared, single threaded, dynamically modifiable program, whose state is shared among all participating nodes - we call this the EVM.

In eUTXO, smart contracts are simply "address guards" that only allow their UTXOs to be used as inputs if the spending transaction exactly follows the logic set forth by the script's author. In other words, any transaction attempting to spend from an address guarded by a smart contract many only do so by providing a proof that its logic is equivalent to the logic outlined by the guard's author. As such, Cardano itself is akin to a shared database that can only be updated according to either canonical (pre-smart contract) or custom (post-smart contract) rulesets. There is no shared "state" (dependencies) of the system, only a shared history of inputs and outputs. Hence, no "Cardano-VM"

This topic has already been addressed from multiple angles, so I will provide links below that go in greater detail. The following Q/A's helped me understand the differences in the structure of UTXO vs Accounts, so they may help you as well:

Referencing an External Plutus Script
eUTXO transaction model Vs Account Based Transaction Model
Can blockchain viewers read the source code of a smart contract if they know its address?
What's the difference between programmable validators and smart contracts?

Thank you very much! This has been immensely helpful.

So... it's essentially wrong to compare eUTXO to EVM, cosmWASM or eWASM? (Apples to oranges)

I am not familiar with cosmWASM, but it is apples to oranges in the sense that smart contracts on (e)UTXO vs Accounts models are hardly comparable.

Great write up ! Very insightful !

Great answer, thanks! I'd be a bit cautious about this statement though: "code execution on cardano is an entirely off-chain process." There is still an on-chain validation part run in Plutus-core as part of transaction validation.

Cardano has what is called Plutus Core.
The short of it is that it's an Abstract Machine made up of lambdas and techno-sorcery that finds a way to execute directly on the client machine via Cardano node. This gives it some efficiencies over the VM approach.
Therefore Smart contract "engine":
EVM (Ethereum) => Plutus Core
N.B. Plutus is usually used in a blanket manner, usually folks mean Plutus-Tx which is a Haskell derivative.


text:
Is there a way for a contract to look at the duration of the timeslot?
Are there oracles for knowing in real time the duration of the Cardano time slot in real time ? One learns in the Plutus Pioneer Program that the duration of this time slot can change, is there a way to give Ada to my children in 3 years (and not 6 or 1.5 years ^^) ?

Simple timelocking scripts have been around since before smart contracts were launched, though they do rely on slot length as their notion of time. You can read more about them at IOHK's simple scripts repo.
While slot length can indeed be changed, that doesn't mean that it will be changed without a significant heads up. Currently, slotLength is a non-updateable protocol parameter, meaning it would require at least an HFC to change, which we would be aware of ahead of time.
For this reason I would argue the slotLength parameter is currently, by far, a more reliable source of time than any oracle. The former has roughly the same security/reliability guarantees as something like Max-ADA-supply, whereas the latter is only as trustworthy as the underlying data aggregator.
If I were time-locking UTXO's for years ahead, I would use the slot-based time locking scripts mentioned above, in combination with an emergency fallover key that is non-timelocked and buried/kept somewhere safe, just in case of whatever.

What does it mean  HFC to change ?


text:
Mathematical equivalence of Account and eUTxO model
I've heard that the eUTxO model and the Account model are mathematically equivalent in terms of expressiveness in various YouTube videos. I've also heard that the eUTxO model is a strict superset of the Account model (ie: the eUTxO model can do everything the Account model can do, and more). Are these ideas/facts true? I've been trying to find a high quality source for this idea/fact but haven't been able to find one.
I tried reading the paper presenting the eUTxO model but my lack of formal math training made it a bit difficult and I didn't find any mentions of Account model equivalence.
Does anyone know of high quality sources which confirm or reject out these ideas?

The reason eUTXO is considered a superset of the account model is because it is possible to create constraint emitting machines (CEMs) on the eUTXO model, as mentioned in the paper you linked. To summarize:
Since "smart contract" logic is encapsulated entirely within individual UTXO(s), it is possible to perfectly capture logic of arbitrary complexity by aggregating and quarantining UTXOs into a sort of "black box" on-chain.
It is this CEM principle that forms the basis of the Hydra Head Protocol; allowing the creation of mini-ledgers that can be configured to behave in an account-style fashion, all while periodically committing snapshots to the overarching UTXO-style main-chain.
All of this is to say, that any and all UTXO logic can be expressed in an accounts-like fashion, but the reverse is not true. Therefore, the UTXO model is, expressively speaking, a superset of the account model.

Thank you for the amazing answer! I know this is a big ask but do you mind elaborating? I don't have intuition for what the following means: perfectly capture logic of arbitrary complexity by aggregating and quarantining UTXOs into a sort of "black box" on-chain. Also, is there any chance you can elaborate on why the reverse isn't true? Is there a simple example of a UTXO smart contract that cannot be expressed in an account-like way?

UTXOs are like little boxes that contain data (and logic) with zero external dependencies. If we aggregate a bunch of these little boxes into a bigger box (lets call the bigger box a "Head"), we can rigorously guarantee that this new Head is not logically dependent on anything outside of the UTXOs that went into its construction.
However, we cannot make the same zero-external-dependency guarantees for an accounts-based ledger, because it is already, by its nature, one big box/state of constantly changing interdependencies (almost like one big head).

I stumbled across this paper by IOHK which seems to show this sort of equivalence.
I'm going to try to read it and see what I can learn. I suspect this might be the best resource for learning about this mathematical equivalence between those two models.
EDIT: this seems like the paragraph from the paper above which confirms the idea that eUTxO is a mathematical superset of the account model:

Despite the accounting equivalence implied by the
translations, Proposition 2 and the translation of Sec.
5.2 show that it is generally necessary to create several
account-based transactions to simulate the effect of
a single UTXO-based transaction. This is important:
while all the value transfers in a single UTXO-based
transaction are processed atomically and simultaneously, the corresponding account-based transactions
are not guaranteed to be so. Theoretically, there may
be a wide time gap between their executions.


text:
Run a node virtually that can be accessed from different machines
I am trying to run a cardano node, however I am not sure of the best way to go about it. My goal is to create a cardano wallet through python on my own machine. I want to run a cardano node on a VM, and be able to give access to myself and others, so we can all connect to that same node. I was wondering if this is possible, and if so how to go about it. Thanks.

I'd use a docker container setup on some cloud instance which is pretty quick to set up and cheap as well.
There is pretty good documentation available on how to set up a node.
See here:

https://developers.cardano.org/docs/get-started/running-cardano/
https://github.com/input-output-hk/cardano-node#docker-image


text:
Attacking K parameter?
I was thinking, why K parameter isn't a max cap? I mean, if a pool owner is affected by over delegation too, this could become an attack where I (as hypothetical attacker) can delegate 100M ADA through 1k wallets to a pool just to damage its rewards. I could let the other delegators to leave the targeted pool and after that I could quit the pool with all my wallets. While doing it, I will damage my rewards too, but still I could choose to do it consciously. Plus obviously it should work even if you got 63M ADA in your pool and I've got just 10M ADA or something. But however, if K would be a max cap I couldn't do that at all. There is any particular reason I'm not considering because pools can arrive to an over delegation?

In principle, you are correct - such an attack is possible. However, this is where the game-theoretic principles of a well-designed PoS system come into play:
In what scenario would an attacker possibly be so malicious as to forgo tens or hundreds of thousands of ADA rewards, just to lower everyone else's rewards? Remember: the attacker's reward flows would be hurt just as much as everyone else's, so this attack seems incredibly unlikely to happen.
Additionally, putting a hard cap on pool saturation introduces some finicky side effects. For example, if an address is delegated to a fully saturated pool, what happens when a new UTXO (containing ADA) is created at that address? Is it simply not delegated? If so, do we now have to prioritize delegating ADA in the order that it comes in, and then how do we prioritize change-type UTXOs? Compensating for this would require at least a few new workarounds to ledger mechanics, all of which may introduce their own side-effects.
Furthermore, even if this attack does happen, other delegators will be quickly incentivized to re-delegate to a different, non-oversaturated pool, until saturation is reached for the targeted pool.

Yes, it's a theoretical attack, but very expensive as noted by @zhekson. The evidence to date suggests the cost sufficiently mitigates.
In practice (other) delegators simply leave until saturation drops.

Thanks for your reply guys.
Yes indeed this kind of attack will impact your rewards and we all know it, but for me we should think in order to favourite the security and the fairness to all.
This attack is unlikely but it's still possible. I mean if you have 10-100M ADA to use for it, you could probably don't care about 1-2 months of loosing rewards.
Regarding a pool owner, if your K is attacked often your delegators can choose to change their pool to never come back, they are not forced to delegate always the same pool so I can potentially attack your K a few times and you are potentially going to loose some\many delegators forever because of it.
Regarding the delegators, now we are in a moment where many tokens are being launched through ISO ISPO RISO etc. so if you are forced to leave a pool because someone decide to attack K or simply because biggest wallets are rushing in your pool, it could be not fair at all for you.
On the other hand, to block this kind of potential attack could be quite simple to me, because even if a max cap on K could be hard to code as zhekson rightly said, we should just write in the code something like "if you are going to make the overdelegation then you will be penalized for it, but not all the others in that pool and the pool owner".
I'm not a coder so I could be wrong about that, but probably it's just about to add something in the staking code regarding the single staking addresses while they are delegating, without affecting all the other chain transactions.
In general, to be responsible for your bad actions\faults but not for the others ones, looks even more fair to everyone for me. Although we want to think that this type of attack is not possible because it is relatively expensive, or rather not profitable for the attacker in a short therm view, we can immagine situations where a pool owner or a group of pool owners would like to attack some other pool owner\groups to gain delegators or something.

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


text:
Week 4 issue with Cabal build: Not in scope: type constructor or class 'JWT.EncodeSigner'
When running cabal build or cabal repl in the core/week04 folder I get the following error message when building the playground-common-0.1.0.0 package:
src/Auth.hs:130:41: error:
    Not in scope: type constructor or class 'JWT.EncodeSigner'
    Module 'Web.JWT' does not export 'EncodeSigner'
    |
130 |         { _configJWTSignature       :: !JWT.EncodeSigner
    |                                         ^^^^^^^^^^^^^^^^

I am in the correct branch in the plutus-apps repo as per the cabl.project file in code/week04. I've run cabal update and it was successful.
Does anyone have any ideas how to resolve this?

Do you run cabal from nix-shell?

yes, I do. It appears the issue was that I ran nix-shell under an old commit (for week 3) and restarting the shell after the commit was changed allowed cabal build to run

Be sure to do a git pull for both 'plutus-master' and 'plutus-pioneer-program'.
Then set the right git-checkout tag (of the week's cabal project file)
Restart nix-shell so it builds the 'plutus-master', after that you can do the following to resolve missing dependencies in the 'week' folder:

cabal clean
cabal update
cabal build
cabal repl

This should work

Thanks, the key here for me was to restart the nix-shell. Once I did this everything flowed as expected.


text:
Yoroi wallet using cardano-cli
I have a cardano-cli/cardano-wallet server set up, and I was trying to load a previously created Yoroi wallet by using the 12 word pass phrase, but it seemed like it created a new wallet instead of recovering the existing wallet.
Questions:

when you use POST /wallet does it only restore wallets that had previously been created within that server (and if none are found, create a new wallet)?
does that mean that the 12 word pass-phrase is not universal, and recovering a wallet on different Cardano platforms would not be consistent (I don't think this is the case, because I've been able to use AdaLite and Yoroi interchangeably)
how, using cardano-wallet can I access a previously created wallet and look at the assets?

when you use POST /wallet does it only restore wallets that had previously been created within that server (and if none are found, create a new wallet)?

It restores the "secret key" derived from the "mnemonic pass phrase", then derives addresses. From these addresses, it can check the blockchain for balances and assets linked to these addresses.
If it turns out that this "wallet" already has associated records on the network you're connecting to, then we can label the previous action "restoring the wallet". Otherwise, we can label it "creating a wallet". The tool does not know whether it is restoring or creating - it just translates the mnemonic pass-phrase to a "secret key", etc.

does that mean that the 12 word pass-phrase is not universal, and recovering a wallet on different Cardano platforms would not be consistent (I don't think this is the case, because I've been able to use AdaLite and Yoroi interchangeably)

Not universal across all wallets - it varies depending on the wallet's implementation. For example, the Trezor and Ledger wallets use different styles of derivation.
Another example: even if a wallet uses the same style, if a recovered wallet stops scanning at, say sequential address #1000 but the assets are in address #1001, then the wallet does not "see it", but it is still there in the blockchain nonetheless.

how, using cardano-wallet can I access a previously created wallet and look at the assets?

Specifically for cardano-wallet and their REST API that you seem to be using, after restoring it with the POST endpoint it should return balance and assets. Or if it's already restored, GET /wallets or GET /wallets/{walletId} source: docs

Sources / deeper dive for answers part #1 and #2:
FYI Wallets in Cardano uses a variation of the very popular hierarchial deterministic wallets. For a deeper dive, see:

CIP-1852
BIP-44

Good "first" answer.  Way above average.


text:
zsh: exec format error: cardano-node on MacOS BigSur

I'm getting this zsh: exec format error: cardano-node
I ran file $(command -v cardano-node)
This returned the following
/usr/local/bin/cardano-node: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, stripped
this looks to be correct. So why am I getting "exec format error"
Any help de-bugging would be greatly appreciated.

Did you compile it on that architecture and version of MacOS?
Can only check for you against version 1.33 compiled on Ubuntu which reports a few of differences which might point to the way you compiled?
ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 3.2.0, BuildID[sha1]=b832d0d517ddc9b6e4d692d4cb2fb6663136e8ae, with debug_info, not stripped

Thank you for the reply, I'm running this on MacOs BigSur I have an intel i7 processor on the mac. So it is 64 bit is there something else I need to check?  I did the Brew install  with cardano-node version 1.33.0

Did you install an already build binary or did you build the binary from source? The M1 processors also tend to have slight differences.
For mac I would recommend building your own binaries. This is probably the safest besides also checking a checksum or hash of the already built binaries.
Here's an instructional link on how to build cardano-node and cardano-cli from source:
Building from source on MacOS

Thank you for the response as it turned out my server instance did not have enough RAM, after upgrading to 16 GB my issues where resolved.


text:
How to get protocol parameters **only for latest epoch** with GraphQL?
How can I get protocol parameters only for the latest epoch using GraphQL?
I can get protocol parameters with cardano-cli:
cardano-cli query protocol-parameters \
  --testnet-magic 1097911063 \
  --out-file $HOME/cardano/protocol.json

I can get protocol parameters for multiple epochs with help of this query
https://github.com/input-output-hk/cardano-graphql/blob/master/packages/api-cardano-db-hasura/src/example_queries/epochs/epochProtocolParams.graphql

I've found the solution:
query currentEpochProtocolParams {
  cardano {
    currentEpoch {
      number
      protocolParams {
        a0
        coinsPerUtxoWord
        collateralPercent
        costModels
        decentralisationParam
        eMax
        extraEntropy
        keyDeposit
        maxBlockBodySize
        maxBlockExMem
        maxBlockExSteps
        maxBlockHeaderSize
        maxCollateralInputs
        maxTxExMem
        maxTxExSteps
        maxTxSize
        maxValSize
        minFeeA
        minFeeB
        minPoolCost
        minUTxOValue
        nOpt
        poolDeposit
        priceMem
        priceStep
        protocolVersion
        rho
        tau
      }
    }
  }
}


text:
Validator function in UTxO vs eUTxO model
I'm reading the paper which introduces the eUTxO model and I'm having trouble figuring one specific difference between the standard UTxO validator and the eUTxO validator.
It seems that the only argument to the validator in the UTxO model is the redeemer

Whether an output can be consumed by an input is determined by a function
ν attached to the output, which we call the output’s validator. A transaction
input proves its eligibility to spent an output by providing a redeemer object ρ,
such that ν(ρ) = true

While in the eUTxO model it seems that the value, datum, redeemer and transaction are arguments to the eTUxO validator

Overall, to check that an input
with redeemer ρ that is part of the transaction tx is entitled to spend an output
(ν, value, δ), we check that ν(value, δ, ρ, tx ) = true

I understand why the datum, redeemer and transaction are required in the eUTxO validator.
What I don't understand is why value is required in the eUTxO validator but not in the UTxO validator.
Why does the eUTxO model require that the value be passed to the validator while the UTxO model does not?

In the UTxO model, we ARE passing the value into the validation, an output is compromised of both that and the redeemer (witness). The paper just fails to mention that.
I believe that is because the value is not important here, as we just have to understand that in the eUTxO model, it extends the previous model by including the entire transaction object tx and the datum δ, where δ contains arbitrary contract-specific data. This is done to enforce contract continuity and maintain the machine state, respectively.
The description of the UTxO model was just for reference and a quick brief on it. I believe thats why it fails to mention it.


text:
Contract continuity in the eUTxO model
The paper which introduces the eUTxO model mentions an idea called contract continuity:

we need to be able to enforce that
the same contract code is used along the entire sequence of transactions — we
call this contract continuity

and that continuity is achieved by passing the entire transaction to the validator:

Thus a validator can inspect the transaction
that attempts to spend its output and, in particular, it can ensure that the
contract output of that transaction uses validator code belonging to the same
contract — often, this will be the same validator

Based on my current understanding, it's intuitive to me that if a transaction consumes outputs from a single contract, the validator of those outputs can enforce that the new outputs of the transaction use the same validator.
What I'm having trouble understanding is what happens when a single transaction consumes two UTxOs with different contracts. Suppose there are two UTxOs a and b and that UTxO a is validated by scriptA while UTxO b is validated by scriptB. If a single transaction tx consumes both a and b, how is contract continuity preserved?
EDIT: I realize the second item I quoted above isn't quite clear to me and another question popped into my mind, how does validator code relate to the notion of contract and contract output?


text:
Difference when building Testnet and Mainnet addresses
I am creating an address generator for cardano. I am struggling to figure out what the differences would be when building an address for testnet instead of mainnet. What components of the address are different?

If you are using cardano-cli to build the address(es), the only difference would be in specifying which network (mainnet or testnet) the address is for. This is done via the --mainnet & --testnet-magic <MAGIC_NUMBER> flags. The same payment/stake.vkey files can be used in either case.
For example, if you are building a shelley address for the public testnet using cardano-cli, you would replace the following --mainnet flag with the --testnet-magic 1097911063 flag:
MAINNET:
cardano-cli address build \
--payment-verification-key-file payment.vkey \
--stake-verification-key-file stake.vkey \
--mainnet \
--out-file main-shelley.addr

PUBLIC TESTNET:
cardano-cli address build \
--payment-verification-key-file payment.vkey \
--stake-verification-key-file stake.vkey \
--testnet-magic 1097911063 \
--out-file test-shelley.addr

Note: mainnet shelley addresses all begin with addr1, whereas testnet shelley addresses all begin with addr_test

Im not using cli, im trying to generate address using other libraries. Comparing testnet and mainnet on daedalus, the derivation paths are the same, but they have different addresses. Is there somewhere that distinguishes a mainnet address from a testnet?

derivation paths of public/private keys is the same for mainnet and testnet, the difference is in deriving the address. I'm not sure about other building addresses from other libraries, but the keypairs will be the same


text:
Onchain validation fails for hard-coded pkh
When modifying the week5 code in e.g. Signed.hs from
mkPolicy pkh () ctx = txSignedBy (scriptContextTxInfo ctx) $ unPaymentPubKeyHash pkh

to the hard-coded pkh from Wallet 1,
mkPolicy pkh () ctx = txSignedBy (scriptContextTxInfo ctx) $ PubKeyHash "a2c20c77887ace1cd986193e4e75babd8993cfd56995cd5cfce609c2"

the validation fails with
CONTRACT STOPPED WITH ERROR: "\"WalletError (ValidationError (ScriptFailure (EvaluationError [\\\"PT5\\\"] \\\"CekEvaluationFailure\\\")))\""

I verified in the repl:
mockWalletPaymentPubKeyHash (knownWallet 1)
a2c20c77887ace1cd986193e4e75babd8993cfd56995cd5cfce609c2

and also in the offchain code logging Contract.ownPaymentPubKeyHash gives the same a2c2...09c2 hash.
What is going wrong here?
I unsuccessfully tried to debug it with
mkPolicy pkh () ctx = traceError $ decodeUtf8 $ getPubKeyHash $ head $ txInfoSignatories (scriptContextTxInfo ctx)

which resulted in an error as well.
CONTRACT STOPPED WITH ERROR: "\"WalletError (ValidationError (ScriptFailure (EvaluationError [] \\\"BuiltinEvaluationFailure of DecodeUtf8\\\")))\""

What is the correct way to debug this? e.g. in this case to check what the pkh used in the onchain code was? Is decodeUtf8 the right function at all for BuiltinByteString -> BuiltinString in this case or is it a special byte string?

Both wallets call mint endpoint and if you explicitly allow only one of the wallets to mint then it will of course throw error. Try removing or commenting the other wallet's call to endpoint.

@Tuvshintsenguun thanks, forgot to mention this: the EmulatorTrace was adjusted to only have 1 mint call from wallet 1.

This was answered in PPP Q&A, the issue was the string literals in Plutus Core code.
Instead, one has to use variables
{-# INLINABLE mkPolicy #-}
mkPolicy :: PaymentPubKeyHash -> () -> ScriptContext -> Bool
mkPolicy pkh () ctx = txSignedBy (scriptContextTxInfo ctx) $
unPaymentPubKeyHash pkh

and put the literal into the liftCode expression:
policy :: Scripts.MintingPolicy
policy = mkMintingPolicyScript $
$$(PlutusTx.compile [|| Scripts.wrapMintingPolicy . mkPolicy ||])
`PlutusTx.applyCode`
PlutusTx.liftCode (PaymentPubKeyHash "a2c20c77887ace1cd986193e4e75babd8993cfd56995cd5cfce609c2")