text:
cardano-cli is marked as depricated. Is there a replacement or is that what we are supposed to use?
I see that the cardano-cli is marked as deprecated.
Can someone tell me what is being used in it's place?
If there is no replacement right now then I would like to know that please.
Just trying to direct my time and attention most productively as I try and get oriented to developing on Cardano.
Much thanks

You are looking at the wrong cardano-cli. It you go to the cardano-node repo, one of the components is the real, current and maintained cardano-cli.

Thank you @erik-de-castro-lopo, I wonder how it is possible to request that a notice of redirection can be placed in the README.md of the old deprecated repository?

I will look into it.


text:
Preferred Library For Working With Zero Knowledge Proofs
I have been thinking about a voting mechanism as seen at the following link.
The same text is also posted on the Cardano forum under governance.
https://johnshearing.github.io/bee_democracy/index.html#voting
Implementation will require working with zero knowledge proofs.
Does the Cardano community have a preferred tech stack or library for working with ZKPs?
Much thanks.

To my knowledge this does not exist in the Cardano suite of things. This is probably why Cardano is giving up to $2 million in prizes with a focus on ZKPs.
https://emurgo.io/hackathon-101-an-introduction-to-zero-knowledge-proofs/
I found this https://github.com/matter-labs/awesome-zero-knowledge-proofs
Which points to Haskel implementations here: https://github.com/sdiehl/bulletproofs

Amazing resources @PREEB. Much thanks!

source: Stack Exchange

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

sort: votes


text:
pub-key hash for Plutus Pioneers - self-certification challenge
The entry form for the Plutus Pioneers - self-certification challenge reads as follows:

Please provide a Cardano public key hash

I am guessing this should be associated with a wallet.
In general I prefer to use a hardware wallet.
So my question is:
How can I get a pub-key hash from a hardware controlled wallet?
Much thanks

Found a great explanation of what the public key hash is:
https://discord.com/channels/826816523368005654/868025141668503582/1176250735986479115
Found one method of obtaining the public key hash from a wallet receiving address using mesh:
https://discord.com/channels/826816523368005654/868025141668503582/1178150850288431174
Found one method of obtaining the public key hash from a wallet receiving address using cardanoscan.io:
https://discord.com/channels/826816523368005654/868025141668503582/1176392536726720563
Much thanks to those contributors.

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


text:
Can a native asset have different rules for minting and burning when using SimpleScripts?
Could I for example have one key to only be used for minting tokens and another only for burning? Or does this require Plutus script?

I believe a plutus script is needed here. If minting with the cli i believe there is only value that can be used with keyhash. Multiple scripts can be combined with logical AND and OR but I don't see a way to include if it's a mint or burn so both keys would be able to mint and burn.
I haven't personally tried it but you can specify more than one public key hash in the validator. In my opinion this should be doable by specifying more than one pubkey hash and check if the mint amount is negative or positive. Then make sure only one key handles minting and one key handles burning.


text:
What kind of dapps can scale using hydra?
I've been reading through the paper on the hydra protocol and seems to have a lot of nice properties. However, what isn't directly clear from the paper is in what kinds of dApps hydra could help scale.
There seems to me to be a couple of limits (please add/debate the list)

All head members must be online
A head member can force the head to be closed
resource heavy? Could I run a head on a mobile phone?

Let consider NFT-maker/pro as an example application. Could they use hydra to
lower the NFT minting fees? The buyers of the NFTs are on the mainchain so setting up an entire head for one transaction isn't reasonable.
What kind of apps would hydra be able to scale?

You may want to read (and contribute to) the discussion happening here: https://github.com/input-output-hk/hydra-poc/discussions/113

Great link, thanks!

Keep in mind that Hydra is a whole suite of protocols, some of which are still in the research phase.
On Hydra Head specifically, you can think of it as a protocol for creating and maintaining fully composable and dynamically available state machines between willing participants, with snapshots being periodically committed to the CSL.
Participants of the Hydra Head are analogous to SPOs; except they are tasked with maintaining consensus only on the state of the head. Depending on the size, scope, and function of each head, the consensus and ledger mechanics may greatly differ between some head protocols, but will nevertheless be settle-able on the main chain. Additionally, the Hydra Inter-head paper describes ways to create channels between heads without having to close them or pre-settle on the CSL.
Hydra Tail is an upcoming paper that, according to the having-read-about-it-long-ago whispers of my mind, describes how individual head participants can offer centralized services to individuals. (i.e. I, as a lone L2 state operator, can offer you and many others some sort of service on my machines).
People with thin clients/mobile devices in remote regions would be able to transact through a single or small handful of trusted operators.
This would in effect, create the first fully interoperable stack of protocols across the ENTIRE length of the THROUGHPUT -------- DECENTRALIZATION spectrum. For the first time ever, we'd have a family of protocols that make the security of a decentralized settlement layer and the throughput of a centralized compute layer interoperable.

Ah, I see, I will have to do some further reading. :)

Is there any paper (or other detailed description) available for the Hydra Tail protocol?

Not yet. So far, papers have been publish about heads, and about cross-head communication.


text:
Can Nami wallet provide the TransactionWitnessSet for minting a native asset?
I'm trying to mint a native asset reusing the keys that Nami already uses. This is to make a minting service that is connected to a specific wallet, and that wallet is always able to mint more tokens if they want to.
However, it doesn't seem like Nami is providing all the signatures that I need. When submitting the transaction I get the following error:
transaction submit error ShelleyTxValidationError ShelleyBasedEraAlonzo (ApplyTxError [UtxowFailure (WrappedShelleyEraFailure (MissingScriptWitnessesUTXOW (fromList [ScriptHash \"9f84ae8b52e374a0cd09e7ec10854309f8dd7b1f5caf69dd658ed6c5\"]))),UtxowFailure (WrappedShelleyEraFailure (UtxoFailure (UtxosFailure (CollectErrors [NoRedeemer (Minting (PolicyID {policyID = ScriptHash \"9f84ae8b52e374a0cd09e7ec10854309f8dd7b1f5caf69dd658ed6c5\"})),NoWitness (ScriptHash \"9f84ae8b52e374a0cd09e7ec10854309f8dd7b1f5caf69dd658ed6c5\")]))))])

I seem to be missing the witness for the native asset script. Is there any way of making Nami sign this or is it impossible? Note that I'm already using the signTx(...) endpoint so it seems to be signing the entire transaction just not what is required by the minting script.
Code:
async function mint(mintData: MintData, wasm: any, walletConnector: WalletConnector){
  const userAddress: Address = wasm.Address.from_bytes(
    Buffer.from(mintData.address, "hex")
  )

  const p = await initTx()

  const txBuilder: TransactionBuilder = wasm.TransactionBuilder.new(
    wasm.TransactionBuilderConfigBuilder.new()
      .fee_algo(wasm.LinearFee.new(wasm.BigNum.from_str(p.linearFee.minFeeA),
                                  wasm.BigNum.from_str(p.linearFee.minFeeB)))
      .pool_deposit(wasm.BigNum.from_str(p.poolDeposit))
      .key_deposit(wasm.BigNum.from_str(p.keyDeposit))
      .coins_per_utxo_word(wasm.BigNum.from_str(p.coinsPerUtxoWord))
      .max_value_size(p.maxValSize)
      .max_tx_size(p.maxTxSize)
      .build()
  );

  const invalidHereafter=10

  if (p.slot === null){
    return
  }

  const ttl = p.slot+invalidHereafter
  const timelockExpiry = wasm.TimelockExpiry.new(ttl)
  const timeLockedPolicyScript = wasm.NativeScript.new_timelock_expiry(timelockExpiry)
  const policyScripts = wasm.NativeScripts.new()
  policyScripts.add(timeLockedPolicyScript)
  const scriptHash = wasm.ScriptHash.from_bytes(timeLockedPolicyScript.hash().to_bytes())
  const policyID = bytesToString(timeLockedPolicyScript.hash().to_bytes())

  //const assetName = Buffer.from(mintData.tokenName, 'hex')
  txBuilder.add_mint_asset_and_output_min_required_coin(
    timeLockedPolicyScript,
    wasm.AssetName.new(mintData.tokenName),
    wasm.Int.new_i32(mintData.amount),
    userAddress,
    );

  const valueFilter: Value = wasm.Value.new(wasm.BigNum.from_str("5000000"))
  //Add inputs
  const utxos: TransactionUnspentOutputs = wasm.TransactionUnspentOutputs.new();
  (await walletConnector.getUtxos(Buffer.from(valueFilter.to_bytes()).toString('hex')))
                .forEach(rawUTXO => {
                  const utxo: TransactionUnspentOutput = wasm.TransactionUnspentOutput.from_bytes(Buffer.from(rawUTXO, "hex"))
                  utxos.add(utxo)
                })

  txBuilder.add_inputs_from(utxos, 0)

  txBuilder.add_change_if_needed(userAddress)

  const toBeSignedTx: Transaction = txBuilder.build_tx();
  const rawToBeSignedTx: string = Buffer.from(toBeSignedTx.to_bytes()).toString('hex')

  const rawWitnesses: string = await walletConnector.signTx(rawToBeSignedTx)
  const witnessSet = wasm.TransactionWitnessSet.from_bytes(
    Buffer.from(rawWitnesses, "hex")
  )
  const witnessSets: TransactionWitnessSets = wasm.TransactionWitnessSets.new()
  witnessSets.add(witnessSet)

  const submitTx: Transaction =
    wasm.Transaction.new(
      toBeSignedTx.body(),
      witnessSet
    )
  const rawSubmitTx: string = Buffer.from(submitTx.to_bytes()).toString('hex')
  walletConnector.submitTx(rawSubmitTx) // <- Error occurs when submitting

}

lol I probably need to use signData(...) I'll update the post if that turns out to be the solution

Where are you running it? is it Ts ? what is this walletConnector objet?

Yes it is possible, i am doing it with out any problems. So the problem must be somewhere in your code. As far as i see you are signing correctly. And you are not adding addressKeyHash in the policy, so there might be a problem related to other utxo? how are you getting the utxos? ...  Can you send a simpler Tx, with out minting?

Instead of using a time-locked script, I required the user to include their wallet key as a witness.
Solution:

export async function mint(mintData: MintData, wasm: any, walletConnector: WalletConnector){
    const userAddress: Address = mintData.address.to_address()
    const netId: NetworkID = await walletConnector.getNetworkId()
    const p = initTxStatic(netId)

    const txBuilder: TransactionBuilder = wasm.TransactionBuilder.new(
      wasm.TransactionBuilderConfigBuilder.new()
        .fee_algo(wasm.LinearFee.new(wasm.BigNum.from_str(p.linearFee.minFeeA),
                                    wasm.BigNum.from_str(p.linearFee.minFeeB)))
        .pool_deposit(wasm.BigNum.from_str(p.poolDeposit))
        .key_deposit(wasm.BigNum.from_str(p.keyDeposit))
        .coins_per_utxo_word(wasm.BigNum.from_str(p.coinsPerUtxoWord))
        .max_value_size(p.maxValSize)
        .max_tx_size(p.maxTxSize)
        .build()
    );

    const baseAddress: BaseAddress = wasm.BaseAddress.from_address(userAddress)
    const scriptPubKey = wasm.ScriptPubkey.new(baseAddress.payment_cred().to_keyhash())
    const pubKeyScript = wasm.NativeScript.new_script_pubkey(scriptPubKey)
    const policyScripts = wasm.NativeScripts.new()
    policyScripts.add(pubKeyScript)

    const hexString = Util.hexEncode(mintData.assetName)
    const assetName: Uint8Array = Uint8Array.from(Buffer.from(hexString, 'hex'));
    txBuilder.add_mint_asset_and_output_min_required_coin(
      pubKeyScript,
      wasm.AssetName.new(assetName),
      wasm.Int.new_i32(mintData.amount),
      userAddress,
      );

    const valueFilter: Value = wasm.Value.new(wasm.BigNum.from_str("5000000"))
    //Add inputs
    const utxos: TransactionUnspentOutputs = wasm.TransactionUnspentOutputs.new();
    const outputs: TransactionUnspentOutput[]  = (await walletConnector.getUtxos(valueFilter))
    outputs.forEach(utxo => utxos.add(utxo))

    txBuilder.add_inputs_from(utxos, 0)

    txBuilder.add_change_if_needed(userAddress)

    const toBeSignedTx: Transaction = txBuilder.build_tx();

    const witnessSet: TransactionWitnessSet = await walletConnector.signTx(toBeSignedTx)

    witnessSet.set_native_scripts(policyScripts)

    const submitTx: Transaction =
      wasm.Transaction.new(
        toBeSignedTx.body(),
        witnessSet,
        undefined
      )
    await walletConnector.submitTx(submitTx)

  }

This error indicates you have all the witnesses you need for the transaction except the minting script and the policy key witness for minting.
You should be able to add a witnessSet to the transaction containing the missing policy script and policy key witness(es) before submitting.


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

How should a transaction that burns tokens look like?

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

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


text:
How to verify that a reward address is associated with a public staking key?
I'm attempting to verify Nami wallets. The scheme is something like this:

Server sends a nonce to frontend
User signs the nonce using their reward address cardano.signData(rewardAddress, nonce)
The signature is sent back to the backend to be verified.

I've managed to do all these steps, including verifying that the nonce has been correctly signed by a given key. But I can not figure out how to make sure that the key the message is signed with corresponds to the address they have given me.
I have to either extract the public key from the reward address or construct the reward address from the public key.
In the @emurgo/cardano-serialization-lib-browser they do this:
const stakeKeyHash = this.headers.address.hash();
const reconstructedAddress = RewardAddress.new(
   checkAddress.network_id(),
   StakeCredential.from_keyhash(stakeKeyHash)
);

...but I'm using Haskell so I have to do it on my own
network_id seems to be one of the strings "Mainnet" or "Testnet"


text:
How to access the current slot in a Plutus validator script?
At the time the Plutus validator script runs, the transaction is not yet part of the blockchain. But the targeted slot of a transaction is known when a node processes the script. Is it possible to access the target slot inside the validator script?

The context of a validator script Plutus.V1.Ledger.Contexts.ScriptContext gives access to the transaction where txInfoValidRange may provide upper/lower bounds of the slot. This, however, requires that a Ledger.Constraints.mustValidateIn constraint has been specified when the transaction was submitted (as done in this example).

I understand that it is considered to be bad practice for a Plutus validator script to depend on the state of the whole blockchain or unpredictable input such as the target slot because it limits verification/testing possibilities.

Nevertheless, there might be plenty of good use cases for using the current slot; for example, an oracle might check if its data is expired and does not want to enforce its users to provide an upper limit in the mustValidateIn constraint.

Accessing any runtime information (including current slot) should not be possible in the validator by design. The reason is that transaction validity needs to be deterministic on construction. The only reason a transaction cannot be executed afterwards would be, if a UTXO was already consumed or the slot is outside of txInfoValidRange (as explained in this Youtube video).
There might be other use cases, but making sure expired oracle data isn't consumed anymore could also be achieved by deactivating an oracle (which would require the oracle contract to support it). And also it is in the best interest of the party creating a transaction to make sure only trustworthy oracle data is consumed.

Does this mean that there is no way other than putting the burden on the oracle's users to check for expiration? The users may not even know what's the appropriate update-cycle for the data they want.
As an oracle provider, I would know about the reliability of my data source. And I might want to set an expiration date in case my network/blockchain access is broken, etc.
Similarly, SSL certificates also have an expiration date because it is a reasonable default: "not doing anything" means automatically invalidated. This is more secure because it removes the "zombies".

Users of an oracle should be able to acquire this information about an oracle. After all you really have to trust an oracle, so the provider should be as transparent as possible.
The oracle could also provide an expiration Slot in it's Datum and only validate transactions that are valid before that expiration (according to txInfoValidRange). The user then needs to restrict transaction validity to a specific slot range.


text:
How do I build a debug configuration of a Plutus project?
When I try to set a breakpoint in a small Plutus project such as this, I always get the following error:
:b Week05.Homework1.mkPolicy
cannot set breakpoint on Week05.Homework1.mkPolicy: module Week05.Homework1 is not interpreted

(Using Windows, cabal version 3.4.0.0, ghc version 8.10.4.)
Removing -fobject-code or adding -fPIC to the ghc-options won't help, which was suggested here for other Haskell projects. -fPIC does even fail as it is not a Windows thing, anyway.
The error is the same for off- and on-chain functions. So the INLINABLE pragma is not to blame.
Does this have anything to do with the PlutusTx compiler?

This may have to do with Haskell being a functional language. Meaning that unlike imperative languages, there are no 'breakpoints' due to the nature of the language. The other link you mentioned only works with I/O operations which follow an 'imperative' style. The answer for your question would be to find a new way to debug functional programs, seeing as they don't work with imperative style debugging.

mkPolicy is an on-chain validator code, is lifted to template Haskell and it gets compiled to core plutus and executed when the UTXO locked by that script is spent. AFAIK, core-plutus is not Haskell, so the breakpoint will be ignored.


text:
ZeroKnowledge Proofs in Plutus?
From what I heard Plutus / Smart Contracts will bring also the possibility to do Zero Knowledge Proofs.
But I struggled to find further Details in the Documentation.
So here are my Questions:
Anyone knows where to find more detailed documentation on how / if ZK Proofs will be implemented in Plutus.
If ZK Proofs will be implemented into Plutus are they limited to the domain of ada / token transactions or can they be considered as some sort of ZK Framework to proof other Datasets from other Domains as well (i.e. age)?

Some info can be found in this document: https://iohk.io/en/research/library/papers/soniczero-knowledge-snarks-from-linear-size-universal-and-updateable-structured-reference-strings/
Some bits in this video with Markulf Kohlweiss about Zk-SNARK https://www.youtube.com/watch?v=cAJERtcZamc
And in this video of Charles: https://www.youtube.com/watch?v=M67Z1d-sUug
However looking at it from the perspective of someone trying to apply it to real world problems it all still seems to be in the research phase?

Yes, Plutus makes it possible to validate zero knowledge proofs as it is a Turing-complete language. However, verifying zero knowledge proofs can be very complex, and go over the execution budget. To allow for a more efficient execution of zero knowledge proofs, the IOG team is working in introducing built-in functions of the most expensive operation required when verifying pairing-based zk-proofs, pairings. These type of proofs have the most efficient verifiers. You can find more information on the use cases of pairings in the draft CIP (note that this is a draft as it stands).
https://github.com/cardano-foundation/CIPs/pull/220
There is a bunch of different possible ZK proofs, and implementing a ZK verifier does not necessarily bound the statements that one can verify. IOG is involved in an open source effort of the implementation of Plonk, one such proving system.
https://github.com/ZK-Garage/plonk
However, there are no concrete plans on when this will be used to verify statements on chain.


text:
Pool Rewards distribution via SmartContract
For the Pool I run I would like to setup a SmartContract which automatically claims the rewards and sends a certain percentage to each of three organisation I support.
Is such a thing possible with smart contracts?
Can a SmartContract claim rewards?
Or do I have to claim the rewards "manually" and then send them to the Smart Contract to to it's work ?

Is there a reason your "three organizations" can't just stake from their own wallets and manage their own rewards?

I wan't to support three organisations via the rewards the PoolOwner (me) earns. The idea is to establish an automatic way to donate the pool owner rewards. The Rewards of "regular" delegators are not touched by this.

I think it would make more sense to write an off-chain script to do this for you. There is no trust involve (you already have access to your own spending key); there is no need to get the network to validate your transfers. And you are going to need a script/off-chain worker anyway to trigger the smart contract to send funds.

Ok thnx for the clarification, I thought about offline code initially, but like the fact that a Smart contract has the distribution written in code. I guess the best solution is then be to claim the rewards manually and send them to a smart contract address. Kind of an hybrid approach.

The funds from a smart contract can be delegated to a stake pool. So if you wanted to have all the staked funds live at the contract you could accomplish something similar to what you are proposing.
There isn't such thing as "automatically" for Plutus smart contracts. They are passive. That being said, it might still make sense for you to set it up in a way that anyone (usually you) could trigger the distribution of the rewards. Each of these transactions will cost a small fee of course.

Can you explain hat you mean by "smart pool" never heard that ?

Typo. Meant "stake pool." Woops. Fixed it.


text:
Detailed Minting policy documentation?
I found several Articles which deal with Minting Policy's for native tokens as:

https://cardano-ledger.readthedocs.io/en/latest/explanations/policies.html#minting-policy
https://github.com/input-output-hk/cardano-node/blob/master/doc/reference/simple-scripts.md
https://docs.cardano.org/en/latest/native-tokens/getting-started-with-native-tokens.html#token-minting-policies

But none of them has a detailed desciption of syntax and functions provided in smartcontracts as of today (mary era).
Any hints are welcome.

You were almost there, the token policy scripts are actually the multisig/nativescripts. As you know token policy's are not turing complete contracts, for that you should be looking at Plutus. Here's the documentation regarding the NativeScripts as scripts to use as token policy with all syntax and features.
https://docs.cardano.org/projects/cardano-node/en/latest/reference/simple-scripts.html

thnx Ashish that was the pointer I was looking for.

The link doesn't work anymore. Here's the archived page: https://web.archive.org/web/20210601112403/https://docs.cardano.org/projects/cardano-node/en/latest/reference/simple-scripts.html

Whoever decided to change the above URL and dumb-down the whole website and make it flashy is a horrible person


text:
Cardano-cli Handshake error after Daedalus update
After updating Daedalus for the Vasil hardfork, I get the below error when running this cardano-cli command
cardano-cli get-tip --testnet-magic 1097911063

cardano-cli: HandshakeError (VersionMismatch [NodeToClientV_9,NodeToClientV_10,NodeToClientV_11] [12,13])

My cardano-cli is still version 1.33.0 but I have already updated Daedalus. Is there anything I need to do on my part after updating Daedalus?

My cardano-cli is still version 1.33.0 but I have already updated Daedalus.

That is the problem right there. I suspect the node that is started by Daedalus is either 1.35.0 or 1.35.1 (ie these releases support the Vasil HF). The cardano-cli version needs to match.

You need to use Daedalus version >= v4.12.0 , the download links can be found here.
In case you see older version, clear the browser cache or open the page in Incognito mode.


text:
What do i pass in as the parameter to create a new Ed25519KeyHash using cardano-multiplatform-lib
I am using Dc Sparks multi-platform-lib to build my transaction.I want to add a required signer in my transaction. There is a add_required_signer method in the TransactionBuilder class and it takes in a parameter of type Ed25519KeyHash. Right now I am creating a new Ed25519KeyHash like this
const walletConnection = await window.cardano.nami.enable();
const raw = await walletConnection.getChangeAddress();
const changeAddress = WASM.Address.from_bytes(
  Buffer.from(raw, 'hex')
).to_bech32();
let signer = WASM.Ed25519KeyHash.from_bech32(changeAddress);

This is the error that it returns.
Deserialization failed in Ed25519KeyHash because: Invalid cbor: expected tuple 'hash length' of length 28 but got length Len(57).

What is the correct value I need to pass to create a new Ed25519KeyHash


text:
Simulate Minting Event In EmulatorTrace
My application has a minting script and a validator script that works together. I am using EmulatorTrace to test my application.How do i simulate a minting event in EmulatorTrace?

There are plutus-contract tests, such as MustMint.hs, that demonstrate the use of each minting tx constraint: mustMintCurrencyWithRedeemer, mustMintValueWithRedeemer, mustMintCurrency & mustMintValue. Hope that helps.


text:
How to Start a New Project
Let's say I have downloaded all the necessary things needed to start developing on Cardano and I just opened up the terminal. I want to start building a new project. What are the commands I run.
Example -- If I was going to do this for React I would run the following command and start coding.
npx create-react-app my-app
cd my-app
npm start

What is the equivalent of that for Plutus.

Please take a look at this post https://cardano.stackexchange.com/a/9648/2335

There is no npx create-react-app my-app on cardano unfortunately, but there is a helpful repository that has the project structure necessary to start working with plutus.
So, first, you need to nix-shell inside the plutus-apps repo:
$ git clone https://github.com/input-output-hk/plutus-apps # if you haven't already
$ cd plutus-apps
$ git checkout <current-tag>
$ nix-shell

The git checkout part just need's to be done in the first time you run this or whenever you change the cabal.project file. "<current-tag>" can be found inside cabal.project file (in this case it would be plutus-starter-devcontainer/v1.0.14)
So, assuming you are already on a nix-shell, it would look like this:
$ git clone https://github.com/input-output-hk/plutus-starter.git
$ cd plutus-starter
$ cabal update
$ cabal repl

Way longer than the create-react-app one, but that's mainly because of nix-shell, after a while you get used to it.

Why do we need to do the command git checkout  ? I am following the plutus-pionner-program and I have to do this for every week's folder too. Why cant we just run nix-shell and start up the client ?

Because plutus-apps is being constantly developed and so some syntax / features change from lecture to lecture

If your app is fairly simple and all you need is to be able to send transactions to an address, send transactions to a smart contract or redeem assets from a smart contract then there is a create-react-app to get you started here:
Create React App on Cardano Developer Portal

inside the terminal you would be able to make a custom directory (or folder tree) using the commands mkdir and cd which make a folder and change the current folder your in respectively.
Doing this will separate your project files from the plutus files, but by running nix-shell your environment would still be the one required to compile plutus smart contracts.
To use this with vscode from the terminal navigate to your project directory and run code .. This should port your nix-shell environment into the vscode one, if it doesn't you may have to change some settings in vscode.
Between this and @Mateus answer your good to go.


text:
What is the role of datum in spending a transaction
So i am going over the plutus-pionner-program right now and he keeps on iterating this point. Transaction that spends a script output need to provide the datum of that script. Transaction that send money to a script address just need to provide the hash of that script. What is the point of all this ? I thought datum was used to keep track of the state of the script.What role does datum play in using a output from a script address and what role does datum play in sending to a script address.

I thought datum was used to keep track of the state of the script.

It can be and often is. This is how its used in a StateMachine, for example.
The cardano chain is 'lean': only the necessary information to ensure the integrity of the chain is required and kept on the chain.
A script is required and run only if a transaction spends from the address, and that script requires the datum to be available.
Sending to a script address from  a payment address doesn't require the script to be run. In the minimalist spirit the chain needs only to record the hash of the datum to ensure that when the UTXO is spent this spending transaction has provided the right datum.
The design requires "off-chain" components of a DApp to take a much greater role for handling state than, say, ethereum. Whatever builds a transaction is responsible for ensuring that all datums and hashes are sensible ones.
Use of datum hashes has been flagged as a pain point:
https://github.com/cardano-foundation/CIPs/tree/master/CIP-0032


text:
Script to only accept payments in 100 Ada
How do i create a simple script that users can deposit ada into but only 100 ada per transactions , nothing less than that and nothing more. The transaction will not go through if it is not 100 Ada.

Cardano is a decentralized system, anyone can send anything to any address with any datum attached to it (no one can be censored). There is no way of stopping anyone from sending something to an address, and thats a good thing.
What you can do however is enforce the "spendabilty" of a script address that you created. So an UTxO at an address can only be spend if it sends 100 ada to a predefined address. What are you trying to achieve? If it is something along the line of; I want some to logic to be performed only if 100 ada is payed, then just add the above condition in that plutus validator.

Yeah , thats what I was trying to do. I only want to perform certain action if 100 ada is payed.


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

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

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

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

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


text:
How to see UTXOs at a script
I am creating a function that takes in UTXOs at a script as a parameter. I know there is a function Plutus.Contract.utxoAt but how do i see what that will return ? I am still developing out my script and it is not on the chain yet.I need to see what utxoAt will return in order to pass it in to a function.

It will return a map containing the TxOutRefs of the provided address. Perhaps these are what you want your script to validate? Unless I'm misunderstanding your intention, you can't use these contract functions onchain. They are useful for offchain actions such as inspecting and building transactions.

Yeah , turns out I can just put that in a print statement and run it in playground. I’ll be able to see what it returns in the log.


text:
What is the mkValidator Script
In Plutus scripts there is a mkValidator where it takes in the datum , redeemer , and script context. In the plutus-pionner-program , the plutus scripts they show us uses these three parameters to decide if a transaction will go through. I am looking at the the plutus-use-cases repo and in it most of the scrips dont do it the same why they do it in the lectures. How does this mkValidator work , what is the purpose of it , and is there additional resources that I can read or watch on this

A validator script locks transaction outputs. This function is where you define conditions to unlock them. https://plutus.readthedocs.io/en/latest/tutorials/basic-validators.html

Heads up that the link is dead now.

Link has been corrected

On Cardano logic can be enforced on how UTxO's are spend by attaching a "script" to the transaction + some inputs that will be used to run the script (the datum, redeemer and context). Visualize this script as a black box where the inputs go in and a boolean is the output. If given the inputs the black box return true, then the UTxO may be consumed (the enforced logic of the script is met).
In it core this script is generated from a haskell function that in the plutus-pioneer-program we often call the mkValidator function (it can have any name). This function should have at least 3 inputs, namely the datum, redeemer and context. But note that it can have more inputs that you could define! This mkValidator function is then compiled to a script that is used on the blockchain using template haskell. In this stage all function inputs are filled in expect the datum, redeemer and context (these should be filled in the usage on the blockchain when a UTxO connected to this script is consumed).
Hope this helps


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

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

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

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

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

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

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

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

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


text:
Daedalus Node is Not the Latest Version
I am running Daedalus to use the Cardano-Cli. Right now when I run the command
cardano-cli query tip --testnet-magic 1097911063

It returns this, which states that it is still in the Alonzo era.
{
    "era": "Alonzo",
    "epoch": 214,
    "hash": "add989729d61973bb82174179887a089ae9648b28d211e9cfc83993aed3b7068",
    "block": 3680416,
    "slot": 62504629,
    "syncProgress": "99.74"
}

Do I have to update the node myself? Or do I have to wait for Daedalus to do it and download a newer release? If so, when will the updated version be out?

There will be an updated version of Daedalus for testnet running the new node by the end of the week (most likely Thursday, taken from Discord). You can probably download it from here once it's ready:
https://testnets.cardano.org/en/testnets/cardano/get-started/wallet/

let the node sync
the output you shared shows
    "syncProgress": "99.74"

meaning the node is not synced with the blockchain.
as soon running the command you see
   "syncProgress": "100.00"

you should be able to enjoy your Vasil testnet


text:
AMD64 Error Warning When Setting Up Grapgql Docker in Mac M1
I am following the following guide to set up graphql on my M1 Mac. https://github.com/input-output-hk/cardano-graphql#overview. All the containers are up and running but i can't visit local host to play around with graphql.The containers i am running have a amd64 warning error. Is there a way to get past this warning ? Has anyone else been able to setup cardano-graphql on M1 Mac?

Took me like 6+ Months to figure out all the requirements and what modules need to get loaded first...
This guide helped a lot https://robferguson.org/blog/2022/02/19/getting-started-with-cardano-graphql/
And he coverers building on mac.
These steps assume you have a docker GraphQL git environment already created and volumes ending in *_db-sync-data and *_postgres-data are empty. If you are tring to sync DB-Sync then remove Postgres and db-sync-data volumes. Ogmios data will be fine.
If you have data in  *_db-sync-data and *_postgres-data, please remove the data. We need a fresh state for all of this to work. See https://github.com/input-output-hk/cardano-graphql/wiki/Docker#rebuild-cardano-db for help. (If you use CGQL only select postgres)
1st
Start Ogmios and let it sync up to 80-99% depending on what
snapshot you download (I suggest waiting until its at least 95%
synced).
`Docker-compose up -d` then `Docker-compose down` finally
`docker-compose start cardano-node-ogmios`

This will only start Ogmios, wait a day or until you are at 70-90%.
2nd
Now we need to sync cardano-db-sync-extended. Go to the IOHK snapshot https://update-cardano-mainnet.iohk.io/cardano-db-sync/index.html#13/ (PS we are in folder 13/ right now, but look in 12/ folder for older snapshots) and choose the latest snapshot (if Ogmios is synced to 95%) or an older snapshot from folder 12/ if you are synced below 95%.
NOTE choosing a snapshot that is before that current sync point of Ogmios is fine, but getting a snapshot that is past Ogmios sync point will cause DB-Sync to delete any blocks past Ogmios sync point and can take a bit longer to delete then re-sync.
Syncing without a snapshot can take 3+ Days, I tried once and Ogmios was fully synced it took DB-sync 3 days to only get to ~70% and I have SSDs.
If you look at the Ogmios logs you should see one saying what slot & block it is currently at:
[3d54f2c4:cardano.node.ChainDB:Notice:2262] [2022-06-05 16:59:45.33 UTC] Chain extended, new tip: b57fbffcfccc13b56f0f869bf0b1dc699c4b020217ff9292d3504f56b83448bf at slot 62882094 {"severity":"Info","timestamp":"2022-06-05T16:59:45.341328986Z","thread":"3454","message":{"Health":{"tag":"HealthTick","status":{"startTime":"2022-06-04T13:55:56.922570134Z","lastKnownTip":{"slot":62882094,"hash":"b57fbffcfccc13b56f0f869bf0b1dc699c4b020217ff9292d3504f56b83448bf","blockNo":7337678},"lastTipUpdate":"2022-06-05T16:59:45.341113964Z","networkSynchronization":1.00000,"currentEra":"Alonzo","metrics":{"sessionDurations":{"max":0,"min":0,"mean":244854.64556962025},"totalMessages":6957619,"runtimeStats":{"currentHeapSize":2551,"maxHeapSize":10242,"gcCpuTime":522927267999,"cpuTime":5356749610627},"activeConnections":5,"totalUnrouted":0,"totalConnections":84},"connectionStatus":"connected","currentEpoch":343,"slotInEpoch":69294}}},"version":"v5.1.0"}
Which shows I am at Block: 7337678 and Blockchain Slot: 62882094
So I know I use the latest release "db-sync-snapshot-schema-13-block-7334319-x86_64.tgz" since 7337678 > 7334319.
Now we need to start DB-Sync:
There are 2 ways to do this.
One way is to let db-sync download the file from IOHK but there is a chance that the download can become interrupted and will not finish or continue after. (easiest but may not work..)
The other way is to manually download the snapshot and edit docker-compose.yml to have DB-sync load it from a local file instead of downloading(suggested)
Way 1 - not-recommended
export NETWORK=mainnet &&\ RESTORE_SNAPSHOT=https://update-cardano-mainnet.iohk.io/cardano-db-sync/12/db-sync-snapshot-schema-12-block-6764999-x86_64.tgz \ docker-compose up -d &&\ docker-compose logs -f Insert your snapshot link instead of mine.
Then wait ~2 hours and the download should be down and the system should start adding/altering tables in the DB-sync log.
If you see messages saying download was interrupted or stopped and it can not resume. Then try Way 2 and delete volumes *_postgres-data and .
https://github.com/input-output-hk/cardano-graphql/wiki/Docker#rebuild-cardano-db for help on removing volumes
Way 2 - Recommended
Navigate to container folder, then create a "snapshots" directory and give it access to all users (777).
Now we download the snapshot to "snapshots" using wget:
 wget https://update-cardano-mainnet.iohk.io/cardano-db-sync/13/db-sync-snapshot-schema-13-block-7334319-x86_64.tgz
Next, we need to edit docker-compose.yml, look for "cardano-db-sync-extended" then the volumes should look like this:
   volumes:
    - ./config/network/${NETWORK:-mainnet}:/config
    - db-sync-data:/var/lib/cdbsync
    - node-ipc:/node-ipc
    - db-sync-tmp:/tmp
    - ./snapshots:/snapshots

Finally at the bottom of Docker-compose.yml, look for and edit the Volumes array.
It should look like this:
volumes:
  db-sync-data:
  node-db:
  node-ipc:
  postgres-data:
  db-sync-tmp:

Now we can start DB Sync and Postgres
export NETWORK=mainnet && \ export RESTORE_SNAPSHOT=/snapshots/*FILE_NAME* && \ docker-compose up -d
which will start Postgres, Hasura, DB-Sync, GraphQL and Ogmios (if not already running).
Let DB Sync run for a day or so then it should be down unpacking. If you see anything saying that DB-sync is rolling back to genesis and the amount of block to be deleted is >2-5K then your snapshot was too far ahead and you need to wait for DB-sync to delete all those Blocks, before it uses to Hasura to continue syncing.
At this point, it might be worth it to restart the DB-sync process with older snapshot, But it is hard to say how long the deletion will take and depends on your system setup. If it is more than 5-10K of blocks that need to be deleted then I say re-start the DB-sync process with a older snapshot, or close DB-sync and wait for Ogmios to sync more.
GraphQL may come up with a fresh install after running the docker-compose up command from Github, but db-sync never fully syncs so it is never usable for me.
After DB-sync is done, if GraphQL port is still not online then restart the GraphQL module only and wait a day. docker-compose restart cardano-graphql
the GraphQL port and interface should come up after 1-3 hrs after DB Sync is fully synced and Ogmios is around 99-100%
Errors I saw
`psql:/tmp/db-sync-snapshot-hc6bN9lE7U/db-sync-snapshot-schema-12-block-6451499-x86_64.sql:238416086: ERROR:  could not extend file "base/16384/214298": No space left on device
HINT:  Check free disk space.
psql:/tmp/db-sync-snapshot-hc6bN9lE7U/db-sync-snapshot-schema-12-block-6451499-x86_64.sql:238416150: ERROR:  could not write block 35045 of temporary file: No space left on device
CONTEXT:  parallel worker`
https://robferguson.org/blog/2022/02/19/getting-started-with-cardano-graphql/
Be carful using docker image prune since it could delete your Ogmios data and add an extra day or two to the whole sync process. But normally the Check Free disk Space error is because the system can not unzip the snapshot because of space limitations.
Even if you should have enough space, I found that sometimes I needed to delete all my volumes to get it to work.
Background
Ive been trying to get GraphQL to work for months now... I've tried on a few different servers over the months, but I just recently have been able to get it online.
Also make sure your system has the requirement to run the full stack (32GB Ram needed and SSDs strongly encouraged):
https://github.com/input-output-hk/cardano-graphql/releases
Hope this helps and saves people some months like me XD


text:
Type PaymentPubKeyHash not found
I have the following datum type
data ProjectSubmitDatum = ProjectSubmitDatum
  { vProjectOwner :: PaymentPubKeyHash,
    vProjectRegistrationFee :: Integer,
    vProjectCategory :: BuiltinByteString,
    vFundPayIdentifier :: PaymentPubKeyHash
  }
  deriving (Show)

I also have the module imported like this
import Ledger.Address

The following error pops up when i run cabal repl
src/QuadraticVFSC.hs:45:19: error:
    Not in scope: type constructor or class ‘PaymentPubKeyHash’
   |
45 |   { vFundOwner :: PaymentPubKeyHash,
   |                   ^^^^^^^^^^^^^^^^^

you need to import either the whole module like this:
import Ledger

or the specific type like this:
import Ledger (PaymentPubKeyHash)

Still not working when i import the whole module. When i was importing specific type it said it does not export PaymentPubKeyHash.

Also check you have the right git commits (precisely the commit of plutus-apps as found in the cabal.project). PaymentPub... is relatively new. It used to just be Pub...

If it can’t be found, you most probably have an older version of plutus-apps. You can change the tags in the file cabal.project.

You neeed to import PaymentPubKeyHash it like the following:
import Ledger.Address qualified as Address                      (Address, PaymentPubKeyHash(..))
This works for me and you can checkout my working code on testnet here:
https://github.com/lley154/cardano-lottery/blob/main/src/OnChain.hs
Cheers,
Lawrence


text:
A Script With Multiple Different Datum Types
I have 4 different Datum Data Types in my script because for 4 different use cases in my script.
data FundCreationDatum = FundCreationDatum
  { vFundOwner :: PaymentPubKeyHash,
    vPrizeAmount :: Integer,
    vProjectLabel :: [BuiltinByteString],
    vPrizeDistributionRatio :: [Integer]
  }

data ProjectSubmitDatum = ProjectSubmitDatum
  { vProjectOwner :: PaymentPubKeyHash,
    vProjectRegistrationFee :: Integer,
    vProjectCategory :: BuiltinByteString,
    vFundPayIdentifier :: PaymentPubKeyHash
  }

data VotingActionDatum = VotingActionDatum
  { vProjectToVote :: PaymentPubKeyHash,
    vVoterPayAddress :: PaymentPubKeyHash,
    vAdaLovelaceValue :: Integer,
    vVoteFundIdentifier :: PaymentPubKeyHash,
    vActionName :: BuiltinByteString
  }
  deriving (Show)

data ConToMatchPool = ConToMatchPool
  { vFundAddress :: PaymentPubKeyHash,
    vPrizeFund :: Integer
  }
  deriving (Show)

I then bundled the 4 data types into a single data type with the Maybe monad.
data QuadraDatum = QuadraDatum
  { qCreateFund :: (Maybe FundCreationDatum),
    qVoting :: (Maybe VotingActionDatum),
    qSubProject :: (Maybe ProjectSubmitDatum),
    qContrPool :: (Maybe ConToMatchPool)
  }

I am trying to send a utxo with datum attached like this.
start cp = do
  let dat = QuadraDatum qContrPool
            {vFundOwner = cpFundOwner cp
            ,vPrizeAmount = cpPrizeAmount cp
            ,vProjectLabel = cpProjectLabel cp
            ,vPrizeDistributionRatio = cpPrizeDistributionRatio cp
            }
      tx = Constraints.mustPayToTheScript dat $ Ada.lovelaceValueOf $ (cpPrizeAmount cp)
  ledgerTx <- submitTxConstraints typedValidator tx
  void $ awaitTxConfirmed $ getCardanoTxId ledgerTx

I am getting the following error
 error:
    • Couldn't match expected type ‘Maybe FundCreationDatum’
                  with actual type ‘FundCreationDatum’

let's say we have a Maybe Integer type, then the value must be assigned as either Just 3 or Nothing.
Directly assigning  it as 3 won't work.
So your QuadraDatum should be   created as
  let dat = QuadraDatum
              (Just qContrPool)
              (Just {vFundOwner = cpFundOwner cp
                  ,vPrizeAmount = cpPrizeAmount cp
                  ,vProjectLabel = cpProjectLabel cp
                  ,vPrizeDistributionRatio = cpPrizeDistributionRatio cp
               })
               Nothing
               Nothing

Also, better approach is to use multiple constructors something like this
data QuadraDatum = FundCreationDatum
  {
    vPrizeAmount :: Integer,
    ...
  }|
  ProjectSubmitDatum
    {
      vProjectRegistrationFee :: Integer,
      ...
    }
  deriving (Show)


text:
Get Value of Datum from a UTXO
I currently have a utxo that i am getting like this.
initalMatchPool <- Map.filter (findInitalAmount fundAddress) <$> utxosAt scrAddress

How do i get the value of the datum attached to this specific utxo ?

The ChainIndexTxOut type has a data field called _ciTxOutValue :: Value and another that is _ciTxOutDatum :: Either DatumHash Datum I'll show you how to get the value. Getting the datum is the same process with the extra step of having to extract it from the Either binding.
utxos <- utxosAt ...
list = Map.toList utxos
firstUtxo = head list
ci = snd firstUtxo
val = _ciTxOutVale ci

utxos is type Map(TxOutRef ChainIndexTxOut)
list is type [(TxOutRef, ChainIndexTxOut)]
firstUtxo is type (TxOutRef, ChainIndexTxOut)
ci is type ChainIndexTxOut
val is type Value
All those lines can be combined to vals = _ciTxOutValue (snd (head (Map.toList utxos))) or if you want the sum of all the of the values instead of just the value in the first utxo at the address, you can do vals = _ciTxOutValue <$> (snd <$> Map.toList utxos)

I am getting type errors from using this.

@szhang9921 Can you share your code?

it works now , the type error was because i was parsing the final value wrong. Thanks

The upshot is that you might not find a datum, but instead get a hash of the datum (it depends).
When submitting a transaction, the full "unhashed" datum is not automatically attached to the output. This to save space and add use cased where the sender wants to keep the datum a secret. If it is not attached, you will not find it onchain, only the hash of the datum used. Reversing this is (computational) impossible by construction.
In the other case, where there is one attached, you can retrieve it. As stated by Kyle Murphy the constructor ChainIndexTxOut(1) that resulted from the filter "findInitalAmount fundAddress" over all UTxO's sitting at the script address scrAddress contains all info known of these outputs fitting the condition you specified.
The function utxosAt returns a map of two fields, Map TxOutRef ChainIndexTxOut (2). Each TxOutRef contains the hash of the transaction that made this utxo and an associated id relative to the other outputs of that transaction (TxOutRef TxId Integer). Now the other field in the Map is the ChainIndexTxOut which can contain one of two things depending on the query. If you queried a script address, this will be

Note That the _ciTxOutDatum constructor holds a Either DatumHash Datum. So if the UTxO contains a datum you can retrieve, you can extract it with Right like below.
getDatum :: ChainIndexTxOut -> Maybe Datum
getDatum o = case _ciTxOutDatum o of
            Right  i               -> Just i
            Left   j               -> Nothing

I hope this helps.

Great explanation. However, I believe your last sentence is inaccurate and in order to read the datum from the call to _ciTxOutDatum we match it using Right and not Left.

OffChain:
It's a datum hash - so there is no reverse lookup if you don't know how to construct datums for a given contract.
Datum values are usually provided by the consumer of a script UTxO.
OnChain:
If this is onchain code (which it does not look like), you can use a function called findDatum to lookup datums provided by the consumer of a script UTxO.


text:
What is the data type returned from the function utxosAt scriptAddress
I want to use the value returned from the function utxosAt scriptAddress. What is the value that this function will return ? Is it going to be in a list , json etc.....

A (Map TxOutRef ChainIndexTxOut) see here.
A good example can be found in the pioneer program of how to utilize that
function:
{...}
utxos <- Map.filter (isSuitable pkh) <$> utxosAt scrAddress
{...}
where
   isSuitable :: PubKeyHash -> TxOutTx -> Bool


text:
How to see the values of things as you code
How do I test different plutus functions to see if its applicable to be used in my code. How would I create the parameters that these functions would take in.
For example below is a Vesting contract from the Plutus-Pionner-Program. How do i see what happenes when you run this function.How do I test out what each individual function return when a parameter is passed in.
give :: AsContractError e => GiveParams -> Contract w s e ()
give gp = do
    let dat = VestingDatum
                { beneficiary = gpBeneficiary gp
                , deadline    = gpDeadline gp
                }
        tx  = Constraints.mustPayToTheScript dat $ Ada.lovelaceValueOf $ gpAmount gp
    ledgerTx <- submitTxConstraints typedValidator tx
    void $ awaitTxConfirmed $ getCardanoTxId ledgerTx
    logInfo @String $ printf "made a gift of %d lovelace to %s with deadline %s"
        (gpAmount gp)
        (show $ gpBeneficiary gp)
        (show $ gpDeadline gp)

How would I pass in the necessary information to this to test if it runs or not.
Basically what I am asking is how do i just start hacking on Plutus. Just run some of the functions that Plutus have ,pass in some parameters , and see what it returns. I know i can run it in GHCI but I feel like I have some gaps in my knowledge and it is not connecting yet.

I share your dilemma. I am no expert, but my understanding is that whereas other languages tend to be imperative (do this to that, and then take that and do this to it), Haskell is more about defining what something is. Therefore, there is no interim state or progress status to easily query or capture (eg. alert('here!'); in javascript). Add to that the multi-nested user defined (often other-user defined ie. plutus development team) types and "builtin" types and the need to define instances to view something (eg. deriving Show) in your code, and I too find myself wandering blind and lost.


text:
How to detect a wallet change event
How do i detect that my user has switched their wallet to a different one in browser. When a user connects their wallet to my web app, we store their wallet address temporarily for use in the future.Let's say they are currently interacting with my web app using Nami wallet. Nami wallet allows user to switch multiple different wallets. How do i detect that a user has switched to a different wallet.
In Solana and Ethereum they have something like this.
connector.on(...)

Is there an equivilant of that for Cardano.

     var handle: any = await window.cardano.nami.enable() handle.experimental.on('accountChange',(addresses: any ) => {
    console.log(addresses)
  }

As far as I know, there isn't.
You probably need to check the cardano.wallet.name periodically.


text:
How can metadata.json properties be changed after a token is minted?
I've minted a token but some of the metadata.jsosn properties don't look so great. Is there a way to update them?
The general form I've tried is:
cardano-cli transaction build-raw \
        --fee $fee \
        --tx-in $txhash#$txix \
        --tx-out $address+$output \
        --metadata-json-file metadata.json  \
        --out-file matx.raw

Technically you cannot change the metadata for a token once its minted. Thats the whole point of putting something on the blockchain-its immutable. On Cardano, token metadata is just metadata in the minting transaction. What you are doing is just adding new metadata to a new transaction with the token. This is not changing the minting metadata. You should just burn the token and start fresh.

This seems to work:
export address="address the token was created on"
export txhash="transaction hash the token was create don"
export txix="index of txhash above"
export funds="funds at the txhash"
export policyid="the token policy id"
export fee="0"
export output="0"
export tokenamount="the countof the token at the txhash"

cardano-cli transaction build-raw \
        --fee $fee \
        --tx-in $txhash#$txix \
        --tx-out $address+$output+"$tokenamount $tokenpolicy.$tokenname" \
        --metadata-json-file metadata.json  \
        --out-file matx.raw

fee=`cardano-cli transaction calculate-min-fee --tx-body-file matx.raw --tx-in-count 1 --tx-out-count 1 --witness-count 1 --mainnet --protocol-params-file=protocol.json | cut -d " " -f1`
echo "Funds? $funds"
echo "Fee? $fee"
output=$(expr $funds - $fee)
echo "Output? $output"
echo "Addr? $address"
echo "txhash: $txhash#$txix"

# redo the transaction aboev w/correct fee
cardano-cli transaction build-raw \
        --fee $fee  \
        --tx-in $txhash#$txix \
        --tx-out $address+$output+"$tokenamount $tokenpolicy.$tokenname" \
        --metadata-json-file metadata.json  \
        --out-file matx.raw \

# sign the transaction
cardano-cli transaction sign \
            --signing-key-file test.skey \
            --signing-key-file policy/policy.skey \
            --tx-body-file matx.raw \
             --mainnet \
            --out-file matx.signed

# submit the transaction
cardano-cli transaction submit --tx-file  matx.signed --mainnet


text:
cardano-wallet for pab-local-cluster
Does anyone have an example of how to execute the cardano-wallet CLI for the pab-local-cluster in plutus-apps (tag: v2022-01-17)?  I can get access to to the local wallet server APIs, but I need the cardano-wallet CLI so I can create new wallets.   I am running the local cluster as per "cabal exec plutus-pab-local-cluster" but do not see how to execute the cardano-wallet CLI that can connect with the local wallet server that is running.

Are you working using nix-shell? If you have Nix and call nix-shell first in plutus-apps dir, it will load shell where cardano-wallet CLI will be available, and you can cabal build/exec/etc from there also.
(also, you can create wallets using REST API as well)

Hi @MikhailLazarev, thanks for the repsonse.
Yes, I am using nix and when in the nix-shell, can access the cardano-wallet CLI, but it is not connected to the local cluster.
I've tried to add some params to cardano-wallet serve, but it is unable to connect to the node. The REST API works.
cardano-wallet serve --node-socket /run/user/1000/test-cluster3561/node/node.socket --testnet /run/user/1000/test-cluster5446/node/byron-genesis.json
[cardano-wallet.network:Warning:27] [2022-01-26 19:46:51.18 UTC] Couldn't connect to node (x19). Retrying in a bit.

FYI - I got the cadano-wallet CLI to work with the pab-local-cluster on ubuntu linux, I just setup a simple proxy as per below.
$ simpleproxy -L localhost:8090 -R localhost:46493

That's good. Can you explain about port 46493? in your answer.

This is the default port used for cardano wallet server with the local pab cluster.


text:
bootstrap chain-index.db
The process to sync the plutus-pab chain-index for the testnet takes over 3+ days now and will take longer as time goes on.   Is it possible to bootstrap the chain-index sync process to reduce the manual sync process?  I've tried copying over the chain-index.db (and referencing that file in the chain-index-config.json  file) that was already sync'd from another machine, but it appears to be starting over again. Thank you.

Copying over chain-index.db should work. What exacly are you running on the command line?

Thanks for confirming.   The command I am running is from the plutus-pab/test-node readme.   cabal exec -- plutus-chain-index --config testnet/chain-index-config.json start-index.

Chain-index tries to use the existing db file, but if anything goes wrong it just starts over, so it's hard to diagnose. It could be a version difference. Or it could be a silly mistake, but without error it's hard to say.
You could try simple things like running it for a bit on the new machine and copying the file over to the old machine and see if it picks that up.

Thanks for the answer and yes, it is a differen't version of chain-index that I am trying to bootstrap, so most likely that is what the issue is.

It seems, that syncing chain-index.db is faster on a Linux in a Windows Subsystem for Linux (WSL2) than in a standalone Linux. This might be caused of a better virtual memory manager on Windows or some special compiled-in kernel features.
On my Windows 11 Home / WSL2 Ubuntu-20.04 system with 16 GB RAM and AMD Ryzen 5 3500U 2.10 GHz processor and SSD, syncing on 2022-04-20 took about 14 hours.
Kernel version of my WSL2 (uname -r): 5.4.72-microsoft-standard-WSL2 of 2021-06-07, see Kernel Updates.


text:
Re-Implementing Policy Hashing in Python
As the title says, I want to to reimplement the hashing part of a policy script in Python 3.
I have already made a post over at forums.cardano.org, and someone has pointed me to the right direction of serializing to CBOR according to the CDDL specs.
Here's the relevant part of the CDDL specifications:
native_script =
  [ script_pubkey
  // script_all
  // script_any
  // script_n_of_k
  // invalid_before
     ; Timelock validity intervals are half-open intervals [a, b).
     ; This field specifies the left (included) endpoint a.
  // invalid_hereafter
     ; Timelock validity intervals are half-open intervals [a, b).
     ; This field specifies the right (excluded) endpoint b.
  ]

script_pubkey = (0, addr_keyhash)
script_all = (1, [ * native_script ])
script_any = (2, [ * native_script ])
script_n_of_k = (3, n: uint, [ * native_script ])
invalid_before = (4, uint)
invalid_hereafter = (5, uint)

CBOR and CDDL are both new to me, so I'm not sure if I am doing it right.
According to the above specification, my script
{
   "type":"all",
   "scripts":[
      {
         "keyHash":"37c19eca0d623d804bfeb8951bf1eb0f7fe193deeb71793985dbd25e",
         "type":"sig"
      },
      {
         "type":"before",
         "slot":32241869
      }
   ]
}

would evaluate to:
native_script = [1, [[0, $hash28], [5, uint]]]
Is this correct? Do I need to use any cbor tags for serializing?
Here is my attempt so far (I've tried many variations already, but this feels like the most correct one):
import hashlib
from cbor2 import dumps, loads, shareable_encoder, CBORTag

class Sig:
        def __init__(self, hash, slot):
                self.hash=hash
                self.slot=slot

def default_encoder(encoder,value):
        encoder.encode([1, [[0, value.hash.encode()], [5, value.slot]]])

obj=Sig("37c19eca0d623d804bfeb8951bf1eb0f7fe193deeb71793985dbd25e", 32241869)

serialized = dumps(obj, default=default_encoder, value_sharing=False)
print(serialized.hex())
m=hashlib.blake2b(digest_size=28)
m.update(serialized)
print(m.digest().hex())

result = loads(serialized)
print(result)

Needless to say, the code does not calculate me the same policy id as
cardano-cli transaction policyid --script-file test.script does.
I am using the library cbor2, which seems the best maintained one for python. Also, I use blake2b with digest_size set to 28 bytes since the ledger specs say blake2b_224 is used for multisig scripts. I am however also not sure if the other parameters in the hash function need to be set or not. My haskell skills are also not the best, so trying to look up in the original source code didn't get me very far, and I've tried so now for several hours :-)
If anyone could help me, it'd be very appreciated.

It seems I was close, but the str.encode() function was not the correct one to use.
Also a zero byte needs to be prepended to the data to be hashed. Thanks to user bwbush from the cardano forum for helping me out, couldn't have done this without his help!
Here's the final solution:
import hashlib
from cbor2 import dumps, loads, shareable_encoder, CBORTag

class Sig:
        def __init__(self, hash, slot):
                self.hash=hash
                self.slot=slot

def default_encoder(encoder,value):
        encoder.encode([1, [[0, bytes.fromhex(value.hash)], [5, value.slot]]])

obj=Sig("37c19eca0d623d804bfeb8951bf1eb0f7fe193deeb71793985dbd25e", 32241869 + i)

serialized = bytes.fromhex("00") + dumps(obj, default=default_encoder, value_sharing=False)

m=hashlib.blake2b(digest_size=28)
m.update(serialized)

print(m.hexdigest())


text:
How can I convert `Slot` to `TokenName`
I feel like this should be pretty easy, but I'm stumped. How can I use a slot number as a token name?
I'm currently trying to encode the slot integer as a ByteString:
slotNumberTokenName :: TokenName
slotNumberTokenName = TokenName { unTokenName = encode $ getSlot slot }

but I get the error
    • Couldn't match expected type ‘ByteString’
                  with actual type ‘bytestring-0.10.12.0:Data.ByteString.Lazy.Internal.ByteString’
      NB: ‘bytestring-0.10.12.0:Data.ByteString.Lazy.Internal.ByteString’
            is defined in ‘Data.ByteString.Lazy.Internal’
          ‘ByteString’ is defined in ‘Data.ByteString.Internal’
    • In the ‘unTokenName’ field of a record
      In the expression: TokenName {unTokenName = encode $ getSlot slot}
      In an equation for ‘slotNumberTokenName’:
          slotNumberTokenName
            = TokenName {unTokenName = encode $ getSlot slot}
    |
153 |     slotNumberTokenName = TokenName { unTokenName = encode $ getSlot slot }
    |

I am using Data.Aeson.encode, so maybe there is a different function to do that conversion.
Anyhow, any help would be appreciated. Been looking at this for longer than I'd like to admit.

I've just run this in the REPL with success. Not sure if it is the best way, though.
TokenName { unTokenName = Data.ByteString.Char8.pack $ show (toInteger (getSlot 1)) }

This worked. Thanks. I agree there might be a more direct way of doing it, but I'm not picky for now. Can always improve it.

This can be done with Data.Binary. See https://stackoverflow.com/a/2284193/10069673
Another possibility would be to convert the int to a string and then convert the string to a ByteString.

int to string: https://stackoverflow.com/a/2784280/10069673
string to ByteString: https://stackoverflow.com/a/40491001/10069673

Hmm. I got the same error with Data.Binary.encode as I got with Data.Aeson.encode. Seems like it would work :/ I got Chrismo's suggestion to work though. Thanks!


text:
Is it possible to make multiple transactions atomic?
A concrete example would be flash loans, where you could borrow some value from a lending script, do something interesting with it, and return the borrowed amount to the script with a fee, all in one transaction.
Intuitively this feels like it would need to be multiple transactions with separate outputs, but the lending script needs to verify that it is receiving sufficient value in return before it will ever lend anything.
How might this be modeled in Plutus to work?

Transactions on Cardano can be made up of many state changes. The transaction as a whole is atomic and a state change in the transaction will only be performed if all the changes can be performed.
For something like flash loans, as @Marek-Mahut points out, instead of having multiple transactions imperatively executed, each transaction just includes the before and after state. Flash loans are no longer needed in Cardano's model.
You could have a contract that allows you to redeem some ADA as long as you replace it with some interest in the same transaction--which is the equivalent of a flash-loan--but why would you ever do that? Plutus validators don't check that they're getting paid, they check that the state after redemption will be valid. The flash loan no longer serve the purpose of unlocking liquidity inside contracts. That comes for free with the EUTxO model.
tl;dr: All transactions on Cardano are made up of atomic state changes. This allows for what would be atomic sets of transactions on other blockchains.

Flash loans are not possible within the eUTXO model as each transaction is a single state transition, where a typical flash loan consist of two state transitions within a single transaction.
In my opinion, this is one of the most interesting security/safety features of the eUTXO model.

That "two state transitions within a single transaction" is what I mean by "atomic." Yeah.
The safety here sounds comforting, but in describing the EUTxO model, Lars suggested that anything on Ethereum would be theoretically possible on Cardano--maybe I read too much into it. I'm far from understanding the limitations of the EUTxO model, but Haskell has ways of modelling this safely with the STM monad. I'd hope in the future Plutus could be extented to allow it.

Yes, it was mentioned already that Lars called it a flash loan by mistake in one of the presentations, but he meant smart contract composability - similar, but a different concept.


text:
Why can't the PAB webserver find a socket in PAB-Nami demo?
I'm trying to run the PAB-Nami simple demo in the Plutus Apps repo. When I run the PAB, either using cabal or with the nix-shell script, I'm getting the error:
plutus-pab-nami-demo: Network.Socket.connect: <socket: 18>: does not exist (No such file or directory)

I'm not sure what's going wrong, and there is no mention of configuring the socket in the README.
Any ideas?

Start up a Cardano Node.
Also, make sure to set the node socket path to to location of your node.sock file is:
export CARDANO_NODE_SOCKET_PATH=/cardano-node/example/socket/

It would make sense if it was looking for a Cardano Node, but the instructions specifically say, "It doesn't use a local Cardano node, nor the chain index." I might try it anyway.

I just needed to spin up a Cardano Node. Thanks.

I want to award you the answer, but we should probably only include the Cardano Node in the answer. The index and wallet aren't necessary, and it doesn't use the socket path env var.

I revised my answer.  Thanks!

The node socket  env var isn't used AFAICT. It uses the pscSocketPath value in plutus-pab-executables/demo/pab-nami/pab/plutus-pab.yaml. I actually have an PR up on the repo to fix the instructions:
https://github.com/input-output-hk/plutus-apps/pull/362

Although my answer helped you along, it seems like you've discovered the actual solution.  I'm not sure the best way to make the changes on this post.  I think I'll leave as-is for now.

Cool. I'll add an answer once my PR goes through, I guess. Thanks for your help!

The issue was I needed a Cardano Node running and I needed to point at the socket. To point your PAB at the socket, update the pscSocketPath value in plutus-pab-executables/demo/pab-nami/pab/plutus-pab.yaml. I got node running following the instructions here.

I created a PR to update the docs to include this information. That has been merged.


text:
How to submit a script transaction using `cardano-cli`
I'm trying to go through the Alonzo Testnet exercises to get more familiar with the deployment process for Plutus contracts. I've gotten confused by the instructions in sheet 3:

Download the pre-built AlwaysSucceeds.plutus Plutus script, and obtain the script address. cardano-cli address build …

I've downloaded the file and saved it as AlwaysSucceeds.plutus but when I run the command:
cardano-cli address build --payment-script-file AlwaysSucceeds.plutus --testnet-magic 1097911063

I get the error:
Command failed: address build  Error: AlwaysSucceeds.plutus: AlwaysSucceeds.plutus: openBinaryFile: does not exist (No such file or directory)

The ellipses ... are throwing me off, like it's supposed to be obvious what to include. Could someone point me in the right direction of what I'm missing? Maybe I just skipped some docs, but I suspect I'll be similarly confused with subsequent ellipses.

Your command invocation looks correct. But the error suggests that the file AlwaysSucceeds.plutus is not in the directory where you are running the command. Either make sure you run the command from the directory the file is in, or give the full path to the file.

I've given the full path, and that doesn't help. I'm running from the Docker container, so I thought maybe the CLI's path was from in the container. I've tried copying the Plutus file over to the container and using the absolute path, but I'm getting the same error.

AlwaysSucceeds.plutus: openBinaryFile: does not exist (No such file or directory) means the file is missing.


text:
How to validate transaction where number of tokens are generated based on the value locked in a contract?
As far as my understanding token with some amount can be forged by using this constraints.
Constraints.mustForgeValue SomeValue

And ada can be locked into smart contract using mustPayToTheScript if i am not wrong.
So how to validate this transaction where some ada can be deposited to the contract and contract forges the equivalent amount of tokens according to the amount of ada locked in smart contract.

Yes, Constraints.mustForgeValue and Constraints.mustPayToTheScript are used to define/create a transaction that forges tokens or locks tokens in your script respectively (https://youtu.be/6VbhY162GQA?t=1720).
There are multiple script types that validate different aspects of a transaction.
If you want to spend funds locked in a script(address) you need a validator script (Plutus.V1.Ledger.Scripts.Validator) that will validate any transaction consuming the UTXOs locked in that script. To lock funds in a script you need to transfer funds to that script, thus creating a new UTXO that is owned by the script.
If you want to forge tokens in a transaction you need a minting policy script (Plutus.V1.Ledger.Scripts.MonetaryPolicy) which validates that the forged tokens adhere to the specified policy. Minting policy scripts don't have a Datum and Redeemer available, because the transaction is not consuming a UTXO locked in the minting policy. I don't think sending funds to a minting policy makes sense or is even possible.
In your case you might want to have two scripts:

MonetaryPolicy: validates the minting transaction
Validator: A script that manages funds created from minting

The minting policy then has to make sure that the adequate amount of ada is being transferred to the fund-managing-script when validating the minting transaction.
When creating the minting transaction you can use Constraints.mustPayToOtherScript to send funds to the script.


text:
Is the length (in characters) of a token policy id always the same?
Let's say I have the following native token unit d5e6bf0500378d4f0da4e8dde6becec7621cd8cbf5cbb9b87013d4cc537061636542756433323639 that consists of the policy id d5e6bf0500378d4f0da4e8dde6becec7621cd8cbf5cbb9b87013d4cc and asset name 537061636542756433323639.
The asset name is a HEX representation of the name. Therefore it can vary in length.
But the policy id is some sort of a hash of the policy, so I'd assume the length of the string is always the same. Is this correct?
What I want to achieve is to split the asset name and the policy id e.g. like this:
'd5e6bf0500378d4f0da4e8dde6becec7621cd8cbf5cbb9b87013d4cc537061636542756433323639'.substring(56)
> "537061636542756433323639"

The policyId is the hash of the policy script. It is a blake2b-224 hash resulting in 28 bytes and a hex length of 56 chars. So, your code will always work and is the right way to do it.
Find the spec defining the scriptHash here, note that the scriptHash is of type hash28 denoting the hash length.
Also, the assetName can be of any length between 0-32 bytes. Something to keep a note of in your application, this also means that there can be a token without assetName. Find the assetName length spec here

Yes, the policy ID is indeed defined as a ScriptHash in the specifications. Its length is 28 bytes.

Thanks for the answer. Coud you provide a link to the specification you mentioned?

https://github.com/input-output-hk/cardano-ledger-specs/blob/683bef2e40cbd10339452c9f2009867c855baf1a/shelley-ma/shelley-ma-test/cddl-files/shelley-ma.cddl#L251


text:
Is there a minimum amount of ADA I can send in a transaction?
Can I send 1 lovelace (0.000001 ADA) to another address or is there a minimum amount I need to send?
Of course there will also be the transaction fee of (currently) ~0.16 ADA, so such a transaction would not make much sense in most cases. Still I'm curious if it would work.

There is a minimum UTxO transaction size of 1 ADA not including fees. That means the absolute minimum transaction is 1 ADA + fees.

Is there any information why this is the case? This might become a bit of a problem in case the price keeps rising.

It is to reduce dust/lots of small UTxOs and goes back to when ADA was $0.02. I've seen people mention plans to make this value change dynamically, or to have a vote on changing it. You can find more information here https://cardano-ledger.readthedocs.io/en/latest/explanations/min-utxo.html

I am really curious about upcoming changes to all parameters that go back to when ada was rather cheap. Minimum transaction size and especially transaction cost are two very important examples and it will be interesting to see how a change or vote will actually look like.

Is 'gas' a thing in Cardano? I think only Ethereum has 'gas'. Like Bitcoin, Cardano just has tx fees.

There is an additional amount of minimum ADA for a UTxO if that UTxO will contain native assets, based on how many unique policies are present. This may be what the answer refers to as 'gas', or they could mean the tx fees, but it would be good to clarify. 'Gas' is not a term used in the Cardano documentation

@EddySchauman-Haigh that link doesn't work - where can I find the 1 ADA + fees minimum docs?

Seems like a tx-fee cash grab. Good for the network validators, bad for users. I understand if a transaction should have a minimum in total but having a minimum per output in a tx only decreases the utility of the chain.. i.e. no micro-transactions and multi-asset development isn't cost-effective. Cardano shouldn't focus on layer-1 problems and should instead think about actual layer-2 utility, imo

In addition to fees (txFeePerByte + txFeeFixed) as shown in the protocol parameters below, you can see that there is as well a minUTxOValue field that specifies the lowest UTxO output.
Therefore, a transaction cannot contain less than txFeePerByte + txFeeFixed + minUTxOValue. These three parameters can be changed once governance is active.
Protocol parameters
    "txFeePerByte": 44,
    "minUTxOValue": 1000000,
    "stakePoolDeposit": 500000000,
    "decentralization": 0,
    "poolRetireMaxEpoch": 18,
    "extraPraosEntropy": null,
    "stakePoolTargetNum": 500,
    "maxBlockBodySize": 65536,
    "maxTxSize": 16384,
    "treasuryCut": 0.2,
    "minPoolCost": 340000000,
    "maxBlockHeaderSize": 1100,
    "protocolVersion": {
        "minor": 0,
        "major": 4
    },
    "txFeeFixed": 155381,
    "stakeAddressDeposit": 2000000,
    "monetaryExpansion": 3.0e-3,
    "poolPledgeInfluence": 0.3


text:
Can I use a custom word list for my wallet recovery phrase?
Is it possible to use a custom list of words to generate my Cardano wallet recovery phrase?
The reason I think this would be useful is, that one could use words from other languages.
As far as I know the recovery phrase has a checksum (the last word), so it's not possible to just replace some words with random other words in an existing recovery phrase.

According to CIP3: Wallet key generation, Cardano is using seed words from BIP39, therefore you can use words included in BIP39 only.


text:
Will I receive rewards for all epochs when I switch my stake pool?
I am currently delegating my ADA to stake pool A. I want to switch to stake pool B. What exactly happens with my rewards when I do this?
Will there be an interruption in the reward payout or will I still get rewards for every epoch?

You will continue to get rewards every epoch. Cardano works on epoch "snapshots" that occur every 5 days. It takes 3 epochs to get paid the rewards from a snapshot. This means that if you change stake pools, it will take 3 epochs (from the first snapshot that the change is effective) to receive rewards from the other pool. However, the other two epochs you will still get rewards because the snapshots with your ADA in the old pool will be paying out.
The only time you stop getting rewards is when you stop delegating your ADA and that is included in a snapshot. After the snapshot with your wallet undelegated, you will get the remaining rewards for the next two epochs and rewards will stop on the third epoch.


text:
Is there a maximum amount of ADA I can send in one transaction?
This question is related to one of my previous questions: Is there a minimum amount of ADA I can send in a transaction?
I wonder, if there is a minimum amount of ADA I can send in one transaction, is there a maximum amount too? Or would it theoretically be possible to send all 45B ADA in one transaction (if someone would own all ADA there is)?

The limit amount of output ADA is specified as Word64 which is an 64-bit unsigned integer, therefore the maximum output is 18 446 744 073 709 551 615 lovelaces in the current implementation.
So, sending all 45 billion of ADA is theoretically possible.

Where did you see Word64? I don't think there is a direct artificial limit. See the definition of TxOut and Value. Value uses Integer, which has no limit. https://playground.plutus.iohkdev.io/tutorial/haddock/plutus-ledger-api/html/Plutus-V1-Ledger-Tx.html#t:TxOut https://playground.plutus.iohkdev.io/tutorial/haddock/plutus-ledger-api/html/Plutus-V1-Ledger-Value.html#t:Value


text:
Is there an API or website where I can see all addresses that hold a specific native token/asset?
I want to get all addresses that hold a specific native asset/token. I'm not talking about NFTs but tokens that have a quantity of more than one. Examples would be the spacecoins or the hosks.
I want to do this using an API or a website (without running my own full node). Options would be blockfrost.io or other websites like pool.pm, cardanoscan.io, explorer.cardano.org or similar services.
Are there tools that can do this already out there somewhere?

You are probably looking for the Blockfrost.io's /assets/{asset}/addresses endpoint that lists all addresses containing a specific asset.

This is exactly what I was looking for. If there are other services that provide the same functionality, I'd still be interested to know about them.

There is a website called cardanoassets.com where one can see the mint history and transactions that include a specific asset. This doesn't answer the question but is related so I'm leaving it here too.
Example: https://cardanoassets.com/spacecoins-250


text:
When I switch to another stake pool, do I need to withdraw my rewards first?
I'm using Yoroi and want to switch to another stake pool. I never withdrew my rewards from the current pool. What happens to my rewards when I switch pools? Do I need to withdraw them before I switch to another pool?

No, you do not need to withdraw rewards before moving stake pools.
Cardano wallets use two accounts: one for spending ADA and one for collecting rewards. While this may sound strange, it actually has many benefits (which I won't get into here). In order for earned rewards to be spent, they must be moved from the rewards account to the spending account (become an UTxO) which requires a transaction fee. Until the funds are needed it is fine for them to stay in the rewards account since they are still in your wallet (the pool doesn't have your funds) and they count towards your wallet balance and earn compound rewards. The main take away here is that the rewards are in your wallet and go with you wherever you stake your wallet.

Great explanation, thanks!

Your rewards are not on the pool, they are in an address owned by you. You don't need to withdraw them before redelegating.

I found a similar question on reddit & an answer references the shelley specification which could be interesting

Please be careful with "link only" answers. They are often subject to link decay, and can become dead links, in which case sch answers become useless. Even if you are sure that the link won't die, it is consider good practice on StackExchange sites to avoid link only answers, by providing an overview, a sum-up, or an slight overview of what the links are describing related to the OP question.


text:
Can smart contracts be used to mint native assets?
Cardano doesn't need to use smart contracts to mint native assets. But is it possible to mint native assets using smart contracts? And if so, is there an example how this can be done?

This is the subject of week 5 of the plutus pioneer program. You can find examples in the Github repo.
In the Signed.hs module, there's an example for how to mint tokens, and the NFT.hs for how to mint Non Fungible Tokens.
There's also a full lecture on that subject by Lars.

Agree to start with Lecture 5.  If you can't wait for the Plutus Application Backend to get deployed, there is also and exercise in Alonzo Purple for minting a NFT using the Command Line Interface CLI.  You can find it at the Alonzo github repository.

What's the link?


text:
How to get data from the Cardano blockchain using SQL queries?
I found the following screenshot where someone uses SQL to query the Cardano blockchain.
What is this tool called?
https://ipfs.blockfrost.dev/ipfs/QmTNaaR38P19rDfA1SuEN1h4wmcDNMoLg5pZdPxVyX42YG

Side note: The image is linked to an NFT: https://pool.pm/af52014edb909c70f34ef19fe96ba59142007a4c5e8a4cc9ff0b1c37.AdamWasHere

The tool in question is cardano-db-sync.


text:
How can I create a serialized transaction that can be submitted to the blockchain without a local full node?
My goal is to send a transaction (e.g. send 1 ADA from addr1A to addr1B) using the following endpoint of the blockfrost.io API:

"Submit an already serialized transaction to the network."
https://docs.blockfrost.io/#tag/Cardano-Transactions/paths/~1tx~1submit/post

It requires a serialized transaction. How can I create a serialized transaction without a local full node? (With a full node this could be done using the cardano-cli).
The emurgo/message-signing library seems to provide this functionality but I'm not sure how to use it. The example they provide just signs some random string.
Are there any other libraries that can be used for this?
The library would need to be able to

Create a transaction (with metadata)
Calculate the fees
Sign/serialize the transaction

There is the cardanosharp-wallet library that provides this functionality. They have a section in their README.md that explains signing transactions.

To add to @eddex's answer, another option would be to use the Emurgo's cardano-serialization-lib. There are not many examples available in their documentation, unfortunately.
Link: https://github.com/Emurgo/cardano-serialization-lib
For a guideline on how to use the library specifically for creating transactions, I found a good example in the blockfrost-js repository. The usage of cardano-serialization-lib can be found in one of the helper files.
Link: https://github.com/blockfrost/blockfrost-js/blob/fb9a55fee07927f8d7c8b0a5aa9efd2d3daf6c77/examples/simple-transaction/src/index.ts


text:
How is it possible to know how many blocks a pool will mint in the next epoch?
I just saw this tweet: https://twitter.com/SmaugPool/status/1428010540711006218

Next epoch (285) should be great at 109% luck with 19 leader slots

At the time the tweet was made, epoch 284 was still in progress.
How is it possible that the stake pool owner already knows how many slots/blocks he gets assigned in the next epoch? Can this information be retrieved from the blockchain?
Also wouldn't this mean that one could always check which pool has the most blocks assigned and then switch to that pool for the next epoch?

Yes, the slots allotted to a pool for minting in the next epoch can be calculated (36 Hours before the epoch). Cncli is a community tool (available at github repository) made by, Andrew Westberg (@AndrewWestberg-BCSH), Michael Fazio, Andrea Callea, Thomas Diesler. The details provided are quite exhaustive. Sample output of the leader log command is below
{
 "status": "ok",
 "epoch": 227,
 "epochNonce":   XXX",
 poolId":    --------",
 "sigma": 0.0028306163817569175,
 "d": 0.5,
 "assignedSlots": [
 ...
 {
     "slot": 13083245,
     "slotInEpoch": 382445,
     "at": "2020-11-05T23:58:56-08:00"
 },
 {
      "slot": 13106185,
      "slotInEpoch": 405385,
      "at": "2020-11-06T06:21:16-08:00"
 }
      ...
 ]
}

The selection of slot leader mechanism is explained nicely in NerdOut

Also wouldn't this mean that one could always check which pool has the most blocks assigned and then switch to that pool for the next epoch?

The number of blocks calculated for the next epoch is, among other things, based on a snapshot of the delegations to each pool taken at the beginning of the current epoch.
This means that if you were not staked with the pool at the beginning of the current epoch, your stake will not be earning rewards for the coming epoch (the epoch during which the calculated number of blocks will be minted).
If you delegate to a pool once they know how many blocks are going to be minted in epoch X (i.e. within 36 hours prior to epoch X starting), your stake will be part of the snapshot that helps determine how many blocks will be minted in epoch X+1, and it is during epoch X+1 that your stake will start earning rewards.

Since I can't mark 2 questions as accepted answer, this is not the accepted answer. Still this answers the second part of my question, so this answer in combination with raghus answer is what I was looking for. Thanks Chrismo!

Result from cncli-leaderlog shows me, that we had 1 assigned block 3 days before. But no block minted, relay and block producer are running well.
Can you help me, what should I check? and eventually correct for the next assigned slot? Or the result from cncli-leaderlog.sh are not correct?
Thanks, MB
{
  "no": 1,
  "slot": 39334091,
  "slotInEpoch": 281291,
  "at": "2021-09-05T20:53:02-07:00"
}

Hi! welcome to the Cardano stack. If you have a particular doubt please create a new post with your question.


text:
How can I mint a token without a name for NFT royalties?
The proposal for Cardano NFT royalties CIP-0027 suggests that a nameless token should be used to store the royalties information.
Usually a mint transaction looks something like this:
cardano-cli transaction build-raw \
--mary-era \
--fee 195509 \
--tx-in b1ddb0347fed2aecc7f00caabaaf2634f8e2d17541f6237bbed78e2092e1c414#0 \
--tx-out $(cat payment.addr)+4804491+"1 677d3bbe3e01eeab498cd8786f7d261d92bd6ecea12109a332e86374.MountainGorilla"\
--mint="1 677d3bbe3e01eeab498cd8786f7d261d92bd6ecea12109a332e86374.MountainGorilla"\
--out-file matx.raw

Source: https://silas-stulz.medium.com/you-want-to-create-your-own-nft-heres-how-you-do-it-on-the-cardano-blockchain-9a0bbf8caa39

As we can see in the mint part, the new token is a combination of the policy id 677d... and the token name MountainGorilla.
Is there any example how a nameless token can be minted?

Native assets as far as I’m aware can have the empty string for the token name. In theory you should be able to just leave the token name empty so the token ID will just be the policy ID. I’m not sure if the . is still required though, but as you can see from the docs, it’s just a ByteString object, which can be empty.
https://alpha.marlowe.iohkdev.io/doc/haddock/plutus-ledger-api/html/Plutus-V1-Ledger-Value.html#g:2


text:
What alternatives to Eternl mobile wallet with dApp connectors do exist for Cardano?
I'm currently using Eternl on my mobile phone to connect to and use dApps. However, they only allow a select few dApps to be used within the wallet and on top of that charge a fee for using dApps like Minswap.
Are there any other Cardano mobile-wallets that support dApps, preferably without restrictions, so I can connect to any website I want? And if not, are there any other mobile-wallets that support dApp connection?

The mobile version of Flint Wallet is said to support arbitrary CIP30 dapps. For example, I've successfully run Marlowe transactions on Mobile using Flint.


text:
Will transactions created with a local cardano-node be faster if I add more relays to my node topology file?
I'm using a local cardano-node to do some transactions from time to time. Recently I noticed some error messages in the logs of the node. It seemed like the connection to the relays-new.cardano-mainnet.iohk.io relay had some problems.
While searching for ways to solve this, I realized that I can set up multiple relay nodes in my mainnet-topology.json file. Is this something one should do? Will it make the node more resilient and will it improve transaction speed?
Bonus question: Where can I find a list of relay nodes (including port and valency)?

If your connection(s) to the IOHK-hosted relays was in fact the problem, then yes, connecting to other SPO relay nodes should help alleviate the issue.
I couldn't find one single list containing pools' public facing relays, but if you search for a specific pools' metadata using any explorer like Cardanoscan, you can find their metadata URLs which contain their relays' info. I'd recommend having a good number of single pool operators as buddy relays. You can refer to the single pool alliance topology registry for a list of such pools
Alternatively, Guild Operators' topologyUpdater script allows SPOs to automatically push their relays' IPs and ports to one location where it also pulls from to update everybody. This greatly simplifies the process of finding peers, though it is heavily centralized and only intended as a stopgap until full p2p is released.

I already had a look at the topologyUpdater script before asking this question but it seems like the API has some sort of IP whitelisting when fetching the list of relays, therefore I wasn't able to use it. The single pool alliance topology registry seems like what I need, thanks!


text:
When there are multiple liquidity pools for the same pair on SundaeSwap, which one is used for my trade?
Let's say we have two liquidity pools for token X and ADA (X/ADA)

pool 1 has 10 X and 10 ADA locked -> price is 1
pool 2 has 20 X and 10 ADA locked -> price is 2

What happens if I buy X/ADA now? In this situation, SundaeSwap shows the price of one of the pools, but it's not always the one with the better price (depending on if you buy or sell).
Could I order a buy and a sell and it would automatically buy for 1 ADA and sell for 2 ADA?
Example:
There are 2 pools for MIN/ADA:

I want to sell MIN for 0.3 ADA on the first pool. That seems to work:

But when I buy, I obviously would want the price of the second pool and buy 1 MIN for 0.27 ADA. But also here it shows the price of the first pool, which is more expensive.

Is this only a display issue and I would actually be able to buy 1 MIN for 0.27 ADA?

According to the CIO of SundaeSwap on Discord it's "picking the pool that gives you the best rate for your trade size". So in theory I believe, yes, it should only be a UI issue.
However, I have not confirmed this myself and the answer is from early December, so it might also be outdated.
https://discord.com/channels/830939534174453800/915669612350292038/917624514043600996