text:
Can't compile Plutus Playground examples: Could not find module `Playground.Contract' (Ubuntu 20.04)
I can't compile any of the example scripts using Plutus Playground gui:
Compilation Error, Line 2, Column 1 (jump)
 error:
    Could not find module `Playground.Contract'
    Use -v (or `:set -v` in ghci) to see a list of the files searched for.
  |
2 | import Playground.Contract
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^
Compilation Error, Line 3, Column 1 (jump)
 error:
    Could not find module `Plutus.Contract'
    Use -v (or `:set -v` in ghci) to see a list of the files searched for.
  |
3 | import Plutus.Contract
  | ^^^^^^^^^^^^^^^^^^^^^^
Compilation Error, Line 4, Column 1 (jump)
 error:
    Could not find module `PlutusTx.Prelude'
    Use -v (or `:set -v` in ghci) to see a list of the files searched for.
  |
4 | import PlutusTx.Prelude
  | ^^^^^^^^^^^^^^^^^^^^^^^

Looks like all non-standard modules are considered missing (screenshot from playground gui after hitting "Compile").

I'm using Ubuntu 20.04. Here's what I did:

Installed nix using sh <(curl -L https://nixos.org/nix/install) --daemon (multi-user installation)
Cloned plutus-apps (latest, currently: dd1678bba97e489dc54f2384a7be81e32659ba76)
Ran nix-shell in plutus-apps dir.
Started playground server inside the nix shell using

$(nix-build -A plutus-playground.server)/bin/plutus-playground-server webserver

and client:
npm start

At this point gui was running ok, but I was getting errors while trying to compile examples:
ConnectionError (HttpExceptionRequest Request { host = "localhost" port = 8009 secure = False requestHeaders = [("Accept","application/json;charset=utf-8,application/json"),("Content-Type","application/json;charset=utf-8")] path = "/runghc" queryString = "" method = "POST" proxy = Nothing rawBody = False redirectCount = 10 responseTimeout = ResponseTimeoutDefault requestVersion = HTTP/1.1 proxySecureMode = ProxySecureWithConnect } NoResponseDataReceived)

After some googling/debugging I came up with a solution to connection errors - running the server with:

WEBGHC_URL=http://localhost:8081  $(nix-build -A plutus-playground.server)/bin/plutus-playground-server webserver -p 8081

and changing client configuration in webpack.config.js:
    devServer: {
        contentBase: path.join(__dirname, "dist"),
        compress: true,
        port: 8009,
        https: false, // changed from true due to CA errors
        stats: "errors-warnings",
        proxy: {
            "/api": {
                target: "http://localhost:8081", // port changed from 8080
            },
        },
    },

After these changes playground at least tries to compile the scripts, but it looks like webghc doesn't see plutus packages.
As I mentioned I'm using Ubuntu 20.04 and ghcup with following tool versions:
✔✔ ghc   8.10.7   recommended,base-4.14.3.0 hls-powered
✔✔ cabal 3.6.2.0  latest,recommended
✔✔ hls   1.6.1.0  latest,recommended
✔✔ stack 2.7.5    latest,recommended
✔✔ ghcup 0.1.17.6 latest,recommended

My nix.conf:
» cat /etc/nix/nix.conf

build-users-group = nixbld
substituters        = https://hydra.iohk.io https://iohk.cachix.org https://cache.nixos.org/
trusted-public-keys = hydra.iohk.io:f/Ea+s+dFdN+3Y/G+FDgSq+a5NEWhJGzdjvKNGv0/EQ= iohk.cachix.org-1:DpRUyj7h7V830dp/i6Nti+NEO2/nhblbov/8MW7Rqoo= cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY=
experimental-features = nix-command flakes

Does anyone know what I'm missing? Please halp :)
EDIT:
Output of nix-shell command:
» nix-shell                                                                                130 ↵
trace: To materialize project.plan-nix for cabal-install entirely, pass a writable path as the `materialized` argument and run the 'updateMaterialized' script in 'passthru'.
trace: WARNING: 8.10.5 is out of date, consider using 8.10.7.
trace: haskell-nix.haskellLib.cleanGit: /nix/store/dgp5f75dgadnxvy1mybjky2hm7wyxnpl-cardano-node does not seem to be a git repository,
assuming it is a clean checkout.
trace: To make project.plan-nix for cardano-node a fixed-output derivation but not materialized, set `plan-sha256` to the output of the 'calculateMaterializedSha' script in 'passthru'.
trace: To materialize project.plan-nix for cardano-node entirely, pass a writable path as the `materialized` argument and run the 'updateMaterialized' script in 'passthru'.
trace: WARNING: 8.10.5 is out of date, consider using 8.10.7.
trace: To make project.plan-nix for cardano-node a fixed-output derivation but not materialized, set `plan-sha256` to the output of the 'calculateMaterializedSha' script in 'passthru'.
trace: To materialize project.plan-nix for cardano-node entirely, pass a writable path as the `materialized` argument and run the 'updateMaterialized' script in 'passthru'.
trace: To make project.plan-nix for haskell-project a fixed-output derivation but not materialized, set `plan-sha256` to the output of the 'calculateMaterializedSha' script in 'passthru'.
trace: To materialize project.plan-nix for haskell-project entirely, pass a writable path as the `materialized` argument and run the 'updateMaterialized' script in 'passthru'.
trace: To materialize project.plan-nix for haskell-project entirely, pass a writable path as the `materialized` argument and run the 'updateMaterialized' script in 'passthru'.
trace: To materialize project.plan-nix for haskell-project entirely, pass a writable path as the `materialized` argument and run the 'updateMaterialized' script in 'passthru'.
nix-pre-commit-hooks: hooks up to date
pid 1234077's current affinity list: 0-15
pid 1234077's new affinity list: 0-15

Does your plutus-app checked out commit (dd1678bba97e489dc54f2384a7be81e32659ba76) match your cabal project file dependency declaration of plutus-apps (see tag of repo)?

Did you logout and login after installing nix? Your reachable paths where software might needs to be updated after install. If this is the case, just purge the plutus-app directory and git clone it again. Also check when you enter your nix-shell stuff is being pulled from somy hydra.iohk server.

@William-BerlinPool I'm just trying to get the playground working without any other external projects. (not using plutus-pioneer-program repo atm)

@Fermat I did log out / log in after installing nix. Running nix-shell (for the first time) downloaded lots of deps from cache. I've pasted output of subsequent runs in the main post. I also tried to run playground using Ubuntu 20.04 on Windows WSL2 with the same result.

If you would like we can debug it together on the IOHK dev discord channel collaborate room? Just post a message there and Ill contact you :)

@Fermat I'd love to, but I'm not on that discord. Can you send me a link?

https://discord.gg/m8pHXMDu is the IOG technical community discord server.

@Fermat posted in #pioneers-questions

It turned out that I was starting the playground server wrong - I was trying to use nix-build inside a nix shell.
What actually works (without any code modifications):

server:

> nix-shell
> cd plutus-playground-server/
> plutus-playground-server

client:

> nix-shell
> cd plutus-playground-client/
> npm start

I also added allow-import-from-derivation = true to my nix.conf (as
cardano-node docs suggest).
My nix.conf is now:
substituters        = https://hydra.iohk.io https://iohk.cachix.org https://cache.nixos.org/
trusted-public-keys = hydra.iohk.io:f/Ea+s+dFdN+3Y/G+FDgSq+a5NEWhJGzdjvKNGv0/EQ= iohk.cachix.org-1:DpRUyj7h7V830dp/i6Nti+NEO2/nhblbov/8MW7Rqoo= cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY=
experimental-features = nix-command flakes
allow-import-from-derivation = true

Thank you @Fermat for your help :)


text:
Plutus transaction error PT5
I am building a transaction where I use the following function to make my datum and redeemer,
writeJSON :: PlutusTx.ToData a => FilePath -> a -> IO ()
writeJSON file = LBS.writeFile file . encode . scriptDataToJson ScriptDataJsonDetailedSchema . dataToScriptData . PlutusTx.toData

But when I build a transaction to consume an UTxO at the script address I get the following error,
Command failed: transaction build  Error: The following scripts have execution failures:
the script for transaction input 0 (in the order of the TxIds) failed with:
The Plutus script evaluation failed: An error has occurred:  User error:
The provided Plutus code called 'error'.
Script debugging logs: PT5

I am very certain that my redemeer and datum are correct. My onchain code is the following
data MyDatum = MyDatum
    { pubKey :: Integer
    } deriving (Show, Generic, FromJSON, ToJSON, ToSchema)

data MyRedeemer = MyRedeemer
    { privKey :: Integer
    } deriving (Show, Generic, FromJSON, ToJSON, ToSchema)

data Params = Params
    { params_p :: Integer
    , params_g :: Integer
    , params_bits :: Integer
    } deriving (Generic, FromJSON, ToJSON, ToSchema)

unsafeParams :: Params
unsafeParams = Params p g 64
        where
                p = safePrime64
                g = (safePrime64 - 1) `PlutusTx.Prelude.divide` 2

PlutusTx.makeIsDataIndexed ''MyDatum [('MyDatum, 0)]
PlutusTx.makeLift ''MyDatum
PlutusTx.makeIsDataIndexed ''MyRedeemer [('MyRedeemer, 0)]
PlutusTx.makeLift ''MyRedeemer
PlutusTx.makeLift ''Params

{-# INLINABLE mkValidator #-}
mkValidator :: Params -> MyDatum -> MyRedeemer -> ScriptContext -> Bool
mkValidator (Params p g _) (MyDatum pub) (MyRedeemer priv) _ = pub == exponentiateMod g priv p

Where the the validator checks whether or not the redeemer is the exponent of the datum via modular exponentiation. Perhaps I incorrectly indexed my datum and redeemer with the makeIsdataIndexed function?

Your error means that the validator script returned an error. In the newer version of node, I think 1.33 or 1.34 you can see the exact error message which is thrown from the validator.

I am currently running 1.33, ill update to 1.34 and see what I get there. Thanks for the tip!

PT5 alone means that the validator returned False. You can break down your script into multiple steps of computation and add some traceIfFalse calls along the way to see more context why it happend to be False overall.

source: Stack Exchange

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

sort: votes


text:
The pool of validators. Who owns it?
Good day , I am relatively new to Cardano ecosystem and want to understand how it works specifically with Ouroboros protocol.
Watching the video in IOHK channel I got some insides but still have many questions. Specifically
The protocol chooses the validator from the pool based on the amount of stakes they have. Where this pool is located, who controls it ? Can participants just run nodes locally and always vote for themself instead of going to this pool ?
The Epoch is split into slots and each slot is 20 seconds which means every 20 seconds Cardano protocol takes some transactions from the pool and create a block.
The question is , where those transactions are stored prior to creating a block ? What is the limit of transactions stored in one block and why ?

Stake pools are registered on-chain via a registration certificate. That certificate contains the hash of the cold key and hash of the VRF among other things. The pool operator then generates a KES key and opcert signed by the cold key, and runs their pool with these secrets. The node then identifies it's own leadership schedule using the VRF key and starts creating blocks based on stake it has. Typically a new pool needs over 1M Ada delegation to regularly make blocks every epoch. You can run with less than that, but you'll have a lot of epochs with zero rewards which tends to lose delegators over time.

This is from what I have understood so far with Ouroboros in general:

The protocol chooses the validator from the pool based on the amount
of stakes they have. Where this pool is located, who controls it ? Can
participants just run nodes locally and always vote for themself
instead of going to this pool ?

In Ouroboros Proof of Stake design, they have this thing called "slot leader" in every epoch. This slot leader means "The pool that have the right to create the next block". Slot leader is chosen prior the current epoch, chosen by the proportion amount of ADA to total ADA staked in the network [1]. One Stake Pool, given enough ADA they have, could create multiple block in one epoch. You can see this on https://adapools.org/, the number of expected blocks that they will produce vs the actual block they've made.
The Stake Pool Operator do not have control of those ADA in the pool. The delegators who delegate their wallet (which have some amount of ADA in it) to a Stake Pool only provide a certificate of the delegation. This certificate consists information about 'which Stake Pool does this wallet delegate to'.
That said, participants cannot run a node and have their node selected everytime, because the network have this slot leader system.

The Epoch is split into slots and each slot is 20 seconds which means every 20 seconds Cardano protocol takes some transactions from the pool and create a block.

In Cardano, -only true in current Shelley era-, the block will be on average created every 20-40 slot, which translates to 20-40 seconds because 1 slot = 1 second [2]. You can check this on https://cardanoscan.io/, and see the slot ticker running every second.

The question is , where those transactions are stored prior to creating a block ? What is the limit of transactions stored in one block and why ?

The transaction is stored in the 'Mempool' (Memory Pool), a list of already signed transaction but haven't made it into a block yet. The next slot leader will pull transactions from this mempool and then include it into a block. This mempool is located in every machine running the stake pool. The block have a capacity of max 80KB [3]. Every transaction will be varying from 600Bytes to 16KB, so each block will have different number of transactions stored in it. You can check Cardanoscan to check how many transactions happened in one block.
I hope this can answer your question
References:

Ouroboros: Cardano’s Proof of stake blockchain protocol. – https://youtu.be/D4HegNgnuNo
Design Specification for Delegation and Incentives in Cardano – https://hydra.iohk.io/build/3744897/download/1/delegation_design_spec.pdf
[Article] Cardano Developers Propose Block Size Increase – https://www.coindesk.com/tech/2022/02/02/cardano-developers-proposes-block-size-increase/

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


text:
find holders from same policy but different asset name
I have a policy ID with hundreds of NFT with different asset name (for eg TTS19, TTS20, etc)
what is the easiest way to find all addresses/wallets which have this NFT(holders)?
I tried with koios and blockfrost but since all nft have a different unique hex asset name I can't show all addresses.
thank you in advanced,
TTS17
theTokenSquare

Using Blockfrost you could check for all "assets of the given policy" using this endpoint:
/assets/policy/{policy_id}

(https://docs.blockfrost.io/#tag/Cardano-Assets/paths/~1assets~1policy~1{policy_id}/get)
and then for each asset you can get the holder through this endpoint:
/assets/{asset}/addresses

(https://docs.blockfrost.io/#tag/Cardano-Assets/paths/~1assets~1{asset}~1addresses/get)

thank you mate, that was the combination of requests i had on my mind and understanding.  - we were looking for direct only one request for only one policy for all the assets once.

A of time of posting available services of blockfrost and koios require you to query combination of multiple endpoints. So therefore for more advanced/specific usage you probably best of querying cardano-db-sync instance your self.
As example you take a look at asset_address_list.sql at github.com/cardano-community/guild-operators repo how to build your query.


text:
Ways to ensure at any given time at most one UTxO sitting at the script address that can be consumed
I can think of one solution, which is the validator script checks if a specific NFT is locked by the script address. Because of the nature of the NFT, it ensures there is at most one UTxO sitting at the script address at any given time that can also be consumed.
This is to ensure there is a chain of UTxOs sitting at the script address without forking.
I wonder if there are any other solutions.

Have you met the statemachine (https://github.com/input-output-hk/plutus-apps/blob/main/plutus-contract/src/Plutus/Contract/StateMachine.hs)
There are examples in the plutus-use-cases and the later weeks of the PPP.
It works like you describe: using an NFT to keep track of state

Yeah. I was aware of state machine. I was just wondering if there were any other alternative solutions.

By watching PPP Week 7 lecture, using ThreatToken within state machine is another way to achieve it.

Yes, you can use a policy id as a parameter to that script and say that the script can only be consumed if it contains a token with that policy ID. You then mint an NFT and send it to this script (which should have the policy ID from your NFT as a parameter).
Since NFTs are unique, this will be the only UTxO that can be consumed, because the rule enforces that the script can only be consumed if it has that specific unique token.

As far as I know there is no such way to ensure that only a single UTxO exists at any given address since anyone can send ADA to some address - independently of whether it's a script address or not.
Also a validator script only runs when an output is spent from the validator's address. Therefore there is no check in place/ available that could possibly run when new UTxOs are created at some address.

You are right that anyone can send ADA to the script address, which will make multiple UTxOs sitting at the same script address.

Perhaps I should've asked my question differently. I intended to seek ways to ensure at any given time at most one UTxO sitting at the script address can be consumed. This is to ensure there is a chain of UTxOs sitting at the script address without forking.

Sounds like you sort of state machine to me.Without more context it's difficult to understand the problem. One way I could imagine doing something like that is perhaps by spending and recreating all but one UTxO that is suppose to be chained.That way the validator sees all inputs (chained UTxOs) and can ensure only one is correctly consumed (technically all are consumed) but the validator can check if all other output references are recreated at the script address with the correct datum.
That way you can perhaps chain utxo consumption but still not sure if that's a good solution for your prob

State machine indeed sounds a good solution by using its threadToken.

You generally CAN'T prevent the creation of UTxOs
But you can check that all UTxOs sitting at the validator address are included in the transaction
This way if say you have 2 or more UTxOs, you have to include all of them for the transaction to succeed, and then have one single UTxO as output (or zero if all the founds are sent away)
Doing so should minimize the number of UTxOs, the more the validator is run, the more often the number of UTxOs is reduced to one (or zero)
Edit:
some useful functions that you can use to check all the validator UTxOs are included are:
scriptOutputsAt :: ValidatorHash -> TxInfo -> [(DatumHash, Value)]

findContinuingOutputs :: ScriptContext -> [Integer]

getContinuingOutputs :: ScriptContext -> [TxOut]

findTxInByTxOutRef :: TxOutRef -> TxInfo -> Maybe TxInInfo

and the list goes on, just have a look at <your docs from plututs-apps>/haddock/plutus-ledger-api/html/Plutus-V1-Ledger-Contexts.html

In this case, can we design a validator script in a way such that it can ensure ALL UTxOs sitting at the script address are included in the transaction? I think we are not able to achieve it as validator script does not have a global view beyond the spending transaction.

@Qin the validator is part of the transaction, it is possible then to include all his utxos

If all UTxOs sitting at the script address are included in the transaction, then consuming all of them and outputting a single UTxO would be a solution. However, the validator is not able to guarantee that all UTxOs sitting at the script address, without omission, are included in the transaction.

@Qin Yes a validator cannot build a transaction but it can fail if the transaction does not respects some criteria; in this case the validator should fail if not all UTxOs are spent; I'm editing the answer with some function that may turn usefull

"But you can check that all UTxOs sitting at the validator address are included in the transaction". I don't think you can, validatos only have access to what is provided inside the transaction, you might very well have 10 script UTxOs and only provide two of them as inputs


text:
Whats the Diffrance between Plutus scripts and Cardano Native Scripts?
What are the key differences between Cardano native scripts and Plutus scripts, from a developer's perspective?

This has been answered before, see here

thanks man i will do


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

But on my computer
$date "%s"
1649413267

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

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

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

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

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

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

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

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

The chain start time is set in the configuration.

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

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

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


text:
What are the ways to make a validator script start to "live" on-chain?
What are the scenarios in which a validator script will start to "live" on-chain? By "living" on-chain, I mean there is at least one UTxO sitting on the script address.
A trivial answer is anyone sending some ADA to the script address of the validator script will create an UTxO sitting on the script address.
Another possible solution is having a "parent" validator script that is designed in a way such that consuming it will lead to creation of an UTxO sitting on the script address of a "child" validator script.
I wonder if there are any other ways.

Having an UTxO that a validator can spend doesn't activate the validator ( I suppose that's what you mean by "live" )
the validator only executes when trying to consume one of his UTxOs, but NOT when creating an UTxO.
So a validator only "lives" when spending (or minting, or staking), but in general is just a passive address.
You can think at validators as a person that makes the decision to sign a transaction based on a set of instructions (Plutus)
You as a person can receive ADA or Token without your need to allow the transaction; on the contrary, you as a person have to allow a transaction that uses one of your UTxOs by signing it, following your own logic
the same is true for validators, anyone can send ADA or tokens to them without any logic that allows that, but in order to spend a validator UTxO you need to run his logic, which makes him live

Yeah, you are absolutely right about script address being passive. My question wanted to know different ways to create an UTxO sitting at a given script address. There are already two ways that I have mentioned in the question. I just wanted to know any other possible ways to achieve it.

@Qin then what you are asking is for all possible ways to create an UTxO, and as the name "Unspent Transaction Output" implies, you need a transaction for that, no other ways

That is for sure that a transaction is needed. The two ways mentioned in the questions are two different types of transactions that can create an UTxO sitting at the script address. I was wondering if there were additional types of transactions other than the two mentioned in the question that can also create an UTxO sitting at the script address.


text:
Filter for utxos that was send from a specific public key address
In the pionner program they have this logic where they filter through utxos and get a specific set of utxos.
{...}
utxos <- Map.filter (isSuitable pkh) <$> utxosAt scrAddress
{...}
where
   isSuitable :: PubKeyHash -> TxOutTx -> Bool

How can i modify this to make it so that it filters utxos that came from a specific public key address. Basically get all utxos sitting in a script address that came from a specific public key.

Assuming each UTxO at the script address has a datum that contains the PubKeyHash you can compare against, then you can use the above code like so:
data UTxODatum = UTxODatum
    { pubKey :: !PaymentPubKeyHash }

{...}
    isSuitable :: PaymentPubKeyHash -> ChainIndexTxOut -> Bool
    isSuitable pkh o = case getUTxODatum o of
        UTxODatum{pubKey=pubKey} -> pubKey == <your specific pkh>
        _                        -> traceError "Unhandled datum type"
{...}

getUTxODatum :: ChainIndexTxOut -> UTxODatum
getUTxODatum o = case _ciTxOutDatum o of
    Left _ -> traceError "unexpected datum"
    Right (Datum d) -> do
        let parsedDatum = PlutusTx.fromBuiltinData d :: Maybe UTxODatum
        case parsedDatum of
            Just s -> s
            _ -> traceError "Unknown datum type"


text:
To use state machine or not to use state machine? This is a question
Some validator scripts can be implemented with or without state machine. This is a decision that has to be made by the developer.
I wonder what are the pros and cons of using state machine. What factors should be considered when making the decision.

A state-machine gives you a framework for testing and reasoning about your code. It's generally much easier to think in terms of state machines where transactions are transitions, every transaction is one transition from one state into another, so knowing the initial conditions, you can think about what should be the outcome and test for it.
One "direct drawback" of representing things as state machine is that it forces you to include datums of both inputs you spent but also outputs you send to (since your validator must control the transition goes into the right state). There are cases where you may not want to reveal the datum upfront and obfuscating behind a hash is quite handy.
Another drawback is the maturity / usability of the current state machine framework in PlutusTx. Works well enough for simple scenarios but gets in the way of more complex cases and, adds a non negligible overhead. Yet, implementing a state-machine by hand is relatively easy.

Can you provide some example for "gets in the way of more complex cases"?


text:
Is it possible to upgrade a State Machine?
I wonder if it is possible to design a State Machine that has a special state transition that can upgrade the State Machine, meaning creating a new UTxO sitting at a new script address (instead of the old script address), representing the upgraded State Machine. After the upgrade, future transactions will be validated using the new State Machine.
I am not sure if this upgrading functionality is achievable using State Machine. If so, how can it be achieved?

Make a statemachine with a transition "Update".
Use Constraints (or otherwise, eg check) to layout in which contexts an "Upgrade" is permissible. For example "must be signed by my special key".
Make the upgrade target state a final state (isFinal s == True)

Et voila. You have "upgraded" your statemachine.
Obvs cardano validators are immutable - you can't upgrade them in the "mutate a thing" way

Thanks! Your approach will finish the current validator. I think additionally the update transition has to explicitly guarantee the creation of an UTxO sitting on the updated validator, to ensure the updated validator will be available.


text:
setting up the PAB - could not start the plutus-chain-index
I'm trying to follow the lesson 6 of iteration 3 of the plutus-pioneer-program
when trying to start che chain index trough the command (fromn the plutus-apps repository)
plutus-chain-index --config ./plutus-pab/test-node/testnet/chain-index-config.json  --socket-path $CARDANO_NODE_SOCKET_PATH start-index

the following error raises
plutus-chain-index: user error (autoMigrate: Not performing automatic migration due to data loss)

I'm assuming is unable to find the database, so I also tried to specify the cardano-node db folder but the following error is raised
plutus-chain-index: SQLite3 returned ErrorCan'tOpen while attempting to perform open "<cardano-node db folder>": unable to open database file

so I tried ot specify a brand new path, but got
plutus-chain-index: SQLite3 returned ErrorCan'tOpen while attempting to perform open "./tmp/chain-index.db": unable to open database file

does anyone knows how to correctly start the chain index?


text:
Can temporary forking occur in Cardano's protocol?
In Bitcoin's protocol (and similar PoW systems), at one point chain might temporarily split in two and two different chains will be maintained up until one outpaces the other and proves itself as the correct one.
I thought this phenomena is not possible in Cardano since for every slot a delegator is already selected beforehand so we theoretically know from which validator/delegator to expect new block i.e. we cannot have two validators creating the same block for the slot. This is what I thought up until watching a video by Cardano's chief scientist who made be doubt my premise (https://youtu.be/nB6eDbnkAk8?t=1563).
I would love to know if I am getting something wrong? From the video it seems he is explaining the scenario that I thought cannot even happen in Cardano's protocol.

That's incorrect. The ouroboros praos protocol is based on random distribution, and there's still a low probability of multiple pools being assigned the same slot. With as many slots as there are, even with a low probability this still happens fairly regularly. Furthermore you can not have a collision on the exact slot and not have consensus with the next pool and have a fork because a pool after yours made a block without yours in the chain. The security window is 3k/f which is the largest a chain can ever rollback which is 36 hours on Cardano mainnet.

Cardano is a permissionless public blockchain with a fully dynamic validator set, which means that the validators/miners can join/leave the network at any time. Much like Bitcoin and Ethereum, this means that anyone can join and contribute to block production. However, this also means that it is possible for honest parties to propose multiple valid chain extensions, thus creating a fork. The network must then employ some kind of chain-selection rule to eventually converge on a canonical chain.
Cardano can have two validators creating the same block for the same slot, even though the leadership scheduled is (privately) known. Such temporary (a.k.a. "shallow") forking is healthy and natural behavior for permissionless systems with probabilistic finality, like Bitcoin, Ethereum, or Cardano. In such systems, security guarantees are probabilistic in nature - the deeper a given block is from the current local height, the higher the probability of that block being on the canonical chain.


text:
Using custom datum for `mustPayToOtherScript` in off-chain code
Lets say I on-chain i have a Datum like so:
data RandomDatum = RandomDatum {
   { tn :: !TokenName
   , cs :: !CurrencySymbol
   , nn :: !Integer
   } deriving (Show)

Off chain I'm trying to form and submit transaction with:
...
let dat = RandomDatum {
       tn = ""
     , cs = ""
     , nn = 1
    }
    constraints = Constraints.mustPayToOtherScript vh dat val

ledgerTx <- submitTxConstraintsWith lookups constraints

But my compilation always fails, because dat is not of type Datum.
I have also tried:
constraints = Constraints.mustPayToOtherScript vh (Datum $ PlutusTx.toBuiltinData dat) val

Question
How could I convert RandomDatum imported from my on-chain code file?

I dig more into this and now I think it doesn't work because PlutusTx.unstableMakeIsDatafails to generate required instances for FromData

Problem was I didn't provide correct type to submitTxConstraintsWith call.
If this was code from Plutus Pioneer Program week one where there is a definition:
data Auctioning
instance Scripts.ValidatorTypes Auctioning where
    type instance RedeemerType Auctioning = AuctionAction
    type instance DatumType Auctioning = AuctionDatum

Call should look like this:
ledgerTx <- submitTxConstraintsWith @Auctioning lookups constraints

Also datum needs deriving (Show, Generic, ToJSON, FromJSON) for serialization
data RandomDatum = RandomDatum {
   { tn :: !TokenName
   , cs :: !CurrencySymbol
   , nn :: !Integer
   } deriving (Show, Generic, ToJSON, FromJSON)

As far as I know your datum types are required to conform the Data type.
Try:
PlutusTx.makeIsDataIndexed ''RandomDatum [ ('RandomDatum, 0) ]

{...}
let randomDatum = RandomDatum { ...params... }
    tx          = mustPayToTheScript randomDatum $ Ada.lovelaceValueOf amount
{...}

Maybe I'm missing some Haskell Language pragma which is required for this? What pragrams are required for this? I do have PlutusTx.makeIsDataIndexed in separate on-chain code file but I still get this error.

@KugisMugis In that case, can you post complete on chain and off chain code?


text:
PlutusData construction using @emurgo cardano-serialization-lib-browser
I have a JSON format needed for PlutusData serialization (but the format is not a standard datum in a list). The datum is wrapped in Maybe monad, so you'll note the nested lists (an array inside the outermost fields).
{
  "fields": [
    {
      "fields": [
        { "bytes": "581ccb9fba6103382ffac26484e35af190bc885510f6a25ee3dbdc673bea" }
      ],
      "constructor": 0
    }
  ],
  "constructor": 0
}

The inner bytes are CBOR hex of a sample pubkeyhash. We know that to construct the inner datum we'd do:
const datumPkh = PlutusData.from_bytes(pkhCBORBytes);

to insert that in a list is also trivial:
const innerList = PlutusList.new()
innerList.add(datumPkh)

However, since we cannot add a PlutusList to a PlutusList, would we convert the innerList to bytes and read those bytes into a PlutusDatum like:
const outerList = PlutusList.new()
outerList.add(PlutusData.from_bytes(innerList.to_bytes()))

Or, should we do something else like a ConstrData's value to_bytes() and then a PlutusList.from_bytes...etc.?
We know we can't tell if the end results are the same from the hashes of the data in cardano-cli and the serialization lib as noted in: https://github.com/Emurgo/cardano-serialization-lib/issues/333 and https://github.com/Emurgo/cardano-serialization-lib/issues/247

Maybe this will help,
typhonjs supports creating plutusDataCbor using utility method
const plutusDataBuffer = typhonjs.utils.createPlutusDataCbor({
    constructor: 0,
    fields: [12, 12],
});

const plutusDataCBOR = plutusDataBuffer.toString('hex');

You can pass in whole JSON object to generate plutusData.

Doesn't seem to like the structure of:
{
"fields": [
{
"fields": [ CBORBytesOfPkh ],
"constructor": 0
}
],
"constructor": 0
}

Mehul was correct. @strictahq/typhonjs does work correctly and produces the same result as
cardano-cli transaction hash-script-data --script-data-file test.json
Where test.json contents are:
{ "fields": [{ "fields": [{ "bytes": "cb9fba6103382ffac26484e35af190bc885510f6a25ee3dbdc673bea" }], "constructor": 0 }], "constructor": 0 }

and JS content
import { utils } from '@stricahq/typhonjs';
import { Buffer } from 'buffer';
import { PlutusData, hash_plutus_data } from "@emurgo/cardano-serialization-lib-browser"
const pkh = Buffer.from(await getPubKeyHash());
const datum = utils.createPlutusDataCbor({
  fields: [{ fields: [pkh], constructor: 0 }],
  constructor: 0,
});
const plutusDatum = PlutusData.from_bytes(datum);
const datumHash = hash_plutus_data(data);
console.log(Buffer.from(datumHash.to_bytes()).toString('hex'))

We are still trying to determine if that pkh needs to be CBOR encoded first, but that is secondary now that the structure works and produces the same hashes.


text:
how i send cardano native tokens from one wallet to another in unity?
I need little help from you guys.  how can I send Cardano native tokens from one wallet to another in unity?

Heres two links that might help. Blockfrost dotnet SDK: https://github.com/blockfrost/blockfrost-dotnet and how to import external dotnet libs as Plugins in Unity: https://docs.unity3d.com/Manual/Plugins.html (haven't tried it myself yet though)

Maybe start with the blockfrost APIs. Unity should have a simple way to call external APIs.
Main site https://blockfrost.io/
Docs https://blockfrost.dev/


text:
How to make the ThreadToken for a StateMachine available to and verifiable by every participant?
In a StateMachine, TreadToken can be used for uniquely identifying the "genuine" UTxO sitting at the validator script of the StateMachine. A TreadToken is automatically created when the StateMachine is created by the first participant (wallet).
My question is how the other participants (wallets) can get the ThreadToken created for the StateMachine? Besides, when a participant somehow receives a ThreadToken, how can he/she verify that the received the TreadToken received is authentic?

They have to check that the state token is minted with the default minting policy.
The default minting policy and SM validator are coupled so that if this is verifiable, then all is well.

A TreadToken is automatically created when the StateMachine is created by the first participant (wallet).

Not necessarily. You can "Start" a SM by sending a UTXO to an address that corresponds to a SM. This is precisely why you might want to verify that the the thread token is an NFT.
If the default minting policy is not used then they'll need to do more homework. Again this might be fine. It might not.
It's possible to replace the default minting policy with a non-parameterized minting policy that shoe horns the uniqueness into the token name only.
In this case it would be much easier for a user to verify uniqueness, provided a trusted source has already verified "This CS will only make NFTs"
(policyId is a synonym for currency symbol)
An aside. It might also be desirable that the thread tokens aren't NFTs.
More generally, there are many ways you might want to modify the implementation of statemachine as available in Plutus. Its just one way to do it.

Thanks. But is it possible to derive the currency symbol of the default thread token from its state machine?


text:
How can I code a liquidity pool?
I am really interested in how i can code a liquidity pool using Plutus.
What are the mechanics & the components I need to handle? Is there a specific pattern, skeleton to follow?

I think a good starting point are the following links bc the question is fairly broad. Perhaps also take a look at existing Dexes that (plan to) open source their code.

https://www.youtube.com/watch?v=CPfcyDaDtt8
https://plutus-pioneer-program.readthedocs.io/en/latest/pioneer/week10.html


text:
How to achieve a minting policy script that locks after certain number of images (assets) have been minted on the fly
Let's say I want to run an NFT campaign, where the minting policy only allows minting of 100 NFTs (each one is different), and then the policy should lock.
If this minting policy were a Plutus script, I'm assuming I would need to pass in a parameter holding the current mintCount and then the validation would test if the mintCount is less than the limit.
That seems simple enough, but I'm assuming this relies on the off-chain code obtaining an accurate count of total mints under the policy for the parameter input and serializing access to the transaction minting process (i.e., avoid running minting transactions in parallel).  Is this correct?
Suppose this minting policy should lock because the max number of NFTs have been reached, but the off-chain code screws up and passes in a mintCount parameter that allows more minting to occur.  Is there some way to write a script that locks for good, once a previous transaction has failed?
Besides passing in a mintCount, are there other strategies for enforcing a minting policy that locks after a certain number of NFTs has been reached?  Instead of on-the-fly minting, is there some strategy of minting NFTs up-front that could achieve a certain max count?

You could use a combination of a plutus validator script with a specific datum and a minting policy.
The minting policy just checks for the validator script has ran.
And the validator script checks the datum's counter to be increased correctly and it fails when your max number has been passed, see other related question below.
Collection Uniqueness using Counter as asset name


text:
Why do we need the ```plutus-chain-index``` to run and why does it take so long to sync
I'm trying to set up a PAB in order to test my contracts
Currently I have:

fully synced a cardano-node running on testnet
fully synced cardano-wallet tracking one wallet
a plutus-chain-index syncing at an absurd slow rate
a pab instance that displays
[pab:Info:1] [2022-04-11 14:07:59.27 UTC] Restoring PAB state ...
[pab:Info:1] [2022-04-11 14:07:59.27 UTC] No contract instance were restored in the
PAB state.
[pab:Info:1] [2022-04-11 14:07:59.27 UTC] Starting PAB backend server on port 9080

and connecting to that instance, for example trying
http:localhost:9080/swagger/swagger-ui

does not works the first hours but it does after at least 5 hours, even if the chain-index syncing sits at 0.76% after all that time.
my questions are

Why do we even need a plutus-chain-index instance running if it is ok at 0.76%
How can I get more information on when the PAB is ready?

Where is the progress of chain index now? I have trouble to sync too. I opened an issue here: https://github.com/input-output-hk/plutus-apps/issues/429

The chain index provides data such as datums and utxo values.
Its data from the chain but organized in a way that's more convenient and faster to query than is possible with the node directly.
It's intended to be a 'db-sync-lite'.

You can run with --verbose flag. But it will dump a lot of stuff out.
You should also be able to hit localhost:9083/swagger/swagger-ui (provided you are using the default config).

They've been numerous problems with the chain index, with many being fixed recently. I recommended taking the latest version if you aren't already.


text:
Is it possible to generate all stake pool files and keys using Cardano Serialization Lib?
To successfully create and register a stake pool, we are require to generate:

Payment keys and address
Stake keys and address
Stake pool cold key
Stake pool hot key
Stake pool VRF key
Stake pool operational certificate

We can do all this using cardano-cli.
Is it possible to do it using https://github.com/Emurgo/cardano-serialization-lib as well?

No, it's not possible at the moment.
I have found this commit of the cardano-multiplatform-lib that starts giving some support for these kind of tasks related to generating different types of certificates (stake pool ones included):
https://github.com/dcSpark/cardano-multiplatform-lib/commit/d9ec0ce32136deda2a497dd1c04e6dce8932ba5a
The PR is in progress yet. We will need to wait a little more for dcSpark team, in order to have full support for this feature.
In the meanwhile, I suggest using cardanocli-js to generate stake pool certificates.
Like this:
const CardanocliJs = require("cardanocli-js");

const shelleyGenesisPath = "/path/to/your/testnet-shelley-genesis.json";
const options = {
  shelleyGenesisPath,
  network: "testnet-magic 1097911063"
};

const cardanocliJs = new CardanocliJs(options);

const nodeKeyGenKES = cardanocliJs.nodeKeyGenKES(stakePoolName);
const nodeKeyGen = cardanocliJs.nodeKeyGen(stakePoolName);
const nodeOperationalCert = cardanocliJs.nodeIssueOpCert(stakePoolName);
const vrfKeyAccount = cardanocliJs.nodeKeyGenVRF(stakePoolName);

Check out this link about generating keys:
https://developers.cardano.org/docs/get-started/cardano-serialization-lib/generating-keys


text:
Listening for rollbacks
How can you listen for all chain rollbacks? For example every time there is a rollback, based on the depth, I'd like to take some action on my app's backend. Is there any API that could enable this?


text:
How is metadata typed on the blockchain
I am reading through the haddock documentation to find the way metadata is attached to a transaction. In this documentation (1) we have
data Blockchain = [Block]
data Block = [OnChainTx]

Where

and

Now my question is, where and how is metadata appended? My guess is that the only place it could be is in the txData field. And if so, take the example of NFT metadata. By CIP 25 it is of a certain JSON format. Is this than converted via JSON -> data -> BuiltinData and finally wrapped in the Datum type?

I think it just not possible to retrieve metadata from the transaction info that is server into a validator script. Perhaps in the future :)

Also see https://cardano.stackexchange.com/questions/2093/append-metadata-to-transaction-from-plutus-code

The transaction metadata lives outside of the transaction body, inside of the auxiliary_data. In the Babbage ledger era, you can see this in the wire spec (CDDL)
here
In particular, the metadata is defined
here.
In Haskell, you can see that the metadata is
defined
as a map from Word64 to Metadatum.
(I've chosen the Alonzo auxiliary data type to link to here, which is re-used by the Babbage era).
And Metadatum is the JSON-like structure defined
here.

Note that the transaction metadata is a different type than the Datum type used by Plutus, though the structure is nearly identical. (txData contains Datum, not Metadatum.)

CIP-25 is provides a schema for expressing NFT Metadata within the transaction metadata. So in particular, it specifies using the number 721 as the transaction metadatum label ( a reference to the Ethereum NFT standard ERC-721 ), and proceeds to specify the rest of the structure. The cardano-cli is capable of converting JSON metadata files into the correct wire format, and attaching it to a transaction (with the hash in the transaction body, so that it cannot be corrupted).


text:
Collateral Address for react app
how I can get users collateral address from wallet?
I am using nft-maker-pro for creating a small NFT market place. I need collateral address for that like https://d-wallet-playground.yellowhouse.gmbh/wallet this.

I am not familiar with the tool but the collateral is usually provided by whoever is creating the transaction to be submitted. And as long as a smart contract isn't being run and fails during validation your collateral is save.
So if you use a light wallet like nami send yourself 5-10 ADA and use that as collateral.

Is there any way to get that address?

It's your own wallet address. You can just copy it when you have Nami installed and setup.

According to CIP-30
"api.getCollateral()"
so you can get it in your react application by using:
const api = await window.cardano[WALLET-NAME].enable()
const changeAddress = await api.getCollateral()

The easiest way to get a collateral UTXO is to use a library like Helios which is both an on-chain smart contract Plutus compiler and an off-chain transaction builder.   Helios has some convenience wrappers/helpers for working with CIP30 spec so you don’t have to do the CBOR conversions for example.
Here is the code.

    // Determine the UTXO used for collateral
    const colatUtxo = await walletHelper.pickCollateral();

    tx.addCollateral(colatUtxo);

Or if you need the change wallet address, you can use.
// Get change address
const changeAddr = await walletHelper.changeAddress;

Check out the full source code here in my Helios examples repo:  https://github.com/lley154/helios-examples/blob/main/nft/pages/index.tsx


text:
Error message harvesting in the minswap farm
I have liquidity pairs on app.minswap.org. I have 5 ada as collateral. I am trying to harvest rewards in the farm. I get this error message: Unexpected error value: "Not enough ADA leftover to include non-ADA assets in a change address"
I am using the nami wallet.
Not sure what I can do to remedy this issue. Thanks

I have the same problem as mentioned above.
I could not withdraw or migrate from ADA-MIN Farm. Always receiving: " Failure Notice: Need additional 5000000 lovelace but only 2939420 lovelace is available to choose." I have put addionial >100 ADA in attached Nami wallet but still the same problem. No clue, what do do anymore.. any help is very welcome! :-)

Native assets normally need to be sent along with 1 or 2 ADA ie can not be sent just on their own.
Check the MinSwap docs for minimum requirements when harvesting:
https://docs.minswap.org/yield-farming

Any change that's left over needs to be at least 1 ADA - if the change contains native assets then it's even more.
To solve the problem, just fund your wallet with an additional 10 ADA to be save and you should be able to harvest your minswap yields.
If you wanna get into details take a look at this:
https://docs.cardano.org/native-tokens/minimum-ada-value-requirement

Thanks, adding 50 ADA worked. I was able to harvest.

Would appreciate if you can mark my comment as answer with the checkmark then


text:
Multi-signature time-locking script
I am trying to create a multi-signature time locking script similar to this example. I want to lock assets into a script to be released at a later date.
{
    "type": "all",
    "scripts": [
        {
            "type": "after",
            "slot": 55596400
        },
        {
            "type": "sig",
            "keyHash": "..."
        }
    ]
}

According to the docs linked above, I have to add the --invalid-before [slot] argument, where slot is greater than or equal to the value specified in my script (55596400 in my example). By doing that, I cannot submit the transaction until that slot number.
I was hoping to be able to lock the assets into a script address that could then be redeemed by the holder of the key specified in the script after the given slot. So my questions are:

Is that not possible with a multisig script?
If not, what is the purpose of a time-locked multisig script? I guess I could give the assembled transaction with the needed witness off-chain, but then nothing prevents me from spending the assets before the given slot.
Is there a way to do what I'm wanting to do?

It is possible
The script used in the above example is used to construct an address from which funds UTXOs can only be used if they follow the logic specified by the script.
Looks like you've already done it! Just continue following the instructions in your linked example for creating and funding the script address. Be sure to test with a round trip before committing any large funds!

Thank you! I was running into an error that looked exactly like this https://forum.cardano.org/t/transaction-submit-error-on-testnet-for-time-locked-policy-script/57449 and got off the path. I was just witnessing with the wrong key. :( I appreciate you confirming that what I was wanting to do is possible and for pointing me in the right direction.


text:
Emulator trace throws `BuiltinEvaluationFailure of UnIData` error with simple minting policy
Source
https://github.com/tomazvila/plutus_minting_test
Problem
Running smart contract with simple minting use case fails to mint.
Error
Slot 00001: *** CONTRACT STOPPED WITH ERROR: "\"WalletContractError (ValidationError (ScriptFailure (EvaluationError [] \\\"BuiltinEvaluationFailure of UnIData\\\")))\""

Setup
cardano_node@demoserver:~/coreapp_testing/new_repo$ uname -a
Linux demoserver 5.4.0-100-generic #113-Ubuntu SMP Thu Feb 3 18:43:29 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux
cardano_node@demoserver:~/coreapp_testing/new_repo$ cabal --version
cabal-install version 3.6.2.0
compiled using version 3.6.2.0 of the Cabal library
cardano_node@demoserver:~/coreapp_testing/new_repo$ ghc --version
The Glorious Glasgow Haskell Compilation System, version 8.10.7

How to run
cardano run trace

Problem was that Minting script is expecting Integer as a redeemer:
mkPolicy :: TxOutRef -> Integer -> ScriptContext -> Bool
mkPolicy utxo _ ctx = validate

And off-chain code with:
TxConstraints.mustMintValueWithRedeemer unitRedeemer val

call passes unitRedeemer. Validator tries to deconstruct unitRedeemer to Integer and throws an error.
Bonus: Constraint.mustMintValue passes unitRedeemer by default


text:
How to use plutus script withness in other plutus script
How can we reference the use of other scripts in a plutus validator?. Wat I was trying to making is an validator that only validates if an other predetermined plutus scripts also validates in the same transaction. What I tried is the following naive implementation with a type problem
{-# LANGUAGE DataKinds           #-}
{-# LANGUAGE MultiParamTypeClasses      #-}
{-# LANGUAGE DeriveAnyClass      #-}
{-# LANGUAGE DeriveGeneric       #-}
{-# LANGUAGE FlexibleContexts    #-}
{-# LANGUAGE NoImplicitPrelude   #-}
{-# LANGUAGE OverloadedStrings   #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell     #-}
{-# LANGUAGE TypeApplications    #-}
{-# LANGUAGE TypeFamilies        #-}
{-# LANGUAGE TypeOperators       #-}

{-# OPTIONS_GHC -fno-warn-unused-imports #-}

module Onchain where

import           Control.Monad        hiding (fmap)
import           Data.Aeson           (ToJSON, FromJSON)
import           Data.Map             as Map
import           Data.Text            (Text)
import           Data.Void            (Void)
import           GHC.Generics         (Generic)
import           Plutus.Contract
import           PlutusTx             (Data (..))
import qualified PlutusTx
import           PlutusTx.Prelude     hiding (Semigroup(..), unless)
import           Ledger               hiding (singleton)
import           Ledger.Constraints   (TxConstraints)
import qualified Ledger.Constraints   as Constraints
import qualified Ledger.Typed.Scripts as Scripts
import           Ledger.Ada           as Ada
import           Playground.Contract  (printJson, printSchemas, ensureKnownCurrencies, stage, ToSchema)
import           Playground.TH        (mkKnownCurrencies, mkSchemaDefinitions)
import           Playground.Types     (KnownCurrency (..))
import           Prelude              (IO, Semigroup (..), Show (..), String)
import           Text.Printf          (printf)

data MyDatum = MyDatum
    { pubKey :: Integer
    } deriving (Show, Generic, FromJSON, ToJSON, ToSchema)

data MyRedeemer = MyRedeemer
    { privKey :: Integer
    } deriving (Generic, FromJSON, ToJSON, ToSchema)

data ContractInfo = ContractInfo
    { contractValHash :: ValidatorHash }

contractInfo = ContractInfo { contractValHash =  "67f33146617a5e61936081db3b2117cbf59bd2123748f58ac9678656"}

PlutusTx.makeIsDataIndexed ''MyDatum [('MyDatum, 0)]
PlutusTx.makeLift ''MyDatum
PlutusTx.makeIsDataIndexed ''MyRedeemer [('MyRedeemer, 0)]
PlutusTx.makeLift ''MyRedeemer
PlutusTx.makeLift ''ContractInfo

{-# INLINABLE mkValidator #-}
mkValidator :: ContractInfo -> MyDatum -> MyRedeemer -> ScriptContext -> Bool
mkValidator contractInfo _ _ ctx = traceIfFalse "Signature not there" $ signed
        where
              info :: TxInfo
              info = scriptContextTxInfo ctx

              sigs :: [PubKeyHash]
              sigs = txInfoSignatories info

              pubkeyHash :: ValidatorHash
              pubkeyHash = contractValHash contractInfo

              signed :: Bool
              signed = pubkeyHash `elem` sigs -- THIS IS NOT WELL TYPED AND WILL NOT COMPILE SINCE pubkeyHash is actually of type ValidatorHash.

{-# INLINABLE mkValidator2 #-}
mkValidator2 :: BuiltinData -> BuiltinData -> BuiltinData -> ()
mkValidator2 _ _ _ = ()

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

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

validator2 :: Validator
validator2 = mkValidatorScript $$(PlutusTx.compile [|| mkValidator2 ||])

validator :: Validator
validator = Scripts.validatorScript typedValidator

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

scrAddress :: Ledger.Address
scrAddress = scriptAddress validator

scrAddress2 :: Ledger.Address
scrAddress2 = scriptAddress validator2

Where 67f33146617a5e61936081db3b2117cbf59bd2123748f58ac9678656 is the ValidatorHash of the validator2 derived from printing scrAddress2. So the first validator mkValidator will validate only if the transaction also contains a validating consumption of an UTxO at the validator2 address? Now of course this will not validate since a validatorHash is not contained in the signature list of type txInfoSignatories :: [PubKeyHash]. But still this would be desirable to have right? I could use this with some minting policy.
On testnet I tried changing the type of contractValHash to PubKeyHash, but this does not work either since scripts have no signatures in the txInfoSignatories field.

Is it perhaps possible to access the TxInType field?

This contains a reference to a script validator (but not really in its compressed form, only in the lamba calculus form).

I just had to sleep a night on it. Obviously one can look at the incoming addresses and lookup the validatorhash in the credentials there. For example use
filter (\x -> (ScriptCredential . addressCredential . txOutAddress) x == ValHash) $ txInfoInputs ctx

to get the transaction input of that script you want present.


text:
What are the current options for spending a UTxO at a script address?
If the following script is protecting a UTxO
{
    "type": "all",
    "scripts": [
        {
            "type": "after",
            "slot": 1000
        },
        {
            "type": "sig",
            "keyHash": "..."
        }
    ]
}

and the slot has passed and I have the private key specified by the keyHash property, what are my options for spending a UTxO sitting at the script address?
I know that I can use cardano-cli to manually build a transaction that sends the UTxO to a wallet address I own, provide my key as a witness for the transaction and then submit it.
I am fine with doing this but are there any other "user friendly" options for spending this UTxO for users not wanting to use the cli?
I was hoping to find something that might allow me to tell my wallet about this script address and then have the wallet either track this address or build the transaction to "spend" the UTxO into a wallet address. I understand there could be difficulties around this for scripts requiring multiple signatures, etc. but am just looking for other currently available options.

To be user friendly, such features would have to be implemented in wallet software like Daedalus, Nami, Eternl, etc. In principle, there is no reason why this can't be done, in fact I'd imagine someone out there has already written some simple wrapper scripts that simplify the CLI workflow. However, for real user friendliness, we'd have to wait for someone with the right shovel to come along.

Thank you. That's what I figured but wanted to see if maybe I had missed something in my research. You have been very helpful in my Cardano journey and I really appreciate it.


text:
Different Data tyoes for datum
I have two main actions that user can do. They both require sending utxos to a script address. The datum I want produced by these two actions are different. I want one of the datum like this
data VotingDatum = VotingDatum
  { projectPubKey :: PaymentPubKeyHash
  , amount :: Integer
  , fund :: Integer
  , paymentPubKey :: PaymentPubKeyHash
  }deriving (Show)

and the other one like this.
data StartDatum = StartDatum
 { startFund :: Integer
 , fundPrize :: Integer
 }deriving (Show)

I was thinking of putting these two in a single data type like this
data ContractDatum = ContractDatum
 { voteDatum :: Maybe VotingDatum
 , startDatum :: Maybe StartDatum
 }

How would i set the value of these fields if i did it like this. Can i do it like this ?
I am currently setting the value of the types like this
start sp = do
    let dat = StartDatum
                { startFund = spFund sp
                , fundPrize = spAmount sp
                }

How can i have two different data types for the datum. How can i set the value of it , and how would i access the value of it.

You can combine the two like this
data DatumAction = VotingDatum | StartDatum

Then you can specify in you validator which case is used like this
mkValidator :: DatumAction -> redeemer -> ScriptContext -> Bool
mkValidator datumAction redeemer context = case datumAction of
    VotingDatum -> do something with type bool
    StartDatum  -> do something with type bool

Hope this helps, also see (1) and (2).

Yea , this is what i am looking for but I think i am missing something.It giving errors saying it couldn't match type StartDatum with type DatumAction and it couldnt match type VotingDatum with type Datum Action


text:
How to interpret complex transaction data on cardano blockchain
for many of you this may seem as a complete noob question, but I am as many new to this world and can need a hand with this question.
I am currently looking at some random transactions of some NFTs and I am interested to follow how the the funds moved and what was exchanged. I am currently looking at an complex example of inputs and outputs for this transaction:  0e8bea7ba9c1041d2561df7814be45d29a755d7bd0ea55127e0b92589fef50dd.
I know that one NFT (d5e6bf0500378d4f0da4e8dde6becec7621cd8cbf5cbb9b87013d4cc537061636542756432) was transferred with this transaction. But it seems like that there are also other assets transferred.
I am interested in getting to know what price was paid for this NFT for this transaction, but the input data throws me off... If there were multiple assets exchanged how can they all come from different input addresses, but end up in only two addresses in the output. Also can there be any conclusions drawn for the NFT price being made from the 3000000000 lovelace int the output?
For reference here the data that I look at currently. The data comes from Blockfrost's transaction endpoint
These are the inputs:
{'addr1q8drvrh7zd9xcenkkatr72zew7s4zxaexz3knm25nvk9sdwz08dtlwcmxp6k0z4peenj7a6px4mm84lqlwcnvsdg60ms7nqqqy': {'amount': [{'quantity': '1600000',
                                                                                'unit': 'lovelace'},
                                                                                {'quantity': '1',
                                                                                'unit': '16a2a21a7ed8a67c5254eda1f8d6041021b53f49ef53e18e3e572546456e7468656f7332353034303941'}]},
 'addr1q8dyg95ylje8ae95r2s2l5tyl0jtswnnpgc3h0j7e4e27pwz08dtlwcmxp6k0z4peenj7a6px4mm84lqlwcnvsdg60msq725nl': {'amount': [{'quantity': '1481480',
                                                                                'unit': 'lovelace'},
                                                                                {'quantity': '1',
                                                                                'unit': '1131301ad4b3cb7deaddbc8f03f77189082a5738c0167e177223309743617264616e6f4269747331383237'}]},
 'addr1q9cfmycakxay3y5qhn506eune2pa8z4ewm96w8a75gdkdqkz08dtlwcmxp6k0z4peenj7a6px4mm84lqlwcnvsdg60mscy0j02': {'amount': [{'quantity': '200850834540',
                                                                                'unit': 'lovelace'},
                                                                                {'quantity': '2535',
                                                                                'unit': 'cfee97ff8359f07a0a395a72b424bc6e030503390d864b86d4e0ecf84b41495a454e'},
                                                                                {'quantity': '1',
                                                                                'unit': 'd5e6bf0500378d4f0da4e8dde6becec7621cd8cbf5cbb9b87013d4cc537061636542756432'},
                                                                                {'quantity': '25',
                                                                                'unit': 'd894897411707efa755a76deb66d26dfd50593f2e70863e1661e98a07370616365636f696e73'}]},
 'addr1q9ec78mw889j7y8jj7lvh026mef78tv4x0qgvgnpwh0lym7z08dtlwcmxp6k0z4peenj7a6px4mm84lqlwcnvsdg60msg69x63': {'amount': [{'quantity': '1444443',
                                                                                'unit': 'lovelace'},
                                                                                {'quantity': '1',
                                                                                'unit': 'f0ff48bbb7bbe9d59a40f1ce90e9e9d0ff5002ec48f232b49ca0fb9a6e7963'}]},
 'addr1q9nmqf9tftv0ptvyshdeetchz7enqgu6m2v04gctgr62pgkz08dtlwcmxp6k0z4peenj7a6px4mm84lqlwcnvsdg60ms8yydm5': {'amount': [{'quantity': '1481480',
                                                                                'unit': 'lovelace'},
                                                                                {'quantity': '1',
                                                                                'unit': 'f0ff48bbb7bbe9d59a40f1ce90e9e9d0ff5002ec48f232b49ca0fb9a62616e6b746865756e62616e6b6564'}]},
 'addr1q9wt3x052yktn74ej03u4unst3lmzxywhac2kcjnqahzlm7z08dtlwcmxp6k0z4peenj7a6px4mm84lqlwcnvsdg60msla4g7q': {'amount': [{'quantity': '1500000',
                                                                                'unit': 'lovelace'},
                                                                                {'quantity': '330434765',
                                                                                'unit': '1dd1a7dde0e1e82761325ee5f4719d0d4b7c24dfba77d9bee01eed4b4d454f57'}]},
 'addr1qygw382y23qrk6w0rwpu5mecje4ej6eqhpqz2qsnphhnhfxz08dtlwcmxp6k0z4peenj7a6px4mm84lqlwcnvsdg60msug9lhc': {'amount': [{'quantity': '1444443',
                                                                                'unit': 'lovelace'},
                                                                                {'quantity': '1',
                                                                                'unit': 'f0ff48bbb7bbe9d59a40f1ce90e9e9d0ff5002ec48f232b49ca0fb9a6c6f6e646f6e'}]},
 'addr1qyh0p0lfwx4pu8yfvh6sz0rrrhhcxhlvz8dehrzp6njrk27z08dtlwcmxp6k0z4peenj7a6px4mm84lqlwcnvsdg60ms2krpxp': {'amount': [{'quantity': '1481480',
                                                                                'unit': 'lovelace'},
                                                                                {'quantity': '1',
                                                                                'unit': 'd5e6bf0500378d4f0da4e8dde6becec7621cd8cbf5cbb9b87013d4cc537061636542756436333930'}]}}

and these are the outputs:
{'addr1q8dyg95ylje8ae95r2s2l5tyl0jtswnnpgc3h0j7e4e27pwz08dtlwcmxp6k0z4peenj7a6px4mm84lqlwcnvsdg60msq725nl': {'amount': [{'quantity': '197857877370',
                                                                                'unit': 'lovelace'},
                                                                                {'quantity': '3148145',
                                                                                'unit': 'lovelace'},
                                                                                {'quantity': '1',
                                                                                'unit': '1131301ad4b3cb7deaddbc8f03f77189082a5738c0167e177223309743617264616e6f4269747331383237'},
                                                                                {'quantity': '1',
                                                                                'unit': '16a2a21a7ed8a67c5254eda1f8d6041021b53f49ef53e18e3e572546456e7468656f7332353034303941'},
                                                                                {'quantity': '330434765',
                                                                                'unit': '1dd1a7dde0e1e82761325ee5f4719d0d4b7c24dfba77d9bee01eed4b4d454f57'},
                                                                                {'quantity': '2535',
                                                                                'unit': 'cfee97ff8359f07a0a395a72b424bc6e030503390d864b86d4e0ecf84b41495a454e'},
                                                                                {'quantity': '1',
                                                                                'unit': 'd5e6bf0500378d4f0da4e8dde6becec7621cd8cbf5cbb9b87013d4cc537061636542756432'},
                                                                                {'quantity': '1',
                                                                                'unit': 'd5e6bf0500378d4f0da4e8dde6becec7621cd8cbf5cbb9b87013d4cc537061636542756436333930'},
                                                                                {'quantity': '25',
                                                                                'unit': 'd894897411707efa755a76deb66d26dfd50593f2e70863e1661e98a07370616365636f696e73'},
                                                                                {'quantity': '1',
                                                                                'unit': 'f0ff48bbb7bbe9d59a40f1ce90e9e9d0ff5002ec48f232b49ca0fb9a62616e6b746865756e62616e6b6564'},
                                                                                {'quantity': '1',
                                                                                'unit': 'f0ff48bbb7bbe9d59a40f1ce90e9e9d0ff5002ec48f232b49ca0fb9a6c6f6e646f6e'},
                                                                                {'quantity': '1',
                                                                                'unit': 'f0ff48bbb7bbe9d59a40f1ce90e9e9d0ff5002ec48f232b49ca0fb9a6e7963'}]},
 'addr1qyk5ncxm5d4x0gzwx8k63jev36a00a4yrelw2lrld42m9lxe3t9p2xq8fjyyn8e87aqg7tpajpdhpkyn8dhszr35kvvsgg0ml6': {'amount': [{'quantity': '3000000000',
                                                                                'unit': 'lovelace'}]}}

UTXO model allows for transactions with 1 to 1, 1 to n, n to 1, or n to n inputs to outputs. Additionally, many addresses can be (and often are) derived from the same set of master keys. This means your single wallet may contain multiple UTXOs sitting in multiple addresses, all controlled by you.

When you want to send assets, wallet software(s) will employ some kind of UTXO-selection algorithm to automatically select which UTXOs to use in the transaction, such that everything you want to send gets sent, without having to use every single UTXO in your wallet. Naturally, some of the assets in input UTXOs are still yours, and so they are sent back to the origin address or another "change" address in your wallet. This usually involves consolidating all of your "change" assets into a single UTXO that is sent back to you, appearing like any other tx-output.

Since we do not yet have standards in terms of DEXs and oracles, it is hard to tell what price was paid for an NFT just by looking at the inputs and outputs of a transaction. It may be possible to do this by analyzing the specific smart contract (assuming it is open source) that the transaction(s) interacted with, but this would be a more involved process that just querying one or two transaction IO's.

Perhaps someone else who is adept at analyzing specific smart contract utility can help out with this last part.

thanks a lot for this explanation! really appreciate it!


text:
cardano-wallet vs cardano-cli for an application
I'm creating an application and was trying to figure out whether to use cardano-wallet or cardano-cli for my product. I like the fact cardano-wallet has endpoints & is very easy to setup, although cardano-cli seems like it'll be great. My product will allow lots of users to create wallets & send & receive but I was hesitant to use cardano-wallet becuase someone once told me cardano-wallet is better for single users that want to manipulate their wallets, not for large enterprise applications.
Can someone with more experience chime in?

cardano-wallet is a framework built for high level control over cardano-cli, and (or some version of it) is the backend for wallet software like Daedalus, Yoroi, Eternl, etc. High level features include: automatic coin/UTXO selection, quick transaction workflow, easy wallet/key derivation, and most importantly, prepackaged endpoints to a running node.
cardano-cli provides a low level command interface with the node, which affords high modularity and customizability for enterprise applications.
So... which you decide to use depends on the nature and scale of your app. Perhaps a bit of both? :)

Thank you for this well detailed comment, I will probably be using both in the future, I didn't know that cardano-wallet interfaces with cardano-cli fully.

I would add a fence-sitting "it depends on your use case" and what your time line is.
The cli can be utilized to build Txs without secret information. Given that light wallets following CIP 30 disclose all available UTXOs and other necessary info (not wallet secrets obvs) to build Txs on the users behalf. Light wallets generally allow users to sign a Tx, even though they cannot build them. So if you want to deliver a usable product tomorrow, this is at least feasible.
The wallet, and to some extent the cli, have been designed for personal use in the sense that they need access to sensitive information. The wallet only operates with secret keys.
To use the cardano wallet, either you force users to host their own wallet in their own instance, or you run instances and they use your platform.
The former is a technical barrier, and the latter undermines blockchain.
How well does it scale to have hosted cardano-wallet as a service? No clue. Its trivially parallelized so its probably fine but i'm sure its not optimized for that use case.
(This has now been fixed but) For the cli, it used to require secret keys to build transactions here. Just reflective of this not being the focus of the design.
Other options: cardano-serialization-lib to build Txs in browser. There are a bunch of other nascent projects trying bridge this gap between "Technically feasible" and "Actually usable"

I see with cardano-cli in order to build a transaction I need a --signing-key-file once you sign the transaction as well, when creating wallets you need to store the --payment-verification-key-file & --signing-key-file. How can I avoid storing these on my cardano-node if I want to just use the cardano-cli for my service? Can I allow the user to keep these keys on their device & then sing them on the client side? Also would I be able to use cardano-addresses  to create recovery keys for these wallets created with cardano-cli?

My knowledge is now dated, but when I was trying to do this the logic was to build on your machine with cli, and sign on their machine. Nami (and others) have the capability of signing and submitting external Txs. They cannot however build or even verify.


text:
Cardano Core Node has high Tip Diff in gLiveView after upgrading node(s) to 1.34.1
After upgrading my nodes to 1.34.1, I noticed that the Tip Diff KPI in gLiveView began returning high 200+ results and the block propagation times increased by a couple seconds.  The relay nodes are running fine, no change in behavior.
In addition to the node upgrade, I did implement a firewall threat detection and blocking service called "SNORT" on my WAN.
I have attempted to reboot the nodes, but behavior remains.
Node version: 1.34.1
gLiveView version: 1.26
Overall, I feel that the relay and core nodes are operating fine but perhaps the issue is with gLiveView.
NOTE
The missed slot leader checks KPI did not change.  The value still show "favorable" data after upgrade just as it did before upgrade.
All help / information is very much appreciated.
Nick

my 1.34.1 tip diff is showing regular metrics.

How did you configure SNORT? Try to stop the service and see if kpi is returning back to normal.

If not

Switch back to cardano-node 1.33.0 and see if kpi is returning back to normal.

Hope it helps

Thanks for the suggestion.  I did temporarily stop the SNORT service, so we will see over the next few days if the KPI values return to normal.  Thanks again!

In troubleshooting this issue further, it appears that reinstalling gLiveView on all nodes has resolved the issue.  I will continue to monitor the core node for a couple days before confirming as solution.
NOTE I have restored the SNORT service on the WAN
Thanks

This issue has been resolved by reinstalling gLiveView to the latest version.  No issues are caused by the SNORT service on my firewall.
Thank you, Nick

nice to hear that


text:
Is there a way to validate a policy Id,and to check if a string is an actual policy id?
im trying to build something in cardano, and i want to check if policy id provided by the user is an actual policyid?
after research i found that blake2b_224 is used for hashing the policy id,is there away to validate that a string was blake2b_224 hashed

Depending on your usecase...
If you just need to know it exists, then you can scan the chain (db-sync, chain-index, blockfrost,...)
If you need to verify it against a minting policy, you'll obvs need access to that too and do the hashing like what KtoZ says. There are however resources listing currency symbols. (TBC, but) CardanoScan records and verifies native scripts (not plutus atm)

Beyond the length of the hash digest (28 bytes in this case), no. Unless you have the pre-image (that is, the raw policy script) in which case you can rehash it and compare.


text:
Understanding this transaction - why isn't it spending the full amount?
I'm doing some analysis on Db-sync and I came across a situation where it appeared the full EUTXO at an address was not being spent so wanted to see what I was misunderstanding.
Here is the first transaction:
https://cardanoscan.io/transaction/23141e4c6fed6114dc77f5e7d1bd6e115d983e5704dd2206b0af3a41fe924c2b
Notice there are 2 amounts going to the address ending in 3d for 6.4 Ada and 118k Ada.
Now look at what I believe to be the only transaction that consumes the EUTXO at this address.
https://cardanoscan.io/transaction/10beefe48f417f3fdb9d164da95adf78e9efaf22f24c0a24893b68fe8e322f68
I can see the 6.4 Ada being spent but not the 118k. They do have different 'index' fields in db-Sync so is that why? i.e. it's not all the Ada at one address that gets sent, but only enough indexes as needed?
-- Edit --
Just to add clarity:
a) The first transaction has two amounts going back to the same user. This I presume means it's getting back two separate EUTXOs - one containing additional tokens, and the other just Ada.
b) When I look for these transaction outputs in DbSync (tx_out table) the only way I can identify them as separate EUTXOs is if I treat Address + Transaction ID + Index as the unique ID
c) Therefore is it fair to say that when making a transaction the wallet treats everything with a unique Address + Transaction ID + Index as a separate EUTXO, and this is why the wallet did not need to consume the 118k EUTXO from the first transaction?

I think there might be a misunderstanding in the fact that a transaction has several "outputs" - and those outputs are called "UTXO"'s (as long as they are unspent; hence "unspent transaction outputs") - and those can be spent separately.
So one of the UTXOs created by your first transaction holds only Ada (~118k). That output is not used in the second transaction your linking to, though.
Regarding the edit, you can identify any tx output or utxo by "transaction id" + "output index".
The ~118k Ada UTXO for example is still sitting at output index 2 of the transaction 23141e4c6fed6114dc77f5e7d1bd6e115d983e5704dd2206b0af3a41fe924c2b - ready to be spent.

In the first transaction (starting with 23141), there is a single input UTXO with three outputs - the first output (4.5 ADA) going to a non-staking address, the second and third outputs are going back to the sender's address, likely as change.

The second transaction (starting with 10beef) has three inputs and three outputs. The first two inputs are from the sender, and the third input is from a different address, likely a script address. The first output is to the same non-staking address as the first output in the first (above) TX, and the last two outputs are again going back to the sender.

UTXOs are always consumed in whole when used as inputs. The confusion may have been in the fact that the majority of the contents in both transactions go back to the same address, but they do so in the form of new UTXOs. In this case, a lot of ADA and other tokens were all sitting in a single UTXO, so when the user ordered the swap, the entire UTXO was consumed and most of its contents were returned back as change in a new UTXO. Whatever assets were required for the swap were output as separate UTXOs.

Thanks for this. See Edit I've made to my question and see if you agree.

Put more simply, the 118k UTXO was not consumed because none of its contents were needed for the transaction.


text:
Question about Yoroi and Ledger (restore security)
I'm writing today because I have read some issues about Yoroi in the reddit of Cardano. It seems that many people have problems when they want to restore their account. Some of them have lost their ada so I prefer to discuss the matter here !
(here is the link of the reddit's discussion : https://www.reddit.com/r/cardano/comments/tzx29t/hardware_wallet_derivation_path_problem_already )
Currently, I have a Yoroi account which was, when I created it a simple yoroi account (thus, it gave me a seed phrase). But after I have bought a ledger S and so I decided to link this ledger to my yoroi account.
Now, when I connect to my yoroi account I see that I have a "Yoroi-Ledger" (I've put a picture so that you can see).
But the question I'm asking is :
When you add a nano S to an existing yoroi wallet, is the security the same than if you start a brand new yoroi wallet to integrate with the ledger nano S at the beginning?
And if yes what is the procedure to restore it?

There is no clear answer on this subject to I thank you in advance for your help !
Have a great day !

Ledger uses a different derivation path than the default Icarus derivation used by hot wallets like Yoroi and Daedalus. This means that entering the seed phrase you generated on a hardware wallet directly into a hot wallet (like Yoroi) will result in a different wallet being generated/restored than the one on the ledger.
In practice, this means it is probably a good idea to have an extra "backup" ledger device in case the primary one fails and you need quick access to your assets. However, if (worst case scenario) Ledger the company drops off the face of the earth, it isn't too much of a problem. At the end of the day, many many people use Ledger, so someone will automate Ledger's derivation path and make wallet recovery without the device easier.

all right, thank you for your answer and your time, I appreciate !
So in your opinion there is no major risk at this time?
The question I have is also if my computer is broken, I have a new one, I have to download Yoroi again, how can I set up my old account on the new yoroi extansion? Because I see a good number of people who don't succeed in having back their old account because there is no seed phrase.
I start to understand that the ADA are in my ledger so not at risk but without Yoroi account I have no interface to see or use them.
Thank you again, it is great to discuss !

Put it this way: your seed is your ADA, and your seed is on the ledger. So, your ledger is your ADA. If your computer breaks, you can restore your wallet using your ledger device. To restore the wallet in Yoroi, simply select the "Connect to Hardware Wallet" option. Always do a dry run (testnet or small funds on mainnet) if you are unsure about anything.

Okay thank you for your answer !
It can seem strange for you but in fact I'm scared that my Ada are currently in my Yoroi Account and not on my ledger.
Indeed, I have seen lots of people talking about bug on Yoroi (it seems that this app is not liked by the community..) and they did not succeed in find their account again after deleting the app.
It is hard to visualize where are your coins sometimes and when you see some bug with the app you start panicking !

On Yoroi, it says "wallet ledger" so I believe that they are on my ledger.. It would have been great to be able to see on ledger live the exact amount on my key but I can't !


text:
How to get assets with a specifc policy id from a wallet address using BlockFrost OpenAPI
For context, I'm trying to get all NFTs with a policy id, but only from a wallet address. I'm using BlockFrost OpenAPI, and it seems that I can only get assets with a policy id from the entire blockchain?? Using this url : 'https://cardano-mainnet.blockfrost.io/api/v0/assets/policy/{policy_id}'
I tried to filter the assets from this url response : https://cardano-mainnet.blockfrost.io/api/v0/accounts/{stake_address}/addresses/assets
but I only can get 100 assets per page, and I get no info about how much page there is. They explicitly says on the doc that the count is from 0 to 100.

You could do something like:
let assets = [];
let final = false;
let page = 1;

while (final !== true) {
  const req = await get_function(url, page);
  assets = [...assets, ...req.data];
  page++;
  if (req.data.length < 100) {
    final = true;
  }
}


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

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

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

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

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

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

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


text:
How to use Plutus chain index with real testnet
I would like to use Plutus API for getting script datum (datumFromHash) but how to setup and run Plutus chain index on testnet or main net?
I saw there are methods in Plutus.ChainIndex.Types.

The easiest way is to use this tool to run everything you need: https://github.com/input-output-hk/plutus-apps/tree/main/plutus-pab-executables/pab-cli. You probably don't need the PAB or wallet backend, so for just a node and chain-index you can run e.g. pab-cli testnet remotewallet

Thank you. I got the point. One more question. Could you please give a hint how to use/deploy contracts in the case of full usage of PAB( node & chain index in my case.
I want to sign on client side !

Not easy to summarise. Best to look at examples such as the integration test, see https://github.com/input-output-hk/plutus-apps/tree/main/plutus-pab-executables/examples


text:
How to determine the number of actual "transactions" in a transaction?
You may have seen some of the online discussions on Twitter about Cardano TPS (Transactions Per Second) count. It lead me down the rabbit hole of trying to see if I could calculate TPS more accurately. I have listed my findings below but want to get them vetted.
Assumption: A true "transaction" refers to the transfer of value between one person and the next. We will exclude native assets from this for the time being.
Cardano allows for a many to many relationship. Many addresses sending to many addresses. In the Bitcoin world this is known as cojoining or mixing. It is pretty normal to see inputs coming from more than one address on the Cardano blockchain.
There appears to be no easy / clear cut way to calculate TPS but there are the following rules of thumb:

Exclude any UTxOs that were consumed an hour of being created - see
early spend on page 8 to understand why.
You then have to determine which of the UTxOs are "change outputs". In the case of 1 input to many outputs, this can be determined fairly easily. However in the case of multiple inputs from different addresses going to multiple output addresses this seems impossible. It seems that Cardano is set up like a coin mixer in this regard.

Do you agree, and any ideas / suggestions?

I think that you are mixing a couple of concepts here.
In Cardano, same as Bitcoin, a transaction can take various inputs (consume UTxOs) and produce various outputs (new UTxOs to be used by future transactions).
This means I can transfer tokens to 20 different people in the same transaction and that does not mean that I am creating 20 transactions. I will only get one transaction hash (you can check this in any explorer, such as Cardanoscan). So, for TPS, that will count as one, not 20, because the TPS concept is related to the validation of the transaction on chain and not to how many UTxOs you are consuming to create it.
So, under this scenario and with the assumption you have, I think you will find it quite hard (not to say impossible) to determine how many of those UTxOs are really going to one person to another (you will have to know, for example, if one of the output addresses does not belong to the sender of the transaction - maybe they have another wallet? - so you can exclude that one as well). If that wallet does not belong to an SPO or someone publicly exposed, then this won't be possible.

You reminded me I actually answered my own question after I asked this, on my blog: https://reddspark.blog/2022/12/11/transactions-within-transactions/

Here is the final answer I went with
https://reddspark.blog/2022/12/11/transactions-within-transactions/
Open to critique.


text:
How to generate stake registration certificate from extended stake address verification key using cardano-cli
Is there a way for cardano-cli to generate stake registration certificate using the extended stake address verification key (stake_xvk) that was generated from cardano-address CLI?
Steps to generate extended stake address verification key:
 cardano-address recovery-phrase generate --size 15 > phrase.prv
 cardano-address key from-recovery-phrase Shelley < phrase.prv > root.xsk
 cardano-address key child 1852H/1815H/0H/2/0 < root.xsk | cardano-address key public --with-chain-code > stake.xvk

Now I have extended stake address verification key stake.xvk.
From here, I want to generate stake registration certificate using cardano-cli like so:
cardano-cli stake-address registration-certificate \
--staking-verification-key-file stake.vkey \
--out-file stake.cert

But this doesn't work because the content of --staking-verification-key-file is much different that of stake_xvk.

To convert to cardano-cli compatible key files, start with the cardano-address formatted stake.xsk signing key file, then work your way down using the following commands.
cardano-address recovery-phrase generate --size 15 > phrase.prv
cardano-address key from-recovery-phrase Shelley < phrase.prv > root.xsk
cardano-address key child 1852H/1815H/0H/2/0 < root.xsk > stake.xsk
cardano-cli key convert-cardano-address-key --shelley-stake-key --signing-key-file stake_0_0.xsk --out-file stake.skey

You will then need to generate the non-extended (i.e. without the chain code) stake.vkey file which the cardano-cli accepts.
cardano-address key public --without-chain-code < stake.xsk | tee stake.vk
VKEYHEX=$( cat stake.vk | bech32)
cat << EOF > stake.vkey
{
    "type": "StakeVerificationKeyShelley_ed25519",
    "description": "",
    "cborHex": "5820$VKEYHEX"
}
EOF

Now that you have the cardano-cli compatible stake.skey and stake.vkey, generate the stake registration certificate you can use the same command as before
cardano-cli stake-address registration-certificate --stake-verification-key-file stake.vkey --out-file stake.cert

You should then be able to sign the transaction using the extended stake.skey file.

Thanks for the quick response! Sorry if my question was a misleading but I need to find a way to generate certificates just with the verification key. This is because my application is separated into two components; ones generating unsigned transactions and others signing it.

With the commands I posted you will have the stake.skey and stake.vkey. To generate the certificate you just need to run the same command as before, i.e. cardano-cli stake-address registration-certificate --stake-verification-key-file stake.vkey --out-file stake.cert. I will edit the answer for completeness' sake :)

To be able to generate the stake.vkey, the process is the following:
cardano-address key child 1852H/1815H/0H/2/0 < root.xsk > stake.xprv
cardano-address address delegation $(cat stake.xprv | cardano-address key public | tee stake.xpub)

SESKEY=$( cat stake.xprv | bech32 | cut -b -128 )\$( cat stake.xpub | bech32)

cat << EOF > stake.skey
{
    "type": "StakeExtendedSigningKeyShelley_ed25519_bip32",
    "description": "",
    "cborHex": "5880\$SESKEY"
}
EOF

cardano-cli shelley key verification-key --signing-key-file stake.skey --verification-key-file stake.evkey
cardano-cli shelley key non-extended-key --extended-verification-key-file stake.evkey --verification-key-file stake.vkey

Once you have the stake.vkey, you can generate the staking certificate with the command that you listed:
cardano-cli stake-address registration-certificate \
--staking-verification-key-file stake.vkey \
--out-file stake.cert

Credits to ilap (I took the commands from his script)

Okay it worked, but instead of addding 5880 at the beginning, I've added 5840 instead. Adding 5580 threw the following exception:
Command failed: key non-extended-key  Error: ShelleyStake.vkey: TextEnvelope decode error: DecoderErrorDeserialiseFailure "VerificationKey StakeExtendedKey" (DeserialiseFailure 2 "end of input")

Do you know what this number means? cardano-cli that I'm currently using is:
cardano-cli 1.33.0 - linux-x86_64 - ghc-8.10
git rev 814df2c146f5d56f8c35a681fe75e85b905aed5d

Okay my friend did a little bit of research and this is what 5580 means.
The cborhex here contains of 4 parts:

prefix 5880 - bytestring of 128 bytes
signing key (64 bytes)
verification key (32 bytes)
chain code (32 bytes)
Rule for prefixes:

CBOR-encoded bytestring (which is what the 58 identifies)
size (80 means 128 bytes, whereas 40 means 64 bytes, 20 means 32 bytes)

Well done, this will be helpful also for other people. Happy to help :-)


text:
How to query cardano graphql api to get all assets metadata from a specific policy id
currently I'm using blockfrost to request NFT metadata information one by one from a specific policy_id. A policy ID can have up to 10k assets minted so it takes quite a while to fully sync to my local database.
Can I define a graphql schema to do the same thing with dbsync but with just 1 or a few request to the Cardano graphql server?
Was trying on https://graphql-api.mainnet.dandelion.link/ and couldn't figure this out, any help would be appreciated, thanks.

Took a while for me to figure out as well but this works. It will return all the asset ids of a particular policy
query TokensByPolicy($policy_id: Hash28Hex) {
  assets(where: { policyId: { _eq: $policy_id } }) {
    assetId
    policyId
    assetName
  }
}

And you need to pass the policy id as a parameter
{"policy_id": "7be8b5c60e913079bc1ccf58247dbaf5433fcb70d0abc89a7dd333d4"}

You can try it out at https://graphql-api.mainnet.dandelion.link/