text:
About building a transaction using the cli
I've been following this guide https://developers.cardano.org/docs/native-tokens/minting to mint some native tokens but the process of sending native tokens to an address that has multiple UTXOs when I also have multiple UTXOs at my address is unclear to me.

I want to send my native tokens to some foreign address but my wallet has 2 UTXOs instead of just 1 as seen in the guide https://developers.cardano.org/docs/native-tokens/minting#:~:text=Here%E2%80%99s%20what%20the%20raw%20transaction%20looks%20like%3A. For multiple UTXOs, are you supposed to add all of your txhash and txix values for each UTXO to --tx in? What is the syntax/formatting?

I need to set the 'funds' variable here https://developers.cardano.org/docs/native-tokens/minting#:~:text=Copy-,Again,-%2D%20here%20is%20an but there is multiple UTXOs in my wallet. Is 'funds' the total lovelace in all UTXOs in my wallet?

I need to set the 'receiver_output' variable here https://developers.cardano.org/docs/native-tokens/minting/#:~:text=Copy-,Again,-%2D%20here%20is%20an and there are multiple UTXOs at the receiver's address. Is 'receiver_output' the total amount of lovelace at all UTXOs in the receiver's wallet?

Thanks, Myles

A UTXO is an unspent transaction output. That UTXO is tied to an address, and that address is made up of hashes of keys that are tied to payment keys for that address. You can spend a single UTXO, or multiple. It's up to the design of your application. To simplify things, we'll ignore native tokens first.
Lets start with an assumption my wallet has received 2 transactions from others. One is for 1 ada and another one is for 1000 ada. If I try to make a transaction using just the 1 ada one, all I can do is pay the full ada as a fee with no output. If I make one just using the 1000 ada one, i can pay my 0.7 fee in ada and send the remaining of the 1000 ada to another address, the same address, or multiple addresses.
Now, once that transaction is added to a block, the old txins are "spent" and a new utxos are created based on the hash of the transaction you just made and the index.
When we add transactions sending native tokens (not minting yet), things get a little more complicated. For one, every UTXO containing a native asset has a minutxo greater than 1. So every UTXO holding a native asset must have some Ada in the same UTXO. This means you can't just send SANTA tokens without also sending some ada with them. The same rules apply, except you can't spend a native asset as a fee. So all outputs of native assets must add up to all inputs in the TXIN's defined in the transaction.
Earlier I mentioned that you can send to one or multiple addresses as outputs in a transaction. Well, you can also send multiple times to the same address! So I can take that 1000 ada I had in a UTXO and say 100 SANTA tokens in the same UTXO and then send them to the same address in 1.5 ada + 1 SANTA UTXOs to split it up. In this case I'd have 100 outputs to the same address, with a 101st output sending the change of 849 ada and say a 1 ada fee. Each of these new utxos can be spent individually, so now I could individually send out SANTA tokens to people spending 1 of those UTXOs every time.
So now, we finally arrive minting that you were asking about When you mint assets in a transcation, you specify the policy hash and asset name making new assets out of thin air based on a policy you set in your policy script. Those newly minted assets need to be sent totaling the amount minted + any assets consumed from the txins for the minting transaction. So if we take the same example above and say we have 500 SANTA and 1000 ada in a single UTXO. We now mint 10000 SANTA, and we want to output this to a single address in a single UTXO. Now we sent 999 ada + 10500 SANTA to our address. The same goes with burning, but in this case, we mint a negative value and subtract that from the outputs. So if I have that above UTXO and I want to burn 500 SANTA tokens, the output would be 998 ada + 10000 SANTA. I'm using 1 ada fees in these examples for simplicity.


text:
cardano-cli transaction build-raw error
I've minted 1,000,000,000,000,000 SLIME coin following this guide https://developers.cardano.org/docs/native-tokens/minting/#prerequisites but I'm getting an error at the "Sending tokens to a wallet" section. I've attached a screenshot of all the steps I take along with the error I receive:
Command failed: transaction submit  Error: Error while submitting tx: ShelleyTxValidationError ShelleyBasedEraAlonzo (ApplyTxError [UtxowFailure (WrappedShelleyEraFailure (UtxoFailure (ValueNotConservedUTxO (Value 4818307 (fromList [(PolicyID {policyID = ScriptHash "5b314f4ac2716a22741a69c2c213ba515d0d90e5e7c8400474b948ee"},fromList [("SLIME",1000000000000000)])])) (Value 7818307 (fromList [(PolicyID {policyID = ScriptHash "5b314f4ac2716a22741a69c2c213ba515d0d90e5e7c8400474b948ee"},fromList [("SLIME",1000000000000000)])])))))])
The variable "address" is set to my address which I'm trying to send SLIME from, and the variable "receiver" is set to the address I'm trying to send SLIME to.
I greatly appreciate help in solving this headache of a blocker for me, thanks, Myles.

You need to subtract the fee from $receiver_output.

if you can be more specific, at what step? I tried receiver_output=$(expr $receiver_output - $fee + 2000000) and receiver_output=$(expr $receiver_output - $fee) after output=$(expr $funds - $fee - 2000000) and still get the same error: Command failed: transaction submit  Error: Error while submitting tx: ShelleyTxValidationError ShelleyBasedEraAlonzo (ApplyTxError [UtxowFailure (WrappedShelleyEraFailure (UtxoFailure (ValueNotConservedUTxO (Value 4818307 (fromList [(PolicyID {policyID = ScriptHash "5b314f4ac2716a22741a69c2c213ba515d0d90e5e7c8400474b948ee"},fromList [("SLIME",100000000000000 ...

In your final build-raw you need something like (($receiver-output - $fee))

Why are you adding $receiver-output to the --tx-out line where you are minting the tokens? You are not consuming that UTxO, just ignore that UTxO and the 5000000 lovelaces at that address.

receiver_output is balance of utxo spent in txin.

source: Stack Exchange

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

sort: votes


text:
Automatically send funds out using a smart contract
I'm looking for an example or tutorial for how to write a smart contract which locks all ADA sent to it until a threshold of at least 1,000 ADA is reached. Once 1,000 ADA is reached, as much ADA as possible is sent to a pre-defined address and the counter resets. Is this possible with the current Plutus platform?
Thanks, Myles

I am not sure what you mean by automatically send funds out of smart contracts". If you mean without someone actually executing the contract in a transaction, this is not possible. Just people sending ADA to the smart contract address will not trigger the smart contract execution, someone has to do a transaction including the smart contract execution to do what you want.

Thanks for your reply, let me be more specific. I want a script which locks all ADA sent to it until a threshold is reached, like 1,000 ADA. Once the threshold is reached, there's a part of the script which sends out 1,000 ADA to a pre-defined address, and the cycle continues again until at least 1,000 ADA is locked in the contract again. It would be ideal for anyone to be able to send ADA to this script address. Also, what is the difference between triggering and not triggering a smart contract execution?

Just sending ADA to a smart contracts address will not execute the smart contract. Someone must execute the smart contract in a transaction.

Ok I understand that. I'm looking for an actual haskell code example/tutorial to carry this all out.

As @George pointed out, there is no such thing as "automatic" for smart contracts. Everything must be triggered manually by an off-chain actor.
That being said, you could definitely create a script that holds funds in escrow until a threshold is reached, at which point those funds become distributable/claimable.
This is similar to how the auction code works:
Each time someone bids, the auction datum is updated. In the case of the auction, once a deadline has been past, the bids are collectable by the seller and the bidder can claim their winnings.
You could follow a similar pattern where a datum tracks the ADA locked at the script address, and the datum is replaced with an updated datum each time more ADA is locked. At the point the locked ADA passes 1000, the funds become claimable.
There are many ways you could organize the distributions, but the simplest/closest to automatic might be as follows: any transaction that pushes the total equal to or over 1000ADA must distribute to the designated recipients, and all excess tokens will be rolled over to a new datum. That makes the last contribution more expensive, so it might discourage contributions, so you could consider paying the distribution fees with the pot or something else.

thanks so much!! this really helps me get on the right path

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


text:
Question about Plutus smart contract which always succeeds
Can anyone explain in detail why this script, https://github.com/james-iohk/Alonzo-testnet/blob/update-cabal-1.29.0/resources/plutus-sources/plutus-alwayssucceeds/src/Cardano/PlutusExample/AlwaysSucceeds.hs, results in the following output?
Writing output to:
alwayssucceeds.plutus
"Log output"
[]
"Ex Budget"
ExBudget {exBudgetCPU = ExCPU 297830, exBudgetMemory = ExMemory 1100}

Thanks, Myles

The output seems to be generated by this Haskell script (plutus-alwayssucceeds.hs) sitting in the parent folder of the script you linked. "plutus-alwayssucceeds.hs" is defined as the entry point of the executable defined in cabal file here.
When you run command like cabal build, cabal will build "plutus-alwayssucceeds.hs" as an executable, which, when executed, will print out the log pasted in the question above. Notice that the actual plutus script (alwayssucceeds.plutus) is generated by function "writePlutusScript" here.


text:
Question about policy ID for native assets
If the policy ID for a some native token looks like this:
{

"keyHash": "wfwrfasdfasdfsadk4tjwljaldk1234567789123455678",

"type": "sig"

}

Can the token be minted and burned at any time by the owners of the keys? What are the limitations if any for a native token with a policy ID like this?
Thanks, Myles

Yes - this is an example of an unlocked policy. Tokens can be minted and burned under this policy forever with no limits.
Here would be an example of a time-locked policy:
{
  "type": "all",
  "scripts":
  [
    {
      "type": "before",
      "slot": 28515365
    },
    {
      "type": "sig",
      "keyHash": "3a25088ecd68bde986becda8ebc51077222f981cab4214025ccc7bfa"
    }
  ]
}

thanks so much!


text:
Is it possible to decode smart contract code from a script hash?
Given a script address, is it possible to decode the Haskell/Plutus code of said script? How can you verify a script does what someone says it will do?

Somewhat but not completely I think. From one of the replies, I understand now the Plutus Core bytecode is on-chain, so this means it is possible to get the code of the smart contract if you can convert the bytecode back to Plutus / Haskell or some other language? So it's possible but just kind of hard / tedious?

Better as a comment on the original question/answer than to open a duplicate.  But this question has a better title.

On if it's possible to decode the Plutus code of a given contract, there's a possible duplicate of this question here: Can blockchain viewers read the source code of a smart contract if they know its address?.
In case that you want to verify that a compiled code sitting in the blockchain is what their creators claim to be (given that it comes from an open-source project), and you know the Plutus version they used and any other parameters needed, you could recompile the code and compare the resulting script hash with the hash on the blockchain, thus verifying the code is the same.
I'm afraid straight reading of source code from the blockchain right now is not possible. We can expect more tools and possibilities on reading contract's source code in the future since we are still in the "early days" of Cardano's smart contracts.

thanks for sharing that post, it definitely has helped my understanding. From my understanding of it, I guess it is possible to see the code of a smart contract but you have to convert it from Plutus Core bytecode to some other readable language?

Updated the answer with a small idea on comparing open code with the one on the chain.


text:
How will Cardano deal with the rise of quantum computing?
From my understanding, today's cryptography will be vulnerable to attacks from quantum computers soon. Are there any plans that IOG or Charles has mentioned about how Cardano will deal with the rise of quantum computing in the next few years / decade? What measures will be taken to keep the network secure and business as usual?
Thanks,
Myles

While this may be a concern in the future, there is currently no quantum computing system powerful enough to pose a threat to modern cryptographic standards. That being said, there are quantum-resistant signature schemes that can be employed if needed, such as XMSS.
There are drawbacks however; the signatures for such schemes tend to be much larger than the elliptic curve schemes currently used, which would lead to faster chain growth. As such, quantum resistant schemes can and will be deployed as soon as quantum computers pose a significant risk. Until then, they are simply unnecessary.

Thanks for the reply. Waiting until it becomes a problem / poses a significant risk does not seem like IOG's style at all. How do we definitively know what Google's or IBM's quantum computer is able to do? I'm not sure we can answer that. I realize I'm thinking at least a few years into the future but that's why now's the time to start thinking about it.

I don' think IOG is really waiting for it to become a problem, they simply realize that quantum resistance is not a priority right now because there is so much else to do. Considering the conservative approach IOG tends to take when implementing new features, it makes sense that they'd hold off on something that just isn't necessary right now. Charles even mentioned in one of his AMA's (sorry I can't remember which one) that implementing quantum resistance can and will be done, just not in the next year or two.


text:
Benefits and use cases of Sidechains
From my understanding, a sidechain is just another blockchain with smart contract language capabilities which can speak to the parent chain. And both chains speak to each other using smart contracts for the purpose of knowing what and when to mint and burn assets.
Firstly, what are some current technologies or processes that sidechains are a more efficient alternative to? What are some possible benefits of using a sidechain?
Secondly, what are the steps required to build a sidechain which would work with Cardano? For example if I wanted to build a replica of the EVM sidechain being developed by IOG, what  are all the different components I need to build?
Thanks,
Myles

To first part: sidechains can be useful for scalability (de-congesting a primary chain, with cheaper and fast transactions).  Other uses include experimental use or specialisation for particular applications or use cases


text:
Nami wallet API implementation example for web app
Are there any examples out there for how to implement Nami wallet end to end for a website (with or without React)? For example, how can I create a button for my site which upon being clicked asks the user if they want to connect their wallet to the site OR if the user has already granted access, then their wallet is opened where they can create a TX, see their TX history, etc.

The best resource I am aware of for you to get started integrating with Nami wallet is this repository:
https://github.com/dynamicstrategies/cardano-wallet-connector
The sample (available via a Live demo) shows how integrations work with various wallets.
Several other resources I have found useful in developing my understanding of Wallet Integration and the Cardano Serialization Library (A utility to make working with Cardano data structures easier) are:

https://github.com/pyropy/full-stack-cardano - Simple next js integration

https://github.com/dendorferpatrick/nami-wallet-examples/tree/master - A Comprehensive and well-documented breakdown of Nami wallet integration with an applied real-world use case

https://github.com/tango-crypto/cardano-wallet-js - Superbly documented overview of using the Cardano Serialization Library

https://github.com/Felippo001/nami-wallet-api - Lightweight integration with Nami and Blockfrost

https://www.cardano-caniuse.io/ - Site that shows which wallets support various API commands

https://srdjanstankovic.com/2021/12/24/how-to-sign-and-submit-cardano-cli-transaction-using-nami-wallet.html - Nice blog post on signing transactions

Hope that helps!


text:
Disable GitHub Actions when forking cardano-node
Would you please give me a hint of where to look or modify? I don't even know if they have a charge associated.
If  you were to fork https://github.com/input-output-hk/cardano-node.git, the GitHub Actions would continue running autonomously.

github actions are triggered by the contents of the /.github directory - specifically the workflows subdir.
https://github.com/input-output-hk/cardano-node/tree/master/.github
See https://docs.github.com/en/actions/quickstart
You can delete or rename the directory to stop github actions.
Or disable them on your fork
https://docs.github.com/en/actions/managing-workflow-runs/disabling-and-enabling-a-workflow


text:
Does Daedalus perform tasks beyond those of a wallet?
I didn't read the user agreement and just installed. Why does it use a full core 100% of the time?
Is it doing work for the health of the network, or any other type of work besides just being my wallet?


text:
Airgapping Concerns for Block Producer Secrets
I am trying to understand the extreme caution about creating secrets for the BP node.
Is the concern about not knowing what one might lease in the cloud, or how security is in such a company, or their retainment proceeders, or multiplexing protocols, or is it about the software we're building to run the node?
Some cases, air gapping seems silly and I can imagine people outputting these secrets into their DropBox or OneDrive, etc.
If I run my own cluster, I really do not have to airgap right? I can simply mount a tempfs over USB, or any other number of solutions.
Just trying to clear this up.
Where does the cause for concern mainly originate?

The pool keys control the pool and can never be changed. If your pool keys are exposed, then you have lost control of your pool (this doesn't necessarily mean your pledge, but control of the fees, where the rewards go, the deposit, etc.).
If you create these keys on an online machine there is increased risk of the keys being exposed, for example from things like:

Running malicious software (think about how much code written by strangers you run on your machine - software, games, etc.)
Being included in backups left around on drives/USB sticks or uploaded to the cloud

You may consider these risks small, but they're risks all the same. You only have to expose your keys once for it to be game over for your pool.
Given these keys don't need to be on a connected machine, it therefore seems sensible to create them on a machine that is never connected to the internet. It massively reduces the risk.

Thanks, okay, so only I have physical access to these VHDs, fresh installs from truster hashed media. Therefore I am comfortable with creating the secrets on a USB mount within the BP and destroying the USB after preserving what I need. Thank you!

That doesn't sound unreasonable to me. Just be sure that you have good secure backups. You don't want to lose your pool because of something simple like a drive failure. I also keep an off-site backup of important keys.. if my house burned down I wouldn't want to lose access to funds at a time it might be most useful! GL with the pool!

I highly recommend storing your pool keys on a hardware wallet.

Good point - though this is only possible for new pools (where the hardware wallet generates the key). Unfortunately not possible to migrate an existing pool to a hardware wallet because as noted above, the keys cannot be replaced.

@MarekMahut-StakeNuts I happen to have two, Valentine’s Day sale. But I’m a bigger fan of VMs doing a single thing before they are secured and stored away. I am very disappointed with it’s my Ledger purchase. It’s a constant Unicode link spam bombardment combined with Twilio phishing. The efforts wasted on me make me wonder if something like ERM data leaked. Fun fact, Dadalus VMs all take nearly zero bytes after the first. Go ReFS and deduplication. It’s no fun losing a HW wallet, since they cost money, but my VMs are my truly secure wallets. Thank you for the good advice though. I agree


text:
Is the Payment Adresss and associated keys considered a wallet?
When staking to the payment address is one effectively sending ADA to another wallet?
I think this is an interesting question because one asks if it could then be added to a wallet application like Daedalus, or something else..

A wallet consists of two sets of keys {private and public} and the addresses derived from them. There are different types of addresses like Payment address and staking address. Payment addresses can be used for receiving payment through transactions that require fees. The reward address of a wallet can not be used for receiving payment.
Overall we can say the public and private keys are the core components of a wallet.
Staking does not involve sending any ADA out of wallet.

Sure sounds like a wallet.

If you want to understand how payment address, public pvt keys etc you can read this chapter
https://docs.armada-alliance.com/ai-blockchain-edu/wallets


text:
Using rsync to copy database
I am spinning up another pool. Can I just rsync the database folder, after everything else has been setup?
They're on the same 10GBe switch, so I will try anyway... but just wondering.

Yes you can copy the files to speed up the database synchronization on a new freshly installed and configured node. Try to copy all the db folder and start the node.

Success! BP and relay done before I noticed (and I was just using the relay as the source).


text:
Can I Share Daedalus Public Key?
I am trying to add my accounts to a coin baalance tracker, but am having a hard time with Daedalus.
The only option that seems to make any sense is sharing the public key with the tracker apps. Is this safe?

for the sake of potential loss of your balance i wold say dont untill your absolutely sure but you would assume yes seeing as its called a public key meaning its publicly visible

Cryptography is the science of secret writing with the intention of keeping the data secret. Cryptography is classified into symmetric cryptography, asymmetric cryptography and hashing.
Private Key:
In Private key, the same key (secret key) is used for encryption and decryption. In this key is symmetric because the only key is copy or share by another party to decrypt the cipher text. It is faster than the public key cryptography.
Public Key:
In Public key, two keys are used one key is used for encryption and another key is used for decryption. One key (public key) is used for encrypt the plain text to convert it into cipher text and another key (private key) is used by receiver to decrypt the cipher text to read the message.


text:
Get live price for token across different Cardano DEXes
I am working on a small pet project and I need to get the live price data for a token across multiple Cardano DEXes.
For instance, I need the live price of WMT on MinSwap, MuesliSwap, GeniusYield and WingRiders. I am aware DexHunter does something similar as an aggregator, but I cannot figgure out how they do it.
So far my thinking is that:

I can get this data straight from the DEXes's smart contracts
I need an oracle for this.

However, I am not sure if these approaches are possible.


text:
How do I design a dApp for 1000 NFTs minted per second
I am brainstorming on the architecture of a Cardano dApp that will be able to issue tickets as NFTs and can scale to around 1000 NFT tickets per second. From what I understand so far on UTXO, a minting transaction would need to consume a UTXO to produce the NFT and, since each block takes around 20 seconds, I would theoretically process 1 ticket every 20 seconds.
My understanding is that this issue is the much talked about concurrency issue sometime back. I have researched 'batching agents' but have not yet fully grasped the idea and if that's the solution.
Is batching the correct solution to this problem, and if so, what would the process flow look like to scale ticket issuance?

You can have unlimited UTxOs in an address, so you don't need to wait for the next block to create a new transaction.
You can also create many chained transactions from a single UTxO in one block. You keep track of the outputs and use them in the next transactions, and submit the transactions in the order of creation to the same node.
You won't be able to mint 1000 NFTs per second because there is not enough space in the blocks for the transactions. You can probably mint between 5 to 10 per second with the current network parameters, depending on the congestion.

We need to understand first what is a NFT: It is a token that only exist ONCE. Can't be two tokens the same.
What we mean with two tokens the same? To understand that we need to know how a token is defined in Cardano.
It is defined by a Currency Symbol and a token name. Both together makes a token. To have two tokens the same we need to have same Currency Symbol AND same TokenName.
Following that we can see that we can have NFTs using the same Currency Symbol but different TokenNames.
What is a Currency Symbol? It is just the hash of the Minting Policy used to mint them.
How we assure that a Currency Symbol is unique? Using an UTXO to create a parameterized Minting Policy. The UTXO, that for his nature is unique, becomes hard coded in the Minting Policy, so when you get the hash of that parametrized Minting Policy, the Currency Symbol, is going to be related with that UTXO and is going to be unique. Same Minting Policy with different UTXO parameter will end up with a different hash and a different Currency Symbol.
UTxOs are unique, they exists only once in the blockchain and when they are consumed they disappear. Never will exist another UTxO equal to one that existed before.
So, you need a particular UTXO to have a particular Minting Policy.
You can create a Minting Policy that is going to run only once, if you check if that particular UTXO is used in the transaction.
Then you need to add extra validation to be sure that in this only time that is running it will mint only ONE token. If you let mint two or more tokens, they will not be NFTs anymore (if they share same TokenName)
But if you check in the Minting Policy that they are using different TokenNames, you also can mint several NFTs (1 unit of each of them) in the same transaction using the same UTXO.
You could potentially mint all 10.000 in the same transaction, with 10.000 different TokenNames, but you will end up with too many different assets in one or several outputs UTxOs and that could lead to some problems of transaction size. So your limit here wil be transaction size.
I never tried the limits here. Ill recommend you to use referencial scripts for the Minting Policy so you dont have to add the size of the script in this transaction and you have all the 16Kb to use in your big outtput with many NFTs.

Could you maybe mint 1000 units of the same NFT, then it becomes rather a token with metadata and an image?
When checking the ticket, you could have the app that is showing the ticket either sign it with their user wallet credentials or have the app send it to you in a transaction in which case you keep track of the wallet address that had that ticket


text:
How do I resolve this Webpack issue with Mesh library on NextJS project
I am trying to set up Mesh library on an existing NextJS project. I am not sure how to handle an issue that seems to be with the Webpack configuration for handling wasm files in the library. I am adding the library and configuration using the guide provided here by Mesh.dev.
The error after starting the NextJS project server is:

ready - started server on 0.0.0.0:3000, url: http://localhost:3000
error - ./node_modules/@emurgo/cardano-message-signing-browser/cardano_message_signing_bg.wasm
Module parse failed: Unexpected character '' (1:0)
The module seem to be a WebAssembly module, but module is not flagged as WebAssembly module for webpack.
BREAKING CHANGE: Since webpack 5 WebAssembly is not enabled by default and flagged as experimental feature.
You need to enable one of the WebAssembly experiments via 'experiments.asyncWebAssembly: true' (based on async modules) or 'experiments.syncWebAssembly: true' (like webpack 4, deprecated).
For files that transpile to WebAssembly, make sure to set the module type in the 'module.rules' section of the config (e. g. 'type: "webassembly/async"').
(Source code omitted for this binary file)

Import trace for requested module:
./node_modules/@emurgo/cardano-message-signing-browser/cardano_message_signing_bg.wasm
./node_modules/@emurgo/cardano-message-signing-browser/cardano_message_signing.js
./node_modules/@meshsdk/core/dist/core.js
./node_modules/@meshsdk/react/dist/react.js

Hi, please read the error message and read the guides. The error says, You need to enable one of the WebAssembly experiments via 'experiments.asyncWebAssembly: true'. And the guide you have pointed out shows exactly the config you need.

Thanks @Jingles I had mistyped the name of the config file. Solved!


text:
Total Ouput in Cardano
Looking at epoch 316 details on CardanoScan (https://cardanoscan.io/epoch/316) and I see that the Total Output value has 53 billion ADA.
What does this field mean? How can it be greater than the total supply of ADA which is 45 billion?

Imagine you have $100, and it exchanges hands 10 times in 1 day. That means in a single day there was $1000 worth of value transfer, even though it was the same $100 moving the whole time. Total Epoch output is the same way. If 1M ADA is transferred 45,000 times in one epoch, thats already 45B ADA total output.
Additionally, change likely makes up the majority of the total output metric. In a UTXO system like Cardano, if I have a single UTXO with 1M ADA in it and I only want to send you 100 ADA, the whole UTXO will be used as an input and two outputs will be created - one to your address for 100 ADA and one back to me as change for 999900 ADA. So even though I only sent you 100ADA, the total output for that Tx would be 1M ADA.

Very interesting. So the value is a 'summation' of all the UTXO amounts that moved around during that epoch. I guess my thinking was around an account-based ledger.


text:
Cardano Serialization Lib Usage
I am going through Cardano developer docs and the different APIs used to interact with the Cardano network. In the list is Cardano Serialization Lib which has the description,

This is a library for serialization & deserialization of data structures used in Cardano’s Haskell implementation of Shelley along with useful utility functions.

I am not sure I understand its intended use. Is it an API similar to Blockfrost, Dandelion or cardano-wallet-js? If it's different, what is the intended application?

Generally I think you can say the point of the serialization lib is to help you manage the off-chain aspects of preparing transactions before you submit them to the network.
It's a standalone library that does not interface with the blockchain, but it provides a lot of data structures and functions to make it easier to build and sign transactions, manage keys, generate and attach scripts and metadata etc..
In contrast, a service like Blockfrost (or Dandelion) directly interfaces with the blockchain and can, for example, take care of submitting the transactions you prepared with the serialization lib.
On the other side Blockfrost can also query on-chain data (eg. fetch a list of utxos belonging to an address) that you can then use to compose your transactions with the serialization lib.
So a typical scenario could be:
1. Blockfrost: Get current network parameters
2. Blockfrost: Get UTXOs by address
3. Serialization Lib: Create a transaction with these inputs and these outputs
4. Serialization Lib: Attach this script and some metadata
5. Serialization Lib: Sign the transaction with this key
6. Serialization Lib: Build the final transaction data structure
7. Blockfrost: Submit the transaction to the network
8. Blockfrost: Check the status / block confirmations etc.

I haven't used cardano-wallet-js, but its an SDK that internally makes use of the serialization lib package, and also connects to your own cardano wallet server (which interfaces with your node / the network) - so in a way you can probably call it a hybrid or a higher abstraction layer, that should simplify things even more, if you're running your own wallet server / node.

Thanks! This is most helpful. So I guess, ideally, I could call/use this library if I was creating a wallet and wanted to handle the transaction building part..

Serialization Lib is the Web3.js or Ethers of Cardano. :)


text:
Error creating a transaction with Cardano Serialization Library
I am trying to create a transaction using the Cardano Serialization Library but I cannot figure out what is going wrong.
The code is
const BlockFrost = require('@blockfrost/blockfrost-js');
const {
PrivateKey, Vkey, Ed25519Signature, PublicKey, Vkeywitnesses , TransactionHash
  TransactionBuilderConfigBuilder,
  LinearFee,
  BigNum,
  TransactionBuilder,
  Transaction,
  TransactionWitnessSet,
  hash_transaction,
  make_vkey_witness,
  Address,
  Value,
  TransactionOutput,
  TransactionInput,
} = require('@emurgo/cardano-serialization-lib-nodejs');

const BLOCKFROST_API_KEY = 'xxxxx';
const PRIVATE_KEY =
  PrivateKey.from_bech32('ed25519e_sk14p2a82zpk7y27pme7sy8yxaw0ad93j47k7dvgnc55e50lfm66a88rmz0zh0ezfqd7x30mclsjaqtkzmazy2l6crfxxd0j9ynmzxn6ac6vryrz');

const RECEIVER_ADDRESS = Address.from_bech32(
  'addr_test1qpzqmyejxwvwal9vx6w0wgezvpmjlp3cqwfg2vkjt0y9fns0d5cyvvu88y78wtfl8xyey3gr3ygpxpphevvmz7ulaf2qrhxz34',
);

const SEND_AMOUNT = '5000000';

const API = new BlockFrost.BlockFrostAPI({
  projectId: BLOCKFROST_API_KEY,
  isTestnet: true,
});

const _transactionConfig = async () => {
  const epoch = (await API.epochsLatest()).epoch;
  return await API.epochsParameters(epoch);
};

const _configureTransactionBuilder = async () => {
  // const protocolParams = await _transactionConfig();
  try {
    return (
      TransactionBuilderConfigBuilder.new()
        .fee_algo(
          LinearFee.new(BigNum.from_str('44'), BigNum.from_str('155381')),
        )
        .pool_deposit(BigNum.from_str('500000000'))
        .key_deposit(BigNum.from_str('2000000'))
        .max_tx_size(16384)
        .max_value_size(5000)
        .coins_per_utxo_word(BigNum.from_str('34482'))
        .prefer_pure_change(true)
        .build()
    );
  } catch (error) {
    console.log(`Error in tx config: ${error}`);
  }
};

const buildTransaction = async () => {
  try {
    const txBuilderConfiguration = await _configureTransactionBuilder();
    const txBuilder = TransactionBuilder.new(txBuilderConfiguration);

    //add key hash input
    txBuilder.add_key_input(
      PRIVATE_KEY.to_public().hash(),
      TransactionInput.new(
        TransactionHash.from_bytes(
          Buffer.from('d56839c08b51e159a3931b36c65b1305aa82e8625a0b2d6969f200b3ddf806cf', 'hex'), //tx hash on ada received from faucet
          0, //index
        ),
      ),
      Value.new(BigNum.from_str(SEND_AMOUNT))
    )

    //tx outputs
    const txOutputs = TransactionOutput.new(
      RECEIVER_ADDRESS,
      Value.new(BigNum.from_str(SEND_AMOUNT)),
    );
    txBuilder.add_output(txOutputs);

    //latest block
    const latestBlock = await API.blocksLatest();
    const currentSlot = latestBlock.slot;
    txBuilder.set_ttl(currentSlot + 7200); //+2h from current slot

    //metadata
    // txBuilder.add_json_metadatum(BigNum.from_str('0'), 'today is a great day');

    txBuilder.set_fee(BigNum.from_str("190000"));
    // txBuilder.add_change_if_needed(SENDER_ADDRESS);
    //build tx
    const txBody = txBuilder.build();

    //make witness
    const txHash = hash_transaction(txBody);

    const witnesses= TransactionWitnessSet.new();
    const vKeyWitness = Vkeywitnesses.new();

    vKeyWitness.add(make_vkey_witness(txHash, PRIVATE_KEY));
    witnesses.set_vkeys(vKeyWitness);

    const signedTx = Transaction.new(txBody, witnesses);

    const response = API.txSubmit(signedTx.to_bytes());

    return response;
  } catch (error) {
    console.log(`Tx compose error: ${error}\n`);
    console.error(error.stack);
  }
};

module.exports = {
  buildTransaction,
};

I am getting the error below. From my research it apparently means I am not using the correct keys for the witness. But I can't find a way to fix it. Any ideas on what could be wrong?
BlockfrostServerError: "transaction submit error ShelleyTxValidationError ShelleyBasedEraAlonzo (ApplyTxError [UtxowFailure (WrappedShelleyEraFailure (MissingVKeyWitnessesUTXOW (WitHashes (fromList [KeyHash \"0c7a0e8dc785e893f8fca246646ba10df9d5bdd5ebed92e72b163e75\"])))),UtxowFailure (WrappedShelleyEraFailure (UtxoFailure (ValueNotConservedUTxO (Value 1000000000 (fromList [])) (Value 5190000 (fromList [])))))])"

ValueNotConservedUTxO (Value 1000000000 (fromList [])) (Value 5190000 (fromList []))
This suggests that your sum of inputs (1000000000) do not match the sum of outputs (5190000), you'd want to send the delta (i.e. input - (output + fees) ), i.e. change back to your original address.


text:
How to compile plutus source code locally?
I'm trying to compile the Plutus source code locally, I tried cabal build in nix-shell,
getting this error
After searching the rest of the dependency tree exhaustively, these were the
goals I've had most trouble fulfilling: base, libsystemd-journal,
lobemo-scribe-systemd, Win32-network

This is the full error I got
I'm working on Ubuntu 20.04LTS OS
Thanks,
Please let me know if my approach is wrong.

Please give more details of the system and the steps you completed. Did you check the documentation at https://docs.plutus-community.com/?

Yes, I followed the documentation and installed Nix(Single-user) and then followed this https://docs.plutus-community.com/docs/setup/CabalBuild.html and when I did cabal build ended up in that error

Did you execute cabal update first?

Yes, this was the output
Package list of hackage.haskell.org is up to date at index-state 2021-08-16T12:54:02Z```

Win32-network - dependency not fulfilled is an indication that if there is a problem in the checked-out version. Would you mind checking with the version used in that particular lecture? I had faced the same issue.

I see you're using Week 1 of the Pioneer Program.  Did you check out the correct plutus tag (in plutus-pioneer-program/code/week01/cabal.project) before running nix-shell ?

You appear to be having issues resolving the dependencies for that particular build of Plutus. In fact, all Cardano builds depend on libsystemd (on Linux).
If you have incompatible versions of libsystemd and libsystemd-journal you get the rejection that you're having in regards to the dependencies. It appears Plutus also depends on these packages.
Please see the following link: cardano-haskell.README.md#system-setup.
I would try:
sudo apt get install libsystemd-dev

Then, try and reboot a terminal window, checkout to the correct branch within the Plutus.git repository.
Ensure you checkout the tag provided within the plutus-pioneer-program.git/code/week01/cabal.project file, which I believe is ea0ca4e9f9821a9dbfc5255fa0f42b6f2b3887c4.
Then, you should be able to boot a Nix-Shell from the Plutus repo, navigate to week01 and run cabal build.
If you've followed those steps (see below for some links that may be of help) and you're still having problems, we may need some more information.
Related links that may help:

Cardano-crypto-class-2.0.0 (conflict: pkg-config package libsodium-any, not found in the pkg-config database)
libsystemd-journal Packages For Ubuntu
Cardano Haskell System Setup | Very Similar Issue (Same Package Conflict)

Try in the nix-shell try this:

cabal update
cabal build

btw: first time building with cabal can take up some time


text:
Sync Daedalus with a local testnet node
I have set up a Cardano development environment and build a node which is fully synced to the testnet network.
How can I make my Daedalus wallet use/point to that local testnet node instead of synching again to the online/main testnet?

To anyone who may need a similar setup, I got this working after many trials. From my local cardano node, I copied the contents of the db directory into the chain directory of the Daedalus wallet.
I then updated the configuration file topology.yaml to use localhost in the addr parameter.
It works and I can receive tAda from the  testnet faucet.

Daedalus is a full node itself, this mean that he doesn't connect to an external node to sync the blockchain.
As the official website says:
"Daedalus is a full node wallet. This means that unlike light wallets (e.g.Yoroi, Adalite etc.) Daedalus downloads a full copy of the Cardano blockchain and independently validates every transaction in its history."
Here I found a Reddit Link where a similar question was made.

Well true, Daedalus is a full node, but on a fresh install ,it needs to connect to the Cardano network to sync to the latest blocks. What I was trying is to get it to use my local node which has already synced.


text:
Cardano-cli error when submitting transaction
I am following the cardano developers tutorial to create NFT using Cardano-cli
At the end, when submitting the transaction I get the following error :

Command failed: transaction submit  Error: Error while submitting tx:
ShelleyTxValidationError ShelleyBasedEraAlonzo (ApplyTxError
[UtxowFailure (WrappedShelleyEraFailure (UtxoFailure
(OutputTooSmallUTxO [(Addr Testnet (KeyHashObj (KeyHash
"a7102f357a41445de696f938ca97ebe94cc93ec7c587bee7374cffc7"))
StakeRefNull,Value 0 (fromList [(PolicyID {policyID = ScriptHash
"6980e14a6a158448066df02b641657f798275ac1ea1177cf517180c0"},fromList
[("NFT1",1)])]),SNothing)]))),UtxowFailure (WrappedShelleyEraFailure
(UtxoFailure (ValueNotConservedUTxO (Value 996981629 (fromList
[(PolicyID {policyID = ScriptHash
"6980e14a6a158448066df02b641657f798275ac1ea1177cf517180c0"},fromList
[("NFT1",1)])])) (Value 200000 (fromList [(PolicyID {policyID =
ScriptHash
"6980e14a6a158448066df02b641657f798275ac1ea1177cf517180c0"},fromList
[("NFT1",1)])])))))])

I have two questions :

Can someone help me to identify the error ?
Is there some documentation/tool somewhere to understand the cardano-cli errors ? I had some in the past and they are not indicative at all imo

Thank you so much

1) You actually have 2 errors: OutputTooSmallUTxO, ValueNotConservedUTxO.
Error 1: OutputTooSmallUTxO
As mentioned here, it is right that minimum to send ADA is 1 ADA, but since you are sending an NFT, that requirement is roughly 1.4ish ADA on the minimum to attach when sending the NFT (as fee is calculated by size of transaction, check out here Minimum ADA for Token Bundles)
I'd suggest for now just say 1.6 ADA or just go with 2 ADA (2 000 000 lovelace) if you're on testnet if you just want it to work.
Error 2: ValueNotConservedUTxO
This stems from not balancing the transaction. You have to remember that everything that goes in, must go out. So if Anna has 50 ADA and 1 NFT, and wants to send 25 ADA to Bob, the resulting output would be 24 ADA and 1 NFT back to Anna | 25 ADA to Bob | 1 ADA for fee
2) For the errors, just keep reading into them as they explain themselves to an extent. Keep going into the parenthesis and it can help to separate it out by lines. Here is a good resource you can input the errors by specific name: IOHK lookup. You can match the error text to the CLI command you did (if you add your command it can explain better). Most errors are from not balancing the fees, which is sort of fixed with the new cardano-cli transaction build which includes fees and doesn't make you calculate them, but you still need to make sure the tokens are balanced as well (if minting new and all that).

It says that you have OutputTooSmallUTxO which means that your ADA output for the address must been too small. As I can see you're output is 200000 lovelace which is 0.2 ADA.
Minimal ADA per transaction is 1 ADA so try increasing output to at least 1 ADA.

The error you are looking for is ValueNotConservedUTxO.

Not that I know of, but most of them are pretty obvious. If not, usually a quick google does the thing.


text:
About slot battles and db sync
I wanted a way to check if a pool is having some sort of slot dispute with somebody else's pool for the right to mine a block.
I couldn't find a solution for that, maybe using dbsync I don't know exactly if its possible to check that information without be the owner of that pool in question.
I'm accepting suggestions or directions on how to query these block disputes for a pool analysis tool we are creating.
thank you

db-sync only records accepted blocks. Blocks that are rolled back are removed from the database before the roll forward.

You can also check the logs on your block producer or on a relay.
This is how a slot battle looks like in the logs (it happened less than half an hour ago):
Dec 22 07:16:53 relay4 bash[3623433]: #033[35m[relay4:cardano.node.ChainDB:Notice:365]#033[0m [2021-12-22 07:16:53.43 UTC] Chain extended, new tip: 701733ec51d44a307341e9fecb3ae7b921b3a8529fffcf1cda958aeaac813c9c at slot 48591122
Dec 22 07:16:53 relay4 bash[3623433]: #033[34m[relay4:cardano.node.ChainDB:Info:365]#033[0m [2021-12-22 07:16:53.60 UTC] Block fits onto some fork: 0cd72eebab15a4e66b3225694928938362c0aef931186ea5aaeffd9830753c63 at slot 48591122
Dec 22 07:16:53 relay4 bash[3623433]: #033[34m[relay4:cardano.node.ChainDB:Info:365]#033[0m [2021-12-22 07:16:53.66 UTC] Valid candidate 0cd72eebab15a4e66b3225694928938362c0aef931186ea5aaeffd9830753c63 at slot 48591122
Dec 22 07:16:53 relay4 bash[3623433]: #033[35m[relay4:cardano.node.ChainDB:Notice:365]#033[0m [2021-12-22 07:16:53.66 UTC] Switched to a fork, new tip: 0cd72eebab15a4e66b3225694928938362c0aef931186ea5aaeffd9830753c63 at slot 48591122

db-sync doesn't track forks so can't be analyzed to identify slot battles. There are some 3rd party tools, such as cncli that do track forks so you can analyze the data from the view of one of your nodes. Note that it can only be analyzed if it's running when it happens though. Here's a reference video that could help in understanding what they are, why they occur and how to analyze them using cncli and sqlite queries: https://www.youtube.com/watch?v=Cm5pBM7UYa0

On a relay node running cardano-node install cncli and get it fully sync'ed.
Query the cncli database using sqlite:
sqlite3 cncli.db

.schema chain

select id, block_number, slot_number, hash, pool_id, orphaned from chain where pool_id = 'the_poolid_you_want_to_check' and orphaned = 1;

That should give you some ideas.


text:
Cardano-Wallet Killed
I'm trying to figure out how to use cardano-wallet  https://github.com/input-output-hk/cardano-wallet/releases/tag/v2021-06-11
Still no success because it shows a message Killed whenever I try to execute any command.
My relay is 100% synced on test-net, I did the installation wget latest release for linux 64 cardano-wallet-v2021-06-11-linux64.tar.gz
extracted copy all files to /usr/local/bin and so far so good, but when i try to execute cardano-wallet serve it shows killed and does nothing.
I'm running this node of version 1.27.0 on a docker container in a Mac M1 machine, I don't know if its relevant to say because its supposed that docker emulates a complete operational system.
Already did apt-get update and upgrade, no success.
Thanks

I want to answer my question and I'll update the documentation of the project I'm creating about that.
First this setup won't work, macos M1 and running a test net node, unfortunately, wasn't compatible so I moved on to linux machine.

Could potentially be some incompatibility with the M1 chip, with such a new chip architecture. Check out https://doesitarm.com/app/haskell/


text:
OutputTooSmallUTxO error, trying to send more than 9 tokens
I have a generated wallet, so I need to use these commands to transfer my minted NFT's out.
I'm not stuck with this very odd and annoying stuff, saying OutputTooSmallUTxO...
I really don't know what to do about it, I'm copying here the commands I'm trying omitting the names and policy ids for privacy and easy for you guys to helping me out...
cardano-cli transaction build-raw \
--mary-era \
--fee 0 \
--tx-in $tx_id#0 \
--tx-out $sender+6506622+"1 token1 + 1 token2 + 1 token3 + 1 token4 + 1 token5 + 1 token6 + 1 token7 + 16 token8 + 101 token9" \
--tx-out $recipient+0+"1 token1 + 1 token2 + 1 token3 + 1 token4 + 1 token5 + 1 token6 + 1 token7 + 16 token8 + 101 token9" \
--out-file tx.raw

fee=$(cardano-cli transaction calculate-min-fee \
  --tx-body-file tx.raw \
  --tx-in-count 1 \
  --tx-out-count 2 \
  --witness-count 1 \
  --mainnet \
  --protocol-params-file protocol.json | awk '{ print $1 }')
afterfee=$(($total_balance-$fee-2000000))

cardano-cli transaction build-raw \
--mary-era \
--fee $fee \
--tx-in $tx_id#0 \
--tx-out $sender+$afterfee+"1 token1 + 1 token2 + 1 token3 + 1 token4 + 1 token5 + 1 token6 + 1 token7 + 16 token8 + 101 token9" \
--tx-out $recipient+2000000+"1 token1 + 1 token2 + 1 token3 + 1 token4 + 1 token5 + 1 token6 + 1 token7 + 16 token8 + 101 token9" \
--out-file rec_matx.raw

Error:
    Command failed: transaction submit  Error: Error while submitting tx: ShelleyTxValidationError ShelleyBasedEraMary (ApplyTxError [UtxowFailure (UtxoFailure (**OutputTooSmallUTxO** [(Addr Mainnet (KeyHashObj (KeyHash "...")) (StakeRefBase (KeyHashObj (KeyHash "..."))),Value 2000000 (fromList [(PolicyID {policyID = ScriptHash "..."},fromList [("x",1)]),(PolicyID {policyID = ScriptHash "..."},fromList [("token1",1),("token2",1),("token3",1),("token4",1),("token5",1),("token6",1)]),

(PolicyID {policyID = ScriptHash "..."},fromList [("x",16),("x",101)])]))])),UtxowFailure (UtxoFailure (ValueNotConservedUTxO (Value 8506622 (fromList [(PolicyID {policyID = ScriptHash "mmmmmm....."},fromList

[("y",1)]),(PolicyID {policyID = ScriptHash "..."},fromList [("x",1),("a",1),("x",1),("x",1),("b",1),("x",1)]),(PolicyID {policyID = ScriptHash "xxxxx"},fromList [("n",16),("a",101)])])) (Value 8506622 (fromList [(PolicyID

{policyID = ScriptHash "..."},fromList [("x",2)]),(PolicyID {policyID = ScriptHash "..."},fromList [token list]),
(PolicyID {policyID = ScriptHash "..."},fromList [token list])]))))])

The final goal is to transfer out all these tokens to another wallet in order to clean this out because I have to mint more 23 NFT's now...

On first glance it seems like your not building  your outputs in the transactions properly.
When using the same address to mint multiple tokens and NFTs, you need to build an output for them when building a transaction. On testnet you may want to use fresh addresses to avoid this.

yeah I just did it again using a new walet. thanks


text:
How does a Cardano DApp client authorize a payment?
Am I correct in thinking that this requires a DApp connector on the same device as the User's wallet?
Or could you have an app on the user's device that doesn't connect to their wallet, but somehow authorizes a transaction and sends that digital signature to your Dapp server which is running the PAB, which then submits the Tx?
My guess is it's the former, and the process would work like this:

dapp server sends the dapp client a message containing the
information required to make the Tx

dapp client has off chain code to construct the Tx, either simple Tx or smart contract Tx.

dapp client calls the dapp connector with the Tx, and the dapp connector requests permission from the user

when the user gives permission/enters their spending password, the Tx is submitted to the network by the dapp connector.

Does this sound correct?

That sounds correct. However, you're very flexible in who composes the transaction and who actually submits it to the network.
In general at some point a transaction needs to be signed by the end user's wallet (which holds the private key to your funds) - and this is the step that requires some sort of interface that is the DApp connector (possibly also to identify the user by the public address in the first place).
Regarding the client and server side of DApps, there is no single architecture that fits all use cases.
You can have a setup in which 1) the client passes its public address to the server, which then 2) generates a transaction, 3) passes it to the client for signing; 4) the client passes it (or even only the "signature" for this tx) back to the server for 5) final verification & server-side signing, before the server then 6) submits it to the network.
On the other hand a DApp strictly doesn't need a server at all, and everything could happen on the client side (eg in the browser through a lib like this https://www.npmjs.com/package/@emurgo/cardano-serialization-lib-browser) - you can generate your transactions and submit them to the network through a wallet's dapp connector (eg using Nami wallet https://github.com/Berry-Pool/nami-wallet).
(A transaction is composed of a body, the witness set and optional metadata. The witness set holds the "signatures" of the different parties required to submit the transaction - thats how you can pass these parts around, compose them modularly, store them for later use / server side verifications etc. between clients and server)


text:
Pioneer Lecture 4 recursion - how is it not infinite?
In the solution for the Lecture #4 (cohort 1 I guess, I'm following on Youtube)
payContract :: Contract () PaySchema Text ()
payContract = do
      pp <- endpoint @"pay"
      let tx = mustPayToPubKey (ppRecipient pp) $ lovelaceValueOf $ ppLovelace pp
      handleError (\err -> Contract.logInfo $ "caught error: " ++ unpack err) $ void $ submitTx tx
      payContract

It appears that payContract calls itself, and this is required to get the payTest1 and payTest2 functions to actually run.
My question is: how does this not recurse infinitely? Where is the condition that stops it?
I'm still learning Haskell as I go and I come from a C# background, so I'm still getting my head around the functional programming thing.
TIA

payContract blocks on the first line of the do block until the pay endpoint is invoked. The input of the invocation is put in pp.
pp <- endpoint @"pay"

It then executes the endpoint invocation by creating the transaction and submitting it, and returns to the blocked state waiting for the next invocation.
It does recurse indefinitely, thus ensuring that the contract endpoints are available.

Thanks @vcwebco - that makes sense. When I am running the Emulator from the cmd line by calling payTest1:
payTest1 :: IO ()
payTest1 = runEmulatorTraceIO $ payTrace 1000000 2000000
does the payContract fn keep running while it's blocked listening for the endpoint call in a separate thread even after payTrace returns?
How does the Emulator know to stop listening for endpoint calls?

@marcel_g - contracts get activated within the context of a wallet, e.g in payTrace with code line h <- activateContractWallet (Wallet 1) payContract. That makes the endpoint(s) available for invocation, e.g. with callEndpoint @"pay" h $ PayParams. Note that activation is not global. The visual representation in the playground simulator shows wallets with the contract already activated (buttons), and with the ability to add more.

Simply put, it could recurse infinitely.
Haskell doesn't have loops, so this is the equivalent of a while loop or something, where the exit case is the Contract monad throwing an error.
If you want to learn more, check out this page on tail recursion in Haskell.


text:
strange cabal build behaviour - won't detect changes to code file
This might have something to do with me working in a docker container, that is an ubuntu version of linux, with nix installed and plutus-starter cloned.
I'm currently updating a plutus script I wrote based on an older version of plutus-starter, so I'm trying to update it.
When I go into nix-shell and enter 'cabal build', I get a build error, which is unsurprising because there have been a lot of changes in plutus.
However, if I change the file, either in VS Code on my MacOS host, or using vim inside the nix-shell in the container, and then try 'cabal build' again, I get the exact same error.
Cabal is not reloading the modified file.
If I enter 'cabal repl', at first it shows the same error as 'cabal build' and has not loaded the current version of the file, BUT THEN if I specifically load the file while in cabal repl, it does actually see the change.
Why is 'cabal build' not seeing file changes?
Exiting the nix-shell and going back in does not fix this or refresh the file.
I've noticed that when I edit the file in VS Code, it does not seem to update the last modified time on the file, but using vim inside the container does update the modified time, and cabal build still doesn't see reload it.
Am I missing a ghc or cabal option somewhere?
My next attempt is to try to run my container as a VS Code devcontainer, but I suspect there's something wrong with my cabal set up inside the ubuntu container.
the actual error isn't important, because no matter what nonsense I put in to replace 'Ledger.getDatum', the error is always the same.


text:
Any up to date Plutus tutorials for how to use the Emulator Trace?
I've recently updated my plutus-starter based app to the latest version, and it now references plutus-apps v0.1.0, and there are a lot of changes compared to what I started with in January.
It seems the data types and functions for using wallets and setting up the Emulator has changed a lot.
Does anyone have a link for a good tutorial on how to run the Emulator to test your contracts out?
TIA.

You can refer to the plutus-contract tests which use the Emulator Trace
https://github.com/input-output-hk/plutus-apps/tree/main/plutus-contract/test/Spec

ok, Thanks. I'm going to look at some files like plutus-apps/doc/plutus/tutorials/Auction.hs, to try to figure out how this testing/emulator set up all works.


text:
What's a BabbageOutputTooSmallUTxO error? How to access minAda in Plutus code?
I'm trying to convert a V1 contract to V2, and I have offchain code that mints a token with a OneShotCurrency, and then pays the token plus 1 ada to my script.
It worked with Plutus libraries from Feb. 2022, but I'm trying to upgrade it to match the upcoming Vasil HF, so I'm using plutus-apps v1.0.0-alpha1
In the emulator it is currently giving me this error:
TxnValidationFail Phase1 d6dddf483108cdd66915dac9c81d5c41263de34272366f11517debd1597ba3fc:
    CardanoLedgerValidationError "ApplyTxError [UtxowFailure (UtxoFailure
                                 (BabbageOutputTooSmallUTxO [((Addr Testnet ...

It appears that the min Ada amount is higher than 1 Ada, because if I change it to 10 Ada, it works.
Does anyone know if there's Plutus code for checking for the minAda required for a tx, without using the cardano-cli?

This was just answered here.
The min UTxO output value calculation has changed for the Babbage era. Make sure you're using the latest version of whatever library/ sdk you're using to construct transactions.

Yes, you're correct, the Babbage era has changed the calculations. You can no longer submit a tx that pays an NFT to a script, such as an oracle script, without including an amount of Ada with it. This might have already been the rule on the testnet and mainnet, but the Emulator used to let it go. I've upgraded to the V2 libraries, so now the Emulator enforces this rule.

I unfortunately asked 2 questions in one, and since @william answered one of them he should get the credit for the answer.
To answer the second question for future reference, there is indeed a Plutus function that does get the min amount of Ada so you can add that to your Tx Constraints: maxMinAdaTxOut
    let c = Constraints.mustPayToOtherScript (oracleValidatorHash oupOracle)
                    (V1LedgerScripts.Datum $ PlutusTx.toBuiltinData oupNewFee)
                       $ ((assetClassValue (oracleAsset oupOracle) 1) <>
                          (Ada.toValue maxMinAdaTxOut))

I've tested this within the Emulator and it does indeed work.

Good point! I forgot to mention that. Great that you've found out yourself.

18.5 is a lot of ada to be passing around just to satisfy minUtxo. You'll probably find that most outputs only need a little more than 1 ada when they hold a few tokens and some datum. It would be best to calculate the realistic maximum for your application, see evaluateMinLovelaceOutput.


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

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

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

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

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

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

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

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

export default new Loader();

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

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

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

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

Use node-fetch 2.6.6 and it should work


text:
Cardan Hobby Project - Concept question
As hobby, I am trying to build a small website (using cardano db and nextjs) that would work as described :

The website displays on its front page a "message" .
The "message" is decided by the owner of pre-defined NFTs (NFT_A and NFT_B)
During odd days, the "message" of NFT_A owner is displayed; (NFT_B
for even days)
"message" should be stored on cardano database and be easily
retrievable from the NFT id

To achieve that, I am considering the following :

"message" will be store as metadata in TX; (the "message" displayed should be the metada on the latest TX)
The message will be retrived by using a blockfrost.io api call

Do you think this is the right approach ? do you have any remark ?
Thank you so much :)

I'm not sure if you will query blockfrost each time someone lands on the website or once per day?
In case you start running into quota you could also run your own cardano-graphql instance to query metadata for asset (token) or you can use already hosted solution by gimbalabs https://gimbalabs.com/dandelion/graphql-api

Thanks for your answer !
I thought about querying blockfrost one per day, and do a static redering of the website.
I am not so familiar with graphql but I thought it would be simpler to just go for an pre build solution ^^


text:
Did I just convert my ada to a wrapped/pegged token?
I purchased ada on binance us and for some dumb reason, I used the BEP2 network vs the Cardano network to send my ada on binance us to Daedalus/ledger. It all shows up in Daedalus as ADA but after reading some threads did I just convert this to a wrapped token vs a native token? I'm still pretty new to this and may be misunderstanding this, but I want to ensure the ada I have in my Daedalus wallet is the native token and not wrapped or pegged, and if it is what do I need to do to get back the native token? Thank you in advance.

As long as you use the Daedalus mainnet client and see your balance, you are using ADA.
To be absolutely sure you can copy your public address and look it up on the cardano explorer: https://explorer.cardano.org/en/address?address=YOUR_ADDRESS
Example:
https://explorer.cardano.org/en/address?address=addr1qy273uqgsnv2v9hrllgp32g4gkxke85d8nsk4nup6t354kyluklkqpppvma530cs4se0gd46m5njrwtqraknat2ef9rq4v2my2
There you'll be able to see your ADA balance

Dude! Thank you so much, I've spent hours looking for this answer and after utilizing this tool I was able to verify that I did actually use the cardano network and all is good, thank you so much, this was super helpful, now I can go to bed:)

@ChristopherJManganello glad eddex was able to help you. Make sure to upvote and accept the answer, so others can see that this issue has been solved for you.

Got it, thank you all so much, this is a wonderful community so far:)


text:
Cardando project idea
I'm currently very interested in getting deeper in web3 and blockchain development. I will have this masters dissertation to which I'd like to propose a project that allowed me to develop some sort of infrastructure or dapp for the Cardano ecosystem.
I have particular interest in infrastructures such as bridges and was thinking about proposing a prototype for a bridge between Cardano and another blockchain such as Cosmos or Polkadot. I know this may be a daunting development process, and definitely not a "one man job". However, do you think this could be a somewhat interesting project to approach from a proof of concept perspective? As a means to engage in this development field, as well as eventually adding value to the ecosystem?
Let me know your thoughts on this, and any suggestions or feedback will be more than welcome!
Thanks!

So in summary, you are wondering whether or not it would be worth it to do a project where the goal is to build a bridge between Cardano and Cosmos or Polkadot?

@NikeDattani, yeah that's exacly it :) I am also open to other suggestions for projects, basically all feedback is welcome

Welcome to the community. While this stack exchange may not be a good fit for questions that open themselves up for rather subjective answers, I figured this topic (would people find this project interesting) may come up often enough to warrant a compilation of resources to better answer and pursue such undertaking.
Project Catalyst (introduced in 2020) is a fund for community innovation. You could gauge the interest on various Cardano community channels (official Telegram, several discord servers, the weekly Project Catalyst town hall, reddit etc) or post a proposal right away on ideascale during the proposal stage of a Project Catalyst fund. The community-run site https://cardanocataly.st/ has further information and links to additional resources.

Thanks for the feedback, I’ve considered some of those options, but found this to be the most straightfoward channel to start with. Nonetheless I’ll give them a try :)


text:
haskell-language-server used in VSCode Haskell extension produces spurious INLINABLE compilation error message
When compiling supplied code for Plutus Pioneer Program, the haskell extension for VSCode IDE reports a compilation error.  This prevents a lot of useful IDE functions from working, because the IDE doesn't analyze an uncompilable file. The code compiles correctly in ghci (cabal repl) and using command line "cabal build"
The error is related to the template Haskell code that is required to write Plutus validators.  Error states that a name is not INLINABLE, but it is.  I have verified that ghc and haskell-language-server are both using same Haskell compiler (8.10.4.20210212).  Does anyone know how to eliminate the error while using VSCode?
related (unanswered) Stack Exchange question: related issue

source code here

I found a workaround that is sufficient to get my IDE usable.
**WORKAROUND: ** By comparing the cabal files for Plutus week10 (which compiles OK in IDE) with week07 (error), I discovered that adding the GHC argument -fplugin-opt PlutusTx.Plugin:defer-errors into the ".cabal" file suppressed the error and allowed IDE functions like code completion to work.    With this insight, I discovered that this issue had been reported in Plutus Issue  3454 and this workaround described in a Plutus Pull Request.

Can you add a more complete example of the diff you made to the .cabal file?

Here's a diff which shows how to fix this: https://github.com/paymog/plutus-pioneer-program/commit/7a1c2ff206aeaca9496075f18e2989901aeda9fe
@KenA does your VSCode navigate to type definitions with this fix? My installation keeps telling me that no definitions can be found.

I seem to have a partial solution, that wasn't available at the time the question was asked. (I spent a lot of time trying to get my VS Code and HSL to work with a Ubuntu dev container I'd started in July of 2021, but I couldn't get it going. I was trying to get HSL to load the nix environment before building or use nix build instead of the default, but that stuff was over my head.)
Eventually I found the plutus-starter project and the plutus-starter container on IOHK.
Basic solution:

clone the plutus-starter repo to local
open a new window in VS Code, then open the repo folder.
this will ask to open in a devcontainer, click yes
this will DL the container from Docker Hub, and create and run it. (will take a while)
then in the VS Code terminal, run cabal update and cabal.repl
this will take a while to build the project.
Cmd-Shift-P and select Reload Window
This at least shows me type info on roll over, and will go to definitions and references within the project, and will show compiler errors, and have some code hints, etc.
The error at the top of the code file is still there though. The plutus-starter.cabal file has the defer-errors option defined in it, but it's behind a flag, and I'm not sure how to get HSL to set the flag to true and then send it to cabal.
I'm also not sure yet how to transfer this to an existing Plutus project. My approach going forward is just clone the plutus-starter repo and make a copy and then start my future projects in there.


text:
Calculate tx fees via Blockfrost or any other provider?
Is there a way to calculate transaction fees without having to go through cardano-cli? Maybe something like Blockfrost? or any other API providers? I don't want to run a local node to do that.

If you don't want to run a local node, how are you expecting to submit the transaction? The normal way of doing this is to use cardano-cli to first calculate the free and then use it to submit the transaction.

@ErikdeCastroLopo, I intend to submit it via Blockfrost.

Transaction fees are computed based on two factors: size of the transactions, and required resources (memory and CPU steps).
As Melroy van den Berg mentioned, transaction size increases the fee linearly:
fee_for_size = a * size(tx) + b

Both a and b are specified in protocol paramaters. You can get the latest parameters with Blockfrost using this endpoint:
/epochs/latest/parameters

min_fee_a is the coefficient, while min_fee_b is the constant.
Blockfrost also provides another endpoint for finding the required resources for a given transaction (I don't remember the exact names used in its response, but let's call them memory and steps).
And if you take another look at the protocol parameters, you may notice two other fields: price_mem and price_step. These are, respectively, price increases per memory and cpu steps. Therefore, you can compute your final transaction fee:
fee = fee_for_size + fee_for_execution

where:
fee_for_size      = a * size(tx) + b
fee_for_execution = memory * price_mem + steps * price_step

This only applies if you know your execution units. To find them out, you might want to use Blockfrost endpoint https://docs.blockfrost.io/#tag/Cardano-Utilities/paths/~1utils~1txs~1evaluate/post

Fee calculation is actually pretty simple.
0.155381 + 0.000044 * size
Where size is the transaction size in bytes.
More info

This does not include the Smart Contract fee. The values you used are also subject to change,

answer could be improved by explaining where those numbers come from and be linking the documentation of that process.
This way users can set your comment as an answer

You can use TyphonJs NPM library,
https://docs.strica.io/lib/typhonjs/classes/Transaction.html#getFee


text:
How to run Plutus code on Alonzo Purple without the PAB?
I am trying to run my Plutus code on Alonzo Purple. However, the PAB currently isn't able to connect to the Alonzo Purple testnet.
Since the off-chain code lives in the Contract monad, do I need to somehow write code to 'interpret' the Contract monad and issue commands against the wallet and node?
Is there some example code to look at?

For now, and until we have tools for it (the PAB for instance), you have to write your off-chain code as CLI transactions, which is obviously not ideal but the only solution at the moment.
I suggest going through the exercises of the Alonzo-testnet to learn how to interact with Plutus scripts using cardano-cli.
The PAB is under heavy development but we don't have any release date for either the testnet or the mainnet.

What does 'write off-chain code as CLI transactions' mean? I understand that I'll have to call the cardano-node/cardano-cli/wallet to submit transactions and query the blockchain and what not. However, the off-chain code lives in the Contract monad. So, do you think I also need a layer to interpret the effects from the Contract free monad into the CLI? If so, is there any code examples I can take a look at?

No, there is no interpreter for now. What I mean by CLI transactions is, whatever off-chain code you have in your Contract monad you can re write it as a CLI transaction (because off-chain is nothing more than transactions). I suggest looking into the docs of cardano-cli and through the exercises of the Alonzo-testnet.

I looked at the Alonzo-testnet exercises but those pages are just an outline of exercises.  There was no detail and no step-by-step instructions.  Am I missing something?  I will be honest here - trying to learn this is becoming an exercise in frustration due to a lack of quality documentation.

Exercises are meant to have holes, if you want step-by-step check Alonzo-solutions. The documentation is lacking but we have to accept it and keep digging it ourselves.


text:
How to solve the Plutus scalability issue?
This issue is one that'll plague projects trying to build on Cardano.
Let's consider Lecture 10 of the first iteration of the Plutus Pioneers Program (https://www.youtube.com/watch?v=Dg36h9YPMz4&feature=youtu.be&ab_channel=LarsBr%C3%BCnjes), if I want to send a swap transaction, I have to consume the latest pool state (containing the token balances owned by the pool). Does it mean in any block there can be only one transaction per pool? If two or more users are trying to consume the latest UTXO, only one transaction will be successful and other users have to change their transactions to reference the new UTXO.
Here are some links where it's mentioned:- https://twitter.com/LarsBrunjes/status/1390331642103877633?s=19- General approach for allowing multiple smart contract transactions per block

This should not be thought of as a scalability problem, but more as a design parameter for whatever smart contract you are building.
There are many creative ways in which projects are trying to make the liquidity pools work. SundaeSwap is using the Scooper model, which you can read about here. It goes over the tradeoffs for each popular type of DEX, and why they chose the Scooper model. Definitely worth a read.
I think that Cardano's eUTxO architecture is uniquely suited for orderbook DEXes. Since there is no global state to worry about (unlike EVM L1's), it also eliminates several design constraints that you have to worry about in designing EVM apps.
Each project is taking a unique approach, and it's worth looking at all of the major ones as a developer I think. Some of the most interesting DEXes so far are:

SundaeSwap (Scooper model + AMM)
Minswap (another AMM)
Genius Yield (this one is really interesting because it is orderbook-based and Lars himself is the CTO).

So I guess the short answer is, there are definitely ways to get around the issue of many transactions trying to consume the same output, and that isn't necessarily a roadblock for scalability. However, building with UTxO in mind is always better than trying to build a 1-to-1 replica of EVM dApps.

In other discussion, Lars said a real implementation of something like this or the Oracle could use - instead of an NFT - its own currencySymbol, and then have multiple UTxOs which could be grabbed concurrently at one time.
Here there is talk of "read-only" inputs :
https://github.com/Emurgo/Emurgo-Research/blob/master/smart-contracts/Unlocking%20The%20Potential%20Of%20The%20UTXO%20Model.md


text:
Cannot send a transaction using Plutus
I get the following error when I try to send a transaction that locks some ADA in a UTXO:
[pab:Warning:41] [2022-01-28 11:58:42.88 UTC] WalletClientError

"ConnectionError (HttpExceptionRequest Request {\n  host                 = "localhost"\n  port                 = 8090\n  secure               = False\n  requestHeaders       = [("Accept","application/json;charset=utf-8,application/json"),
("Content-Type","application/json;charset=utf-8")]\n  path                 = "/v2/wallets/70cf045f3e980335f39035b14d6dcc165001bea0/transactions-balance"\n  queryString          = ""\n  method               = "POST"\n  proxy                = Nothing\n  rawBody              = False\n  redirectCount        = 10\n  responseTimeout      = ResponseTimeoutDefault\n  requestVersion       = HTTP/1.1\n
proxySecureMode      = ProxySecureWithConnect\n}\n (ConnectionFailure Network.Socket.connect: <socket: 16>: unsupported operation (Cannot assign requested address)))"
Can anyone help?

Which set up are you using: the VScode container or Nix?

@Angelo, I'm using VScode container


text:
What is the minting cost of an NFT?
What is the minting cost of an NFT? If it depends on some factors, can they be made explicit?

All fees on Cardano are deterministic, so you'll always know the cost of the tx before you submit it. NFTs usually have metadata, depending on the amount of metadata included in the NFT will be factored into the fee and presented to you.
This article goes into detail on how the fee is calculated, keep in mind that the metadata size while reading this.
https://iohk.io/en/blog/posts/2017/10/19/how-cardanos-transaction-fees-work/


text:
What are the benefits of the two accounts model?
In some answer (see there) someone explained that there are several benefits for the two accounts system (one spending account and one reward account). What are those benefits? Wouldn't it be more practical to get your coins directly on your spending account?

For the user, yes, it would be easier to just get your rewards on your spending account as a UTXO. However, this is not scalable at all.
What this means is that every 5 days, the network would be flooded with hundreds of thousands of transactions to pay out everybody's staking rewards. Someday, it would be millions. Sooner than we think... billions.
Instead, the clever researchers and engineers came up with a system of the rewards account. This ada is "virtual" in that it doesn't really exist on chain until it's claimed with a transaction.
They made it so that the rewards values would count toward staked ada so you can continually accrue compounding rewards without having to flood the network with actual rewards transactions.  Once you claim it (Yoroi), or create any outgoing transaction (Daedalus), this rewards ada then becomes a utxo on the blockchain and thus non-rewards ada. If you don't need it, it's best to leave it be and only claim when you have to use it. You'll also save transaction fees by not continually claiming your rewards.
Clever, isn't it!


text:
What is Alonzo?
I have heard about the Alonzo update, but I was not able to understand exactly what this will change for cardano. It is said it is a step toward Goguen, but that is not very explicit. How many steps do remain to get there? What will it achieve?

Cardano's Gougen era, which is the era that will enable what is generally understood as smart contract capabilities comparable to Ethereum's, consists of three major Hard Fork Combinator (HFC) events:

Allegra – Transaction metadata capabilities
Mary – Native assets (the Cardano pendant to ERC tokens on Ethereum)
Alonzo – Smart contract capabilities

The original Cardano roadmap defines 5 main Eras: Byron, Shelley, Goguen, Basho and Voltaire. Each of these include several milestones, usually in the form of a hard-fork that changes some of the underlying ledger rules in order to enable some new features and functionalities.
We are currently in the Goguen era. The transition from the Shelley era to the Mary era was enabled by the Mary hard-fork. But the main hard-fork that will bring smart-contract functionality to Cardano is Alonzo. There are a few other steps to get there, like a multi-stage testnet roll out, but essentially there should be only one single hard-fork involved.

Yes but what will Alonzo achieve exactly?

Alonzo will give programmable blockchain, by the way of smart contract functionality. It will provide Plutus language support to write smart contract.

@raghu and so what remains to do to get to goguen era? I thought Goguen era was just that.

The Goguen era is complete, only if smart contract (Alonzo) is in place. Smart Contract is still not in mainnet. We can only say that we are in full Goguen era.

@raghu So you mean that Alonzo is the final step of Goguen era?

@Distic that's what he meant, yes.

@vaz But in your answer you wrote "there are a few other steps to get there", so if you could just elaborate a bit on what will be possible after Alonzo and what will remain to do, I would be able to accept your answer.


text:
How will stake pools be prevented from cheating the fixed fee?
Cardano, as opposed to Ethereum, has a fixed transaction fee (currently 0.17ADA). There has been no problem with this fixed fee and no-one tried to cheat. Probably it is because there is not much to get from cheating, because it seems to me that stake pool could cheat the fixed cost if they wanted to:

For example, Binance holds a big part of the stake. So, they could offer you a refund for say 50% of your fees if you do your transaction with them (instead of sending your transaction to the network, you send it to them). So you would have to wait a little bit (but not so much) but you would get lower transaction fees. Binance would receive more transactions to handle, but if they have at least roughly twice more transactions it is profitable for them.

If the network becomes saturated, stake pools will be able to ask people to pay a subscription fee to see their transactions processed.

I think there is not much of a mechanism to prevent that to happen. Is there?

The reward for Stake Pool Operator (SPO) depends upon three factors :-

Amount of ADA Pledged by the SPO
Deligation from other wallets
Percentage he sets while registering the pool.
The reward is calculated by the network in a decentralized manner and paid to the relevant address. This reward does not depend on the fees included in the transactions forming part of the block minted by a SPO. For example in a block even if there is no transaction he still gets his reward.

Therefore there is no incentive for selecting transactions that include a higher fee. The transactions which will be from part of a part are selected irrespective of the number of fees in them. This is a major improvement over Bitcoin protocol which had a utopian view that few minors will include transactions with 0 fees. The fee decoupling from the network consensus mechanism is a major innovation of the ouroboros protocol.

No I think you are wrong for two reasons. First, the fees are taken into account in the SPO reward. They are just not significant now because the issuance rewards are way higher. Second, if the number of transaction are saturated, they can use any off-chain channel to make people pay higher fees.

This link explains the formula for calculating the rewards https://forum.cardano.org/t/understanding-shelley-reward-formula-and-k-a0-parameters/33391. I could see no component of the fees of transactions processed by a particular node. R is the total reward available for epoch which is made up of complete fees collected and inflation component. Moreover, an off-chain channel makes no sense since after 20 seconds a block is likely to clear the transaction with network fees. If more than 50 %(in terms of stake) of pool owners join a cartel then it's a different story.

So now I understand better what you meant by "This reward does not depend on the fees included in the transactions forming part of the block minted by a SPO.". It explains that the SPO cannot offer to take transactions with significantly lower fees (which might be the problem right now). But it does not explain why the SPO could not ask (off-chain) for higher fees once there are much more transactions (which is not the case right now).

There is no benefit to any SPO to try and put transactions into the blocks they create.  All transaction fees are aggregated at the end of the epoch then distributed proportionally to SPOs based on number of blocks created in that epoch.
You can have a centralized actor like Binance be a payment processor, they can construct transactions with multiple outputs which tend to be smaller per payment, but it would only help if your funds were already in Binance, which is bad for you.


text:
How is it possible to know who I'm staking with in the eUTXO model?
In the eUTXO model, we use a new key each time we receive some ADA (or perhaps not each time, but often anyway). So when someone sends me some ADA to a new address, this address is unused and has never been seen on the network. However, the network somehow knows that this address is mine, as the balance is counted in my stake. How does it work?

You are actually using only one single key. From this key, you can derivate a number of different accounts and addresses.
If you look closely at all these Shelley addresses in the wallet of your choice, you will notice it has two parts, which are:

Payment part, the first part of a Shelley address indicates the ownership of the funds associated with the address.
The second part of a Shelley address indicates the owner of the stake rights associated with the address. We call it, the delegation part.

You will notice that for all your addresses, the delegation part is the same. This is how, even using different addresses for payment, you can have all of them be managed by one single stake key.
Read more in CIP 19: Cardano Addresses.


text:
How many validator nodes on cardano
How many validator nodes are there that verify 1 transaction block on cardano?

That question is a little confused/confusing.
So far (at mainnet chain tip), there are over 2500 block producers that have created at least one block.
For epoch 329 (last complete epoch) there were 1102 distinct block producers.
Does that answer your question?


text:
Stuck at Creating Keys for Token - cardano-cli address key-gen
I feel like an idiot but I am stuck at creating the keys for a token.
Here is the code:

cardano@transmission:/home/transmission/Documents$ sudo mkdir policy && cd policy

cardano@transmission:/home/transmission/Documents/policy$ cardano-cli address key-gen
--verification-key-file policy.vkey
--signing-key-file policy.skey

Command failed: address key-gen  Error: policy.skey: policy.skey: openBinaryFile: permission denied (Permission denied)

Do you have any idea why I am being denied permission for this command?
Thank you very much!

Ok I am an idiot for asking and answering this,but I am doing it anyways in case somebody stumbles in the same problem.
The folder for the keys needs to be created in the the directory where the node is in. In my case Cardano.

Your "policy" directory is owned by the root user, since you used sudo mkdir policy. No need to use sudo to make directories in your home folder, you can either remove and re-create "policy" without sudo, or change the owner with sudo chown -R <username> <directory>


text:
Does Yoroi support the gateway-like features of Metamask?
A really powerful feature of Metamask is that websites can easily use it to connect your wallet - i.e. uniswap, sushiswap, and so on. Does Yoroi support a similar feature?
If not, are there other tools that do?

No, Yoroi doesn't interact with Metamask. However, Yoroi does have this functionality in development-as I understand it.
Here is a clip of one its developers speaking on this matter.


text:
What randomness algorithm does Yoroi use for wallet generation?
What randomness algo does Yoroi use for the wallet generation? Interested in seeing how secure it is.

Yoroi is using the bip39 JavaScript library to generate the mnemonic.
When we look at its code, we can discover the generation is actually pretty simple:
function generateMnemonic(strength, rng, wordlist) {
    strength = strength || 128;
    if (strength % 32 !== 0) {
        throw new TypeError(INVALID_ENTROPY);
    }
    rng = rng || randomBytes;
    return entropyToMnemonic(rng(strength / 8), wordlist);
}

We see that as no random number generator (rnd) is defined, it uses the randombytes library by default, which is in place using the Crypto.getRandomValues() function that is provided from your browser.
To sum this up, Yoroi is using randomness algorithm of your browser, which - depending on the browser - is your system-level entropy source.


text:
Will the Cardano Rust project eventually allow you to write Smart Contracts?
Discovered this: https://cardanorust.iohk.io/
Looks great. Any rough sense on when Cardano Rust will support smart contracts? Is it being worked on now? Would be amazing.

No, the project in question is a toolbox that has been used in the Byron era of Cardano and could be considered outdated right now.
When someone implements the Cardano node in Rust, it will have to have the support for Smart Contract to match the ledger specification.

The last commit was Feb. 4th, 2020. So, no it's not being worked on—at least not recently. See the Github repo here.


text:
What encoding is used for Yorois Wallet export?
Yoroi has a feature to export a wallet as a “key” (Options=>Wallet=>Export Wallet=>Export). I guess that it is the public root key, since the description says:

The below you can find your wallet's public key information.
Public keys allow seeing the wallet history for the wallet, but does not allow to spend or move the funds in any way (private key is not included)

For testing purposes I created a test wallet and this is the "key" that Yoroi gives me:
95e74df114717de17ebfb24c05f9fd1c8019bb6f1de117eec10a43670a692866b837a4a5f51d62f3dc3d630d075c8e39e5294323ba146c386c48123aeef5438a
So my question is: How is this key encoded? It does not have any default prefix and seems to be quite long.
I guess that, e.g. for use with the cardano-addresses tool, the key maybe just needs to be converted using the bech32 tool, correct? If so, then what prefix must be used?
Thanks.
PS: This question is part of a bigger question, which I split up into sub-questions, as recommended in the original question.

After a lot of trial and error, I figured it out myself.
TLDR
The "key" that results from the Yoroi export indeed needs to be encoded with bech32, using the prefix acct_xvk.
Demonstration/Proof
To test this, we need multiple things:

The seed phrase of our test wallet (for this demonstration we store it in the file phrase.prv): maximum vacuum toe conduct jazz tray romance crawl fossil wisdom disease crazy mountain bird discover
The "key" exported by Yoroi (for this demonstration we store it in the file root_yoroi_raw.pub): 95e74df114717de17ebfb24c05f9fd1c8019bb6f1de117eec10a43670a692866b837a4a5f51d62f3dc3d630d075c8e39e5294323ba146c386c48123aeef5438a
The bech32 tool.
The cardano-addresses tool.

We can now test, whether we can get the same results using our seed phrase and the exported key:
./cardano-address key from-recovery-phrase Shelley < phrase.prv > root.xsk
cat root.xsk | ./cardano-address key child 1852H/1815H/0H | ./cardano-address key public --with-chain-code > root.xvk

./bech32 acct_xvk < root_yoroi_raw.pub > root_yoroi.pub

cat root.xvk
cat root_yoroi.pub

This gives the following result:
acct_xvk1jhn5mug5w977zl4lkfxqt70arjqpnwm0rhs30mkppfpkwznf9pntsday5h636chnms7kxrg8tj8rneffgv3m59rv8pkysy36am658zsh2qnm6
acct_xvk1jhn5mug5w977zl4lkfxqt70arjqpnwm0rhs30mkppfpkwznf9pntsday5h636chnms7kxrg8tj8rneffgv3m59rv8pkysy36am658zsh2qnm6

This means, that the key exported by Yoroi, when being bech32 encoded with the prefix acct_xvk matches the extended public root key that can be derived from the seed phrase.


text:
Why is there a small difference between addresses derived by the cardano-address tool and Yoroi?
Let's consider a Yoroi test wallet with the following seed phrase:
maximum vacuum toe conduct jazz tray romance crawl fossil wisdom disease crazy mountain bird discover
The first address generated by Yoroi is then:
addr1q96a42g6ajjhu5gfw8gch2w0vflfxkqw53pxyufgacscal5f0vdmnq834g9upwe2g0cfzwemmwvfnyawg89g8xeqx4kstanhan
However, if I derive the first address using the cardano-addresses tool like this (where phrase.prv holds the seed phrase):
./cardano-address key from-recovery-phrase Shelley < phrase.prv > root.xsk
cat root.xsk | ./cardano-address key child 1852H/1815H/0H | ./cardano-address key public --with-chain-code > root.xvk
cat root.xvk | ./cardano-address key child 0/0 | ./cardano-address  address payment --network-tag mainnet

I get the following address: addr1v96a42g6ajjhu5gfw8gch2w0vflfxkqw53pxyufgacscals656txx
For direct comparison:
addr1q96a42g6ajjhu5gfw8gch2w0vflfxkqw53pxyufgacscal5f0vdmnq834g9upwe2g0cfzwemmwvfnyawg89g8xeqx4kstanhan
addr1v96a42g6ajjhu5gfw8gch2w0vflfxkqw53pxyufgacscals656txx
So the first part of the addresses is identical (except for the first letter after the prefix), but there seems to be missing something. What am I doing wrong?
Thanks.

There is indeed missing a part of the address: the delegation part. For more information, please refer to this partially duplicate question and CIP-0019.
To derive Yoroi addresses from a seed phrase using the cardano-addresses tool:
./cardano-address key from-recovery-phrase Shelley < phrase.prv > root.xsk
cat root.xsk | ./cardano-address key child 1852H/1815H/0H | ./cardano-address key public --with-chain-code > root.xvk

# Derive the stake key.
cat root.xvk | ./cardano-address key child 2/0 > stake.xvk

# Only the index of the payment address is incremented to yield the next Yoroi address:

# First address
cat root.xvk | ./cardano-address key child 0/0 | ./cardano-address address payment --network-tag mainnet > payment.addr
./cardano-address address delegation $(cat stake.xvk) < payment.addr > payment-delegated.addr

# Second address
cat root.xvk | ./cardano-address key child 0/1 | ./cardano-address address payment --network-tag mainnet > payment.addr
./cardano-address address delegation $(cat stake.xvk) < payment.addr > payment-delegated.addr

# Third address
cat root.xvk | ./cardano-address key child 0/2 | ./cardano-address address payment --network-tag mainnet > payment.addr
./cardano-address address delegation $(cat stake.xvk) < payment.addr > payment-delegated.addr