text:
Why do we need parameterized contracts? Can't we just use datum?
While writing validation as:
mkValidator :: SomeContractParam -> SomeDatum -> () -> ScriptContext -> Bool

Could't we pass the same thing to Datum instead of using Contract Parameter?

Yes. It's important to have both options though.
Remember that the script address is derived from a hash of the compiled script code. So, if you parameterize parts of the script, the script address will be different with each parameter.
An example Lars gives in the PPP is an NFT. If you parameterize the forging policy to take a specific UTxO, and that script consumes that UTxO, you guarantee that there is only one instance of that policy. Only the person who owned that UTxO could possibly create that token, thus guaranteeing the creation only happens once.
If you had the same UTxO field in the datum, any instantiator of the script could specify some UTxO they own and the script address would be the same. Since the Currency Symbol is in fact the Script Address, any caller could create duplicates of the token and those tokens would be fungible.

Are you proposing using SomeDatum' = (SomeContractParam, SomeDatum) in lieu of SomeDatum as the actual datum to use so that you can drop the SomeContractParam mkValidator argument?
If so, then here is a problem. It is easy to find all the UTXOs at an address (including script address), by using utxoAt, so when you have different script addresses associated with different SomeContractParam values, utxoAt will separate out the UTXOs for you by the SomeContractParam. If you use (SomeContractParam, SomeDatum) as the actual datum and one script address for handling all the different SomeContractParam values, you can't easily segregate the UTXOs by SomeContractParam especially when the blockchain stores only DatumHash and not Datum. So e.g. you can't easily specify "spend UTXOs from among those that match a certain SomeContractParam" -- you would have to lookup the datum of all the UTXOs somehow.
Furthermore you would have to include the datum in the ScriptLookups submitted for the transaction in order for the validator to get the SomeContractParam value from the datum, resulting in needing to encode the transaction request with more bytes.


text:
How to know if a transaction (tx) succeed or failed after awaitTxConfirmed?
How to know if a transaction (tx) succeed or fail after awaitTxConfirmed? Is there any function to get a tx on-chain by TxId?

awaitTxConfirmed is actually part of the off-chain code, so your computer is checking the chain to see if the transaction has become part of the ledger.
Sadly, right now awaitTxConfirmed does not know that a transaction has failed and if it did fail, your smart contact would be blocked, unless you introduce a logic to time out if your transaction is not included in the ledger for some amount of blocks for example.
However, I know the plutus team is working to solve this and we might have this functionality soon in Plutus.

source: Stack Exchange

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

sort: votes


text:
Why do Daedalus and Yoroi not support multi account delegation?
I am not programmer, but I am interested in development from user point of view.
I was looking for a way how to delegate to different pools from a single wallet and Adalite was the only wallet which supports this option.
I found also other users asking this question. Why is so little talked about this feature which could help mainly the smaller pools to get delegators when people will be able to divide their funds easily among several of them?

A better place to get the ball rolling on this issue would be the GitHub repo https://github.com/input-output-hk/daedalus/issues/1763

It's coming, but it isn't high priority right now in face of critical features. You can just make multiple wallets using a wallet like adalite.io till its possible.

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


text:
There is a CPU spike once per hour when logging "TraceLedgerEvent.TookSnapshot". Is it a bug, or is there a fix?
About once an hour, when TraceLedgerEvent.TookSnapshot is written to the log, there is a CPU spike and at the same time the slotMissedNum is increasing. Is this a bug in the node? Or is there a fix?
cardano-node v1.27.0
CPU 6Core
Mem 16GB

+1. Welcome to our new community and thank you so much for contributing your question here! We hope to see much more of you in the future !!! Please take a look at the edits that I suggested since they may improve how well your question is received here.

That CPU usage spike is only at most 8% of the CPU capacity, which is extremely small. I get spikes on my laptop CPU of 100% for longer time intervals than the spikes here, when just casually browsing the web.
If anything is being written anywhere on the computer, or anything is happening such as slotMissedNum increasing, I would  expect a CPU usage spike of around the size of the extremely small spikes you're seeing here.
I hope that takes care of the CPU spikes part of the question. If you believe that the increasing of slotMissedNum is a bug, then that's a different matter, for which I'm not immediately able to offer a solution, but that bug can be addressed entirely independently since the CPU spikes do not create any additional concerns.

Some of you have pointed out the same problem, what do you think?
https://github.com/input-output-hk/cardano-node/issues/2731

To clarify on the above answer, this spike occurs when it rights the state of the ledger in memory to disk at an interval. As the above comment states, it's a very small spike. If we didn't do this periodically, you'd have to rebuild the entire ledger state from scratch every restart of the node.

I think you mean, as the above answer indicates.


text:
Can you write dapps in C based languages?
Are there any good YouTube videos that are walk-through style for using a C-based language to write smart contracts, issue tokens and create NFTs?

Currently, you cannot write and deploy a smart contract in C on Cardano.
For native tokens (incl. NFTs), see the developer portal.
For writing smart contracts, you can use Marlowe or the more powerful Plutus.

Not currently.
There is work being done on the IELE VM. In theory this will allow any language that can compile to LLVM to be used to write smart contracts on Cardano. This includes C and C++, among other languages.


text:
"description error" occurred in Yoro Wallet
description error keeps popping up when I try to delegate or send a full delegation from Yoroi. What is the solution?

Can you please give a more detailed description of what you're trying to do? A screenshot would help too.


text:
Structure of the Address type from Plutus.V1.Ledger.Address
When I use scriptAddress on a validator of my SC I got the following result:
Address {addressCredential = ScriptCredential 22261390d0b365fef5a12bc33a29987fe10b28ed58e1036d27b0db43c613edad, addressStakingCredential = Nothing}

Is 22261390d0b365fef5a12bc33a29987fe10b28ed58e1036d27b0db43c613edad the script address?
Why doesn't it start with addr_test1?

The piece of data you show is encoded in Base16. Addresses are however typically encoded as Bech32 which allows for defining human readable prefixes like "addr_test".
As a matter of fact, it is possible to encode the same underlying data payload in different formats. The preferred one for presenting the data to end users should be Bech32, but Base16 may be a sensible choice for interoperability in contexts like command-lines or developer tools since it has wider support than Bech32.

And how to convert this address to bech32 in haskell?

https://hackage.haskell.org/package/bech32

This does not actually encode it correctly. When using the CLI, the address output of both is different: ScriptCredential /= base16 representation of cardano cli address

That is because a script credential isn't an address. Addresses have a header for type and discrimination; have a look at: https://github.com/cardano-foundation/CIPs/tree/master/CIP-0019

The sriptAddress is in Base16 (aka Hexadecimal)
You need to do a few things to it to transform into an address:
Add "70" to the front for Testnet, or "71" for Mainnet
The Header for Testnet is "70" and for Mainnet "71"
To work out why you need to go read CIP19:
https://cips.cardano.org/cips/cip19/#shelley-addresses
And then look up the
Header bits '011100000' for Testnet or
Header bits '011100001' for Mainnet
In a binary to Hex table, such as here:
https://www.rapidtables.com/convert/number/binary-to-ascii.html
Then you need to convert it into Bech32 and then further add "addr_test" to the front for Testnet, or "addr" for Mainnet. This is best all done with the help of some libraries.
Here is a sample script that does this, and as a bonus also gives the CBORHex of the script
{-# LANGUAGE DataKinds         #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE TemplateHaskell   #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeApplications  #-}
{-# LANGUAGE TypeFamilies      #-}

module Test where

-- Haskell Imports
import Prelude hiding (($))
import Data.Maybe
import Codec.Serialise (serialise)
import qualified Data.ByteString.Lazy as LBS
import qualified Data.ByteString as B
import qualified Data.ByteString.Short as SBS
import qualified Data.ByteString.Base16 as Base16
import qualified Data.Text as T
import Codec.Binary.Bech32 as B32
import Data.Text.Encoding as TE
import Data.Aeson.Encode.Pretty (Config (..), defConfig, encodePretty', keyOrder)

-- Plutus Imports
import Cardano.Api (serialiseToTextEnvelope)
import Cardano.Api.Shelley (PlutusScript (..), PlutusScriptV1)
import qualified Ledger hiding (singleton)
import qualified Plutus.V1.Ledger.Scripts as Plutus
import Plutus.V1.Ledger.Address (scriptHashAddress, Address)
import PlutusTx
import PlutusTx.Prelude hiding (Semigroup (..), unless, (.))
import qualified Cardano.Binary as CBOR
import Cardano.Codec.Bech32.Prefixes (addr_test, addr)

--------------------
-- Create Validator
--------------------
{-# INLINABLE mkValidator #-}
mkValidator :: BuiltinData -> BuiltinData -> BuiltinData -> ()
mkValidator _ _ _ = ()

validator :: Plutus.Validator
validator = Plutus.mkValidatorScript $$(PlutusTx.compile [|| mkValidator ||])

----------------------------------------
-- Create PlutusScript from validator
-- Print the CBORHex
----------------------------------------
script :: Plutus.Script
script = Plutus.unValidatorScript validator

scrAddress :: Ledger.Address
scrAddress = Ledger.scriptAddress validator

scriptShortBs :: SBS.ShortByteString
scriptShortBs = (SBS.toShort . LBS.toStrict . serialise) script

srlScript :: PlutusScript PlutusScriptV1
srlScript = PlutusScriptSerialised scriptShortBs

scriptCBORHex :: B.ByteString
scriptCBORHex = Base16.encode $ CBOR.serialize' srlScript

-------------
-- Generate JSON format
-- for Validator CBORHex
-------------

textEnvelopeJSONKeyOrder :: T.Text -> T.Text -> Ordering
textEnvelopeJSONKeyOrder = keyOrder ["type", "description", "cborHex"]

textEnvelopeJSONConfig :: Config
textEnvelopeJSONConfig = defConfig { confCompare = textEnvelopeJSONKeyOrder }

textEnveloper = encodePretty' textEnvelopeJSONConfig (serialiseToTextEnvelope Nothing srlScript) <> "\n"

----------------------------------
-- Generate PlutusScript Hash
----------------------------------
validatorHash :: Plutus.ValidatorHash
validatorHash = fromJust (Ledger.toValidatorHash scrAddress)

validatorHashHex :: String
validatorHashHex = show validatorHash

-----------------------------
-- Create Script Address
-----------------------------

addHeader :: String -> String -> T.Text
addHeader h v = T.pack (h Prelude.++ v)

{-
Header for Testnet is "70" and for Mainnet "71"
To work out why you need to go read CIP19:
https://cips.cardano.org/cips/cip19/#shelley-addresses

And then look up the
- Header Bits '011100000' for Testnet or
- Header Bits '011100001' for Mainnet
In a binary to Hex table, such as here:
https://www.rapidtables.com/convert/number/binary-to-ascii.html

The header is in Base16 format (aka Hexadecimal)

-}
header :: String
header = "70"

validatorHashHexWHeader :: B.ByteString
validatorHashHexWHeader = TE.encodeUtf8 (addHeader header validatorHashHex)

binary :: B.ByteString
Right binary = Base16.decode validatorHashHexWHeader

{-
Prefix for Testnet: "addr_test" and Mainnet: "addr"
These prefixes are imported from Cardano.Codec.Bech32.Prefixes
-}

dataPart :: B32.DataPart
dataPart = B32.dataPartFromBytes binary

{-
The bech32 representation is derived in 2 steps:
- bech32 = prefix + dataPart
- and where dataPart = header + validatorHash
-}
addrBech32 :: T.Text
Right addrBech32 = B32.encode addr_test dataPart

main :: IO ()
main = do
    putStrLn ("Script CBORHex: " Prelude.++ show scriptCBORHex)
    putStrLn ("Script Addr: " Prelude.++ show addrBech32)

Because plutus uses (Template) Haskell, hence deterministic.
Your SC is going to run as is when it goes live. Every output you get while developing your SC on the testnet/pc is applicable when you eventually move it to the mainnet.
So, it becomes impractical to expect a different output during development and a different one in production.

I dont think you understood my question. On Alonzo testnet all script addresses start with addr_test1 but the string inside the Address struct does not have that format? What is this string then?


text:
Pay out your salary from employer to employee in ADA (crypto)
How can I arrange for my company that I can pay my employee's in crypto ADA coins or crypto on the Cardano network?
I would like to facilitate my employee's that they have the option to pay a part of there salary in cryptocurrencies.
What are the possibility's within this matter, what is necessary for me to do or what is still being developed to get to this point?

It depends on your country. You should be well-acquainted with your responsibilities in terms of payroll withholding for taxes.
However, with respect to automating a system to pay your employees, I would recommend that when they would usually provide their banking details for direct-deposit, offer the alternative of instead providing a payment address to a Cardano wallet. At the end of every pay period, you can simply have Ada transferred to the wallet address on file instead of drafting a wire transfer.
If there is some concern that employees might lose access to their wallets, you could also offer to generate wallets with seed phrases for your employees so that both you and the employee knows that employee's seed phrase. Employees can then transfer their funds from their wallets immediately upon receipt; however, if an employee loses access to his or her wallet, you will be able to recover it for him or her.
I would also provide a receipt with the value of Ada upon sending it so that the employee will be able to calculate capital gains and losses to report to your country's version of the IRS. This will also provide you with a copy so that you can do the same.


text:
Trying to get a Testnet Node Running
Can anyone help me troubleshoot this? I am trying to get a testnet node running. After syncing for quite a while I get this error:
[DESKTOP-:cardano.node.DnsSubscription:Error:70] [2021-08-26 14:36:47.71 UTC] Domain: "relays-new.cardano-testnet.iohkdev.io" Application Exception: 54.151.49.138:3001 HeaderError (At (Block {blockPointSlot = SlotNo 1598400, blockPointHash = 02b1c561715da9e540411123a6135ee319b02f60b9a11a603d3305556c04329f})) (HeaderProtocolError (HardForkValidationErrFromEra S (Z (WrapValidationErr {unwrapValidationErr = ChainTransitionError [OverlayFailure (VRFKeyBadNonce (Nonce "81e47a19e6b29b0a65b9591762ce5143ed30d0261e5d24a3201752506b20f15c") (SlotNo 1598400) (Nonce "e209c5d22fe51d58485759cc9edca776cb505c1afb2ba5f98f8a6a979a7589e4") (CertifiedVRF {certifiedOutput = OutputVRF {getOutputVRFBytes = "t\231\145\196\165ZhA\137S\209{Z<1\194\225]Yq\235\&7#!\161:\147\129Q\236x\207\195z\170\155\182mw\141\182\135\249\209\178\134\&3_:\167b\135\204\&4\205Z\172\230\163\226\EM\DC2\226\182"}, certifiedProof = CertPraosVRF "!\202\180:L)*\DC2\250\SOH\141V \240Z\EOT\n\183\245\141\SUB\191\ETXQ\"\EOT\155A\SOH'\160LD\253\204Z\249\129/i\178\237p\155\140\240\142\183)LG\137q\248\DLE\DC1\130W\183\162\149\DEL6=[5\225/18\154\192=\242\255\181\f\190\190\t"}))]})))) (Tip (SlotNo 1598271) 4b9ea00e776ff866b1e562bc41ea5531090aaa2991891579b32ce691d8b684c6 (BlockNo 1597004)) (Tip (SlotNo 35619383) 8cce4530864892c20e2467f349fb3e22bb7965e620c286b9b01c689e94019520 (BlockNo 2861367))

You need to double check your genesis fine is 100% correct. Do not copy paste it, download it. Even one space of difference can be problematic.

I had changed some values in the config files that solved some other errors I was seeing, but since I do not know enough about how things are setup, I went ahead and started from scratch making sure to download the files as you suggested. Everything is working correctly now. Thanks for the info.

Thank you, I think this is because of the genesis file. I will fill it as an answer, please flag it if helpful.

This could happen when you genesis file is not matching your peers. Make sure you download the file, without editing. Even a single space of difference will result in a different genesis hash.


text:
Can't create keys for an NFT. cardano-cli address key-gen
Having trouble create a key for an nft.
Code:
cardano-cli address key-gen \
 --verification-key-file payment.vkey \
 --signing-key-file payment.skey

Error:
error: Found argument 'address' which wasn't expected, or isn't valid in this context

Any help is appreciated

can you show the output of cardano-cli --version ?

I'm getting the same error for cardano-cli version: 1.0.1.

Do not build/use the client from https://github.com/input-output-hk/cardano-cli

Assuming your cardano-cli version is up to date, if you are typing in the command exactly as typed above, you will need to escape the line breaks like so:
cardano-cli address key-gen \
  --verification-key-file payment.vkey \
  --signing-key-file payment.skey

that was my first thought, but that doesnt lead to this error message


text:
When will fees be finalized on the Alonzo testnet to reflect mainnet experience? Will it be on Sep 1?
I noticed the fees being shown to the Alonzo testnet users haven't been representative.  It was mentioned on Aug Cardano 360 it is being finalized.  Will it be implemented right out of the gate on 1 September with the public testnet release?

It is not confirmed yet, but that is the plan.


text:
Problem with creation of wallet using Javascript
Im using linux-Ubuntu in the WSL of the Windows 10.
I have installed Cardano-node and Cardano-cli. Node v14 (latest stable version) ghc 8.10.6
Im trying to create a wallet but on this command:
node src/create-wallet.js
I get this error:
const paymentVkey = options.paymentVkey
                                ^
TypeError: Cannot read property 'paymentVkey' of undefined
    at CardanocliJs.addressBuild (/home/marcelolinux/minter3/node_modules/cardanocli-js/index.js:316:33)
    at createWallet (/home/marcelolinux/minter3/src/create-wallet.js:7:11)
    at Object.<anonymous> (/home/marcelolinux/minter3/src/create-wallet.js:11:1)

Im following this (maybe) out of date tutorial.
I'have tryed with ghc 8.10.4 , also tryed configure the testnet but did'nt work also.
Can anyone help me to Mint Nft's using Javascript? I'm needing it for my final project of a course of Web Development.

I checked the npm page for cardanocli-js and found that you need to pass an options object to the AddressBuild method.

const createWallet = (account) => {
  cardano.addressKeyGen(account);
  cardano.stakeAddressKeyGen(account);
  cardano.stakeAddressBuild(account);
  cardano.addressBuild(account);
  return cardano.wallet(account);
};

createWallet("ADAPI");

needs to be altered to include an options object per the documentation.
It should be altered to be;

const createWallet = (account) => {
  const payment = cardano.addressKeyGen(account);
  const stake = cardano.stakeAddressKeyGen(account);
  cardano.stakeAddressBuild(account);
  cardano.addressBuild(account, {
    paymentVkey: payment.vkey,
    stakeVkey: stake.vkey,
  });
  return cardano.wallet(account);
};

createWallet("ADAPI");

This worked for me. I hope this helps.

Thank you! Worked for me also. You Rock dude.

I am also having the same problem on window using cardano-node-1.29.0-win64.  cardanocli-js node module has issue on windows doesn't know how to create folder correctly, I need to modified "index.js" file.  After fixing all that I finally run into the same problem you are facing.
For ubuntu, I got some weird problems not able to access my cardano-cli even I have it in my path, node is having trouble accessing.

I tried to build it manually by passing in skey and vkey files but no luck still, any help would be appreciated.


text:
Making Dapps with Flutter
I have not used Plutus yet, but I’m in the pioneer program and will start soon. I am wondering if you can integrate the smart contract code with Flutter as a front end?

Sure, as long as you have a backend that runs a full node and can submit your transactions to the network. Or you could use a third party API like https://blockfrost.io to achieve the same.

Checked out blockfrost.io, I see you can send transactions and query the blockchain but I don't see anything about smart contract calls. Sorry I'm a newbie. Hope we get like an ethers.js package

Smart contracts are not supported by the blockfrost API yet since they are not available on the mainnet and testnet yet. But they should add it in the near future I think.


text:
Error trying to compile cardano-node on Raspberry Pi
I tried to compile the cardano-node 1.27.0 for Raspberry PI4 following the instructions and everything gets well until I do the:
cabal build all

Then all compiles until I get this error:
   src/Testnet/Byron.hs:71:20: error: [-Woverflowed-literals, -Werror=overflowed-literals]
    Literal 8000000000000000 is out of the Int range -2147483648..2147483647
   |
71 |   , totalBalance = 8000000000000000
   |                    ^^^^^^^^^^^^^^^^

<no location info>: error: [-Wunused-packages, -Werror=unused-packages]
    The following packages were specified via -package or -package-id flags,
    but were not needed for compilation:
      - ansi-terminal-0.11

Can someone tell me why is this? Thanks

Hi and welcome to the Cardano stack exchange! Can you please provide a bit more information? What instructions did you follow (link)? And how did you make sure you use the the correct version of the source code?

Is your Pi possibly running a 32 bit OS?

Oh, thanks! I looked with uname -m and it says armv7l su 32bits. I will download a 64bits os image and try again and update the question.

You could have a look at this. It shows how to setup the Pi4 to build cardano-node, but you could also simply run the cardano-node in docker.

Welcome to our community! Unfortunately this is a link only answer unless you summarize what that link tells us in terms of showing how to setup the Pi4. This type of answer is best left as a comment, which unfortunately you won't be able to do without earning a bit of reputation by writing high-quality (much longer) answers.


text:
Is there a penalty for having two block-producing (BP) nodes in a pool that try to mint a block in the same slot?
Is there a penalty for having two block-producing (BP) nodes in a pool that try to mint a block in the same slot? For example, I'd like to bring up a new BP node in another region, but that results in two serving BP nodes for a brief moment, and just maybe that moment just happens to be the leader slot for the pool. What's the worst case scenario under this condition?

There is no such penalty at the protocol level.
However, you will probably get called out on Twitter :)

Hi, thanks! Can you explain what actually happens in this scenario? My guess is that there's a "slot battle" but in this case the VRF key would be the same for both nodes, so I'm not sure how the protocol handles this situation.


text:
Where to find the code for Alonzo / Plutus / Smart contracts?
I am currently learning about Plutus and how to write smart contracts in it by following the Plutus Pioneers course on Youtube.
However, I'm curious to know how things work from a node perspective: How a Cardano node receives and validates a transaction that has a smart contract attached to it.
What repos/branches should I take a look at?
I also asked this at Reddit/r/CardanoDevelopers.

Given that you're looking for what node (likely you mean protocol) does, the code you're looking for is distributed across repositories.
You can find the source code for interaction with node (API) here, while the propogation/consensus aspect can be found at ouroboros-network repo.
All the component-level repositories use ledger derivates from executable specs here - note that I've shared Alonzo specs which is not being used on mainnet yet, but given the background provided in your question.
Lastly, the plutus spec/execution code itself used for testnet(s) - as you're prolly aware - resides in plutus repo


text:
Would anyone respond / share who is working in the real estate space with Cardano?
Who is working within real estate on blockchain, and especially within ADA/Cardano?

Here is a comprehensive list of Cardano partners.
It's not immediately obvious which/if any are real estate projects.


text:
How is access control managed with smart contracts in (e)UTXO?
I've seen Charles mention this a little bit in some of his videos. He sort of laughs it off like the answer is obvious, but I'm not deep into the technicals. I also had an Ethereum developer bring it up, so I tried to do my own research and could not find the answer. Maybe it's so obvious that it doesn't really require a technical answer, but I'm here for a response either way. Specifically, the Eth dev said:
"Unspent outputs is the issue. Change addresses and smart contract interaction just doesn't vibe. This is exactly why ethereum is account based. Because it's the only rational way to do smart contract interaction."
Now, obviously there are many dapps from many devs running on the testnet right now, so I'm wondering what the technical rebuttal would be to this concern.
Thanks for all your contribution to the Cardano community!

I'm interested in this too. Here is another similar thread: https://cardano.stackexchange.com/questions/722/general-approach-for-allowing-multiple-smart-contract-transactions-per-block/2407#2407
I'm glad you've asked a new question about it, since I still haven't gotten a straight answer either.

Maybe I'm misunderstanding what people mean by "access control". Is Marek Mahut's answer what you were looking for?

If you think about it, your smart contact is attached to a specific UTXO. And somehow, in multi user environment, we need to distinguish the true smart contract output from other outputs that might also include this smart contact.
And the way we do this is to put an specific NFT on the output. Because an NFT can only exist once therefore is unique, there can only be one UTxO at the script address that holds the NFT and thus identities your smart contact.
This article from Robert Kornacki explains it in details, mostly:

(...) dApp UTXOs having no in-built uniqueness property which make
them clearly and reliably identifiable from others. This can be
potentially capitalized on by bad actors, or may simply cause problems
due to bad protocol design of new devs who are just getting their
bearings. This clearly is a major issue that must be addressed,
however we luckily have a great innovation which tackles this problem
precisely, NFTs.
(...) Because each NFT can only be created once and UTXOs have the ability
to hold tokens, this means that if we put an NFT inside of the UTXO of
the dApp we are deploying we can guarantee that no one else can do the
same. The NFT acts as an unforgable unique identifier that makes it
trivial for anyone and everyone to see which UTXO is the true
deployment of the protocol. Each dApp frontend must merely save the
currency ID of the NFT in order to be able to use it to verify that
any UTXO it finds at the smart contract address has the correct NFT
inside. If the UTXO does not, it is treated as invalid and ignored. It
does not matter whether the invalid UTXO was created by mistake or by
a bad actor on purpose, it is not the correct UTXO that we are looking
for and thus filtered out. To ensure that the uniqueness property is
forever held, the smart contract tied to the UTXO must specify that
the NFT is never allowed to leave the dApp. In other words, every time
someone spends the dApp UTXO, the NFT must be held in an output that
is also locked by the same dApp smart contract (this technically
changes in the context of dApp updates, but we can skip over that for
now). This NFT preservation check is the only code required to
guarantee the uniqueness property of the dApp. If this check is not in
place then it may be possible for a bad actor to steal the NFT and put
it in his deployment, thereby destroying all guarantees we had
originally.


text:
How to figure out what address to query for utxos when minting
Following the iohk guide to minting assets we identify the input utxo using the following command:
cardano-cli query utxo --address $address --testnet-magic 1097911063

This is all well and good if you know the address which you wish to query. However, if you are using wallet software (including cardano-wallet) you will find that the change behavior of wallets will move assets across addresses (but within the same wallet). As such, just because you sent ada to an address at one time does not mean you will find it there in the future if you have performed any transactions since sending it.
We'd like to know if anyone is aware of a better approach to identifying a source utxo for buildling an asset minting transaction when starting with a wallet rather than with an address and using the core standard toolset cardano-wallet, cardano-cli, cardano-address, etc

If you run this bash script, you will create a wallet, load it in cardano-wallet and get all the info you need, including the address you are needing. The script if going to create some files for the wallet in the same folder where you are running it.
I can show you also how to do it using only Cardano Cli if you want.
Firts, set this ENV variables for everything to work:
CARDANO_WALLET=rute to your cardano wallet folder
CARDANO_WALLET_PORT=port used in the cardano wallet server (eg. 9091)
CARDANO_NODE=rute to your cardano node folder
NETWORK_WITH_MAGIC=testnet-magic 1097911063

#!/bin/bash

if [ -z "$1" ]; then
    echo "File name:"
    read file
else
  file=$1
fi

if [ -z "$2" ]; then
    echo "Name:"
    read name
else
  name=$2
fi

if [ -z "$3" ]; then
    echo "Passphrase (10 or more characters):"
    read passphrase
else
  passphrase=$3
fi

echo "Creating Wallet with name $name passphrase $passphrase in $file.json"

phrase=$($CARDANO_WALLET/cardano-wallet recovery-phrase generate)

x=''
sep=''
for word in $phrase
do
    x=$x$sep'"'$word'"'
    sep=', '
done

cat > $file.json <<- EOM
{ "name": "$name"
, "mnemonic_sentence": [$x]
, "passphrase": "$passphrase"
}
EOM

echo "Saved restoration file to $file.json"

echo $phrase | $CARDANO_WALLET/cardano-wallet key from-recovery-phrase Shelley > $file.root.prv

cat $file.root.prv | $CARDANO_WALLET/cardano-wallet key walletid > $file.id

wallet_Id=$(cat $file.id)

echo "Wallet ID:" $wallet_Id

curl -H "content-type: application/json" -XPOST \
  -d @$file.json \
  localhost:$CARDANO_WALLET_PORT/v2/wallets

echo ""

addresses=$(curl -H "content-type: application/json" \
      -XGET localhost:$CARDANO_WALLET_PORT/v2/wallets/$wallet_Id/addresses | jq -r '.[]' )

echo $addresses| jq -r '.id' >$file.addrs

echo "Wallet Addresses:"

echo $addresses| jq -r '.id' | nl

address=$(echo $addresses| jq -r '.id'| sed -n 1p)

echo ""

echo "Firts Address:" $address

echo $address> $file.addr

echo "UTxOs At Address:"

$CARDANO_NODE/cardano-cli query utxo --address $address --$NETWORK_WITH_MAGIC

I hope it helps!

for the first point / question, about finding the source address
i would do the follow,
create a "project in blockfrost :
blockfrost.io/
and then execute the commands below:
curl -H 'project_id: type_blockfrost_Project_ID'
https://cardano-mainnet.blockfrost.io/api/v0/txs/${tx_hash}/utxos
| jq '.inputs' | jq '.[0]' | jq '.address' | sed 's/^.//;s/.$//'

I appreciate your feedback, but using a third party service is not an option. We are interested in the low level details of how to do this using Cardano directly.
Further, I think you've misunderstood our goals. We are not trying to determine the utxos related to a tx. We are trying to find a utxo to use as input to a minting tx.

ok the "source" confused me.
sorry for the misunderstanding.
the only option i find for the "cardano-cli query utxo " is only --address.-
then, sorry mate still dont have answer

here is a list of subcommands of the cardano-wallet.
i didnt know you can do it from "wallet",
but looks like you have this options.
transaction
create


text:
Connect cardano-wallet to pre-production testnet
We use the prescribed docker compose from iohk. Here is the cardano-wallet excerpt:
cardano-wallet:
    image: inputoutput/cardano-wallet:2022.8.16
    container_name: cardano_wallet
    volumes:
      - wallet-testnet-db:/wallet-db
      - node-ipc:/ipc
    ports:
      - 8091:8090
    entrypoint: []
    command: bash -c "
        ([[ $$NETWORK == \"mainnet\" ]] && $$CMD --mainnet) ||
        ($$CMD --testnet /config/$$NETWORK/genesis-byron.json)
      "
    environment:
      CMD: "cardano-wallet serve --node-socket /ipc/node.socket --database /wallet-db --listen-address 0.0.0.0"
      NETWORK: "testnet"
    restart: on-failure

Now that we are connecting our node to pre-production, we are getting the following error:
cardano_wallet    | cardano-wallet: ExceptionInLinkedThread (ThreadId 17) (HandshakeError (Refused NodeToClientV_13 "version data mismatch: NodeToClientVersionData {networkMagic = NetworkMagic {unNetworkMagic = 1}} /= NodeToClientVersionData {networkMagic = NetworkMagic {unNetworkMagic = 1097911063}}"))

This makes sense to me. It looks like the wallet is trying to connect to the old testnet using the old network magic 1097911063. The problem is that it isn't clear how to get it to connect to preprod instead.

The problem here was that iohk updated the 2022.8.16 image tag with new configurations but without creating a new tag. If someone gets the latest version of that image then using NETWORK=preprod should work.


text:
What's the difference between `unstableMakeIsData` and `makeIsDataIndexed`?
In the docs about validators a function named unstableMakeIsData is used, but has the following comment:
-- 'unstableMakeIsData' is a TemplateHaskell function that takes a type name and
-- generates an 'IsData' instance definition for it. It should work for most
-- types, including newtypes and sum types. For production usage use 'makeIsDataIndexed'
-- which ensures that the output is stable across time.
unstableMakeIsData ''Date

It seems inconvenient to have code that needs to be changed for production so I'm curious why this is required. For example, why not just use makeIsDataIndexed in development too? What benefit does unstableMakeIsData have?
I tried searching for both function names across the docs, but the only instances are in two different comments along these same lines.

The URL is now broken. 404

@Elrond_EGLDer I've updated it to what seems to be the same page hosted on another domain. Thanks!

If you take a look at the code you can see that makeIsDataIndexed takes 2 arguments (datatype and mapping) but unstableMakeIsData takes only 1 argument, so it's faster to use (that's why it's used in examples)

Usage example:
PlutusTx.makeIsDataIndexed ''Action [('Deposit,0),('Choice,1),('Notify,2)]

With unstableMakeIsData it would look like this:
PlutusTx.unstableMakeIsData ''Action

You can find more context in this commit as well. Note, that unsafeMakeIsData was later renamed to unstableMakeIsData.
The old `makeIsData` would encode/decode based on the ordering of the
constructors, which isn't stable. We *need* this to be stable across
time, since tools other than our Haskell programs might be producing
datums/redeemers (e.g. CBOR tools in other languages), so we really
don't want this to change unexpectedly.

So we avoid it everywhere. The exception is the usecases: they're just
examples so it's fine for them to be unstable.

Marlowe is probably the most annoying, but I think we *do* care about
the Marlowe types being stable!

Aha, perfect! I didn't see any examples using makeIsData so didn't realise it took this extra data. Makes sense now, thank you!

Great answer, I will award the bounty on Monday just in case somebody can come up with a better answer.  But a better answer seems unlikely. :-)

makeIsDataIndexed take 2 values and we use it when we are working with stable data and we don't them to be changing in the future so we index them explicitly to ensure.
Example: makeIsDataIndexed ''Bool [('False,0),('True,1)] so if we refer 1 we will get True and 0 False.
unstableMakeIsData only takes one value and this value won't be changing in the future which mean that there is no need to index it it is only one value.
unstableMakeIsData ''()
Hope it helps


text:
Is the Cardano testnet indefinite and immutable?
As the Cardano mainnet, will the Cardano testnet be maintained indefinitely and immutably or it will perish at some point in time?

No, there are plans to reset the testnet in the future, probably sometime after Goguen.
But it is immutable forever, if you keep the blockchain data.

Since it could be reset that means it's being maintained by a central entity or does it run on top of volunteer nodes?

It is run by the IOG DevOps' team, but most of the nodes are run by the community.

Well, we can assume that it will be maintained indefinetely because Cardano will also will be under development.
In the same way as in system administration you have Dev, Staging and Production environments in Cardano we also need to have testnet before pushing that in mainnet.


text:
Cabal build Caradano-cli Cardano-node error
I'm trying to create a Cardano staking pool on a raspberry pi 4 with 8GB of RAM. I've been following the coin cashew tutorial for staking pools: https://www.coincashew.com/coins/overview-ada/guide-how-to-build-a-haskell-stakepool-node#1-install-cabal-and-ghc
I finally got the cabal build for cardano-cli and cardano-node. I have also checked that ghc is on 8.10.4 but for some reason getting this error:
ghc: could not execute: opt
cabal: Failed to build Diff-0.4.0 (which is required by
test:cardano-cli-golden from cardano-cli-1.29.0). See the build log above for
details.
Failed to build Only-0.1 (which is required by test:cardano-node-test from
cardano-node-1.29.0, exe:cardano-node from cardano-node-1.29.0 and others).
See the build log above for details.
Failed to build StateVar-1.2.1 (which is required by test:cardano-node-test
from cardano-node-1.29.0, exe:cardano-node from cardano-node-1.29.0 and
others). See the build log above for details.
Failed to build Win32-network-0.1.0.0 (which is required by
test:cardano-node-test from cardano-node-1.29.0, exe:cardano-node from
cardano-node-1.29.0 and others). See the build log above for details.
Failed to build abstract-par-0.3.3 (which is required by
test:cardano-node-test from cardano-node-1.29.0, exe:cardano-node from
cardano-node-1.29.0 and others). See the build log above for details.

The logs it's telling you to read are the same ones we'd need to read to be of any assistance.

You dont need to compile the code on raspberrypi. It takes 7+ hours.
Use the prebuilt binaries from armada-alliance.
https://github.com/armada-alliance/cardano-node-binaries/tree/main/static-binaries
Join the telegram channel

Find some resources and prebuilt binaries for arm here.
armada-alliance.com


text:
How to get balance of an address using Cardanosharp
I am trying to develop a simple program where I am able to generate an address successfully using a public key and a stake key. The network type is TestNet.
How can I check the balance of the generated address?
Code snippet is as follow:
var existingaddresses = _Addresses.Find(x => x.WalletId == wallet.Id).ToList().Count;
            var user = _users.Find(x => x.Id == wallet.UserId).FirstOrDefault();
            NetworkType net;
            if (IsMainNet)
            {
                net = NetworkType.Mainnet;
            }
            else
            {
                net = NetworkType.Testnet;
            }
            Mnemonic mnc = keyService.Restore(wallet.Words, WordLists.English);
            PrivateKey masterKey = mnc.GetRootKey(user.Password);
            string PaymentPath = $"m/1852'/1815'/0'/0/"+ existingaddresses;
            PrivateKey paymentPrv = masterKey.Derive(PaymentPath);
            PublicKey paymentPub = paymentPrv.GetPublicKey(false);
            string stakePath = $"m/1852'/1815'/0'/2/"+existingaddresses;
            PrivateKey stakePrv = masterKey.Derive(stakePath);
            PublicKey stakePub = stakePrv.GetPublicKey(false);

            Address address = addressService.GetAddress(paymentPub, stakePub, net, AddressType.Base);

Now I want to check the balance of the generated address.

You can use the Blockfrost.io API to get information about the address. I'd recommend using the blockfrost-dotnet package for this.

I have tried it but i am getting content not found exception which means this Address doesnot exist on test net. Isnt it? What can be the reason?

I think this happens if the address has never been used.

agreed. as address is never used. Any idea what can be done to activate the address on testnet?

Send some tADA to that address: https://testnets.cardano.org/en/testnets/cardano/tools/faucet/


text:
Test node failure
I successfully setup a testnet node over the weekend, all was running fine - I was able to create wallets and perform transactions etc.
However when I try to run the node today I am getting some errors, I haven't changed any config, I literally just turned the machine off and when I booted back up it didn't work (see error at the bottom)
I have downloaded the latest config files, I also deleted some data from the immutable folder in /db  - it synced up again but then gave the same error
I hope someone can help, many thanks in advance.
Environment
Ubuntu 18.04.5 LTS (Bionic Beaver)

cardano-node 1.27.0 - linux-x86_64 - ghc-8.10
git rev 8fe46140a52810b6ca456be01d652ca08fe730bf

cardano-cli 1.27.0 - linux-x86_64 - ghc-8.10
git rev 8fe46140a52810b6ca456be01d652ca08fe730bf

cabal-install version 3.4.0.0
compiled using version 3.4.0.0 of the Cabal library

The GHCup Haskell installer, version v0.1.16.2

Startup command
cardano-node run \
   --topology /home/adam/dev/cardano-node/relay/testnet-topology.json \
   --database-path /home/adam/dev/cardano-node/db \
   --socket-path /home/adam/dev/cardano-node/relay/node.socket \
   --host-addr 127.0.0.1 \
   --port 1337 \
   --config /home/adam/dev/cardano-node/relay/testnet-config.json

Errors
[HPE-LX-M:cardano.node.ErrorPolicy:Notice:824] [2021-09-01 23:23:22.35 UTC] IP 3.129.133.68:3001 ErrorPolicySuspendConsumer (Just (ConnectionExceptionTrace (SubscriberError {seType = SubscriberParallelConnectionCancelled, seMessage = "Parallel connection cancelled", seStack = []}))) 1s
[HPE-LX-M:cardano.node.DnsSubscription:Error:1037] [2021-09-01 23:23:22.55 UTC] Domain: "relays-new.cardano-testnet.iohkdev.io" Application Exception: 18.132.238.21:3001 MuxError (MuxIOException Network.Socket.recvBuf: resource vanished (Connection reset by peer)) "(recv errored)"
[HPE-LX-M:cardano.node.ErrorPolicy:Warning:824] [2021-09-01 23:23:22.55 UTC] IP 18.132.238.21:3001 ErrorPolicySuspendPeer (Just (ApplicationExceptionTrace (MuxError (MuxIOException Network.Socket.recvBuf: resource vanished (Connection reset by peer)) "(recv errored)"))) 20s 20s
[HPE-LX-M:cardano.node.DnsSubscription:Error:1035] [2021-09-01 23:23:22.69 UTC] Domain: "relays-new.cardano-testnet.iohkdev.io" Application Exception: 3.124.178.139:3001 MuxError (MuxIOException Network.Socket.recvBuf: resource vanished (Connection reset by peer)) "(recv errored)"
[HPE-LX-M:cardano.node.ErrorPolicy:Warning:824] [2021-09-01 23:23:22.69 UTC] IP 3.124.178.139:3001 ErrorPolicySuspendPeer (Just (ApplicationExceptionTrace (MuxError (MuxIOException Network.Socket.recvBuf: resource vanished (Connection reset by peer)) "(recv errored)"))) 20s 20s

Out of mere curiosity, why 1.27.0 and no 1.29.0?

Today the Alonzo hardfork was done on the Testnet, you should update your cardano-node and cardano-cli to version 1.29.0.

I had the same error. I don't know exactly what this is about. But I just deleted the whole db folder and created node.socket again. Resync, then it's back

Thanks all, I will update later and try again and let you know how it goes

All sorted, thanks for the heads up; guess I'd better start keeping up with the updates!


text:
Confusion with cardano db sync schema and UTXO model
I am confused with the tx_in and tx_out schema on Cardano dbsync and the transaction process as a whole. For example:
Alice has 10000 ADA distributed as 3000, 5000 and 2000 ADA in three different EUTXOs. If she wants to send 6000 ADA to Bob then she can sends two EUTXOs to Bob, e.g. 5000 and 2000 ADA (total 7000 ADA) and receives a new EUTXOs of 1000 ADA back, right?.
For Alice, are those 7000 ADA stored in the tx_out table and the 1000 ADA in the tx_in table? Will she get the 1000 ADA back into the same address or a different one? If she receives the 1000 ADA back to a different address, will the same transaction block contain both transaction, i.e. address used to send ADA to Bob and the other address used to receive ADA back? Will they have the same transaction id?

Thanks for your question.

send about 6000ada to bob then he sends the two UTXOs to bob i.e. 5000ada and 2000ada (total 7000 ada) and he receives a new UTXOs of 1000ada back, right?

Correct. For regular transactions, the sum of the transaction inputs values must match the sum of the outputs (This isn't strictly true, as there are fees and the possibility to create native assets in a transaction too)

for alice, is not 7000ada stored in tx_out table and 1000ada in tx_in table?

Correct. A total of 7,000 ₳ would appear in Alice's tx_out and 1000 ₳ in Alice's tx_in, while Bob would see just the outputs of 6,000 ₳ - balancing the transaction inputs and outputs.

Will the receiver(alice) get the 1000ada back to same address or different?

Alice will receive the change to the same address which created the transaction.

Will they have the same transaction id?

Yes, any given transaction can have multiple inputs and multiple outputs.
If you want a patiently presented video that describes the model in an adequate amount of details, I'd recommend The first lecture in the Plutus Pioneers program.

One more thing to add maybe, Alice doesn't "send" the transactions to Bob, they're marked as "spent" and 2 completely new EUTXOs are crated: one with 6000 ADA and the other with 1000 ADA


text:
Exception trying to run test node
I am trying to run a node for testing. I have been through the installation and downloaded the config files from iohk but I am getting an exception when the configs are parsed:
AesonException "Error in $: parsing PartialNodeConfiguration failed, expected Object, but encountered String"

cardano-node: Aeson exception:
Error in $: parsing PartialNodeConfiguration failed, expected Object, but encountered String

The command I am using is:
cardano-node run \
--config /home/mark/cardano_configs/testnet/testnet-config.json \
--database-path /home/mark/cardano_configs/testnet/db/ \
--socket-path /home/mark/cardano_configs/testnet/db/node.socket \
--host-addr 127.0.0.1 \
--port 1337 \
--topology /home/mark/cardano_configs/testnet/testnet-topology.json

Any help appreciated

The links to the json files in the tutorial are out of date.  If you open them they contain url to the new location.  I downloaded them with curl so didnt notice.

Please update the question with the link you had used.


text:
How do i resolve this cabal error for cardano-node install?
I followed the Linux tutorial at
https://developers.cardano.org/docs/get-started/installing-cardano-node
and I am getting the following error when I run cabal build all
Unrecognized stanza on line 139
/home/xxx/.cabal/config: Unrecognized field installdir on line 116
Warning: Unknown/unsupported 'ghc' version detected (Cabal 2.4.0.1 supports
'ghc' version < 8.7): /home/xxx/.ghcup/bin/ghc-8.10.4 is version 8.10.4
cabal: No cabal file found.
Please create a package description file <pkgname>.cabal
xxx@MSI:~/cardano-src/cardano-node$ echo "package cardano-crypto-praos" >>  cabal.project.local
echo " xxx@MSI:~/cardano-src/cardano-node$ echo "  flags: -external-libsodium-vrf" >>  cabal.project.local
danastos@MSI:~/cardano-src/cardano-node$ cabal build all
Warning: The build command is a part of the legacy v1 style of cabal usage.

Please switch to using either the new project style and the new-build command
or the legacy v1-build alias as new-style projects will become the default in
the next version of cabal-install. Please file a bug if you cannot replicate a
working v1- use case with the new-style commands.

For more information, see: https://wiki.haskell.org/Cabal/NewBuild

Warning: /home/xxx/.cabal/config: Unrecognized stanza on line 139
/home/xxx/.cabal/config: Unrecognized field installdir on line 116
cabal: No cabal file found.
Please create a package description file <pkgname>.cabal
xxx@MSI:~/cardano-src/cardano-node$

What am I supposed to do here?

With distribution of GNU+Linux are you using? Which version of cabal are you using? Did you use ghcup to install the latest version of ghc? Did you cd in the cardano-src folder (the No cabal file found tells me you're not in the correct folder).
In your question, it would be very helpful if you could describe every step you took until it breaks and show the terminal outputs for each step.

I am in the cardano-node folder and I have
cabal-install version 2.4.0.0
I have The Glorious Glasgow Haskell Compilation System, version 8.6.5 for GHC

I followed this exactly:
I am operating under WSL Windows 10
https://developers.cardano.org/docs/get-started/installing-cardano-node

The tutorial says to install a more recent version of GHC with ghcup install ghc 8.10.4 and ghcup set ghc 8.10.4. Did you do that?

I have version 8.6.5 set
I enter set ghc 8.10.4 but it still shows 8.6.5 ( ghc --version )
It also says GHC ver 8.10.4 already installed;

https://imgur.com/a/RQf88bN

thats a screen shot of the version

The docs say that the command to switch GHC version is ghcup set ghc 8.10.4. You forgot the ghcup.

Same error
https://imgur.com/a/sqwowMo

the GHC version also still remain 8.6.5... that didnt change

https://imgur.com/a/ZAlT0Tb

I unisntalled it and reinstalled it and still get the same 8.6.5 version... it wont go to 8.10.4

Let us continue this discussion in chat.

Ok.. got it figured out. It was path related. Make sure to add /home/xxx/.ghcup/bin to your path.. it needs to be prepended on the path to make sure you are picking up the correct version PATH=/home/xxx/.ghcup/bin:$PATH


text:
Send-tip to pooltool.io
I am trying to send tip info to pooltool.io.
I have already created an account on pooltool.io site and transferred the 1.056 Ada from my stake pool's wallet and I have access to the "manage" tab for my pool.  I have the apiKey and poolId.
When I submit the json data to pooltool.io I get an error response.
This is my bash command used to send the tip information:
RESPONSE="$(curl -s -H "Accept: application/json" -H "Content-Type:application/json" -X POST --data "$JSON" 'https://api.pooltool.io/v0/sendstats')"

This is the contents of the $JSON variable:
{
  "apiKey": "xxxxxxxx-modified for privacy-xxxxxxxx",
  "poolId": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  "data": {
    "nodeId": "",
    "version": "1.30.1:0fb43",
    "at": "2021-10-21T14:20:38.46Z",
    "blockNo": "6399612",
    "slotNo": "43259747",
    "blockHash": "641da85f02d37759fa6bb7e2e9691c2a06728baa2441706c997bc894d276420e",
    "platform": "send-tip"
  }
}

And here is the $RESPONSE value returned:
{"success":false,"dev":true,"message":"Unknown API ID"}

I can't see what the problem is.  Any ideas?
Has there been any change to the web address to send to?

By the way, I do have the correct values for poolId and apiKey.

I can not see anything wrong there. I'd suggest you open an issue on Github and see what they say: https://github.com/papacarp/pooltool.io/issues

It seems that the problem has now resolved itself.  Maybe pooltool.io changed something to activate my apiKey???.  With the exact same code, I am now getting $RESPONSE:
{"success":true,"dev":true,"message":null}

great! thanks for the info.

there was a problem on PoolTool recently and some keys had to be reactivated manually by the operators. I'm sure they probably sorted out yours as well!


text:
Nix is building ghc during on nix build command (How to fix the cache?)
I'm preparing the Plutus Pioneer program and installing the environment.
After installing nix and updating the "IOHK binary cache", I tried to do nix build but it seems that it is building and compiling ghc as shown below and it takes a very long time.
MyMac$ nix build -f default.nix plutus.haskell.packages.plutus-core
trace: To materialize project.plan-nix for Agda entirely, pass a writable path as the `materialized` argument and run the 'updateMaterialized' script in 'passthru'.
[1/1/619 built] building ghc-8.6.5 (buildPhase): clang-7: warning: argument unu

Current nix.conf
substituters        = https://hydra.iohk.io https://iohk.cachix.org https://cache.nixos.org/
trusted-public-keys = hydra.iohk.io:f/Ea+s+dFdN+3Y/G+FDgSq+a5NEWhJGzdjvKNGv0/EQ= iohk.cachix.org-1:DpRUyj7h7V830dp/i6Nti+NEO2/nhblbov/8MW7Rqoo= cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY=

sandbox = true
extra-sandbox-paths = /System/Library/Frameworks /System/Library/PrivateFrameworks /usr/lib /private/tmp /private/var/tmp /usr/bin/env
extra-experimental-features = nix-command
build-users-group = nixbld

I found the following warning message:

If you want to use Nix with this project, make sure to set up the IOHK
binary cache. If you do not do this, you will end up building GHC,
which takes several hours. If you find yourself building GHC, STOP and
fix the cache.

Could you guide me how I can fix the cache?
Thanks in advance.

Is this on an m1 Mac? Binary cache doesn't have Mac arm binaries.

Thanks for your comment, please see below spec of mine. (1.1 GHz Intel Core M, MacBook (Retina, 12-inch, Early 2015) it is a little older one. I've remove all nix installation and install again, found something different log as below but still it is trying to building ghc-8.6.5

MyMac$ nix build -f default.nix docs.site
[1/3/4 built, 134 copied (207.2 MiB), 185.9 MiB DL] building old-ghc-nix: : [1/3/4 built, 134 copied (207.2 MiB), 185.9 MiB DL] building old-ghc-nix: [1/3/4 built, 134 copied (207.2 MiB), 185.9 MiB DL] building old-ghc-nix: trace: To materialize project.plan-nix for Agda entirely, pass a writable path as the materialized argument and run the 'updateMaterialized' script in 'passthru'.
[1/109/730 built, 434 copied (1193.3 MiB), 438.4 MiB DL] building ghc-8.6.5
(buildPhase): "inplace/bin/ghc-stage1" -hisuf p_hi -osuf  p_

I also saw warning: ignoring untrusted substituter 'https://hydra.iohk.io' with Nix in multi-user mode. It was fixed by specifying these substituters in /etc/nix/nix.conf rather than ~/.config/nix/nix.conf. It appears Nix reads both of these configuration files, but does not trust the substituters in the latter.

It may be the case that you edited your nix.conf file after you launched nix-daemon.
You would need to kill and start the daemon again to pick up the updated nix.conf:

$ sudo pkill nix-daemon

and then

$ sudo nix-daemon &

After that. Your non-root user will use substitutes.
source: https://docs.cachix.org/faq#why-is-nix-not-picking-up-on-any-of-the-pre-built-artifacts

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

Thanks for your comments. I tried to solve this issue with various way so anyway I could solve this issue. But I'm not sure what make it run. anyway thanks for your help.

If your systems uses systemd to run services you can restart the daemon using
sudo systemctrl restart nix-daemon.service


text:
segmentation fault when building Plutus-playground.server
I'm following the instructions for installing the Plutus-playground found here
I discovered I must execute the following before step 10
git clone https://github.com/input-output-hk/plutus-apps.git

I cd into plutus-apps/ and this then worked fine (note: in zsh):
[zsh]$ pwd
/Users/jwb/plutus/plutus-apps
[zsh]$ nix-build -A plutus-playground.client

But I got a "segmentation fault" with this:
[zsh]$ nix-build -A plutus-playground.server

Here is the output for clarity:
[zsh]$ nix-build -A plutus-playground.server
zsh: segmentation fault

I switched to bash after the error, but that too failed:
[bash]$ nix-build -A plutus-playground.server
Segmentation fault: 11

Is the plutus-apps repository corrupted? Why would the client build just fine but not the server?

Could you try running GC_DONT_GC=1 nix-build -A plutus-playground.server.

Running macOS Big Sur and this answer solved it for me


text:
How to run smart contracts in the Cardano Blockchain?
I know that since Alonzo was launched smart contracts can be published in the blockchain now, but I have no idea how to do it.
I have read some articles about the Plutus Application Backend though, it's a platform to work with Plutus scripts and provides an API to run those scripts via an endpoint that it's embedded in the script. But this means that smart contracts that run in Plutus are still off-chain in the local machine instead of being running on-chain. Is this true?
Or am I missing something like other library that works with the Plutus smart contracts and can interact with my web DApps?. Please if there is any suggestion I would appreciate it.

How to run smart contract in Cardano Blockchain?

PAB isn't available yet outside of development. The only way to submit and interact with smart contracts on-chain is with the cardano-cli. Here is a thorough tutorial on how to do that.

But it means that smartcontract that run in plutus still off-chain or running in local machine instead of running on blockchain. Is that true?

I'm not sure if this answers your question, but if you are curious where the smartcontracts live, my answer over here might help.

honestly, i would like to create a program for my thesis for achieving my bachelor. so mostly my dapps would be running in public testnet with PAB. is it possible?

I don’t understand, even Charles Hoskinson said the PAB is released. The GitHub page list a pre-release of the PAB. I thought it would be possible (even if at own risks) to connect to the mainnet with it.

You can run smart contracts with the cardano-serilization-lib and its js libraries. Check https://github.com/Berry-Pool/spacebudz to see an example. This allows you to host a web dApp where the user can connect with their Nami wallet, sign transactions that can contain datum, redeemer, everything needed to interact with smart contracts.


text:
How to derive cost from transaction?
Given a transaction where an NFT reached its final destination after a sale, how can I derive the cost of the NFT? For example, if I search for an asset on cardanoscan.io, the assets involved confuse me: RAVE and ROCKET.
Is there a calculation I can do on the inputs and outputs to derive the exact cost of the transaction? Not just the transaction fee but the cost of the token? Or do I have it conceptually wrong?
Thanks in advance for any insight!

If you can identify the size of the tx (bytes) you could utilise the fee calculation formula given the protocol parameters at the time of submission. (This might be tricky, but it is possible if you were inclined enough to find out a fairly accurate ball-park fee)

Cardano's fee structure is quite simple. Fees are constructed around two constants (a and b). The formula for calculating minimal fees for a transaction (tx) is a * size(tx) + b, where: a/b are protocol parameters.

https://docs.cardano.org/explore-cardano/fee-structure

Blockchains do not have an inherent notion of price; one cannot know the price of any asset, including ADA itself, simply by looking at on-chain data (until of-course we develop a robust oracle system). Currently, the price of cardano-assets like ADA, NFTs, e.t.c. is mostly dictated by off-chain markets (mostly centralized exchanges).
Until we have price/liquidity data being posted on chain, there will not be a way to derive asset prices purely from on-chain data. That being said, analyzing the inputs and outputs of transactions on chain may give you insight into the nature of a transaction that you can use to infer what kind of value transfer is going on.


text:
What is minimum RAM for running plutus-playground-server on Ubuntu VirtualBox?
I am facing this issues when running
$ nix-build -A plutus-playground.server
> error: 1 dependencies of derivation
> '/nix/store/39qxl421bhkzks2zrra7vy3yl6qqhsib-zlib-lib-zlib-0.6.2.3-config.drv'
> failed to build

It is probably RAM size issue. What is minimum RAM for running plutus-playground-server on Ubuntu VirtualBox?

I would be surprised if it worked in less that 8G of RAM. Having a decent amount of swap would not hurt either.

I increased to 10GB fo Virtual Box and $nix-build -A plutus-playground.server run successfully. Swap set to 2GB in VM

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

This question could be improved and is not generating good quality answers, please read [answer] and the relevant pinned messages in [help] if you are going to answer this question.

As all answers, it depends on your setup. Currently I run the plutus-playground-server setup on a VM with 8gb of ram available (but the playground only uses 1gb of that space). The thing to consider and optimize is the way you run you VM. I run my VM with the libvirt stack (this hypervisor runs near native hardware speeds, very lightweigth). Also I do not render a DE on my VM. I just SSH into the VM and only use the terminal, this also saves a lot of ram usage. So I guess that 2gb will suffice bare minimum (I have not tested this).
a good guide for this hypervisor: https://octetz.com/docs/2020/2020-05-06-linux-hypervisor-setup/
Good luck!

I have seen, that my setup needs around 12GB. Maybe you can optimize it more, but for me it was around 12GB.


text:
How would Cardano applications function with intermittent internet connection?
With Cardano's ambition of bringing self-sovereign digital identity and finance to billions of people, it is important to consider that many people do not have constant electricity or stable internet.
Right now, running a Daedalus full wallet takes several GBs of storage and will take quite a few minutes to hours to synchronize the blockchain even with a decent internet connection, so this probably won't be an option in that situation. But even with a light wallet like Yoroi for Android, it takes a while to check your balance.
In a situation where you have two people with a smartphone with a Cardano wallet on it that want to transact together, what is the minimal internet traffic and time needed to send funds from one phone, and get final confirmation on the other? Would it matter if the phones are on the same local network?

Most blockchains currently rely heavily on a stable and relatively low-latency internet link. Relaxing the latency requirements may allow for more decentralisation since more people would be able to participate in the consensus mechanism (ie. by setting up a validator), but this comes at the cost of performance (decreased throughput).

what is the minimal internet traffic and time needed to send funds from one phone, and get final confirmation on the other?

If you use a light wallet like Yoroi, the bandwidth requirements are pretty low, a narrowband link of a few kbps should be enough.

Would it matter if the phones are on the same local network?

No, that usually doesn't help since validating a transaction requires the transaction to be broadcasted to the blockchain network, not only among the parties directly involved in the transaction inputs/outputs. However, if the wallets used by those phones are connected to some relay node in their local network (theoretically possible), then it would be different.
Note that the only bandwidth/storage intensive operation is to validate transactions in the way full nodes do. Submitting a transaction does not require much resources.
On the other hand, it is theoretically possible to establish a payment channel between these phones, which may lower the requirements for connectivity (though I don't know of any solution like this in Cardano).


text:
Transaction with Cardano-CLI Sumbmits But Nothing Happens
I am trying to delegate a wallet through cardano-cli for most it was going okay, but more recently even though I get the message Transaction successfully submitted. after submitting the transaction, no money gets transferred. The same happens when I try to delegate the wallet.
I noticed that on the cardano-node logs I get something that makes me think some sort of ofrk is happening?  Ignoring block already in DB
[x-XP:cardano.node.ChainDB:Info:47551] [2022-02-07 13:30:47.64 UTC] before next, messages elided = 94461957158106
[x-XP:cardano.node.ChainDB:Info:47551] [2022-02-07 13:30:47.64 UTC] Ignoring block already in DB: ce7b38a4b05435f4ebe07e1ba52154b6db7131bd062c7809bc5d4ef29b27f3f3 at slot 52674352
[x-XP:cardano.node.Mempool:Info:47597] [2022-02-07 13:30:49.49 UTC] fromList [("tx",Object (fromList [("txid",String "36f15e82")])),("kind",String "TraceMempoolAddedTx"),("mempoolSize",Object (fromList [("bytes",Number 399.0),("numTxs",Number 1.0)]))]

[x-XP:cardano.node.ChainDB:Info:35] [2022-02-07 13:37:17.56 UTC] Block fits onto some fork: ebf7869a4b082c3d4b2ec60d14f2e8d8f803b9e5a3ab9cd7536927dc9a2b8227 at slot 52674744
[x-XP:cardano.node.ChainDB:Notice:35] [2022-02-07 13:37:17.66 UTC] Switched to a fork, new tip: ebf7869a4b082c3d4b2ec60d14f2e8d8f803b9e5a3ab9cd7536927dc9a2b8227 at slot 52674744

I tried to delete the entire db and resync the entire cardano-node but as soon as I tried to make a transaction the same as above happenend.
How can I fix this so to have successful transactions again? what coudl I be doing wrong?

actually it seem the transactions went through now, so I guess it was indeed a bad database, not sure why it still says Ignore block though. Possible that the problem I had earlier was because I was sending transactions in parallel rather than sequentially and made me fork?

Likely this was congestion in getting the transaction adopted rather than the db state being an issue. As for Ignore block, this is normal consensus layer stuff. Another node on network said I have this block, and the node looked at it's current state and decided it's fork was better than the one that block fit on so it never asked for the block.

oh yes, seeing all the discussion developing right now on certain type of transaction having a preferential way with SPOs makes it more clear my problems where transactions go through only every so often. I just told that once submitted, the Tx was taken, even if it was going to take more time.. increasing TTL could help?

SPOs cannot influence the order of the transactions. Most probably what happened is that your TTL wasn't long enough and the deadline slot no had already been surpassed once your transaction was being processed. "Transaction successfully submitted" just means that the transaction passed the initial checks (balanced values, appropriate signatures, sufficient fee, etc) and has been added to the mempool. However, once the transaction actually starts being processed there are other on-chain checks that are performed, such as valid-before, valid-after and any plutus validators.


text:
How to Write Nested Datum in Lucid
I have this in Aiken:
pub type Player {
  X,
  O,
}

pub type Board = List<List<Option<Player>>>

let datum = Datum {
  board: [[Some(X), Some(O), Some(O)], [Some(X), Some(O), None], [Some(X), Some(X), Some(O)]],
  last_player: O,
}

How do I build datum in Lucid with Data.to? Data.to(new Constr(0, [utf8ToHex("Hello, World!")]))
I can't find documentation that explains or gives examples on this
should it be somethign like?:
Data.to(new Constr(0,
  [new Constr(0, [new Constr(1, [new Constr(1, [])]), new Constr(1, [new Constr(0, [])]), ... ]), ... ]
)


text:
Error Applying Redeemer Lucid
I get this error when trying to unlock funds from an UTXO in a contract address:
Uncaught (in promise) "Redeemer (Spend, 0): Attempted to apply a non-function:\n\nCon(\n    Unit,\n)\n\nExBudget {\n    mem: 12788611,\n    cpu: 9492522265,\n}\n\n"

is there any problem in the following code?
async function unlock(ref: OutRef, from: SpendingValidator): Promise<TxHash> {
  const [utxo] = await lucid.utxosByOutRef([ref]);

  const tx = await lucid
    .newTx()
    .collectFrom( [utxo], Data.to(new Constr(0,[])) )
    .addSigner(await lucid.wallet.address())
    .attachSpendingValidator(from)
    .complete();

  const signedTx = await tx
    .sign()
    .complete();

  return signedTx.submit();
}

here is how I take the validator:
const validator = await readValidator();

async function readValidator(): Promise<SpendingValidator> {
  const validator = JSON.parse(await Deno.readTextFile("plutus.json")).validators[0];
  return {
    type: "PlutusV2",
    script: toHex(cbor.encode(fromHex(validator.compiledCode))),
    // some alchemy with Uint8Array and other codes that returns pretty much initial thing but a little different
  };
}

What data structure is specting the Validator? What type is the redeemer? what language you used to make the validator?

The redeemer is Void, while the datum is simply a ByteArray type Datum {hex: ByteArray} validator {  fn check(datum: Datum, _redeemer: Void) -> Bool {complexfunc(datum.hex)}and I used Aiken.
Could it be that the problem resides in the function that processes the Datum's ByteArray inside the Aiken validator? rather than a problem with Lucid?
Although when I test the validator in Aiken it works fine.

I tried just with a simple equality as validator and I still get the same error. this is the utxo I am trying to use: {   txHash: "a183...",   outputIndex: 0,   assets: { lovelace: 10000000n },   address: "addr_test1wr...",   datumHash: undefined,   datum: "d8799f43849480ff",   scriptRef: undefined }
so it shouldn't be related to my validator, but an error related to Lucid code but then it is so simple and boilerplate that I don't really know where to look anymore.

You probably already did, but check that you are actually passing the utxos to the tx, and check that the datum is the right one, the datum seems to be hash or its just a bytestring? how does quering the utxo on cli or looking for the datum in explorers look?
It seems no valid utxo is available for spending or the validator itself its wrong.
take a look at this post that seems to be dealing with a similar problem.
Lucid Error "End of input in bytes"
how are you importing your validators cbor into Lucid?, you can use Lucid blueprint parser examples, or if you where using a CLI ready json file (created with aiken blueprint convert) you can copy paste the cborhex, or import it and parse it.

thanks, I added to the question how I import the validator from the aiken build json - method shown in an aiken example.
and here is tha datum which seem correct to me:
https://preview.cexplorer.io/datum/a105195230a69720e9ea5cc755f03e6ce6af7ac8c579857d5de32739ecb6b75f


text:
Asses Utxos Time In On-Chain Code
Can you assess the time a Utxo was created in on-chain code?
i.e. A transaction to a smart contract that can claim  only Utxos - in that contract address - sent in a specific time period?

Pretty sure that is possible with cardano-db-sync.
Every new UTxO is created by a transaction, which is part of a block and the block will have a timestamp.

is that something queriable from the script context for any utxo input in the tx to the validator?

I was wondering if is something than can be extrapolated from script context with PlutusTx, so provable from the script/validator itself, but I don't think so


text:
Script Execution Failure PT8
I am trying to transact with UTxO from a script address on the pre-production testnet.
I locked the fund ok with Datum, now I get an error when trying to consume that UTxO, it seem that the script is failing. But I am not sure how to get more information on where the problem is coming from, here is the off chain plutus code.
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveAnyClass        #-}
{-# LANGUAGE DeriveGeneric         #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses      #-}
{-# LANGUAGE OverloadedStrings          #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE NoImplicitPrelude #-}

module FaucetValidatorScript
  ( FaucetParams (..)
  , validator
  ) where

import              Data.Aeson                (ToJSON, FromJSON)
import              GHC.Generics              (Generic)
import              Schema                    (ToSchema)
import              Ledger              hiding (singleton)
import              Ledger.Address
import              Ledger.Typed.Scripts
import              Ledger.Value        as Value
import              Ledger.Ada
import qualified    PlutusTx
import              PlutusTx.Prelude    hiding (Semigroup (..), unless)
import              Prelude             (Show (..))
import qualified    Prelude                   as Pr

-- Simple Faucet validator script

-- Usage:
-- Expect one utxo at each contract.
-- Take that utxo as input
-- Create a new utxo with the "change" as output

-- This contract provides an example of using Validator Parameters.

-- For now, the Datum and Redeemer are not used in contract logic
-- Transactions will still have to match the type Integer for Datum and Redeemer
-- The context matters: we want to see that the PPBLSummer2022 token is in the transaction inputs and outputs.

data FaucetParams = FaucetParams
  { accessTokenSymbol   :: !CurrencySymbol
  , accessTokenName     :: !TokenName
  , faucetTokenSymbol   :: !CurrencySymbol
  , faucetTokenName     :: !TokenName
  , withdrawalAmount    :: !Integer
  } deriving (Pr.Eq, Pr.Ord, Show, Generic, ToJSON, FromJSON, ToSchema)

PlutusTx.makeLift ''FaucetParams

{-# INLINEABLE faucetValidator #-}
faucetValidator :: FaucetParams -> Integer -> Integer -> ScriptContext -> Bool
faucetValidator faucet _ _ ctx =   traceIfFalse "Input needs PPBLSummer2022 token"    inputHasAccessToken &&
                            traceIfFalse "PPBLSummer2022 token must return to sender" outputHasAccessToken &&
                            traceIfFalse "Faucet token must be distributed to sender" outputHasFaucetToken &&
                            traceIfFalse "Must return remaining tokens to contract"   faucetContractGetsRemainingTokens &&
                            traceIfFalse "Do we need to check datum"                  checkDatumIsOk
  where
    info :: TxInfo
    info = scriptContextTxInfo ctx

    receiverPkh :: PubKeyHash
    receiverPkh = head $ txInfoSignatories info

    allTokens :: [CurrencySymbol]
    allTokens = symbols $ valueSpent info

    inputHasAccessToken :: Bool
    inputHasAccessToken = (accessTokenSymbol faucet) `elem` allTokens

    valueToReceiver :: Value
    valueToReceiver = valuePaidTo info receiverPkh

    outputHasAccessToken :: Bool
    outputHasAccessToken = (valueOf valueToReceiver (accessTokenSymbol faucet) (accessTokenName faucet)) >= 1

    outputHasFaucetToken :: Bool
    outputHasFaucetToken = (valueOf valueToReceiver (faucetTokenSymbol faucet) (faucetTokenName faucet)) >= (withdrawalAmount faucet)

    -- The UTXO input from Faucet
    ownInput :: TxOut
    ownInput = case findOwnInput ctx of
        Nothing -> traceError "faucet input missing"
        Just i  -> txInInfoResolved i

    -- The UTXO output back to Faucet
    ownOutput :: TxOut
    ownOutput = case getContinuingOutputs ctx of
        [o] -> o -- There must be exactly ONE output UTXO
        _   -> traceError "expected exactly one faucet output"

    faucetInputValue :: Value
    faucetInputValue = txOutValue ownInput

    faucetOutputValue :: Value
    faucetOutputValue = txOutValue ownOutput

    faucetContractGetsRemainingTokens :: Bool
    faucetContractGetsRemainingTokens = (valueOf faucetInputValue (faucetTokenSymbol faucet) (faucetTokenName faucet)) - (withdrawalAmount faucet) <= (valueOf faucetOutputValue (faucetTokenSymbol faucet) (faucetTokenName faucet))

    checkDatumIsOk :: Bool
    checkDatumIsOk = True

data FaucetTypes

instance ValidatorTypes FaucetTypes where
    type DatumType FaucetTypes = Integer
    type RedeemerType FaucetTypes = Integer

typedValidator :: FaucetParams -> TypedValidator FaucetTypes
typedValidator faucet =
  mkTypedValidator @FaucetTypes
    ($$(PlutusTx.compile [||faucetValidator||]) `PlutusTx.applyCode` PlutusTx.liftCode faucet)
    $$(PlutusTx.compile [||wrap||])
  where
    wrap = wrapValidator @Integer @Integer

validator :: FaucetParams -> Validator
validator = validatorScript . typedValidator

As you can see both Datum and Redeemer are given as integers, while Datum has to be exactly the one used to get the datum-hash I guess that the redeemer integer can be any?
here is the transaction used to unlock it but which fails
CONTRACT_TXIN="7325518aff0270f7ef019236977baa8c301e8213a632996e0852480d5df196eb#1"
AUTH_TOKEN_TXIN="95b5308a55dd1648ea6e8f2325c0a7e307240aef1998777bb3ec860a3c32e55c#1"
FEE_TXIN="95b5308a55dd1648ea6e8f2325c0a7e307240aef1998777bb3ec860a3c32e55c#3"
COLLATERAL="95b5308a55dd1648ea6e8f2325c0a7e307240aef1998777bb3ec860a3c32e55c#2"
PLUTUS_SCRIPT_FILE=output/faucet.plutus
ASSET="fb45417ab92a155da3b31a8928c873eb9fd36c62184c736f189d334c.7467696d62616c"
AUTH_TOKEN="07fd9522f3ea6179415f8934ce0aa71b67fac6aa6024a59013bde6d8.506f72636f526f73736f466175636574546f6b656e"
TOKENS_BACK_TO_CONTRACT=267
CONTRACTADDR="addr_test1wrd5y9tudjkdcaxfy0cnuf042xlx4s9xm4xlq8pqdcyyxxsfr38fl"
DATUMHASH="db2b9e43ba6771c834279febfd091fd8cae78dec7ebe86fd9d729d3ba61e38e4"
SENDER="addr_test1vpjkdcxaxvt04vezk6r7vsdn22w40z094wggnpvvp47sy0cauqn90"

cardano-cli transaction build \
--tx-in $FEE_TXIN \
--tx-in $AUTH_TOKEN_TXIN \
--tx-in $CONTRACT_TXIN \
--tx-in-script-file $PLUTUS_SCRIPT_FILE \
--tx-in-datum-value 168 \
--tx-in-redeemer-value 21 \
--tx-in-collateral $COLLATERAL \
--tx-out $SENDER+"2000000 + 33 $ASSET" \
--tx-out $SENDER+"2000000 + 1 $AUTH_TOKEN" \
--tx-out $CONTRACTADDR+"2000000 + $TOKENS_BACK_TO_CONTRACT $ASSET" \
--tx-out-datum-hash $DATUMHASH \
--change-address $SENDER \
--protocol-params-file protocol.json \
--testnet-magic 1 \
--out-file unlock.raw

Command failed: transaction build  Error: The following scripts have execution failures:
the script for transaction input 0 (in the order of the TxIds) failed with:
The Plutus script evaluation failed: An error has occurred:  User error:
The machine terminated because of an error, either from a built-in function or from an explicit use of 'error'.
Script debugging logs: PT8

I would appreciate any help on understanding where the problem comes from or direction on how to debug a plutus script.

See here, PT8 means PlutusTx.List.head: empty list
Perhaps it's because you're using head on an empty txInfoSignatories. You must use --required-signer or --required-signer-hash flags when building the transaction to embed the required signer pubkey in txbody.


text:
ScriptWitnessNotValidatingUTXOW - Transaction Error While Minting NFT With Native Script - Before Slot Instruction Not Working
I am trying to mint an NFT for the zeroOneGame exercise from gimbalabs on the pre-production testnet (babbage-era) but I incur in an error and I can't see what I am doing wrong.
Here are the steps that I am taking:
I create P1.vkey and P1.skey and then build the payment address P1.addr.
I create policy.vkey and policy.skey and then get the hash key for policy.vkey
cardano-cli address key-hash --payment-verification-key-file policy.vkey
> c1ed1f20dee68e6c10a863a5058ff9b44b0ad37f409c38a50fd38f51

I ask for the current slot
{
    "block": 458153,
    "epoch": 42,
    "era": "Babbage",
    "hash": "e4a4ca5c206829d30112a0ed8c95813218d3ccf1713811236081ce2e4933c001",
    "slot": 16656970,
    "syncProgress": "100.00"
}

Now I can create the policy.script
{
  "type": "all",
  "scripts":
  [
    {
      "type": "before",
      "slot": 16670000
    },
    {
      "type": "sig",
      "keyHash": "c1ed1f20dee68e6c10a863a5058ff9b44b0ad37f409c38a50fd38f51"
    }
  ]
}

Now I can create the policyID
cardano-cli transaction policyid --script-file policy.script
> 0de56a658ba5838183a57f6260d8f2919c8350b2186609ebd986cfa8

In the meantime the P1.addr was funded obtanining the following UTxO
cardano-cli query utxo --address $(cat P1.addr) --testnet-magic 1
                           TxHash                                 TxIx        Amount
--------------------------------------------------------------------------------------
95ebaeb5d47bf28842e7551ca467415cfae12f466239b59e90c532405ab88e3a     0        997833047 lovelace + TxOutDatumNone

I can now build the tx.raw for the minting of my NFT.
cardano-cli transaction build \
--babbage-era \
--testnet-magic 1 \
--tx-in 95ebaeb5d47bf28842e7551ca467415cfae12f466239b59e90c532405ab88e3a#0 \
--tx-out $(cat P1.addr)+2000000+"1 0de56a658ba5838183a57f6260d8f2919c8350b2186609ebd986cfa8.7a65726f4f6e6547616d65546573743031" \
--change-address $(cat P1.addr) \
--mint="1 0de56a658ba5838183a57f6260d8f2919c8350b2186609ebd986cfa8.7a65726f4f6e6547616d65546573743031" \
--mint-script-file policy.script \
--witness-override '2' \
--out-file tx.raw

and finally sign it and submit it
cardano-cli transaction sign  \
--signing-key-file P1.skey  \
--signing-key-file policy.skey  \
--testnet-magic 1 \
--tx-body-file tx.raw  \
--out-file tx.signed

cardano-cli transaction submit --tx-file tx.signed --testnet-magic 1

Everything seem correct to me, but unfortunately at this point I get the following error from the cardano-cli
Command failed: transaction submit
Error: Error while submitting
tx: ShelleyTxValidationError
  ShelleyBasedEraBabbage (
    ApplyTxError [
      UtxowFailure (
        FromAlonzoUtxowFail (
          WrappedShelleyEraFailure (
            ScriptWitnessNotValidatingUTXOW (
              fromList [
                ScriptHash "0de56a658ba5838183a57f6260d8f2919c8350b2186609ebd986cfa8"
              ]
            )
          )
        )
      )
    ]
  )

The script witness is not validating the script, yet I have put the right hash of the right policy.vkey in the policy.script, and I am signing the transaction with the relative policy.skey. So the witness should validate the script, why is that not the case?
I see that it mentions something about WrappedShelleyEraFailure, is that something to do with the fact I am not using the right commands for the Babbage era?
Also what is the "W" in the UTXO in ScriptWitnessNotValidatingUTXOW and FromAlonzoUtxowFail indicating?
UPDATE
It seem that the problem was in the script itself. I removed the lines regarding the slot number:
    {
      "type": "before",
      "slot": 16670000
    },

and the transaction went through creating the token, although without the time limit it is not an NFT.
But well it also changes the nature of my question:
Why my time limit instruction isn't working?

When creating a transaction that will consume a script that contains a before you need to add " --invalid-after" to your transaction.
In your case in would look something like :
cardano-cli transaction build \
--babbage-era \
--testnet-magic 1 \
--tx-in 95ebaeb5d47bf28842e7551ca467415cfae12f466239b59e90c532405ab88e3a#0 \
--tx-out $(cat P1.addr)+2000000+"1 0de56a658ba5838183a57f6260d8f2919c8350b2186609ebd986cfa8.7a65726f4f6e6547616d65546573743031" \
--change-address $(cat P1.addr) \
--mint="1 0de56a658ba5838183a57f6260d8f2919c8350b2186609ebd986cfa8.7a65726f4f6e6547616d65546573743031" \
--mint-script-file policy.script \
--invalid-after 16670000 \
--witness-override '2' \
--out-file tx.raw


text:
Understanding Script Failure Error Relating to Order TxIds - (script hash not known)
trying to claim back the first player bet after deadline in the ZeroOneGame from ppbl gimbalabs course on pre-production_testnet I get an error when trying to build the claim transaction.
I have this Player 1 address addr_test1vpn9qvm8tuth36pm0ul70tn7hwl0rtjk6cw9k6gzw5g6pxc8cexwu
cardano-cli query utxo --address $(cat P1.addr) --testnet-magic 1
                           TxHash                                 TxIx        Amount
--------------------------------------------------------------------------------------
2077017595a69be695124ddff5f79c3410121234feed38f8519682239199ad29     0        5000000 lovelace + TxOutDatumNone
f8f17e3515372fa9428abf3e0a30aedc3f11a6ef598d5f9838d35e2e45519bf3     0        992481013 lovelace + TxOutDatumNone

And this contract address addr_test1wrxhzl9vvcf2p8njp2metcf9mkapc9d2fj8a5fszv4ngnecge54yd which received the bet and NFTstate already.
cardano-cli query utxo --address $(cat contract1stGame.addr) --testnet-magic 1
                           TxHash                                 TxIx        Amount
--------------------------------------------------------------------------------------
f8f17e3515372fa9428abf3e0a30aedc3f11a6ef598d5f9838d35e2e45519bf3     1        5000000 lovelace + 1 665c8f0cdf7dc8b939d484d85f80d24c4c50af560be49c58d2b51f38.7a65726f4f6e6547616d65546573743031 + TxOutDatumHash ScriptDataInBabbageEra "f47634d3b1c1caccb51ab10c74958ccb464b0893c3e612b649a4484a6e50eeca"

Then I try to build the transaction to ClaimByFirstPlayer
cardano-cli transaction build --babbage-era \
--tx-in f8f17e3515372fa9428abf3e0a30aedc3f11a6ef598d5f9838d35e2e45519bf3#0 \
--tx-in-script-file ../output/ZeroOneGame.plutus \
--tx-in-datum-file ../output/startGame-DATUM.json \
--required-signer P1.skey \
--tx-in-redeemer-file ../output/firstPlayerClaims-REDEEMER.json \
--tx-in-collateral 2077017595a69be695124ddff5f79c3410121234feed38f8519682239199ad29#0 \
--tx-out $(cat P1.addr)+5000000+"1 665c8f0cdf7dc8b939d484d85f80d24c4c50af560be49c58d2b51f38.7a65726f4f6e6547616d65546573743031" \
--change-address $(cat P1.addr) \
--protocol-params-file parameters.json \
--invalid-before 17168436 \
--testnet-magic 1 \
--out-file tx.raw

But I receive the following error:
Command failed: transaction build  Error: The following scripts have execution failures:
the script for transaction input 0 (in the order of the TxIds) failed with:
transaction input 0 (in the order of the TxIds) points to a script hash that is not known.

Is difficult to understand what it is going wrong from this error, I told that the --tx-in order may have been wrong, but after trying to make it better the error persists.
Is there any obvious mistake I am going through from the information given?

Mystery solved, what Plutus is trying to tell me is that I forgot to put the UTxO/--tx-in of the contract itself.
to the previous transaction I had to add the line
--tx-in f8f17e3515372fa9428abf3e0a30aedc3f11a6ef598d5f9838d35e2e45519bf3#1 \

That error is a weird way to say that the script couldn't find any UTxO related to the contract in the transaction being built.


text:
How to import Yoroi seed phrase to computer using cardano-address for use with cardano-cli?
I'm trying to use cardano-cli to control the addresses controlled by my Yoroi wallet, so I thought the first thing to do is to import the keys and addresses. I did this:
$ # Type the seed phrase for the Yoroi wallet into a file phrase.txt.
$ cat phrase.txt | cardano-address key from-recovery-phrase Shelley > root.prv
$ cat root.prv | cardano-address key child 1852H/1815H/0H/0/0 | cardano-address key public --with-chain-code  | cardano-address address payment --network-tag mainnet

The output is "addr1v..." but in the Yoroi the 0th address is "addr1q...", so they are very different. What am I missing? My ultimate goal is to get the addresses and keys I need to build and sign transactions using cardano-cli, and I'm stuck at even getting the right addresses using cardano-address.

Following the instructions from the cardano-addresses README.md, I was able to generate a "delegated payment address" that matches the 0th address I see in Yoroi. However, cardano-cli transaction sign requires a --signing-key-file, which is normally generated using cardano-cli address key-gen, and I don't know how to get a cardano-cli-style signing key file from the stuff I can get from cardano-address.
I believe cardano-wallet can be used to make payment transactions, but AFAICT only cardano-cli can be used to mint tokens; I don't see anything about minting tokens in the help for cardano-wallet.

Have you checked in Yoroi if the output address "addr1v" is one of your public addresses? Every wallet has many addresses.

IDK how to give Yoroi an address to check whether it is mine, but I have generated a total of 4 addresses in Yoroi and they all start with addr1q and not addr1v. Additionally, I believe the last '0' in 852H/1815H/0H/0/0 is the address index. I suspect the 1q vs 1v has some special significance related to the nature of the address. I suspect that there is some knowledge about different types of addresses, what they are used for, what kinds of prefixes they have and how they relate to one another that I have yet to understand.

addr1v[...] are payment addresses, addr1q[...] are delegated payment addresses: https://github.com/input-output-hk/cardano-addresses#command-line

@eddex You raised a good point. What I was missing is the cardano-address address delegation, which requires the stake verification key to be generated first.

Great that it worked! You could add an answer to this question with the full set of commands so that others can see how you solved it.

I will once I figure out how to generate all the address-related files needed for using cardano-cli to build and sign a transaction. For example, cardano-cli sign requires a --signing-key-file and I need to figure out how to generate that.

You can use cardano-cli to convert an extended signing key to a Shelley-format key (which is what you need in order to sign a transaction).
cardano-cli key convert-cardano-address-key --shelley-payment-key --signing-key-file address.xsk --out-file address.skey

I believe this is the missing piece of information you are after. The steps needed to get address.xsk are the same as those needed to derive the extended verification keys. The answer to this question covers that.
Later edit :
Here are all the steps for getting a signing key usable with cardano-cli from a seed phrase
./cardano-address key from-recovery-phrase Shelley < phrase.prv > root.xsk

# Derive the address signing key
./cardano-address key child 1852H/1815H/0H/0/2 < root.xsk > address.xsk

# Convert the extended signing key to a Shelley-format key
cardano-cli key convert-cardano-address-key --shelley-payment-key --signing-key-file address.xsk --out-file address.skey

# Probably you can need non-extended keys, so if it is the case you can convert with:
cardano-cli address key-gen --verification-key-file extended-address.vkey --signing-key-file address.skey

In my case the address holding funds had this derivation path 1852H/1815H/0H/0/2. In Yoroi you can see the derivation path for an address when you click the ✓ Verify address button.
You can derive any path you need following the steps above.

Is the address.xsk actually the output file from cardano-address key from-recovery-phrase Shelley < phrase.prv > root.xsk? The only .xsk file I can see from the instructions in the README.md is the root.xsk from that command. Does that mean I can't use cardano-cli to control multiple addresses generated from the root.xsk?

No, that is the root signing key. You said you managed to reach the same address as the ones you see in yoroi, so I assumed you derived both the account and the address keys (so a full derivation 1852H/1815H/0H/0/0). You convert an extended address signing key with the command above. I'll edit my answer with a full example once I reach my PC

Cardano cli offers some functions for that
$ cardano-address key from-recovery-phrase Shelley < phrase.prv > root.xsk
root_xsk1hqzfzrgskgnpwskxxrv5khs7ess82ecy8za9l5ef7e0afd2849p3zryje8chk39nxtva0sww5me3pzkej4rvd5cae3q3v8eu7556n6pdrp4fdu8nsglynpmcppxxvfdyzdz5gfq3fefjepxhvqspmuyvmvqg8983

https://github.com/input-output-hk/cardano-addresses#command-line

You have to use some of the other tools in the cardano wallet suite. Get the cardano-wallet from GitHub. Here is an example for how to extract keys and make signing key files.
Basically you need to extract the keys from the seed phrase, and then convert them to CBOR hex, and then create the signing key file which is just a JSON format file.

You can use Daedalus to restore your wallet on the machine and that should create a wallet file with the addresses you need.  Daedalus also contains cardano-cli as its built on cardano-node.
I did not try launching cardano-node / cardano-cli from a Daedalus install though, there may be additional wrinkles to solve.

As an alternative to cardano-address you can use cscli, another open-source CLI tool to derive the cardano-cli compatible skey/vkey files.
Example using a dummy recovery-phrase:
cscli wallet key payment derive --recovery-phrase "walnut decrease buyer wealth eager truth bomb notable twenty" --account-index 0 --address-index 0 --verification-key-file pay_0_0.vkey --signing-key-file pay_0_0.skey

Disclaimer: I am the main developer for cscli so feel free to reach out to me on GitHub if you need help!


text:
Ways to burn tokens?
What are all the ways to burn tokens, including ADA and other tokens? By burning, I mean to remove it from the sum balance of all addresses. E.g. one way is to mint a negative amount of a token. Are there other ways? (Sending tokens to an address that nobody controls doesn't count; I want the token to be completely gone.)
I'm also specifically looking for a way to burn a token after the 'before' slot of the minting policy has passed.

Under what circumstances and for what purpose do you wish to burn tokens?

@gRebel As mentioned in the last paragraph, the specific situation that motivated the question is that I'm trying to burn tokens after the 'before' slot of the minting policy has passed.

That's what you want to do.  I am interested in why.

As long as you do not burn a token, it is not clear that the token can still be owned by someone. Burning is final and undebatable. Burning also has the advantage of garbage collection for the information that nodes have to remember to process future transactions.

There is no way to burn ADA.
You can burn the native tokens, if you have the singing keys for the tokens policy and the policy allows it.
If the policy doesn't allow it (locked by time slot), at the moment, there is no way to burn them, but IOG is going to introduce a way to do it in the near future, so keep them around.

There is no such thing as a "private key for the tokens". The only thing that matters is the policy.

@LarsBrünjes I think he meant the private key for the verification key associated with keyHash used in the policy, so if you don't have that private key, you can neither mint nor burn tokens.

That is correct Joshua, edited the answer for clarity.

Yes, but the point is: The policy does not need to require a key. You can have a policy that only has a deadline, for example.

@LarsBrünjes, is it still not possible to destroy tokens locked by time slot ?
Eager to know more, i want to 'unmint' a minted token for which the time slot has passed ...