text:
"bash: plutus-pab-generate-purs: command not found" issue when run plutus-playground on Ubuntu
I've followed guide for running plutus-playground .
But when I npm run start on plutus-playground-client,  it says 'bash: plutus-pab-generate-purs: command not found'.
Please check screenshot on terminal.

What is issue now?

Can you add the link to the guide(s) you were using. I noticed a similar issue to this and realized it was a result of the guide not being completely current with the repos. Basically one of the steps was changed because something was moved to a different repo.

Having same issue. Any update?

Which guide did you follow? It's best to refer to the plutus-apps repo for up-to-date steps https://github.com/input-output-hk/plutus-apps/tree/main/plutus-playground-client

I am following https://docs.plutus-community.com/docs/setup/MacOS.html
I think I didn't correctly build plutus-pab.
This command : $ nix-build -A plutus-pab fails with error: attribute 'plutus-pab' in selection path 'plutus-pab' not found
I am in the top folder of the plutus-apps repo. Everything else seems to have built.

That content is out of date. Everything for Plutus Playground is in plutus-apps repo now. That cmd would now be $ nix-build ../default.nix -A plutus-apps.haskell.packages.plutus-pab, see https://github.com/input-output-hk/plutus-apps/tree/main/plutus-pab-executables#nix

$ nix-build ../default.nix -A plutus-apps.haskell.packages.plutus-pab works but it doesn't solve my issue.

We're a little different from other sites; this isn't a discussion forum but a Q&A site, where we reserve the answer space for answers. Please check out our short [tour]. Could you please [edit] this to more directly address the question? Thanks.

What is reputation? How do I earn (and lose) it?  Has an explanation of why comments are not an immediate privilege.


text:
How can I enforce a datum type to be correct?
Most types in Plutus are simply wrappers around BuiltinByteString. For instance the bytes in PubKeyHash are not serialized/deserialized to an actual pubkey hash and checked for correctness. So basically any bytestring can be inserted here. A malicious actor could easily block spending a script utxo by adding an invalid pubkey hash.
Is there a way to enforce this/let the validator check the pubkey hash for correctness?

Can you give me an example of a case that you'd care that someone created a UTxO that was unspendable? Anyone can send tokens to unowned addresses whenever they want--essentially burning them.

Hopefully I'm following your question...
I'm not aware of any type checks performed at validation, but I'm also not aware of any situation that a validator/script would need to spend resources preventing this.
In other words, scripts generally operate under the assumption that proper off-chain code is being used in tandem with the on-chain script. The off-chain code does have type checks.
There is always the threat that a malicious actor will go around the expected off-chain code to abuse the script. The onus is on a script developer to write a script that checks for correct values--I am having a hard time thinking of a situation that someone giving the wrong type and that value being misinterpreted as the correct value.

You give the example of a "malicious actor [blocking the] spending [of] a script utxo by adding an invalid pubkey hash." I don't understand how this case is different from the malicious actor sending a random, un-owned pubkey. In both cases it would prevent the spending of the UTxO.
EDIT:
It sounds like at least in the case of PubKeyHash, which by default has no checks on bytestring length, it is possible to submit and validate against invalid pubkeys. Unfortunately, you can't just rely on type check :(.
It is the script writer's responsibility to understand this limitation and include protection for counterparties. For example:

Force a redeemer to use the pubkey that matches the signer of the tx in the context. That way the pubkey always a pre-verified valid pubkey OR
Include additional intermediary datums that can hold funds in escrow for a (potentially invalid) recipient pubkey OR
Check the length of the bytestring to ensure it could be a valid pubkey

Generally, while writing Plutus scripts you try to avoid over-constraining the logic. Since the PubKeyHash type problem isn't obvious, the above solutions might come across as overconstrained or overcomplicated to those outside the know. Documentation is warranted. Hopefully we can get better types for these things in the future to push devs and readers into a pit of success.

Person A makes a borrowing request/offer and locks his collateral in a script utxo. Person B comes along and accepts this offer. He gives person A the loan, destroys the old script utxo and creates a new one with the collateral and new datum, where he also specifies his receiving address (pubkey hash) for the payoff amount. But if the pubkey hash is not valid the validator will always fail and the collateral is locked forever in the utxo.
Only solution I have in mind is adding a required signer and compare the pubkey hash with the signer, but wanted to know if there is a more elegant way.

K. I gotcha. In that case Person B would need to be a deranged actor, but since the loan is overcollateralized it could be a disproportionate loss for Person A. Worth preventing actively.

I'll point out, however, that the redemption of a datum does have type checks. The script needs to be run by the validator. It might be possible for Person A to create a "request/offer" datum with invalid values (according to my current understanding), but it wouldn't be possible for Person B to redeem that datum with invalid values, since the script couldn't possibly run.

Interesting, I'll try that out on testnet, since in the plutus simulator it seems not to be the case. Thanks for the response!

Just tried it on the testnet. The types are not checked even if you redeem a script utxo and create a new one :(.
I was able to set the PubKeyHash to the ByteString "30".

However I realized any bytestring combination, which is 28 bytes long is a valid pubkey hash. That is of course easy to verify.

Oops. Yeah. I guess if the type is a Bytestring under the hood, that's type it's checking.

I'm also failing to understand the wrongdoings of party B. According to your scenario he could only block himself from receiving the collateral. There must be the party A counterpart to closing the contract that should not be impacted by actions of party B.
Don't ask party B to provide the pkh, it is available for you from inside the script via ScriptContext{scriptContextTxInfo}

Yep. That is an easy solution and I can think of other ways too. I think I mispoke for this situation. Generally, there isn't a need to write scripts in a way to prevent an actor from shooting themselves in the foot--they should just be incentivized to use the (ostensibly) safe off-chain code which will prevent error. This types problem is an exception since it can hurt counterparties.

You should be extra careful with data that is being provided to smart contracts by the user. You might prevent user errors by using data from the Context that is already provided to you inside the Plutus script.
From the discussion around answers I'm getting a feeling that the malicious actor is only able to "break" the logic in such a way that is unfavourable for him only.
ScriptContext{scriptContextTxInfo{txInfoSignatories}} gives you access to the public key hashes, in this case Person B public key hash when he consumes initial utxo and is creating a new one.

source: Stack Exchange

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

sort: votes


text:
Why do we need the PAB and how does it work?
We can test Plutus smart contracts using runEmulatorTraceIO which emulates a blockchain and serves as an entry point to post transactions on it (or did I get this wrong?).
So if I can fully test my smart contracts only using runEmulatorTraceIO why do I need the PAB ? If the PAB is necessary to interact with the blockchain, why can I test my contracts without it ?
The purpose of the PAB has not been explained in a clear way, I think. I have tried to get information from the Plutus Pioneer Programm, IOHK and other sources but I'm still confused.

This is my understanding.
the runEmulatorTraceIO was executing transactions on an "Emulated chain" and "Emulated Wallet" and had did not interact with the outside world or real Cardano Blockchain in testnet or mainnet (did not interact with outside endpoint).
The contract application containing business logic is written in Haskell has to run on a user computer and only the validator script written in Plutus runs is executed by the Cardano nodes. As per the blog PAB : Supporting dApp
The PAB helps with building the UTXO transactions in two ways:

Read path - That is, getting information from the chain, and reacting to events that happen on the blockchain.
Write path - This is where we actually construct the transactions that run the Plutus scripts

PAB thus provides means to interact with blockchain as if it is a file using the Haskell program and also helps to interact with the wallet.

Ok, so the emulator trace can be setup with a predefined set of transactions and then run. But it cannot be started and then execute transactions on the go.

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


text:
Memory constraints for smart contracts
I feel like the memory consumption constraint has never been raised and properly discussed before this blogpost:
https://iohk.io/en/blog/posts/2021/11/16/architecting-dapps-on-the-eutxo-ledger/
It is good to have this pointed out even if it is somehow strange that in comes in the form of a blogpost and so late.
The blogpost says:

When adopting such a batching pattern, one should bear in mind that,
whenever N orders sitting at the request script are consumed within a
single transaction, the request script will be executed N times on
transaction submission. Moreover, the memory limit check (triggered
when the transaction is submitted) is realized by aggregating the
memory consumption for each single request script execution, for the
main script execution, and for any MintingPolicy scripts that may also
be executed (i.e., according to protocol design).

My questions are:

Why is the memory consumption the aggregate of all scripts executed ? The result of any given script is a boolean and there is no possible dependency of one script to any other (as no script can access any other as you can verify in the Plutus API). Why does the node need so much memory ? Why doesn't it just need the memory needed for the largest script. The memory could be cleared after each script execution.

How can we compute the memory consumption of a script ? An approximate method would help too.

Question 1: The blog talks about how to handle data concurrently in dapp designs. More explicitly, the case where processes are split across multiple unspent transaction outputs (N outputs) and batched into a single transaction for further processing.
In this setup, each output is locked by a script (can be the same script), so to validate that each is correctly spent, validators have to run the script N times. The protocol parameters describe a maximum amount of memory a transaction can consume as a safeguard, the max_tx_ex_mem parameter. Currently, this is set to 14000000 abstract memory units, this is the limit.
Question 2: The consumption of a script can differ in each transaction, depending on what action is taken by that script. If the script can only perform one action, the consumption would be the same each transaction. If a script can do multiple things, the consumption can differ. To check how much abstract execution units your transaction consumes in total, use the client command,
CARDANO_CLI transaction build \
  --alonzo-era \
  --cardano-mode \
  --testnet-magic "$TESTNET_MAGIC" \
  --change-address "$utxoaddr" \
  --tx-in "$plutusutxotxin" \
  --tx-in-collateral "$txinCollateral" \
  --tx-out "$dummyaddress+10000000" \
  --tx-in-script-file "$plutusscriptinuse" \
  --tx-in-datum-file "$datumfilepath"  \
  --protocol-params-file "$WORK/pparams.json" \
  --tx-in-redeemer-file "$redeemerfilepath" \
  --calculate-plutus-script-cost "$WORK/create-datum-output.scriptcost"

  > cat $WORK/create-datum-output.scriptcost
  [
    {
        "executionUnits": {
            "memory": 1700,
            "steps": 476468
        },
        "lovelaceCost": 133,
        "scriptHash": "67f33146617a5e61936081db3b2117cbf59bd2123748f58ac9678656"
    }
]

For a more in-depth view on how a specific script consumes execution units, have a look at (1)

Thank you for your answer to my second question and the link in (1). This was useful. For my first question, I don't see how your answer addresses it. I am familiar of how Cardano works. I was confused of why "memory consumption" was taking the aggregate of memory consumed (whatever this means) instead of being a metric of how much memory a system would need to be able to computationally evaluate the scripts.

The key point is that for each output, a script is run for the validation that the output can be spent. Since this blog talked about splitting computation across multiple outputs, the total memory consumption in a transaction that spends multiple of these inputs, is the sum of the memory consume by each validation of an output in that transaction. Aggregate of memory = total memory in the transaction. So, why is the memory consumption the aggregate of all scripts executed? Because the script runs N times in these transactions.

I understand the mechanic but it made no sense to me from a computational point of view. E.g. when I program a script that reads 10 files, compresses the content, and then saves it to disk, the sum of the memory used is of no importance as the files can be processed sequentially. Only if processed in parallel, the sum is important. Likewise, with a transaction consisting of multiple scripts: the minimum memory necessary to validate the transaction is independent of the sum of the memory used. It depends only on the maximum memory used per script (plus overhead).

The sum is important since a block producer has to perform the calculation N times and would like to be compensated for each run of the script (especially if it fails after the N-1 check). The memory the blog talks about it the abstract execution unit memory, not the real memory a node might use for validating. Indeed, in a sequential run the ram used by the node might be lower, but this is not of importance. The consumption of the whole transaction matters for the cost made, it is good to remember that we are in a trustless setup.


text:
Is it possible to change the name of a minted native asset?
Native assets are defined by a fingerprint. This is decoupled from the name, so far as I know. Is it possible to modify the name of the asset after minting it?

Any Native asset is uniquely identified by policy id + asset name.

Policy id is the hash of minting policy script, which does not contain asset name.
Asset name is included in the minting transaction metadata.
Therefore multiple assets can have the same policy id.

However, since the assert's name is included in the transaction metadata, it can not be changed.


text:
How is off-chain code decentralized?
Consider this a follow up to this other question that someone else asked: Where is stored off-chain code?
My question: Without a dapp store how does one deploy a Plutus script in a fully Decentralized manner? Would you have to do what SundaeSwap did and get some node operators to run the off chain code for you?
Or perhaps what happens is a user goes to a dapp developers website , clicks on something like “install dapp to Nami wallet”,then the wallet copies the dapp code from the dapp developers server to the users wallet and they then run the off chain code on their browser ? Is that how it works?

The purpose of a dApp store is for script curation, not script availability. Perhaps "dApp Store" is a bit of a misnomer, because software here isn't being sold in the traditional sense. Instead, it is being submitted to the open source community in a setting where professionals can audit/debug the code and report their findings to the community. This is imperative for decentralization because we can't expect everyone to have the level of expertise necessary to know whether the code they are using is sufficient for their purposes. By having trusted entities validate scripts and sign off on them allows us to outsource the code audit to an entity who has a reputation to maintain.
As far as deploying the actual script, the code is run on the client machine (your computer) and the hash of the operation is posted on chain. This is analogous to how simple transactions work - sending/receiving addresses are not stored on chain for each transaction, only the hashes of TX outputs are stored.

So how does the code get onto the users machine? It sounds like the code will originate from a centralized entity (SundaeSwap servers & SundaeSwap website ?) and then run on users browsers and interact with users wallet as need be?
Have I got that right?

@user1761806 yes, that is one of the ways. It really doesn't matter where the user gets the script from -- he could get it from a friend, a contract deployer, compile from source himself, fetch from ipfs.


text:
Feasibility of having multiple persistent UTXOs at a script address
I'm attempting to construct a contract which maintains the state associated with a given NFT. I would like this to be done on-chain as there are ways for the user to attempt to save invalid (manipulated) states and the states are small enough.
When a user wants to change the state, the new accepted state is stored as datum of the output utxo. Successive changes would involve creating a new transaction with the new state as input and redeeming the output of the previous state.
The problem is with my understanding of the how the utxo system works. Would all outputs reside at the same 'address'? Would this mean that if there were 1000 different NFT owners using this contract, there would be a minimum of 1000 utxos sitting at the 'script address' at any given time? Assuming this, would the wallet software attempt to spend all the 1000 utxos before it finds the one valid for a given owner?

Your reasoning is correct - if you don't have a compile time parametrized contract it hashes to the same address and the uTXOs will all reside at the same address.
This should not be an issue though, since you control the creation of the transactions on users behalf or in case of Plutus PAB - you specify constraints that the transaction should satisfy (i.e. must spend specific uTXO). PAB can then construct and submit a transaction satisfying these or export the requirements/constraints for users wallet to resolve.


text:
Delegation Deposit
When delegating for the first time there is a 2 ADA deposit being spent.
Is this 2 ADA ever returned? if yes when is it returned and how?

Yes it can be returned. 2 ADA is the current cost of registering your staking key on chain (this is to prevent sybil attacks). If and when you de-register your staking keys, the 2 ADA is returned to the original address it was sent from.

thanks, eventually I found the unstake option in ccvault.io in the wallets settings, scroll down.


text:
How are Updatable network parameters rolled out to the decentrlaized network, and how are they depreciated?
CIP-0009 contains upgradeable parameters, if certain keyholders sign them, they appear to be changeable without updates to node software or configuration files: https://github.com/cardano-foundation/CIPs/blob/master/CIP-0009/README.md#updatable-protocol-parameters
We just saw a change to block-size and Plutus script size in epoch 306, how was this change effected if it is not reflected in software or config files, is it an on-chain transaction?  How can we discover those in an explorer?
How are Upgrade-able parameters removed?  For example the decentralization flag still shows in mainnet-shelley-genesis.json, has it been removed now, and if so, how?

Upgrade-able network parameters are modified by changing the parameters by writing a transaction into the block-chain itself, nodes then read the parameters from the block history.
Example transaction that changed the block size for epoch 306: https://cardanoscan.io/transaction/bf095309ba20174d1a5c30ea03580cbf8bfe7dd75da1203d9ed51bfd151bb327?tab=protocolupdates

The "certain keyholders" that you are talking about are called genesis keys, and are (for now) the only real way to affect changes/governance on the actual protocol. Before we get to the Voltaire/Governance era, these keys are controlled by IOG, Emurgo, and the Cardano Foundation. Over time and as we transition into the Voltaire Era, those three entities will slowly relinquish the keys' power over to the community.

Thanks but that doesnt answer my question about how changes are effected


text:
Back-to-back transactions produce ValueNotConservedUTxO error
I recently wrote some scripts that mint and send tokens. When I run the script to mint a token and then immediately run the script to send that token to a wallet, I get this error:
Error: Command failed: cardano-cli transaction submit --testnet-magic 1097911063 --tx-file ./tmp/tx_n5sm4btig.signed
Command failed: transaction submit  Error: Error while submitting tx: ShelleyTxValidationErrorShelleyBasedEraAlonzo (ApplyTxError [UtxowFailure (WrappedShelleyEraFailure (UtxoFailure (ValueNotConservedUTxO (Value 0 (fromList [(PolicyID {policyID = ScriptHash "1a1b09e939ec7fd1b60c1e4d71808926421079f679e79d1e9f36561a"},fromList [("TestNFT",1)])])) (Value 992262587 (fromList [(PolicyID {policyID = ScriptHash "1a1b09e939ec7fd1b60c1e4d71808926421079f679e79d1e9f36561a"},fromList [("TestNFT",1)]),(PolicyID {policyID = ScriptHash "584af528f36789c8d5cc9336ec258326cbea8b3983d9d6d40cdc5bce"},fromList [("TestNFT",1)]),(PolicyID {policyID = ScriptHash "6eee44f15e11b84d33bcaaff8096d36fa400f6cb8eaa14007d6fac1b"},fromList [("TestNFT",1)]),(PolicyID {policyID = ScriptHash "b294451d861bc02b49591d9413a12f8b24a0f17c57940c9d78d1074c"},fromList [("TestNFT",1)]),(PolicyID {policyID = ScriptHash "e7ba14bfcb30f171b106ea15984cd25101d73f72fc89f2bb864ff600"},fromList [("TestNFT",1)])]))))),UtxowFailure (WrappedShelleyEraFailure (UtxoFailure (BadInputsUTxO (fromList [TxIn (TxId {_unTxId = SafeHash "7d667aef6319a22a71903fca4d88b69cea24e23c36120e11f34738aa8d90da07"}) 0]))))])

A similar error happens if I run the script to mint a token and then immediately re-run it. It seems like rapid back-to-back transactions cause this. Am I doing something incorrectly?
Edit: I wanted to add that the scripts work as expected if there is a pause (>~1 minute) between each execution.
Any help is appreciated, and I apologize if this is a basic question!

Basically, the error ValueNotConservedUTxO means that your transaction is not balanced. Take a look on this answer to follow the appropiate process to submit transactions.
Other points to consider:

Depending how you're building and submitting your transactions, but consider that your transactions need to be confirmed in order to get your UTxOs updated.

When I run the script to mint a token and then immediately run the script to send that token to a wallet, I get this error

You can't mint a NFT and send it immediately in another transaction because you need to wait until the first transaction (your NFT) get reflected on your UTxOs
But you can mint and send the NFT in the same transaction. I think this is the best approach.

    cardano-cli transaction build-raw \
    --fee <fee> \
    --tx-in <tx_in> \
    --tx-out <your_address>+<change> \
    --tx-out <destination_address>+<minUtxO>+1 <nft> \
    --mint=1 <nft> \
    --minting-script-file <policy-file> \
    --metadata-json-file <metadata-file> \
    --invalid-hereafter=<slot> \
    --out-file <outputfile.raw>

A similar error happens if I run the script to mint a token and then immediately re-run it.

Consider that your UTxOs  get re ordered every time you submit a transaction.

This was very helpful; thank you. The problem was related to UTxOs not being updated, as you said. I'll attempt to mint and send in the same transaction and see how it goes.


text:
Dapp connector for cardano-cli wallets
I've read about the Yoroi dapp connector, but is there a way to connect a wallet which was created with cardano-cli to some dapp?

I tried yesteard i would try with Nami but you must convert your Keys to one compatible with Cardano Serialization Lib, I read that they are compatible here https://github.com/Emurgo/cardano-serialization-lib/blob/master/doc/getting-started/generating-keys.md but i do not know how to use the CBOR in the cardano-cli keys for doing this, but if you start with your 24 words phrase in Cardano-cli, you could use that same 24 words in the Cardano Serialization-Lib, follow the instructions in the page above and connect to Nami.

cardano-cli uses a different way to generate from th other wallets Daedalus or Yoroi.
The creation of the keys via cardano-cli does not include the step of derivation from bip39 mnemonics entropy - which is a prerequisite for using it in other wallets.
Although all the keys conform with the same bip32-Ed25519, cardano-cli do not allow to be recovered via the seed phrase.
It is possible to convert the keys in other direction:
mnemonic-bip39 keys -> cardano-cli vkey/skey format


text:
How to get UTxO transaction id using cardano-serialization-lib
I'm missing transaction prefix in order to get bech32 hash of transaction id using cardano-serialization-lib.
What prefix is used in transaction bech32 hash and how can I find/compute one?
const decodeUtxo =
  (wasm: WasmT) =>
  (encodedUtxo: string): WasmNamespace.TransactionUnspentOutput =>
    wasm.TransactionUnspentOutput.from_bytes(Buffer.from(encodedUtxo, "hex"));

const collateralUtxos = (await wallet.getCollateral()).map(decodeUtxo(wasm));

const prefix = '' // how can I find this?

// to_bech32 function requires prefix
const collateralTxHashes = collateralUtxos.map((utxo) => utxo.input().transaction_id().to_bech32(prefix))

In order to get transaction id using cardano-serialization-lib you should convert transaction id to bytes and convert them to hex string.
Buffer.from(utxo.input().transaction_id().to_bytes()).toString('hex')

Try this one: utxo.input().transaction_id()

Close enough. Only thing left is to load bytes into Buffer and convert it to hex string.


text:
OutputTooSmallUTxO error
I'm following these steps and I get the OutputTooSmallUTxO error.
Not sure what I missed from the steps but here's my parameters and the error as a whole.
tokenname1="Testtoken"
tokenname2="SecondTesttoken"
tokenamount="100000000"
output="0"
fee="300000"
txhash="8a7e45c02cf25cb1b9870fbcc87b61d61cefb514ccfb960bcc7651023ea7ffb2"
txix="0"
funds="1000000000"
policyid=$(cat policy/policyID)
cardano-cli transaction build-raw
--fee $fee
--tx-in "$txhash#$txix"
--tx-out $address+$output+"$tokenamount $policyid.$tokenname1 + $tokenamount $policyid.$tokenname2"
--mint="$tokenamount $policyid.$tokenname1 + $tokenamount $policyid.$tokenname2"
--minting-script-file policy/policy.script
--out-file matx.raw
fee=$(cardano-cli transaction calculate-min-fee --tx-body-file matx.raw --tx-in-count 1 --tx-out-count 1 --witness-count 1 --testnet-magic 1097911063 --protocol-params-file protocol.json | cut -d " " -f1) (This was not incluted in the tutorial and i added it from a block post i found here in reference to a similar issue)
cardano-cli transaction build-raw
--fee $fee
--tx-in "$txhash#$txix"
--tx-out $address+$output+"$tokenamount $policyid.$tokenname1 + $tokenamount $policyid.$tokenname2"
--mint="$tokenamount $policyid.$tokenname1 + $tokenamount $policyid.$tokenname2"
--minting-script-file policy/policy.script
--out-file matx.raw
cardano-cli transaction sign
--signing-key-file payment.skey
--signing-key-file policy/policy.skey
--testnet-magic 1097911063 --tx-body-file matx.raw
--out-file matx.signed
cardano-cli transaction submit --tx-file matx.signed --testnet-magic 1097911063
Command failed: transaction submit  Error: Error while submitting tx: ShelleyTxValidationError ShelleyBasedEraAlonzo (ApplyTxError [UtxowFailure (WrappedShelleyEraFailure (UtxoFailure (OutputTooSmallUTxO [(Addr Testnet (KeyHashObj (KeyHash "63c7e6f65c0185e0afa19657977c86e663873143569b665d23f532ea")) StakeRefNull,Value 0 (fromList [(PolicyID {policyID = ScriptHash "68d7df6ec365f5d9885c451e58e8994741c1970211c01843703f6136"},fromList [("SecondTesttoken",100000000),("Testtoken",100000000)])]),SNothing)]))),UtxowFailure (WrappedShelleyEraFailure (UtxoFailure (ValueNotConservedUTxO (Value 1000000000 (fromList [(PolicyID {policyID = ScriptHash "68d7df6ec365f5d9885c451e58e8994741c1970211c01843703f6136"},fromList [("SecondTesttoken",100000000),("Testtoken",100000000)])])) (Value 177601 (fromList [(PolicyID {policyID = ScriptHash "68d7df6ec365f5d9885c451e58e8994741c1970211c01843703f6136"},fromList [("SecondTesttoken",100000000),("Testtoken",100000000)])])))))])
antonis@adastp:~/tokens$ echo $cardano-cli transaction submit --tx-file matx.signed --testnet-magic 1097911063^C
--tx-in
addr_test1vp3u0ehktsqctc905xt909musmnx8pe3gdtfkejay06n96shpzd3t+0+100000000 68d7df6ec365f5d9885c451e58e8994741c1970211c01843703f6136.Testtoken + 100000000 68d7df6ec365f5d9885c451e58e8994741c1970211c01843703f6136.SecondTesttoken
--tx-out
8a7e45c02cf25cb1b9870fbcc87b61d61cefb514ccfb960bcc7651023ea7ffb2#0

Looks like you don't account for change return value (your $output variable which is zero).
Your transaction spends some UTxO to pay the fee but the rest of this UTxOs ADA has to go somewhere (hence the value not conserved error).
I think you need to look up the ADA value of the --tx-in "$txhash#$txix" (your $funds variable?) and subtract fee from it, which is the unspent ADA you get back.

Thanks I was missing the output=$(expr $funds - $fee)

Nice! Please mark the question as answered :-)


text:
How can I get access to the epoch nonce?
I see the Cardano epoch nonce being used as a source of randomness. How can a non-technical person verify if the nonce used is actually legitimate? Is there a source where I can find the nonce for a specific epoch without running a node myself?

The best way to verify whether or not something on-chain is legitimate is to run a node yourself, be that a transaction, nonce, SC, or whatever else. CNCLI is an excellent tool for use with the node, and can be used to calculate the epoch nonce.
That being said, there are of course other third party sources for (almost) all on-chain data, but a quick google search yields no such luck.
Perhaps Andrew can help us out? :)

If not running node/Daedalus:
Project Koios provides epoch_params endpoint that you can easily view (even from referred docs link), you can fill the epoch you're requesting and click Try button).
Else:
If using CLI with node, you can also use command below to fetch epoch-nonce without any thirdparty tooling:
cardano-cli query protocol-state --mainnet | jq -r .csTickn.ticknStateEpochNonce.contents


text:
How to establish trust between a user's wallet, and the backend of a website?
I am building an application that will hopefully offer a login option via Nami wallet, rather than the typical email/password. I understand how this approach can work for on-chain data, but is it possible (and if so, what are the limitations?) to use wallet authentication to associate users with other site data?
For example, my site will allow users to create "projects" to organize links and relevant data from the website. This data will be stored off-chain in a database. To ensure data privacy, the backend server must be able to verify that the user has access to the correct wallet. Is there a way to generate a site-specific password (i.e. private key) that can be securely stored on the wallet, then sent to the backend for authentication?
One alternative would be to remove centralized storage of private data altogether, and instead store data off-site where only the user can access (such as local file storage). Then this could be loaded using the File System Access API. This is more aligned with the spirit of decentralization, but is not yet widely supported and raises issues for multi-device support.
Of course I could skip the Nami login altogether and stick to the traditional email/password approach for authentication. Then, users would connect to Nami later on when they need to perform an action that involves the wallet. The downside here is the requirement of an email and a longer log-in/sign-up process. Thoughts?

For anyone looking for a more exact solution, below is an explanation for how I implemented this in JavaScript.
To understand the authentication flow, I started by reading this article. While the article is for Metamask and Ethereum, the same flow can be applied with Nami (or Eternl, etc) and Cardano. It goes:

Connect to wallet ->window.cardano.enable()
Send public address to backend -> window.cardano.getRewardAddress()
Store public address and a signature (description + nonce) in database
Return hex string of signature to frontend, and have your wallet extension sign it. This requires the user to enter their staking password. If there is a way to get around this, I'd love to know.

For most wallets -> call signData(publicAddress, signature) on the object returned in step 1.
For Nami (last time I checked the newer method didn't work right) -> window.cardano.signData(publicAddress, signature)

Send the signed signature to backend
Verify that signature was signed by correct wallet (explained below)
Return http cookie with JWT, signed by backend secret key (won't detail how this is done, as there are many non-crypto tutorials of this online)

The most difficult part is verifying the signed nonce. Using this article from Thom's answer, we can see that verification relies on two packages: cardano-serialization-lib-nodejs and emurgo_message_signing.
The first can be added to the backend server through npm or yarn. The second is more difficult, as it is written in Rust. To create a javascript-friendly version, you must first install Rust and wasm-pack. Then, you can clone emurgo_message_signing, start a terminal in that project's "rust" directory, and enter wasm-pack build --target nodejs. The "rust" directory can then be moved into your project's backend directory and imported like a normal package: const MS = require('./message-signing/rust/pkg/emurgo_message_signing').
If you are using TypeScript and ES6, you may run into additional problems because tsc doesn't copy the additional WebAssembly files used by emurgo_message_signing. I got around this by creating a post-install command in my backend's package.json file that copies them over.
Using Thom's example and the example file in emurgo_message_signing, you can get a sense for how to create and verify the signature. This is how I implemented it:
import * as Serialization from '@emurgo/cardano-serialization-lib-nodejs';
import * as MessageSigning from './message_signing/rust/pkg/emurgo_message_signing';
import { randomBytes } from 'crypto';

// Generate a random string of the specified length, consisting of the specified characters
function randomString(
    length: number = 64,
    chars: string = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
): string {
    // Check for valid parameters
    if (length <= 0 || length > 2048) throw new Error('Length must be bewteen 1 and 2048.');
    const charsLength = chars.length;
    if (charsLength < 10 || chars.length > 256) throw new Error('Chars must be bewteen 10 and 256.');
    // Generate random bytes
    const bytes = randomBytes(length);
    // Create result array
    let result = new Array(length);
    // Fill result array with bytes, modified to consist of the specified characters
    let cursor = 0;
    for (let i = 0; i < length; i++) {
        cursor += bytes[i];
        result[i] = chars[cursor % charsLength];
    }
    // Return result as string
    return result.join('');
}

// Generate signable nonce, which includes human-readable description
// Returns hex string
export const generateNonce = async (
    description: string = 'Please sign this message so we can verify your wallet:',
    length: number = 64,
) => {
    if (length <= 0 || length > 2048) throw new Error('Length must be bewteen 1 and 2048');
    // Generate nonce (payload)
    const payload = randomString(length);
    // Return description + nonce
    return Buffer.from(`${description} ${payload}`).toString('hex');
}

/**
 * Determines if a wallet address signed a message (payload)
 * @param address Serialized wallet address
 * @param payload Serialized payload (i.e. message with nonce)
 * @param coseSign1Hex Hex string of signed payload (signed by user's wallet)
 * @returns True if payload was signed by wallet address
 */
export const verifySignedMessage = (address: string, payload: string, coseSign1Hex: string) => {
    const coseSign1 = MessageSigning.COSESign1.from_bytes(Buffer.from(coseSign1Hex, 'hex'));
    const payloadCose: Uint8Array | undefined = coseSign1.payload();

    if (!payloadCose || !verifyPayload(payload, payloadCose)) {
        throw new Error('Payload does not match');
    }

    const protectedHeaders: MessageSigning.HeaderMap = coseSign1
        .headers()
        .protected()
        .deserialized_headers();
    const headerCBORBytes: Uint8Array | undefined = protectedHeaders.header(MessageSigning.Label.new_text('address'))?.as_bytes();
    if (!headerCBORBytes) {
        throw new Error('Failed to convert header to bytes');
    }
    const keyId: Uint8Array | undefined = protectedHeaders.key_id();
    if (!keyId) {
        throw new Error('Failed to get keyId from header');
    }
    const addressCose: Serialization.Address = Serialization.Address.from_bytes(headerCBORBytes);
    const publicKeyCose = Serialization.PublicKey.from_bytes(keyId);

    if (!verifyAddress(address, addressCose, publicKeyCose))
        throw new Error('Could not verify because of address mismatch');

    const signature = Serialization.Ed25519Signature.from_bytes(coseSign1.signature());
    const data = coseSign1.signed_data().to_bytes();
    return publicKeyCose.verify(data, signature);
};

const verifyPayload = (payload: string, payloadCose: Uint8Array) => {
    return Buffer.from(payloadCose).compare(Buffer.from(payload, 'hex')) === 0;
};

const verifyAddress = (address: string, addressCose: Serialization.Address, publicKeyCose: Serialization.PublicKey) => {
    const checkAddress = Serialization.Address.from_bytes(Buffer.from(address, 'hex'));
    if (addressCose.to_bech32() !== checkAddress.to_bech32()) return false;
    // check if RewardAddress
    try {
        //reconstruct address
        const stakeKeyHash = publicKeyCose.hash();
        const reconstructedAddress = Serialization.RewardAddress.new(
            checkAddress.network_id(),
            Serialization.StakeCredential.from_keyhash(stakeKeyHash)
        );
        if (
            checkAddress.to_bech32() !== reconstructedAddress.to_address().to_bech32()
        )
            return false;

        return true;
    } catch (error) {
        console.error('Caught error verifying address', error)
    }
    return false;
};

Any idea why I am getting when calling verifySignedMessage: ERROR [ExceptionsHandler] Deserialization failed in Address because: Encountered unknown address header 0b10101101

Getting this error on: const addressCose: Serialization.Address = Serialization.Address.from_bytes(headerCBORBytes);

@Jingles I'm not sure what's causing that error, but I think I have an idea. After writing my original answer, the authentication processed changed a bit (unless you're using Nami, because their new code doesn't work correctly last time I checked). It's probably an error with the coseSign1Hex parameter being passed into verifySignedMessage. Instead of signing the message with window.cardano.signData, you have to use the signData function on the object returned by window.cardano.enable(). I will update my answer now

@Jingles Here is the CIP that caused the change: https://github.com/cardano-foundation/CIPs/pull/148

Does it still work for you? I tried both Nami and Eternl. Using Nami older method (window.cardano.signData) returned Code: 4. If a wallet enforces data format requirements, this error signifies that the data did not conform to valid formats.. Where both inputs publicAddress and signature are string, for example addrblabla and abcabcabc.

Using Eternl, I managed to signData. Then send to the backend, with the code you provided,let isValid = await verifySignedMessage('addrblabla', 'abcabcabc', '<this is a long string returned after signData using Eternl>'); But this returns the Deserialization failed in Address because: Encountered unknown address header 0b10101101 at Serialization.Address.from_bytes(headerCBORBytes).

@Jingles Sorry, I'm not sure what the problem is then. The steps I provided are working for my site. If it helps, you can check out my code. This file is where most of the frontend magic happens: https://github.com/MattHalloran/Vrooli/blob/master/packages/ui/src/utils/walletIntegration.ts

Thanks. The codes in your repo works. I replaced the backend codes. Had issues on verifyAddress.

@Jingles Glad I could help. Thanks for helping me improve my answer

There are a few options for something like this, Nami specifically supports signData which lets the user sign some arbitrary data with their private key. Your backend can then take this signature and public key to authenticate the user behind the wallet.
So if your data is the same, it will produce a unique signature for each wallet that signs it. You can store this signature in the database (which is totally safe since the signature isn't private information), and use it to associate a particular user with a project or whatever other information you want to store in your database.
An alternative (more centralized) approach is to still have some form of username:password authentication, but instead of letting the user fill in their own password, just sign some data with their wallet and use that signature as their password. When a user logs in, you just need to verify that the password (read: signature) is signed by their wallet. Then you can still use all the standard session handling and user association of a regular application, with some added decentralization and security.
There's some example code here that implements message signing with Nami and verification using Emurgo's message_signing library:
https://github.com/Berry-Pool/nami-wallet/blob/faf5a7a7993defbb7267a25a5f4cef4e06d39c7d/MessageSigning.md

Thank you! This is exactly the type of reply I was looking for.


text:
Is posible to do Batch minting of NFT with each NFT having different image?
Since the metadata is attached to a Tx not to the NFT, and is unique per transaction, there can not be such a thing as a Batch minting of NFT with each one having different metadata for example "image", is it?
I need to mint like 10 000ks NFTs, so i think my NFTs will all share same,  image, and all i can change is the name and policy for doing them unique NFTs. Am I right?
EDIT: In fact it is not possible even that they satisfy  the 721-Standar https://cips.cardano.org/cips/cip25/, is it?

Yes, it's possible. You can mint multiple NFTs using different metadata, all this in the same transaction. Here is an example of how you should structure your metadata
Take a look on this: How to mint multiple NFT assets in the same transaction?
But you have the restriction of the max transaction size, you can't go over that limit. Depending of your metadata, you'll be able to mint 35-45 NFTs in the same transaction.

Will this structure of metadata show specifically for every asset the image in the web wallets?

Yes, because the image displayed is based on the token name and the token name is defined in your metadata.


text:
How to send a native token using the cardano-cli?
What are the steps required to build and send a transaction meant to send for example 10,000 tokens to some given address?

Here is a good explanation of the process to build and submit a transaction.
In your case, your build-raw command should be similar to this:
cardano-cli transaction build-raw \
    --fee <fee> \
    --tx-in <tx_in> \
    --tx-out <your_address>+<change> \
    --tx-out <destination_address>+<minUtxO>+10000 <Tokens> \
    --mint=10000 <Tokens> \
    --minting-script-file <policy-file> \
    --invalid-hereafter=<slot> \
    --out-file <outputfile.raw>

This script can be useful for you https://github.com/invictusappscom/cardano-terminal-wallet/blob/e07119c6130adc36512f30bb554518784e177dc7/send-token.sh
For more info check point 6 at README.md https://github.com/invictusappscom/cardano-terminal-wallet/blob/master/README.md


text:
Serialize a transaction in python
I want to use the "Submit a transaction" method in Blockfrost but it needs an already serialized transaction. Does anybody know how to serialize a transaction in python? (I don't wanna use CLI or anything like that)

Sadly there isn't an easy way of doing this in Python yet, since the serialization library is written in Rust with WASM wrappers. At the moment your best bet is to use Javascript/TypeScript in Node, or use pure Rust, or if you're feeling adventurous it is possible to execute rust functions from a Python code base. It just requires a bit of work, see here.

It is also be possible to construct and sign a transaction using cardano-cli. Quickly searching for a python wrapper I've found https://github.com/creativequotient/automint

Good news, there is a python implementation available! https://github.com/cffls/pycardano
I haven't used it myself but the Readme claims this library is able to build and sign transactions. It even comes with an example for exactly this purpose: https://github.com/cffls/pycardano#transaction-creation-and-signing

That was a lifesaver. Thanks, man!

Can it compile Plutus.  I looked at the docs but I am too new to this whole thing to even be able to tell.  I just want to programmatically generate simple scripts.


text:
Webpack + Cardano ASM serialization library
I'm trying to use a library to access a cardano wallet, right now, I'm in webpack 5 and project run so far until I try to import the cardano library.
It breaks in the same point always:
runtime modules 33.6 KiB 17 modules
modules by path ./node_modules/ 17.5 MiB 49 modules
modules with errors 429 bytes [errors]
  optional modules 78 bytes [optional]
    node:process 39 bytes [optional] [built] [code generated] [1 error]
    node:stream/web 39 bytes [optional] [built] [code generated] [1 error]
  9 modules
./src/index.js 280 bytes [built] [code generated]

WARNING in ./node_modules/@emurgo/cardano-serialization-lib-asmjs/cardano_serialization_lib_bg.js 12128:14-53
Critical dependency: the request of a dependency is an expression
 @ ./node_modules/@emurgo/cardano-serialization-lib-asmjs/cardano_serialization_lib.js 2:0-50 2:0-50
 @ ./node_modules/nami-wallet-api/lib/index.js 635:98-148
 @ ./src/index.js 2:23-48

1 warning has detailed information that is not shown.
Use 'stats.errorDetails: true' resp. '--stats-error-details' to show it.

ERROR in node:fs
Module build failed: UnhandledSchemeError: Reading from "node:fs" is not handled by plugins (Unhandled scheme).
Webpack supports "data:" and "file:" URIs by default.
You may need an additional plugin to handle "node:" URIs.
Critical dependency: the request of a dependency is an expression

If any of you had success using this library and webpack please let me know.
{
  "name": "webpacktemplate",
  "version": "1.0.0",
  "description": "",
  "private": true,
  "dependencies": {
    "fs": "0.0.1-security",
    "html-webpack-plugin": "^5.5.0",
    "lodash": "^4.17.21",
    "nami-wallet-api": "^1.1.9",
    "net": "^1.0.2",
    "node-fetch": "^3.1.0"
  },
  "devDependencies": {
    "webpack": "^5.64.4",
    "webpack-cli": "^4.9.1",
    "webpack-dev-server": "^4.6.0"
  },
  "scripts": {
    "start": "webpack serve --open",
    "build": "webpack",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

I would suggets to import it using a Loder like the Nami Wallet does it. That is the only way I could make it work. Also I would suggest to consider using the browser version.  Also I noticed that the error has to do with fs, i faced the same error but thats related to the way Next.Js Works... If you are using Next.Js .. try following the configuration i use in my project https://github.com/alice1989123/Metahagane . Good luck!

I've also come across this error in webpack, but found that it can be ignored if you use a Loader like so:
class Loader {
  async load() {
    if (this._wasm && this._wasm2) return;
    /**
     * @private
     */
    this._wasm = await import(
      '@emurgo/cardano-serialization-lib-browser/cardano_serialization_lib'
    );
  }

  get Cardano() {
    return this._wasm;
  }
}

export default new Loader();

Then in your components, this should work:
import Loader from './loader'

/* ... other component code ... */

getAddress() {
      window.cardano.getChangeAddress().then((address) => {
        Loader.load() // Note, loading the library here
        this.address = Loader.Cardano.Address.from_bytes( // Now Loader.Cardano resolves
            Buffer.from(address, "hex")
        ).to_bech32()
      })
}

As a side note, I've also found it easier to just call Loader.load() in my beforeMount() callback or similar depending on the library you're using.

Use node-fetch 2.6.6 and it should work


text:
Why does 'cardano-cli query utxo --address $address --mainnet' return an empty list?
I'm trying to list all the utxo's at my Yoroi wallet address. I set the variable 'address' as my receiving address but when I run the command, cardano-cli query utxo --address $address --mainnet, nothing shows up. I also tried this for a Daedalus wallet I have used often and I get the same result (will include a screenshot below). I can confirm there have many tx to and from this wallet so I'm confused why this is the case. I'm using the same linux VM for this command which I have a cardano-node running and synced up to the chain in. Any help is much appreciated!
Thanks, Myles

It is because Yoroi generates a new address after each transaction for privacy reasons. People who only know this address cannot see how much funds you have and what transaction you did in the past. At the same time your wallet can with its private key derive all address and show to you all the funds you have.
Try taking the last address where you received funds. It is displayed in the transaction tab in Yoroi. This address should show some UTxOs if you do the same query.

Cardano-wallet software (which both Daedalus and Yoroi use extensively) derives addresses from a single master key, as described in the BIP-32 standard. This key-derivation is briefly summarized by this infographic:

As you can see, many addresses can be derived from a single master key. Yoroi and Daedalus automatically create and maintain many such addresses for anonymity purposes, since one cannot prove ownership of two or more addresses without possessing the associated keys.
What likely happened in your scenario is you've sent ADA to one of the addresses created by Yoroi, but queried a different address (also created by Yoroi). To solve this, query the same address that you sent the ADA to (as found on a block explorer like cardanoscan, or in the history of wherever you sent the ADA from.


text:
PAB connection to public testnet or mainnet (Example/Tutorial)
Does anyone know and want to share any information on how to connect PAB to public testnet (not simulator) or mainnet? Are there any examples/tutorials for it?

You have the best instruction here https://gist.github.com/mikekeke/883d56c38e0237444ac98ae5257e174f
Also after the setup on the above link, you can use this starter project generated from the Plutus starter template just updated to work with PAB on testnet https://github.com/invictusappscom/plutus-starter-pab-testnet Here main differences from https://github.com/input-output-hk/plutus-starter are that dependencies are updated and it is added plutus-pab.yaml configuration file. Also here instead of simulator it is using the real PAB https://github.com/invictusappscom/plutus-starter-pab-testnet/blob/main/pab/Main.hs
Another useful resources:

https://github.com/input-output-hk/plutus-apps/blob/main/plutus-pab/ARCHITECTURE.adoc
https://github.com/input-output-hk/plutus-apps/tree/main/plutus-pab/test-node

Do I have to run a full node to run the PAB in the testnet?

Yes, you need to have a running testnet node. Also, wallet server and chain-index connected to the node.


text:
cardano-cli transaction submit example with native assets
I'm having trouble using the cardano-cli to send one tx. I have one address with 9 ADA and 10,000,000 each of two tokens with the same minting policy and I want to send 5,000,000 ADA of each token to a foreign address which has 10 ADA and no tokens.
For example
Address that has the native assets I want to send:
TxHash: 123456789123465
TxIx: 0
Amount: 9000000 lovelace + 10000000 1234567891234.token1 + 10000000 1234567891234.token2 + TxOutDatumHashNone
Address which I want to send native assets to:
TxHash: 123456789123456
TxIx: 0
Amount: 10000000
What commands/steps exactly are needed using the cardano-cli from here in order to accomplish sending 5,000,000 of each native token?
Thanks, Myles

First thing to note, you can only send to an address, not a txhash. Can you also provide what commands you've tried already and what error occurs when doing so?

MY_ADDR=addr_test1qzl6m...
#Send lovelace change to my address
CHANGE_ADDR=$MY_ADDR
MY_UTXO_IN=123456789123465#0
RECEPIENT_ADDR=addr_test1...

# Build tx
cardano_cli transaction build \
--alonzo-era \
--tx-in $MY_UTXO_IN \
--tx-out $RECEPIENT_ADDR+9000000+"10000000 1234567891234.token1"+"10000000 1234567891234.token2") \
--change-address $CHANGE_ADDR \
--testnet-magic 1097911063 \
--out-file tx.build

If you have change in native tokens then you need to add another --tx-out to return to your address for example:
TOKEN1_CHANGE=1000
TOKEN2_CHNAGE=2000
--tx-out $CHANGE_ADDR+1400000+"$TOKEN1_CHANGE 1234567891234.token1"+"$TOKEN2_CHANGE 1234567891234.token2"

Sign and submit
# Sign tx
echo "Sign Tx ..."
cardano_cli transaction sign \
--signing-key-file my_payment.skey \
--tx-body-file tx.build \
--out-file tx.sign
echo "Done."

# Submit tx
echo "Submiting Tx ..."
cardano-cli transaction submit --testnet-magic 1097911063 --tx-file tx.sign

Here you can find various examples for sending token and other stuff https://github.com/invictusappscom/cardano-terminal-wallet especially this script https://github.com/invictusappscom/cardano-terminal-wallet/blob/master/send-token.sh


text:
Syntax error near unexpected token `('
I'm trying to set up a Cardano-node using the steps on this web site but I am running into errors regarding the .bashrc file on line 122 If any of you know How to fix this it would be much appreciated.
here's my code https://gist.github.com/FloofyFlare/8f6303830ab9978950f30f28908bd03d

Do you really need to build it from source code?

Have a look at your users .bashrc file on line 122.  If you still can't figure out the error then you will have to post the actual error message and the contents of your .bashrc file so that someone can help.

I found the problem. I got the /home/_____/.bashrc directory mixed up because I did not adapt the name of the user to my situation, as I was following a tutorial. Thanks for the help.


text:
What is the standard metadata schema for nfts
I realize that metadata for nfts has no official standard. However, many 3rd parties render nfts and their attributes which means they are reading meta data according to one or more schemas.
Here is an example of the zombie metadata:
{
   96580bbc4fe27ac0d127db3f8a0dc698c58d303d8cae870f5771f336: {
      ZombieChains00690: {
         Project: "Zombie Chains",
         attributes: {
            Background: "Purple",
            Chains: "None",
            Clothing: "Biker",
            Earrings: "None",
            Eyes: "Zombie",
            Hat: "Baseball",
            Mouth: "Stitches",
            Nose: "Solid",
            Skin: "Red",
            Weapon: "Sword"
         },
         copyright: "2021 Zombie Chains",
         image: "ipfs://QmQTkayfG1GWzenfEm65DLyYVL7MS6sSfWZQyPuFm6XiEV",
         name: "Zombie Chains #00690",
         twitter: "https://twitter.com/ZombieChains",
         type: "image/png",
         website: "https://zombiechains.io"
      },

Does anyone have documentation or knowledge about metadata nft standards?

There is a metadata standard. You can check it here: CIP-0025
{
  "721": {
    "<policy_id>": {
      "<asset_name>": {
        "name": <string>,

        "image": <uri | array>,
        "mediaType": "image/<mime_sub_type>",

        "description": <string | array>

        "files": [{
          "name": <string>,
          "mediaType": <mime_type>,
          "src": <uri | array>,
          <other_properties>
        }],

        <other properties>
      }
    }
    "version": "1.0"
  }
}

Not all follow that standard.

Thank you. I was hoping the standard would describe structure for discussing the attributes of the nft ('attributes' field on the zombie). Looks like there is more work to do. A future CIP perhaps.


text:
What is the output from a transaction when burning tokens?
I'm submitting a transaction to burn token to the blockfrost API and receives the following error
(ApplyTxError
    [UtxowFailure
        (WrappedShelleyEraFailure
            (UtxoFailure
                (ValueNotConservedUTxO
                    (Value 871447193
                        (fromList
                            [(PolicyID {policyID = ScriptHash \"425754c55895d05430ea30c57a6bc2f7f180756f598a5bb0221c3357\"}
                             ,fromList [(\"LoyaltyCoin\",-55)]
                             )
                            ,(PolicyID {policyID = ScriptHash \"bd7f7e20e9d43ffb11fdd3c08f32fc31292f8deb72696e5fe003c832\"}
                             ,fromList [(\"FrankCoin\",3000),(\"SyncroCoin\",1000)]
                             )
                            ]))
                    (Value 871447193
                        (fromList
                            [(PolicyID {policyID = ScriptHash \"bd7f7e20e9d43ffb11fdd3c08f32fc31292f8deb72696e5fe003c832\"}
                             ,fromList [(\"FrankCoin\",3000),(\"SyncroCoin\",1000)]
                             )
                            ]
                        ))
                )
            )
        )
    ]
)

How should a transaction that burns tokens look like?

I don’t know blockfrost but I know that a Cardano-transaction has a special field for minting. You should pass a Value to this field with a negative integer for the tokens you want to burn. Additionally you need to add the currency policy script to the transaction.
A transaction would have as inputs for instance a UTxO with 2 Ada and 55 xyz-tokens. The output would be a UTxO with just 2 Ada. The minting field would be a value with -55 xyz-tokens.
I hope this helps a bit.

Your problem is ValueNotConservedUTxO because your inputs and outputs values not conserved as (Input UTXO ≠ Fee + Amount sent + Change).


text:
Best practice for updating cardano-node/cli?
I'm using a Linux VM on AWS and followed this guide: https://developers.cardano.org/docs/get-started/installing-cardano-node to install everything. What's the best way to go about updating the node and cli while preserving the wallets I've created?
Thanks, Myles

Coincashew's guides are super helpful, especially this one on how to update a stake pool.
In short, you can either download the cardano-cli binaries directly, or build the new release from source in the same git directory as you built in the first time. Just make sure to rename the builds accordingly, and when you are done building, sudo cp the binaries into the user's bin directory; replacing the old binaries with the new ones.

Your wallets have nothing to do with your cardano-node instances or binaries on a machine.
Having the wallet keys on a linux instance on AWS that is running cardano-node (and I assume has a public IP address) is from start a bad idea. Your keys should stay only on a computer where only you have access, in your home, and also as encrypted backups on USB sticks, for example.
Returning to your original question: the normal way of updating cardano-node and cardano-cli is to get the new binaries (you compile them from sources or you download the binaries provided by IOG - links on the releases page on Github), replace the existing binaries on your linux VM and restarting the cardano-node service. Sometimes there also changes to the config files, so it is always a good idea to check the release notes to see if you need to update the config files.

How do you go about updating the config files?

You download the latest configuration files from here: https://book.world.dev.cardano.org/environments.html
and check if there are differences compared to your configuration files (except the topology file). If there are differences, you replace your configuration files with the new ones and restart the node. It is better to download them directly on the server(s) with wget, to be sure they are not altered when you download them. The genesis files are very sensitive, if you change anything in them, you will see errors in the logs. But they don't change, so you won;t need to update them.


text:
Resources to learn about block pipelining?
Are there resources to learn about block pipelining in Cardano as mentioned in this video?

There is a pipelining introduction blog post at
https://iohk.io/en/blog/posts/2022/02/01/introducing-pipelining-cardanos-consensus-layer-scaling-solution/


text:
Plutus Playground vs Plutus Application Backend vs Plutus Application Framework
Is the Plutus Application Backend another name for the Plutus Playground? If not what is the Plutus Application Backend? Also is the Plutus Application Framework the Plutus Playground?

Plutus Application Backend is used to interact with smart contracts built using Plutus (Plutus Framework). Plutus Playground is a tool used to compile smart contracts built with Plutus and simulate transactions and interactions with smart contracts.
Here's a docs for Plutus tools so you can read more about them https://docs.cardano.org/plutus/Plutus-tools

Plutus Application Framework -> A collection of libraries, tools, and rules used to build Plutus apps. Think of it like a toolbox with guides/manuals, or like how Ikea furniture comes in parts and assembly instructions.
Plutus Application Backend -> A set of tools used to test and interact with the apps built with the Plutus Application Framework. Eg. It offers emulated and non-emulated access to the blockchain to determine how an app may perform in a given scenario. Imagine if a popcorn machine didn't just make the stuff but also was able to let you know how much you're making, the quality of the stuff, the bad corns in the machine, etc. You know, fancy stuff.
Plutus Playground -> A curated sandbox environment intended to mimic the blockchain, to try and experience how Plutus apps can work in a real-world/production setting. Think of it like paper trading.
Each of these three can be used independently, but they work best if combined in use.


text:
How are airdrops sent to token holders when NFTs do not belong to contracts?
Since NFTs on Cardano do not belong to a contract, how can token holders be rewarded with an airdrop? Do they need to request it themselves by showing proof of ownership?

Having the NFT on an UTxO on your address is the proof of ownership.
How the token holders receive an airdrop (automatically or only after claiming it) only depends on how the one doing the airdrop wants to do it.

I should have formulated my question better: is there a way for those airdropping to know the owners of the tokens? I do not see how this could work on Cardano. In Ethereum each NFT-owner would be known through the contract

By owner you mean the person holding the NFT?

Yes, that is what I meant. Is there a record of who owns what?

No, the persons owning the wallets are not known. Is there any blockchain where that is public information?

It is very easy to do. All NFTs are named [poliyID].[TokenName]. Simply put that into cardanoscan.io and you can see the wallet that holds any particular NFT. You then just mint (airdrop) a new token into that wallet. Done.
Take for example this blockowl:
3f4360edd7f689b637b44587150e71453a51ba29655336ff374c201c.BlockOwlsStake001
If you put the above into CardanoScan and click Top Holders, you will find the wallet it lives in:
addr1q87xqs5duasp4ehuec9gasy9qptt7zhweg046gh9pa7nmax6yxvvxd5qhurea4rvlj6a8c35twc0654l48avkn79z3mq46yfdm


text:
What are the steps in producing a block in Cardano?
I would love a high-level overview suitable for a beginner that covers collecting transactions, proposing a block, propagating the block, and then finally verifying it.

Here's a five-minute video by Andrew Westberg talking about just this.
In short, the steps are as follows:

A signed transaction is submitted to the mempool of the local cardano-node.
mempools are constantly being synced between the nodes' peers
A stake pool makes a new block by taking all the transactions in their mempool and appending it to the tip of their chain. TX's included in this block are then cleared from their mempool.
Other nodes see the stake pool has an extra block (and hence a longer chain), so they verify the block's legitimacy, and add it to their chain. TX's in the new propagating block are also cleared from everyone's mempool.
Repeat until the network is synced.

Hope this helps!


text:
Why does the full transaction have to be included inside the block?
Transactions are made outside of blocks, and transmitted unconfirmed between all nodes in a network; Nodes advertise new transactions assuming they pass verification to other nodes, who ask for the transaction if they have not seen it before.
It therefore seems redundant to include the full transaction within a block, because we can be pretty sure that most nodes already have most transactions, and if they are missing a transaction on receiving a block, must know at least 1 peer who can supply the transaction on demand (the node that sent them the block).
An SHA256 hash of a transaction is much smaller than an actual transaction, 32 Bytes versus at least 200 Bytes, so why not just list the transaction hashes within a block and let each node confirm they have all the transactions locally that are associated to that block, by calculating transaction hashes and confirm they have everything needed?
Im sure I must be missing something fundamental.
EDIT: I suppose its inefficient on storage, assuming we add 32 Bytes to every transaction, and then an associated 32 Bytes inside the block for each transaction.  100 Transactions per second would fit inside a 64KB block (at 20 seconds per block), but would add an additional, 188GB storage per annum.  Even so storage is relatively trivial compared to block propagation, isn't it?

For some reason this sounds eerily similar to how I imagine block pipelining would work. It was briefly mentioned in the most recent mid-month update:
https://www.youtube.com/watch?v=_JNK4eDZFMA

there is indeed a Cardano-improvement-proposal addressing such reference scripts
https://cips.cardano.org/cips/cip33/
also here on github
https://github.com/cardano-foundation/CIPs/tree/master/CIP-0033


text:
DeserialisationError when exporting UnbalancedTx
When converting my UnbalancedTx to an ExportTx using the export function, I get this error:
Left (Tag \"toCardanoPolicyId\" (Tag \"1 bytes\" DeserialisationError))

What is very strange is that when I submit the unbalanced transaction with submitUnbalancedTx in the emulator it works and the transaction gets executed. So it should be fine. I feel like this is a bug but I could also be missing something. Before digging deeper, I wanted to post this issue to see if someone can help me. Does anybody see what could be the reason for this issue ?
The error comes probably from function toCardanoMintValue on line 531 here: https://github.com/input-output-hk/plutus-apps/blob/main/plutus-ledger/src/Ledger/Tx/CardanoAPI.hs
The contract that I have looks like this:
buyTokensTx :: forall w s. TokenPool -> BuyTokensParams -> Contract w s Text (Either ToCardanoError ExportTx)
buyTokensTx pool param = do
  m <- findTokenPool pool
  case m of
    Nothing -> do
      logInfo @String $ "no token pool found with nft: " <> show (nft pool)
      return (Left $ TxBodyError "Error: cannot find token pool")
    Just (oref, o, state) -> do
      logInfo @String $ "found token pool with nft: " <> show (nft pool)
      let lookups = ...
      let txc = ...
      case Constraints.mkTx @TokenPool lookups txc of
        Right ut -> do
          let unbalTx = Constraints.adjustUnbalancedTx ut
          return (export def myNetworkId unbalTx)
        Left err -> return (Left $ TxBodyError $ "UnbalancedTx error:" <> show err)

I have the same issue as this error Left (Tag \"toCardanoPolicyId\" (Tag \"1 bytes\" DeserialisationError)) Thank you so much for the solution ;)

I finally found the issue and I think I might not be the only one to fall into this trap.
What happened is that I defined an asset class that I used as a placeholder for a stable coin in my smart contracts. I chose the following values that I saw in one tutorial:
stableCoinSymbol :: CurrencySymbol
stableCoinSymbol = "ff"

stableCoinTokenName :: TokenName
stableCoinTokenName = "USDT"

I then used this stable coin in the UTxOs of my transactions. Interestingly this works fine in the emulator, but throws a serialisation error (of course) because ff is not a valid CurrencySymbol.
So changing ff to a random valid one (e.g. 8d803516132f6fb8ddfcf168065886bf44ecc9e0023b570963b4bac8) fixed the issue.


text:
Tx signed by Nami Wallet returning InvalidWitnessesUTXOW in CLI
I am attempting to sign and submit a simple "always succeeds" transaction body built by the CLI and signed with nami wallet.
cardano-cli transaction build-raw \ --alonzo-era \ --fee 200000 \ --tx-in {NAMI_ADDRESS_UTXO} \ --tx-out {SCRIPT_ADDRESS}+1800000 \ --tx-out {NAMI_ADDRESS}+998000000 \ --invalid-hereafter 50000000 \ --protocol-params-file protocol.json \ --out-file tx-script.draft
Signing this file with an initial key in the CLI, I then sign it with nami using
const witnessSet = await window.cardano.signTx(transaction, true);
Generating the following hex CBOR:
a10081825820863d383db3cc7494604d02d3bf214706a18a178ce50eb1f04ad3ef45f50815735840da3ef50001e801bb9580ea361cff86fedef6aab41ebf835dbd246afae02a8b380cbfef0bb1c1ad299b57837dcc04d22a8fc81d713989160513fb14020b7ca203
This hex is sent to the back-end where I do some transformations to get the set in the form of [0, [vkey witnesses]].
let bufferWitness = Buffer.from(witnessSet, "hex");
let witnessDecoded = await cbor.decodeFirst(bufferWitness);

const newWitness = [0]; // Array format accepted by the CLI
newWitness.push(witnessDecoded.get(0)[0]); // vkey witness generated by Nami
console.log('Result:', cbor.encode(newWitness).toString("hex"));

This generates the following hex CBOR:
8200825820863d383db3cc7494604d02d3bf214706a18a178ce50eb1f04ad3ef45f50815735840da3ef50001e801bb9580ea361cff86fedef6aab41ebf835dbd246afae02a8b380cbfef0bb1c1ad299b57837dcc04d22a8fc81d713989160513fb14020b7ca203
Decoded as:
 [0, [h'863D383DB3CC7494604D02D3BF214706A18A178CE50EB1F04AD3EF45F5081573', h'DA3EF50001E801BB9580EA361CFF86FEDEF6AAB41EBF835DBD246AFAE02A8B380CBFEF0BB1C1AD299B57837DCC04D22A8FC81D713989160513FB14020B7CA203']]
When I use cardano-cli assemble to generate the final transaction and submit, I get this error:
ShelleyTxValidationError ShelleyBasedEraAlonzo (ApplyTxError [UtxowFailure (WrappedShelleyEraFailure (InvalidWitnessesUTXOW [VKey (VerKeyEd25519DSIGN "863d383db3cc7494604d02d3bf214706a18a178ce50eb1f04ad3ef45f5081573")]))])
Which I do not understand as the tx body is not altered by the time it is sent to Nami, only signed with a dummy key but I'm assuming that should not affect the witness generated?
Any help would be appreciated, thanks.

I also struggled getting this to work via the cli.  I went with a solution using the Java cardano-client-lib on the backend to create the base tx, and the cardano-serialization-lib browser package in the browser to add a sig.
here's the relevant browser code (selectively copy-pasted from my project, YMMV)
import * as CardanoSerdes from '@emurgo/cardano-serialization-lib-browser'
const Buffer = require('buffer/').Buffer

// helpers
function toHex(bytes) { return Buffer.from(bytes).toString("hex") }
function fromHex(str) { return Buffer.from(str, "hex") }

const txCborHex = "YOUR BASE TX CBOR HEX HERE"

const namiAddr = "nami wallet addr here"

// parse the base tx into the serialization lib model
const transaction = CardanoSerdes.Transaction.from_bytes(Buffer.from(txCborHex, "hex"))
const transactionWitnessSet = transaction.witness_set()
const transactionBody = transaction.body()

// get a handle on the PubKeyHash for the wallet
const walletAddress = CardanoSerdes.Address.from_bech32(namiAddr)
const baseAddress = CardanoSerdes.BaseAddress.from_address(walletAddress);
const baseAddrBytes = baseAddress.payment_cred().to_keyhash().to_bytes()
const pkh = CardanoSerdes.Ed25519KeyHash.from_bytes(baseAddrBytes)

// Add the pkh as a required signer
const requiredSigners = CardanoSerdes.Ed25519KeyHashes.new();
requiredSigners.add(pkh);
transactionBody.set_required_signers(requiredSigners);

// draft a new tx for the user to sign
let toSign = CardanoSerdes.Transaction.new(transactionBody, transactionWitnessSet);

// get the user to sign the base tx in the browser via nami
let txVkeyWitnesses = await cardano.signTx(
    toHex(toSign.to_bytes()),
    true
);
txVkeyWitnesses = CardanoSerdes.TransactionWitnessSet.from_bytes(
    fromHex(txVkeyWitnesses)
);

// add the sig to the base tx witness set
transactionWitnessSet.set_vkeys(txVkeyWitnesses.vkeys());

// compose a new tx
const readyToSubmit = CardanoSerdes.Transaction.new(transactionBody, transactionWitnessSet);

// convert to cbor hex.  you can submit this in the browser with cardano.submitTx() or using cli on the backend
const finalTx = toHex(readyToSubmit.to_bytes())

the npm deps in use are:
    "@emurgo/cardano-serialization-lib-browser": "^9.1.2",
    "buffer": "^6.0.3",

java dep
'com.bloxbean.cardano:cardano-client-lib:0.2.0-preview2'

This turned out to be a very useful answer for integrating a multi-sig pattern with Nami wallet. Thanks for the detailed answer and code.

I made a post on this, maybe this can help you. Basically you'd need to first sign transaction with cli, load transaction to cardano-serialization-lib, clear vkeys from witness-set, sign transaction on the frontend and add vkeys from signature witness-set.
Here's a link to my blogpost: https://srdjanstankovic.com/2021/12/24/how-to-sign-and-submit-cardano-cli-transaction-using-nami-wallet.html

The problem is that cardano-serialisazion-lib reorders the transaction and that makes the original witness invalid, https://github.com/Emurgo/cardano-serialization-lib/issues/311
My solution was

create tx with cardano-cli
deserialize with cardano-serialisazion-lib
serialize with cardano-serialisazion-lib
sign with cli


text:
Transaction Submit Error MissingScriptWitnessesUTXOW
I am currently working on a very simple auction dapp and am receiving this error:
{
    "code": 2,
    "info": "Wallet could not send the tx.",
    "message": "\"transaction submit error ShelleyTxValidationError ShelleyBasedEraAlonzo (ApplyTxError [UtxowFailure (NonOutputSupplimentaryDatums (fromList [SafeHash \\\"c52c505c0d6e374baf48b1e78cd8bdb921d76127e6961bc9100c9e8b45192952\\\"]) (fromList [SafeHash \\\"04c56e48044dae5359a5b2d5a2a73b374f20bd6cc70206e88f42b2a91ecaa408\\\"])),UtxowFailure (ExtraRedeemers [RdmrPtr Spend 1]),UtxowFailure (WrappedShelleyEraFailure (MissingScriptWitnessesUTXOW (fromList [ScriptHash \\\"c1c0f2fbbc40ec587e6a3fd05a43f02e3e23f9debb30d4a62e49e7bb\\\"]))),UtxowFailure (WrappedShelleyEraFailure (UtxoFailure (UtxosFailure (CollectErrors [NoWitness (ScriptHash \\\"c1c0f2fbbc40ec587e6a3fd05a43f02e3e23f9debb30d4a62e49e7bb\\\")]))))])\""
}

MissingScriptWitnessesUTXOW and ExtraRedeemers are confusing me and am curious if anyone else is having these problems? I am using the cardano-serialization-lib to build and sign the transaction.
Let me know if there is any supplemental information I can provide thanks!

It looks like this error went away after removing the first 6 characters of the script's cbor hex. For some reason the cardano-serialization library currently requires the removal of those first 6 characters.

May be it is related to this https://github.com/Emurgo/cardano-serialization-lib/issues/281and this https://forum.cardano.org/t/martify-marketplace-using-cardano-serialization-lib/89037 , handling reedemers and datums its giving problems for me too, I am building a market place using Martify Code.


text:
Marlowe: Value -> Integer
How to change the type of Value to Integer?
Or pass Value type as parameter to Bouds (between (parameter1 :: Value) and  (parameter1 :: Value))?

Could you please describe what are you trying to do?
There is a evalValue function in Semantics.hs which evaluates a Value expression to Integer.

In brief: choiceId name party = ChoiceId name party, next step: payment name party  = ChoiceValue (choiceId name party)... and value payment I want to convert to Integer...
Thanks for the hint. How easy is it to use this function in this case?


text:
Unlock the Funds in the Script with CSL
I'm building a transaction that using UTXO at script as the input.
Seem I signed enough vkey, perhaps include transactionWitnessSet.set_plutus_scripts.
Finally, i got this error Script inputs not supported yet.
Does anyone know work-around solution? ref: https://github.com/Emurgo/cardano-serialization-lib/blob/master/rust/src/tx_builder.rs#L95


text:
How to stop cardano-node from the CLI?
What is the command or process to gracefully stop a cardano-node instance from the CLI?

Depends on how you started the node. If it was started as a systemd service, you'd run the following: sudo systemctl stop <NODE_SERVICE_NAME>
If the node was started using the raw cli command cardano-node run, then you can just run ctrl-c in the same terminal that the node is running in, and it will perform a graceful shutdown.


text:
How Can I Transform an Ed25519KeyHash into a BaseAddress with the Cardano Serialization Library
I am currently attempting to transform a Ed25519KeyHash into a BaseAddress so I can use that address to perform transactions with the cardano-serialization-lib. However, I cannot seem to find a way to do this.
I managed to get a StakeCredential by doing:
StakeCredential.from_keyhash(  Ed25519KeyHash  instance  )
But I cannot find a way to get the BaseAddress. Has anyone figured out a solution for this? Thanks!

I seriously doubt this would be possible. As its name suggest, Ed25519KeyHash is a signature provided through a cryptographic hash of the initial key. Such a process is not reversible and is not intended to be.
I don't know the use case but if you need the initial address the hash comes from, you have to provide it another way.


text:
Is it possible to make a NFT collection by having consumer mint the NFT's
I want to create a NFT collection in which the creator does not have to mint the NFT's but the consumer does through a smart contract that they interact with. Would this be possible to do while sill keeping the same policy ID for each NFT or is that only possible by pre-minting the NFT's and sending them to a storing wallet.

Yes, you can do that.
An example could be to use a sequence number in a validator script (smart contract) in conjuction with a policy.

Validator script (smart contract) should manage the sequence number. For this, you can use the datum. Every time you mint a NFT, check that datum has increased (+1).
Policy can be the same for all tokens. You can append to your token name, the sequence number (here you can find a function to convert integer to bytestring)

Just make sure, to use a dummy NFT in your validator script:

To identify the right UTXO every time you mint
To validate from the policy script that it's included in the transaction.

Here is a good explanation for that.

Nice thanks that helps out a ton.

@georgeos answer is correct
I'd like to point out another way you could implement this:
You could use the consumer's UTxO as an input into the Token Name (it's common to use it as an parameter of the script to affect the policy name). Then you don't need to track state on a datum.
I'll mention, these methods will make the tokens non-fungible and unique, but if anyone can mint the NFTs they might not be particularly scarce--something to keep in mind. That being said, I think there are still some interesting uses for these patterns. And there would be additional ways to make the tokens scarce with time constraints, etc.

Would a boolean statement be a good way to stop the minting of an asset after x number of new NFT's, in the method provided.

Yeah. Plutus scripts are all just Boolean statements, essentially. Only allowing x tokens to be made is a constraint you could add, for sure.

This method will still keep the same Policy ID for all tokens minted right?


text:
Can a smart contract only be interacted with once
Im confused if a eUTXO can only be interacted with and used up once how can you do a NFT sale? If I were to make a smart contract to distribute NFT's from a wallet can that be interacted with by multiple people?

I think I understood the context of your question, but could you add more details to what you mean by "if a eUTXO can only be used once how can you do a NFT sale?" Others might not have as much context and there are many ways to implement an "NFT sale."

You can require a new datum be created as part of the validation.
Validator scripts simply validate transactions that spend UTxOs at the script address. They are able to look at the entire context of the transaction, including the outputs. It is true that a EUTxO can only be spent once, but you can add the requirement that an updated datum be returned to the script address after the old datum is spent, thus allowing the next person to interact with the script.

Additionally, CIP-33 (Reference Scripts) is currently being worked on by Cardano Foundation.
In a nutshell, it would establish a standard for attaching commonly used scripts to outputs that will never be spent; allowing all subsequent transactions to reference said outputs instead of resubmitting the same script every time. This would drastically reduce TX size for such commonly used scripts, making them cheaper and mitigating chain bloat.

CIP-31 is also worth calling out. It would allow read-only UTxOs, where you wouldn’t need to consume the datum on read.

Yes, I believe CIP-33 actually relies on CIP-31,as the former is more of a standard whereas the latter is an actual protocol.


text:
How to check the NFT timelock status?
How can I check the NFT timelock status, besides pool.pm?

You need to have the original script policy to see the lock status (see these slot and before).
$ cat policy.script
{ "type": "all", "scripts": [ { "slot": 24285375, "type": "before" }, { "keyHash": "e97316c52c85eab276fd40feacf78bc5eff74e225e744567140070c3", "type": "sig" } ] }

From that, you can calculate the policy id of it.
$ cardano-cli transaction policyid --script-file ./policy.script
00000002df633853f6a47465c9496721d2d5b1291b8398016c0e87ae

There is no way to reverse this process. You really need to original minting policy.

Agree with @Marek, although there is a manual way to do it.
Let's try the policy of Spacebudz:

You can find the policy in cardano scan
Go to the small script button at the left side of the policy id.
You can check there the invalidAfter slot
Using that slot, you can check in any tool (i.e. cardano-cli or explorer.cardano.org) the current slot to determine if the policy is locked or not.


text:
cardano-serialization-lib-browser loaded as empty module in NextJS
I'm trying to use cardano-serialization-lib in a NextJS project I'm working on, but I'm receiving an exception before initializing the application TypeError: Cannot read properties of undefined (reading 'from_address') in the following code
export const MINTING_POLICY_HASH = () => {
  const vh = Loader.Cardano.EnterpriseAddress.from_address(
    Loader.Cardano.Address.from_bech32(createAccountPolicyBechAddr)
  ).payment_cred()
  // ...
}

After digging a little bit, I found out that Loader.Cardano was returning a module, but an empty one, Loader is defined as follows:
class Loader {
  async load() {
    if (this._wasm) return;

    this._wasm = await import(
      "@emurgo/cardano-serialization-lib-browser"
    );
  }

  get Cardano() {
    return this._wasm;
  }
}

When I tried to print Loader.Cardano (after loading it with Loader.load() and waiting for it to actually be loaded), it gave me this:
Module {
  __esModule: true,
  Symbol(Symbol.toStringTag): 'Module'
}

Meaning, as I said, the module we are importing ("@emurgo/cardano-serialization-lib-browser") is weirdly giving us an empty result. I assume this has to do something with webpack or NextJS and the way they are handling WASM modules, here's my next.config.js:
/** @type {import('next').NextConfig} */

module.exports = {
  reactStrictMode: true,

  webpack(config) {
    config.experiments = {
      asyncWebAssembly: true,
      topLevelAwait: true,
    };

    return config;
  },
};

I used cardano-serialization-lib twice already with gatsby and create-react-app, but never with NextJS, if anyone could help I would appreciate.

I do not know why, but this worked for me
this._wasm = await import(
      "../node_modules/@emurgo/cardano-serialization-lib-browser/cardano_serialization_lib_bg"

:s ES6 notation did not work.
my whole loader:
class Loader {
  async load() {
    if (this._wasm) {
      return;
    }
    /**
     * @private
     */
    this._wasm = await import(
      "../node_modules/@emurgo/cardano-serialization-lib-browser/cardano_serialization_lib_bg"
    );
  }

  get Cardano() {
    return this._wasm;
  }
}

export default new Loader();

Good luck!

You saved my life, thank you. Spent two days trying to figure out what you did in minutes lol


text:
NativeScript vs PlutusScript
In cardano serialization lib what is the difference between NativeScript and PlutusScript? Is there a way to convert from one to the other? I'm trying to load a minting policy script I made as a NativeScript, but I couldn't find any examples of this, while I can see that, spacebudz, for example uses PlutusScript to load their contracts.

I think NativeScript is a simple multisig scripting language while PlutusScript is a Turing complete scripting language. You can find more details and examples of NativeScript here


text:
How to create a large one time NFT minting
I want to mint a NFT collection in one transaction to reduce the cost in transaction fees and time how do I create a CIP-25 compliant one time minting policy? Are there any tutorials out there?

You must specify all the minted items one by one and make a metadata such that all NFTs share the same policy this has been answered before:
How to mint multiple NFT assets in the same transaction?.
Consider the fact that there is maximum size for a transaction, so you can mint between 25 to 30 maybe 35.


text:
How does ledger generate the public keys?
How does the ledger HW wallet generate the public keys it exports to multi-account wallets like Nami/Typhon?
Based on this post by them, it sounds like it might be:

Parent private key is derived from master seed
Many child private keys are generated from the parent private key
The public keys are then generated - one for each child private key

The reason I'm asking is I want to know if I share my Account#0 with someone, do they have a way of knowing my Account#1...n? I looked at the BIP32 standard and it sounds like the answer is no but wanted to check because an additional twist for cardano is the staking address is embedded in the public addresses.
A practical case for this being important is if you do a transaction with someone using Account#0, you don't want them to know your other accounts.

Before activating the accounts feature, I wanted to be sure I can still access my funds even if the wallets using this feature will all disappear (adalite.io, ccvault.io and typhonwallet.io). So I tested it myself with cardano-hw-cli and my ledger device.
The default account starts from the derivation path:

1852H/1815H/0H/0/0 for the payment keys, and the last "0" increments for each ne wkey
1852H/1815H/0H/2/0 for the staking key.
The #1 account starts with:
1852H/1815H/1H/0/0 for the payment keys
1852H/1815H/1H/2/0 for the staking key
And so on: 1852H/1815H/2H/ for the account #2, 3H for the account #3...

I generated a few payment keys and the staking key for the first 5 accounts, then I generated the addresses from them, and compared them with the addresses displayed in the web wallets, and they matched.
Regarding you actual curiosity, I don't think there is any possible way for someone to make a connection between your different accounts. Your payment addresses from one account will be generated from a payment public key and the staking public key, so of course they will be identified by blockchain explorer as being from the same wallet. But I don't see how the different accounts could be linked together.


text:
Mint tokens using plutus scripts with the serialization lib
As I understand, in order to mint a token with the serialization-lib, you must use the function set_mint_scripts, providing a NativeScripts object. This collection of NativeScript objects should determine until what time a token can be minted and by whom.
With the introduction of Plutus, though, we have a new way of minting assets, which is using Plutus scripts. They allow or not the minting and burning of the assets based on arbitrary logic. These scripts are defined in the serialization-lib as PlutusScript and there doesn't seem to be a way of converting a plutus script into a native one (which makes sense since they are different things).
Is my understanding correct? And, if so, did I miss any function or object that is actually able to do what I want? If not, are there any workarounds I could make use of?

Im having the same question, did you found something about this?


text:
How to convert a Cardano address string to the Plutus address class
The title says it. How can I convert an address, such as the one that the Nami wallet returns, to the Address data class in Plutus ?
I have searched the GitHub repository but I could only find this low level function in Cardano.Ledger.Address:
-- | Deserialise an address from the external format. This will fail if the
-- input data is not in the right format (or if there is trailing data).
deserialiseAddr :: CC.Crypto crypto => ByteString -> Maybe (Addr crypto)

If this is the function to use, how to convert the Addr class to the Address class ?


text:
Where to find the latest repo Ledger.Constraints?
Revisiting Plutus pioneer code, I see Ledger-related code e.g.
ScriptContext Plutus.V1.Ledger.Contexts or Interval Plutus.V1.Ledger.Interval. Is there a github repo equivalent for Ledger Constraints? Why are some code on github and some on haddock?

The repos are these:
https://github.com/input-output-hk/plutus
https://github.com/input-output-hk/plutus-apps
You can import Interval, Contexts, and Constraints like this:
import Ledger.Constraints
import Ledger.Contexts
import Ledger.Interval

In the cabal file you would add them like this:
build-depends: ...
             , plutus-ledger
             , plutus-ledger-constraints


text:
How to create an NFT collection sale validator script
If I have a wallet that currently stores x amount of NFT's and I make a validator script that provides one NFT from that wallet in exchange for ADA what would I call to make sure 1 unique NFT goes out to each caller of the said validator script? Specifically how would the validator script know which NFT to give out? Is there a way to sort out metadata of NFT's using script context and pick the next NFT to send out by its number order?

There are onchain validator scripts available like this one, which describe nicely how it can be done.
nft-plutus by Berry Pool

The way that my vending machine does it is that I store all of the total NFT collection in a MongoDB. Then, when my script sees a sale UTXO come into a wallet, it queries the MongoDB for any NFT that is still 'available' and pulls them all down into an array. I then shuffle the array and mint the one in the [0] spot. Finally, I mark the NFT as sold in MongoDB.

This question is about plutus, not offchain solutions.


text:
Cardano address chaos
I'm trying to figure out the relations of the various types of addresses and how to convert one into the other.
The Nami wallet returns from its method cardano.getUsedAddresses() an array with one address that is 114 characters long and looks like this (testnet):
00dc107d6faf3fccbfae8b7446e3703f30200c7ae2767e607c88608a90c0efa54fe993c0f2de5236b46deaa4bc34b36c7c388f53eb51c9885a

This string is apparently the representation of the so called BaseAddress.
Now, I figured out that this format is the concatenation of three parts:

two characters for the network. '00' for testnet and '01' for the main net
A hex encoded 56 characters long hash of the verification key
A hex encoded 56 characters long hash of the staking key

So, I extracted the verification key hash and converted it into the bech32 format (elixir code):
pkh_hex = "dc107d6faf3fccbfae8b7446e3703f30200c7ae2767e607c88608a90"
bytes = Base.decode16!(pkh_hex, case: :lower)
bech_string = Bech32.encode("addr_vkh", bytes)

This gives me the value addr_vkh1msg86ma08lxtlt5tw3rwxuplxqsqc7hzwelxqlygvz9fq6dx76x for bech_string which corresponds to the one confirmed by the converter here: https://input-output-hk.github.io/cardano-addresses/demo
The address shown on the receive screen of the Nami wallet is (testnet):
addr_test1qrwpqlt04ulue0aw3d6ydcms8uczqrr6ufm8ucru3psg4yxqa7j5l6vncredu53kk3k74f9uxjekclpc3af7k5wf3pdqtk6tn9

I am wondering:
A. How can I derive this last address string above from the base address ?
B. Also, how can I convert the addr_vkh-address into a addr-address (of course without the staking key part) ?
C. Is this verification key hash the thing that is called PaymentPubKeyHash in Plutus ?

A. The "last address" and "base address" described above are the exact same data in different representations. What you're calling the "base address" is the hex representation of an address. The bech32 representation is just an encoding of that same data. The bech32 CLI utility is really good for doing these conversions (although the nodejs one you reference above can be used as well)
bech32 addr_test <<< 00dc107d6faf3fccbfae8b7446e3703f30200c7ae2767e607c88608a90c0efa54fe993c0f2de5236b46deaa4bc34b36c7c388f53eb51c9885a
addr_test1qrwpqlt04ulue0aw3d6ydcms8uczqrr6ufm8ucru3psg4yxqa7j5l6vncredu53kk3k74f9uxjekclpc3af7k5wf3pdqtk6tn9

B. The easiest way to understand address formats is at the binary level. You make an assertion above that mainnet addresses are 01 and testnet are 00, which is a true geeneralization, but doesn't explain the whole picture. The CDDL helps with understanding at a bit level how an address is made up: https://github.com/input-output-hk/cardano-ledger/blob/master/eras/shelley/test-suite/cddl-files/shelley.cddl#L89-L100
From this, we see an enterprise address (a base address with no delegation credential) is 0110 if it isn't a script. The hex representation of this is 6. So an enterprise address with just the payment key hash is 60dc107d6faf3fccbfae8b7446e3703f30200c7ae2767e607c88608a90 or in bech32: addr_test1vrwpqlt04ulue0aw3d6ydcms8uczqrr6ufm8ucru3psg4yq3c0kvn.
Here's the cardano-address inspect for that address:
cardano-address address inspect <<< 60dc107d6faf3fccbfae8b7446e3703f30200c7ae2767e607c88608a90
{
    "stake_reference": "none",
    "spending_key_hash_bech32": "addr_test1msg86ma08lxtlt5tw3rwxuplxqsqc7hzwelxqlygvz9fqltwcyd",
    "address_style": "Shelley",
    "spending_key_hash": "dc107d6faf3fccbfae8b7446e3703f30200c7ae2767e607c88608a90",
    "network_tag": 0
}

C. Yes

Thank you for the detailed answer ! So if I don't add the stake key hash it is an enterprise address. This explains why the Nami wallet doesn't recognise 'addr_test1vrw...0kvn' as its own address.


text:
Spending key hash vs payment key hash (pkh)
Cardano speaks in its documentation of the 'spending key hash' (see e.g. here: https://input-output-hk.github.io/cardano-addresses/demo/). In Plutus there is no spending key, there is a PaymentPubKeyHash in Ledger.Address. Are these the same ?

I found no PaymentPubKeyHash, but, from what I know, PubKeyHash is the same as spending key hash

PaymentPubKeyHash is a wrapper around PubKeyHash that was introduced recently to have more type safety and not confound stake and payment key. You can find it defined here: https://github.com/input-output-hk/plutus-apps/blob/main/plutus-ledger/src/Ledger/Address.hs

Interesting... Actually, I think "spending key" is the same as "private key", but "verification key" the same as "public key", so "spending key hash" would probably be "private key hash"


text:
How to run a Cardano relay instead of a full node?
I want to start a relay node not run the full cardano node.
There doesn't seem to be any tutorials for starting a relay node.
Anyone know how can i just a lightweight relay node so that I can run cardano-cli queries ?
Please note i only have 8 GB memory in docker so I can't afford to run a full node using docker or AWS/Google because they will cost a lot.
Thanks

A relay is a full node. I thibk what you're asking is how can I have a light wallet like experience with cardano-cli and the answer to that is you can't; however you can use something like blockfrost API to get the same type of information cardano-cli can provide.

Oh i see :(, thanks for that, it's because i always run out of resources when trying to build a full node on docker.

As the other answer says there is no real difference, a cardano-node is just configured to become a relay, its the same thing underneath.
If you build cardano-node from source, then you can control the number of threads used to compile with the standard -j flag, -j8 being 8 cores, more cores = more RAM needed.  https://github.com/input-output-hk/cardano-node/blob/master/doc/getting-started/install.md/
Still, actually running cardano-node on 8GB might be a bit too small, RAM optimizations are coming.