text:
Where does a smart contract exist, in EUTxO?
In particular, I want to know whether the smart contract is somehow its own entity in the blockchain, or if a smart contract is just a property that EUTxOs may pick up.
EUTxOs are bound by smart contracts via their script addresses. But where actually is the script? To make it more practical-- how does a dapp dev actually get his smart contracts on-chain for others to use?
Some wild ideas passing through my head...
a) you have to reference some off-chain script to cause your EUTxO to operate under it.
b) you have to use a reference EUTxO, whose only purpose is to give a generic source for the smart contract's script,
c) or else, maybe the script is deployed independently on-chain somehow (outside of an EUTxO).
I'm quite ignorant about how EUTxO works; so, a), b), and c) are just to help show you where you need to do surgery.

BACKGROUND:
A smart contract is the combination of off-chain and on-chain code that interact to form some desired behavior.
The on-chain smart contract code is called a script. The script can be compiled and the hash of that compiled code becomes the unique script address for that script.
EUTxOs are values that are owned by addresses on the blockchain. To spend EUTxOs at a script address, a transaction must be validated by the on-chain script.
If the hash of your compiled script doesn't match the script address, or the transaction is not validated by the script, you will not be able to spend the EUTxOs at the script address.
ANSWER:

Where does a smart contract exist, in EUTxO?

Smart contracts exist in combination on and off chain. The state of the smart contract is stored on EUTxOs on-chain, at script addresses. In order to modify the smart contract's state, you must spend EUTxOs and possibly generate new ones with new state. The rules that say how EUTxOs at a script address can be spent are the scripts themselves.
Hope that helps :)

'The on-chain smart contract code is called a script. That script code doesn't need to actually live on-chain though (explained below).'
These two sentences are confusing.
My inital takeaway is -- all of the smart contract's code is called a script, and is off-chain. The on-chain stamp that binds an EUTxO to it is the hash of the script-- called a 'script address.'
So, the on-chain component of a smart contract (script address) serves only to seal EUTxOs under a set off-chain rules (script).
But is some code (beyond Script Addr.) actually on chain? Do you see where I'm going wrong?

I'll put it like this: If you can prove that the code you are having run by the nodes hashes to the script address, is there any need to save it on the chain? BUT, I just read some of the specs here (https://hydra.iohk.io/build/7244348/download/1/plutus.pdf) and it sound like the script is stored on the chain AFAICT. So I'll edit my original post. It's still a useful way of thinking of the on-chain scripts though!

(I've opted for a short answer, aiming to shed enough initial light on it. Of course, this is my take on it and there is a lot more to be said about it.)
Smart contracts do not exist/live on-chain.
They are units of software that exist/live off-chain and that generate transactions specific to the smart contract implementation.
These transactions are executed on-chain and use EUTxOs as inputs.
Transactions are validated prior to execution. Smart contracts implement validators (scripts) to form part of the transaction validation routine. These validators provide validation specific to the smart contract that the transaction belongs to.
A smart contract implementation (currently written in Haskell) can share code between its off-chain implementation and the on-chain validators. The on-chain code is compiled separately into Plutus Core as part of the implementation.
The implementation of a smart contract includes validating the transactions it creates prior to sending them on-chain. This ensures that there can't be failed transactions that incur costs. A transaction may still fail when sent for execution if the input EUTxOs it was validated with are not available any more.
Smart contracts can be invoked programmatically, and there also is a PAB that exposes it through an API. Currently, it is up to the smart contract developer to make it available for use.
However this is an area still very much under discussion. There are (early) plans to make smart contracts available as client browser apps interacting with e.g.Yoroi.

This answer provides me a lot of useful details. It isn't as structurally clear and terminologically clear enough to make me confident in my understanding though. You are dealing with a beginner though, so take that with a grain of salt :) Upvoted.

Thanks @MatthewCapps! The aim of the answer was to be informative knowing it wasn't 'complete' so to speak. I wouldn't call myself an expert, but I think the most important is to share understanding.


text:
Type instance syntax
I have already learned haskell from http://learnyouahaskell.com/chapters, but it doesn't cover the type instance syntax, like this:
data Auctioning
instance Scripts.ValidatorTypes Auctioning where
    type instance RedeemerType Auctioning = AuctionAction
    type instance DatumType Auctioning = AuctionDatum

I known the first line is declared the Auctioning date type, the second line is make Auctioning instance of ValidatorTypes, but what does type instance means? I can't find this syntax from haskell.

This code is implementing the ValidatorTypes "Typeclass" for the Auctioning datatype.
Typeclasses are Haskell's way of handling polymorphism, like abstract classes in an OO language. In this case, the ValidatorTypes typeclass has two associated types, RedeemerType and DatumType, that need to be defined for our validator. Here is the definition of that typeclass.
Check out the "Typeclasses 102" section in the Learn You A Haskell tutorial (scroll down) to learn more.

source: Stack Exchange

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

sort: votes


text:
How can check what version of Cardano-node is running on testnet or mainnet?
I recently ran into sync errors after building/installing cardano-node.  I am pretty sure that the problem was that I had built the wrong version, after re-building to exactly what the documentation stated, it synced fine.  So, this begs the question - is there an easy way to find out what version is running on a remote node?

You could check your startup parameters and note the path to the config file you are using by using
ps -ef | grep cardano-node

There should be a filename after --config
If unchanged, the testnet and mainnet config files are named as such; testnet-config.json and mainnet-config.json.
If the name doesn't suffice, you can check inside this config file which genesis files are used.
Or are you looking for the latest released version of cardano-node? This can be done with the following command:
curl -s https://api.github.com/repos/input-output-hk/cardano-node/releases/latest | jq -r .tag_name

[Source: Guild Operators, Build Node/CLI section]

you may connect to the remote node using SSH/RDP.
Then you can run cardano-node or cardano-cli with parameter --version.
~$ cardano-node --version
cardano-node 1.30.1 - linux-x86_64 - ghc-8.10

~$ cardano-cli --version
cardano-cli 1.30.1 - linux-x86_64 - ghc-8.10

By remote node, I meant the node running on the testnet or mainnet - which I do not own.  So, I don't believe I can ssh into a node I don't own.  I was hoping there either a remote command that I would run that "ask the remote node what version it is running" or it was published somewhere.

The correct answer is any version (that works!). Anybody is able to pick what they want. What matters is what you have in this case. If you feel your version is off, just download another one (Releases!), install it and run it!

True, but I was hoping to avoid a game of "trial and error".

Welcome to software engineering! haha You could do it backwards. Think about possible errors and constraints to later build around that.

Not sure if this is checking a remote node, but are you maybe looking for: cardano-node --version?
Example Output:
cardano-node 1.27.0 - linux-x86_64 - ghc-8.10
git rev 8fe46140a52810b6ca456be01d652ca08fe730bf

Or cardano-cli --version?
Example Output:
cardano-cli 1.27.0 - linux-x86_64 - ghc-8.10
git rev 8fe46140a52810b6ca456be01d652ca08fe730bf

Unfortunately, no (or at least I don't think so).  cardano-node --version will get you what version YOU are running but NOT what version is on the test-net or main-net server(s).  So, I was wondering if the version was posted on some website or if there was a command that could be issued for them to report that info.

Since Cardano is a network of nodes interacting with each other, each node runs its own version, and as long as the versions are compatible, it should be no issue for them to communicate with one another.
If you want to find out the latest version you can run, just head over to the Release Notes (latest version as of this answer is 8.1.2). Alternatively, you can see their releases on their github.

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


text:
The feasibility of stable coins given the min-Ada-value requirement
Cardano requires that every transaction output contains at least a value of 1 Ada. As the documentation points out, this means that it is not possible to send only native tokens in a transaction.
I struggle to understand the usefulness of native tokens given this constraint. In particular, I wonder how it is possible to implement a stable coin on Cardano given this limitation. I understand a stable coin to be a combination of a native token (e.g. USDT) and a smart contract that makes sure there are enough reserves and that the stable coin can be traded for Ada at the current USD exchange rate. The issue here is that these USDT can never be send without also including Ada in the transaction output. Wouldn't this severely impact the usefulness of this USDT (if not completely defeat its purpose)?
How does Cardano implement stable coins then ? And can they be sent without the minimum Ada constraint ?
Edit (clarification):
Note that this min-Ada requirement is fundamentally different from fees. Fees are due and payed to the Cardano network. This minimum Ada, however, needs to be sent to the recipient of the native token.

IOHK is actually working on a solution to stable coins called Djed and you should check it out.
https://iohk.io/en/blog/posts/2021/08/18/djed-implementing-algorithmic-stablecoins-for-proven-price-stability/
Cardano research's first development is bearing fruit year-round.
Also, Hydra scaling is coming, being able to run Hyrda heads on a node will make this issue with ADA fee no longer exist.

Please expand on how the linked "Djed" article answers OP's question

It goes over one of the ways you can pay fees that don't have a min ADA requirement, which eliminates the issue purposed by the OP. When you read the article it explains it in detail that doesn't make sense to copy-paste here when you can read it. I recommend it.

Excellent! That’s indeed relevant to OP’s question. Please edit your answer to add this information.

It seems to work fine on Ethereum. You are required to spend ETH as gas to move stable coins like USDT or USDC.
Native tokens are nice because you don't need to spend extra to move tokens, like you do for ERC20 tokens on Ethereum. On Cardano you just need to include your fee and a tiny amount of ADA.
There are conversations about Babel Fees, which would further improve the experience of using Stable coins by letting you pay your fees in native tokens. It's conceivable that you'd be able to meet your minimum UTxO value threshold in a similar way, but that's wishful thinking.

The equivalent of Ethereum gas fees are just the Cardano fees. Fees are no problem. The min-Ada requirement requires the sender to include 1 Ada in the transaction and to send it to the recipient ! This is totally different from fees and requires the price to be always split in an Ada-part and a native-token-part, which is not feasible without checking the exchange rate of Ada vs this native token. Babel fees are equally useless with this min-Ada requirement.

Why do you need to know an exchange rate? It’s the same as fees in that you have to include extra value for a transaction to be valid. Why do you care if it goes to the recipient vs the network?

Of course 1 ADA/tx could get expensive, but I think that's a separate concern. The value can also be adjusted. I'm sure the chain config value minUTxOValue could be turned down from 1000000 Lovelace to something much lower, especially as the value of ADA increases.

If it is part of the value the recipient gets then it is part of the price and should be disclosed. Try to explain to an average user why he has to pay 20 USDT as well as 1 Ada in addition to the 0.16 Ada in fees.

"The issue here is that these USDT can never be send without also including Ada in the [transaction]. Wouldn't this severely impact the usefulness of this USDT?" This exact statement could be said about fees is all I'm suggesting. I think of it like mailing a package over the blockchain: the fees are the stamp and the minimum ADA is the envelope :) With the added benefit of the envelope being reuseable! I don't think this makes them unfeasible at all, just different from ETH.

You are right, fees impair the user experience too. Most people are used to credit card payments where the transaction fees are hidden from the customer and payed by the recipient. But people know what fees are and can understand the transaction logic. This minimum-ada thing, however, is very confusing and impair the user experience even further in a new way.

EDIT: Yes, it's an issue (see comment).
The output requirement (in plutus at least) is in lovelaces (0.000001 of ADA), so it shouldn't be really an issue.

No, @jey is right. It's 1,000,000 Lovelace. Look at minUTxOValue in the Genesis config here:
https://hydra.iohk.io/build/7370192/download/1/mainnet-shelley-genesis.json

While I agree with you that fees might be a problem for native tokens, I do not understand why you make such a difference between fees and minimum value.
From a practical viewpoint: in Yoroi, when you send a native token, the minimum ADA to send (sum of fees and minimum-ada) is automatically computed. So the difference between fees and minimal transaction is transparent for the user. You do not even need to explain that difference to Yoroi users.
From a theoretical viewpoint: if you do not like the idea of minimum-ada, you can just assume that the fee structure is as follows:

Sending ADA: 0.17ADA
Sending a native token: 1.17 ADA (or a bit more for NFTs)
Receiving a native token: -0.83 ADA

So the minimum ADA value can be seen as some kind of fee. For the sender it definitely is. It is different for the receiver, which might be surprised that the fees are negative. But he should not complain about it.
However, it is true that a 1.17 ADA fee is too high for low value transactions. But this has nothing to do in particular with a stable coin, that can be used for both high-value and low-value transactions.

I have thought more about this min-Ada dilemma and now I think that the best solution is to construct payment mechanism as 2-step procedures on Cardano. In a first step, the sender deposits the stable coins together with the minimum Ada on a script address with validator that only allows the recipient to retrieve the value. In a second step, the recipient takes the stable coins and sends the minimum Ada back to the sender. The drawback is that fees are twice as high. On the other side transactions are safer, as no funds get accidentally send to the wrong addresses.

Regarding Yoroi, I don't think it is done in a transparent way. The user can easily miss that the difference between the available funds and the "balance after" is not the fees. A normal user would get the impression that the transaction he makes costs him only the fees.

"If the UTXO to be created as an output of a transaction is less than 1 ADA, this UTXO cannot be created and then that output is included as transaction fee."Source
I have not owned any fungible tokens yet, however I have owned some NFT's and they are considered to have an ada value of ~1.4. My general assumption is that stable coins (all other native assets) will have a mock ada value and meet this requirement.
With IOHK's commitment to making native assets first calls citizens it would be unlikely that you would be required to have 1 ada at every UTxO even when there are other assets there. At worst case though you are just required to hold 1 ada in a wallet with native assets. This hardly seems like an inconvenience.

It is definitely an inconvenience if you have a wallet with 100 USDC and 1.5 ADA and want to spend 5 USDC. Then you'd have to send 1.4 ADA + 5 USDC (+ transaction fees) to the vendor. The rest of the USDC can't be spent even if you have enough ADA to cover transaction fees because you don't have 1.4 ADA to send with the USDC.

This would be a very apple-ish way to do it. It would mean that only the Cardano Foundation could implement usable stable coins. Cardano views itself as a distributed system. Limiting the ability to create stable coins to a central entity seems like a contradiction.

its only a problem if you are trying to send the ada as well.   "namely: minUTXOvalue" So every UTxO must have a value of at least 1 ada you do not have to send 1 ada in the transaction.

If your native token has a value of 0 Ada, then you need to send the min Ada in the transaction (i.e. include Ada into the UTxO). Even the Yoroi Wallet doesn't know how to explain and display this fact to the app user. If you send native tokens Yoroi shows you your current balance, the fees and the resulting ending balance. The thing is that the ending balance is not the result of the current balance minus the fees. The difference is the min Ada and it is shown nowhere in the UI that you are sending them as well with your transaction.


text:
Is "nothing at stake" still a problem?
I read somewhere that there is no risk of forks because ADA has a built in way of deciding who gets to propose the next block if multiple stakers get selected in 1 round:
The one who rolls the lowest number that satisfies the requirement gets to propose a block.
But if you control a lot of stake, couldn't it happen that you get selected twice? In that case you can first publish the first VRF, purchase a product in that block, then reveal your lower VRF and make a fork where you keep your funds (ie a double spend).
Anything that stops this?

Nothing at stake usually means, a block producer may produce multiple blocks simultaneously and either send those to different nodes, or keep some for later in order to perform a long-range attack.
Now in Ouroboros PoS the slot leaders are pre-compiled and determined by VRF mechanism. Each participating node can easily verify if the produced block was actually built by a valid slot leader.
Also in Cardano's PoS the node does not submit/broadcast his new block, but just announce his current block-height. The remote node then decides if he want/need to fetch this block or not (i.e. a pull mechanism instead of a broadcast/push mechanism)
Also micro forks based on multiple valid blocks for the same slot - which can even happen naturally without bad intentions, based on the random slot leader election - are quickly solved by always choosing the block with the lowest VRF dice result.

just noted I forgot to answer your last question:
I'm not sure what you exactly mean by "selected twice" because of the huge stake.
Every pool will have exactly one VRF dice result for every slot.
So I guess you mean a pool operator controlling two or more large pools, who may are elected for the exact same slot.
It effectively seems possible in very rare random cases: limited to who actually has multiple huge amounts of stake on his pools, and a non-enforceable point in time when these pools dice for the exact same slot.

There are 86400 slots per day and 432000 each 5-day lasting epoch.
Due to the saturation limit (total staked supply / k pools) it is almost impossible to attract  delegations going above the saturation point, especially for a long time (currently with k=500 and ~72% active stake it is ~65M ADA)

A fully saturated (large) pool will be elected for ~55 slots each epoch, out of the 432000
The probability that your second large pool is elected for the exact same slot is very low.
And in the case it will happen, the block including the double-spend TX will be quickly removed from chain, even before the first following confirmation/block. some degree of confirmed blocks on top is always recommended

"And in the case it will happen, the block including the double-spend TX will be quickly removed from chain, even before the first following confirmation/block."

This doesn't make sense to me. You cannot "remove" a block, all you can do is not build on it. If the double spend block was already confirmed and built upon, and the attacker only then (after some blocks built on the other block) releases the lower VRF, aren't the nodes bound by the rules to build on that new block instead?

sorry, with removed I meant "solving the micro-fork by discarding the higher VRF block, choosing the lower-VRF one, and then wait for and build on the next block."
a lower-VRF block released some blocks later does not kick the whole chain of already build blocks. lower-VRF decision only plays out when two concurrent blocks are available to become th new tip.

It's not.
The Ourobouros protocol takes care of "Nothing at Stake" using game theory with mathematically verified algorithms that Prof. Aggelos Kiayias explains by laying out the parts of Ouroboros.
This is part of why Staking on Cardano is the best, no lock-up, 100% liquid, and your ADA never leaves your wallet.  ETH 2.0 needs slashing to cover for this and to stake, you need to SEND your ETH to the node and hope it doesn't do something to get slashed, or worse, the node is compromised by a dishonest admin or poor security.
https://www.youtube.com/watch?v=ur1lttBXAGM
Ouroboros has multiple papers that explain each of the parts. When putting it together nothing tops it.
Just type in Ourobouros in the search for Library.
https://iohk.io/en/research/library/

What about https://github.com/input-output-hk/cardano-node/issues/1132? This seems to be a nothing at stake issue.

authors: ILIFE - 蘋果產品專業維修中心


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

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

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

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

The selection of slot leader mechanism is explained nicely in NerdOut

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

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

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

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

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


text:
adaOf encodes Lovelace/Ada ratio in phantom type
adaOf encodes Lovelace/Ada ratio in phantom type Micro
adaOf :: Micro -> Ada
type Micro = Fixed E6
newtype Fixed (a :: k) = MkFixed Integer

Question: Being that the ratio is already encoded in the type, can I somehow get it, such that I can have a function that takes actual Ada token quantity -- not Lovelace quantity -- and gives back Ada, without hardcoding?
f :: Integer -> Ada
f adaQty = Lovelace (1_000_000 * n) -- don't really want to do this

I actually found the constant in the plutus repo:
lovelacePerAda = Constant 1000000

That constant you found probably isn't the one to use, since it's in the Marlowe libraries. Why are you interested in denominating in major units in your Plutus code? I could see the need in your UI.

Use adaOf
In a GHCi session with plutus-ledger-api in scope:
> import Plutus.V1.Ledger.Ada
> adaOf 1
Lovelace {getLovelace = 1000000}

Great! So that constant I found in Marlowe appears to be a mistake, because it is introducing a second source-of-truth.


text:
How would I create a regular expression to match all of Cardano's public wallet address formats?
Can anyone help me in creating a regular expression to preg_match (php) all of Cardano's public wallet address formats?

What have you tried so far? Can you share your progress? And could you give some examples of the different address formats you try to match with your regex?

Well i know there are 2 address types. The Byron which start with Ae2 and DdzFF. The second address and more recent type starts with addr1. Not sure of the min and max length of these addresses. Can't find much about it.

A regex itself isn't capable of validating if an address is valid or not. You need to have a little more logic. Probably what you're looking for is something like from_bytes/from_bech32/from_base58 utilized in this library: https://github.com/Emurgo/cardano-serialization-lib/blob/master/rust/src/address.rs
If you really need it to just be a regex, shelley addresses are pretty easy to validate in bech32 format, it's addr1[a-z0-9]+ and byron addresses are base58 encoded [1-9A-HJ-NP-Za-km-z]+. But neither of these ensure the address is accepted by the blockchain, it just loosely restricts the character set accepted.

Is something like this available in golang?


text:
How can a private network be created besides Mainnet and Testnet?
I've came across this 2 year old question in Stack Overflow, I'm starting a side project at work to explore the potential of Cardano.
There is an old documentation page that mentions cardano-sl component which has been currently decomposed into several others.
This other page(https://developers.cardano.org/docs/get-started/running-cardano), reads:

Alternatively, you can spin up your own custom Cardano network, but that is outside the scope of this guide.

Bottom line the question is whether it is possible to create custom private Cardano networks besides the mainnet and testnet networks, and if so, where can we find documentation about that process.

It is definitely possible to do that. You can edit genesis and config files to your taste.
Creating a local network is the purpose of the script here and there is a guide here.
There is also a similar set of config files for jumpstarting in Alonzo here

Thank you for your answer Andrej Novikov, I'm currently following https://github.com/input-output-hk/cardano-node/blob/62485960494d914f8efd06ed0d8357d41a8f9d26/doc/reference/shelley-genesis.md which is comprehensive guide on how to Create a Shelley Blockchain from scratch.

@Andrej welcome to our new community and thank you for contributing your answer here! I'd recommend to elaborate a bit, especially when your answer talks about what you "believe" rather than what you "know". It may help to look at some other answers on the Stack Exchange network to see the average length and what's considered a good answer!

Are there equivalent instructions for creating a fresh/local alanzo-era blockchain from scratch?

@robertwb I'm not aware if there are instructions, but I've updated my response to include a link to the local network configuration files targeting alonzo

I'm not very familiar where you would find the right documentation, but it certainly is possible to have multiple cardano-node be connecting to each other, forming a private network. Such a network could also be configured as you like and run with completely different parameters.
One starting point maybe is to have a look how the cardano-wallet does launch a cluster of cardano-nodes locally for testing purposes: https://github.com/input-output-hk/cardano-wallet/blob/master/lib/shelley/exe/local-cluster.hs
This document also has some explanations on how the network is configured and what data (faucets) gets prepared in the code.


text:
Is Cardano pushing developers into an Ethereum-type account model?
Cardano is build on the eUTxO model which it prides to be more robust and easy to think about than the Ethereum account model. When Cardano introduced native tokens it also was proud to announce their elegance and simplicity:

Native support grants distinct advantages for developers as there is no need to create smart contracts to handle custom token creation or transactions. This means that the accounting ledger will track the ownership and transfer of assets instead, removing extra complexity and potential for manual errors, while ensuring significant cost efficiency.

However - and this is a very big caveat - Cardano does not allow transactions that don't also carry a minimum Ada value (which is around 1 to 1.4 Ada). This means that it is not possible to send only native tokens. The sender must also send alongside the native token these minimum Ada to the recepient.
This severely impacts the usefulness of native tokens and forces developers to combine native tokens with smart contracts to work around this restriction. For example, SundaeSwap does not send tokens earned as part of the ISO directly but uses a smart contract where it stores which wallets are entitled to the tokens (see https://www.youtube.com/watch?v=OqNU99s6o_Q&t=1s at minute 12:00). The solution of SundaeSwap pretty much resembles the Ethereum model where a smart contract acts like a central register of who holds how many tokens. It is also a solution that implements an account model, that Cardano views as inferior to the UTxO-model.
So is this the way that Cardano wants their users to go ? Are we all now using the UTxO model only on the surface but then relying on an account model buried in a smart contract to make things work?
Also, why does Cardano implement native tokens when it seems to think at the same time that their UTxO model is not able not handle a possible state bloat due to native token transactions?

The simplicity died when the dream entered development

As I understand it, the SundaeSwap solution is not like ETH account model. The smart contract will temporary store tokens for the address x until the proprietary of this address send the minADA value to "withdraw" tokens. Then he will receive back the minADA + tokens, spending only transaction fees. minADA that has to be sent along tokens is some kind of "bail". eUTxO is versatile, I expect there will be some interesting ideas to manage nicely this constraint.

Short answer, No.
Cardano will have the ablity to use Tokens for fees, but that is in the pipe line as we are just getting step 3 done.
https://iohk.io/en/blog/posts/2021/02/25/babel-fees/
Cardano is currently using only eUTxO, Cardano is a 5 step process and Smart contracts is only step 3. The Account base model isn't good because it needs a globel state like ETH does now which ETH users pay for in the fees of crazyness. Cardano will never be like that due to EUTxO and coming Hydra node that can just plop the Sundae Swap plutus contract on it natively to make using it ever cheaper.
Read these articals and spend some time on IOHKs site, its dense content but it answers all your concerns.
https://iohk.io/en/blog/posts/2021/03/11/cardanos-extended-utxo-accounting-model/

Not sure this answers the question really. Even when we do get native token fees pool operators will only support a smaller amount of tokens for fees so the question is as valid today as in the future.

That's for the market to decide. Since it's cheap to use, there will be a bigger and more diverse market than what ETH can manage with its fees. Cryptokittys clogged ETH alone because of the Account model. That will not happen on Cardano.

Firstly, the min-uTxO-value requirement isn’t an accidental one. It’s primarily designed to serve as a collateral parameter which mitigates flood attacks via spam transactions and activities. This minimumADAvalue is not limited to native tokens but also ADA as well and it’s all integrated into the fee system to ensure seamless implementation. This requirement doesn’t in any hinder/hamper the fluidity or robustness of what native assets are and how they’re used. Note: min-uTxO-value is an adjustable parameter. I’d advise spending more time revising the publicly available documentation for Min-ADA-Value Requirement.
Secondly, SundaeSwap isn’t and should not be the determiner of establishing models from which DApps or other smart contact related developments are built. With that said it’s best to understand the difference in smart contract models between Ethereum and Cardano, unlike Ethereum-based contracts that are essentially built to be automated accounts with address that are imbued with code and execution triggers, Plutus smart contracts are rather simply validating scripts that check, the validity, of transactions of both simple and complex business logic. Plutus scripts do not own any signing keys or any other key that makes up an address on the ledger. If Ethereum contracts are personal assistants then Cardano contracts are bodyguards. As such, DApp architectures and design models will drastically differ from EVM compatible ones and if certain project decides to build their Cardano products by emulating methods and approaches as done in EVM structures, that’s their decision and not a limitation of the Cardano protocol.  More info on Plutus contracts at the IOHK Research Library, keyword: “Functional Blockchain Contracts” to locate the resource.

The min-Ada-value exists to limit the maximum size of the UTXO set. For protecting against spam transactions there are fees. In a sense, it is only the aim to not inflate the minimum system requirements for running a node that requires the min-Ada. I did read the documentation and I am actually working through the Plutus videos and also the published scientific papers to develop smart contracts. So no need to point me to the docs.


text:
Setting up Plutus environment for Apple Silicon computer
I'm trying to setup dependencies to write and test plutus contracts, but I'm worried that the dependencies may not be compatible with the M1 chip.
I have been following these instructions https://www.reddit.com/r/cardano/comments/mmzut6/macos_plutus_playground_build_instructions/
and I am recieving the same error

I'm running an M1 Pro with Monterey and have everything up and running correctly, so it's definitely possible!
This github guide is very useful: Cardano Plutus apps install.
The new M1's use AMD architecture, which is why it's erroring out stating "aarch64-darwin is missing in artifact.nix".
What's most likely missing is adding these two lines to your nix.conf as instructed in the link above
system = x86_64-darwin
extra-platforms = x86_64-darwin aarch64-darwin

This instructs Nix to default to installing packages built for the x86_64 architecture instead of the M1's native aarch64 (i.e. ARM).
Perhaps in the future this won't be necessary, but for now lots of packages aren't built for ARM.


text:
String in Datum
I want to use String or Text in a Datum, like this:
import PlutusTx.Prelude

newtype MyDatum = MyDatum {userReadableStuff :: BuiltinString}
PlutusTx.unstableMakeIsData ''MyDatum

but the complier complains:
• No instance for (PlutusTx.IsData BuiltinString)
    arising from a use of ‘PlutusTx.fromBuiltinData’
• In the second argument of ‘(<*>)’, namely
    ‘PlutusTx.fromBuiltinData arg_a2lNn’
  In the second argument of ‘PlutusTx.Builtins.matchList’, namely
    ‘(pure MyDatum <*> PlutusTx.fromBuiltinData arg_a2lNn)’
  In the expression:
    ((PlutusTx.Builtins.matchList t_a2lNq)
       (pure MyDatum <*> PlutusTx.fromBuiltinData arg_a2lNn))
      (\ _ _ -> Nothing)typecheck(-Wdeferred-type-errors)
• No instance for (PlutusTx.IsData BuiltinString)
    arising from a use of ‘PlutusTx.toBuiltinData’
• In the first argument of ‘PlutusTx.Builtins.Internal.mkCons’, namely
    ‘(PlutusTx.toBuiltinData arg_a2lNi)’
  In the second argument of ‘PlutusTx.Builtins.Internal.mkConstr’, namely
    ‘((PlutusTx.Builtins.Internal.mkCons
         (PlutusTx.toBuiltinData arg_a2lNi))
        (PlutusTx.Builtins.Internal.mkNilData
           PlutusTx.Builtins.Internal.unitval))’
  In the expression:
    (PlutusTx.Builtins.Internal.mkConstr 0)
      ((PlutusTx.Builtins.Internal.mkCons
          (PlutusTx.toBuiltinData arg_a2lNi))
         (PlutusTx.Builtins.Internal.mkNilData
            PlutusTx.Builtins.Internal.unitval))typecheck(-Wdeferred-type-errors)
• No instance for (PlutusTx.IsData BuiltinString)
    arising from a use of ‘PlutusTx.unsafeFromBuiltinData’
• In the first argument of ‘MyDatum’, namely
    ‘(PlutusTx.unsafeFromBuiltinData arg_a2lNv)’
  In the expression:
    MyDatum (PlutusTx.unsafeFromBuiltinData arg_a2lNv)
  In the expression:
    let
      t_a2lNy = PlutusTx.Builtins.Internal.snd tup_a2lNu
      arg_a2lNv = PlutusTx.Builtins.Internal.head t_a2lNy
    in MyDatum (PlutusTx.unsafeFromBuiltinData arg_a2lNv)typecheck(-Wdeferred-type-errors)

I could use ByteString -- about which the compiler has no complaints, and then use helper functions for
Text <-> ByteString, as shown at end of this.  But what I really want is for end user to see the datum in the script, and be able to read directly from the datum.

Not really sure what you mean by "end user to see the datum in the script" and how having a Text or String in the datum would make any difference to this. Datums are not easily visible to everyone and certainly not to "end users".
However, if you want to use BuiltinString in MyDatum, you could write your own instances for ToData, FromData and UnsafeFromData via BuiltinByteString and encodeUtf8/decodeUtf8 from PlutusTx.Builtins.
Something like the following could work:
instance ToData MyDatum where
  toBuiltinData = toBuiltinData . encodeUtf8 . userReadableStuff

instance FromData MyDatum where
  fromBuiltinData = MyDatum . decodeUtf8 <$> fromBuiltinData

instance UnsafeFromData MyDatum where
  unsafeFromBuiltinData = MyDatum . decodeUtf8 . unsafeFromBuiltinData

Note: I had a quick look at the implementation of the builtin encodeUtf8, this might not be what you expect (it seems to be currently ASCII encoding and truncating any code points outside of the 8bit range).


text:
Can't connect cardano-wallet with the node on testnet: blockedIndefinitelyException = thread blocked indefinitely in an STM transaction
I'm following this guide https://developers.cardano.org/docs/integrate-cardano/creating-wallet-faucet#creating-a-wallet-with-cardano-wallet
to learn about Cardano infra.
I have cardano-node running on port 3001 using this command
    ./cardano-node run \
   --topology ./configuration/cardano/testnet-topology.json \
   --database-path ./configuration/db \
   --socket-path ./configuration/db/node.socket \
   --host-addr 127.0.0.1 \
   --port 3001 \
   --config ./configuration/cardano/testnet-config.json

I used the configs that are suggested in the guide. Testnet magic is 1097911063.
I was able to succesfully generate wallets with cardano-cli and create/sign/submit transactions. Now I'm trying to make cardano-wallet work but I can't connect to the node. Here is my command:

    cardano-wallet serve \
    --port 1337 \
    --testnet configuration/cardano/testnet-byron-genesis.json \
    --database wallets/db \
    --node-socket $CARDANO_NODE_SOCKET_PATH

This is what I see in the wallet logs before it shots down:
[cardano-wallet.main:Info:4] [2021-08-20 06:07:38.48 UTC] Running as v2021-08-11 (git revision: e870e5f05e05e22e4de01672b0e7243b2f907153) on x86_64-darwin
[cardano-wallet.main:Info:4] [2021-08-20 06:07:38.48 UTC] Command line: /usr/local/bin/cardano-wallet serve --port 1337 --testnet configuration/cardano/testnet-byron-genesis.json --database wallets/db --node-socket /Users/[hidden]/[hidden]/cardano-node/configuration/db/node.socket
[cardano-wallet.main:Debug:4] [2021-08-20 06:07:38.48 UTC] ServeArgs {_hostPreference = Host "127.0.0.1", _listen = ListenOnPort 1337, _tlsConfig = Nothing, _nodeSocket = CardanoNodeConn "/Users/[hidden]/cardano-node/configuration/db/node.socket", _networkConfiguration = TestnetConfig "configuration/cardano/testnet-byron-genesis.json", _database = Just "wallets/db", _syncTolerance = SyncTolerance 300s, _enableShutdownHandler = False, _poolMetadataSourceOpt = Nothing, _tokenMetadataSourceOpt = Nothing, _logging = LoggingOptions {loggingMinSeverity = Debug, loggingTracers = Tracers {applicationTracer = Const (Just Info), apiServerTracer = Const (Just Info), tokenMetadataTracer = Const (Just Info), walletEngineTracer = Const (Just Info), walletDbTracer = Const (Just Info), poolsEngineTracer = Const (Just Info), poolsDbTracer = Const (Just Info), ntpClientTracer = Const (Just Info), networkTracer = Const (Just Info)}, loggingTracersDoc = Nothing}}
[cardano-wallet.main:Info:4] [2021-08-20 06:07:38.50 UTC] Wallet databases: Using directory: wallets/db
[cardano-wallet.application:Info:4] [2021-08-20 06:07:38.50 UTC] Wallet backend server starting. Using /Users/[hidden]/Dev/cardano-node/configuration/db/node.socket.
[cardano-wallet.application:Info:4] [2021-08-20 06:07:38.50 UTC] Node is Haskell Node on testnet (1097911063).
[cardano-wallet.token-metadata:Notice:4] [2021-08-20 06:07:38.51 UTC] No token metadata server is configured.
[cardano-wallet.token-metadata:Notice:4] [2021-08-20 06:07:38.51 UTC] No token metadata server is configured.
[cardano-wallet.token-metadata:Notice:4] [2021-08-20 06:07:38.51 UTC] No token metadata server is configured.
[cardano-wallet.token-metadata:Notice:4] [2021-08-20 06:07:38.51 UTC] No token metadata server is configured.
[cardano-wallet.pools-db:Info:4] [2021-08-20 06:07:38.51 UTC] Starting connection pool for wallets/db/stake-pools.sqlite
[cardano-wallet.main:Info:4] [2021-08-20 06:07:38.51 UTC] Wallet backend server listening on http://127.0.0.1:1337/
[cardano-wallet.pools-engine:Info:36] [2021-08-20 06:07:38.53 UTC] Chain following starting. Requesting intersection using 221 checkpoints, the latest being 0ac9b1b6<-[107538a4-213041#211999]
[cardano-wallet.network:Warning:14] [2021-08-20 06:07:38.57 UTC] Connection lost with the node. writev: resource vanished (Broken pipe)
[cardano-wallet.pools-db:Info:4] [2021-08-20 06:07:38.60 UTC] Stopping database connection pool wallets/db/stake-pools.sqlite
[cardano-wallet.pools-db:Info:4] [2021-08-20 06:07:38.60 UTC] Closing single database connection (wallets/db/stake-pools.sqlite)
[cardano-wallet.pools-db:Info:4] [2021-08-20 06:07:38.60 UTC] Closing single database connection (wallets/db/stake-pools.sqlite)
[cardano-wallet.main:Debug:4] [2021-08-20 06:07:38.62 UTC] Logging shutdown.
cardano-wallet: ExceptionInLinkedThread (ThreadId 12) (BlockedIndefinitely {blockedIndefinitelyCallStack = [("wrapBlockedIndefinitely",SrcLoc {srcLocPackage = "io-classes-0.2.0.0-8vqCa9RxYeSIAHkGOEppTU", srcLocModule = "Control.Monad.Class.MonadSTM", srcLocFile = "src/Control/Monad/Class/MonadSTM.hs", srcLocStartLine = 296, srcLocStartCol = 16, srcLocEndLine = 296, srcLocEndCol = 39}),("atomically",SrcLoc {srcLocPackage = "cardano-wallet-core-2021.8.11-9CfWGxilOndlEXObu7PRN", srcLocModule = "Ouroboros.Network.Client.Wallet", srcLocFile = "src/Ouroboros/Network/Client/Wallet.hs", srcLocStartLine = 628, srcLocStartCol = 5, srcLocEndLine = 628, srcLocEndCol = 32})], blockedIndefinitelyException = thread blocked indefinitely in an STM transaction})

And this is cardano-node logs
[MacBook-:cardano.node.LocalErrorPolicy:Error:63] [2021-08-20 06:35:34.08 UTC] IP LocalAddress "" ErrorPolicyUnhandledApplicationException DecoderFailure (LocalStateQuery HardForkBlock (': * ByronBlock (': * (ShelleyBlock (ShelleyEra StandardCrypto)) (': * (ShelleyBlock (ShelleyMAEra 'Allegra StandardCrypto)) (': * (ShelleyBlock (ShelleyMAEra 'Mary StandardCrypto)) ('[] *))))) Query (HardForkBlock (': * ByronBlock (': * (ShelleyBlock (ShelleyEra StandardCrypto)) (': * (ShelleyBlock (ShelleyMAEra 'Allegra StandardCrypto)) (': * (ShelleyBlock (ShelleyMAEra 'Mary StandardCrypto)) ('[] *))))))) ClientAgency TokAcquired) (DeserialiseFailure 7 "EraIndex: invalid index 4")
[MacBook-:cardano.node.LocalErrorPolicy:Error:63] [2021-08-20 06:35:35.15 UTC] IP LocalAddress "" ErrorPolicyUnhandledApplicationException (MuxError (MuxIOException writev: resource vanished (Broken pipe)) "(sendAll errored)")
[MacBook-:cardano.node.LocalErrorPolicy:Error:63] [2021-08-20 06:35:36.15 UTC] IP LocalAddress "" ErrorPolicyUnhandledApplicationException (MuxError MuxBearerClosed "<socket: 34> closed when reading data, waiting on next header True")
[MacBook-:cardano.node.ChainDB:Notice:33] [2021-08-20 06:37:24.22 UTC] Chain extended, new tip: 8900454c4bb70632d558d70421c2c25e12cc0b448ace065f61f14df882f048f4 at slot 35072228

Can anyone help?

Did you find any solution? I am facing a similar error.

Could you try running the wallet with the testnet-alonzo genesis file?

I have a similar problem but on the main net. https://cardano.stackexchange.com/questions/11164/unable-to-connect-wallet-to-node-on-mainnet

I am unsure if this will fix your issue, but try running the wallet with the Alonzo genesis file instead of Byron?


text:
Storing Secrets in Smart Contracts
I was wondering if there was an ability to store secrets, such as an API credential within a smart contract. When the contract gets executed it checks something remote. Maybe a weird example, but for example my paypal balance. Under certain conditions maybe even execute certain API functions (send money) if certain conditions are met.
To do that some sort of secret needs to be stored and associated with a wallet address.
I know it sounds crazy, but I'm interested in the technical ability of Cardano/Plutus.
Thanks

I think, this I not possible. If you want your smart contract to know about your balance or any off-chain fact (including random numbers), then you need to push this fact either to the blockchain or give it as an input to the smart contract.
This former is done by oracles. The operator of the oracle regularly pushes information (such as exchange rates, random numbers...) to the smart contract which stores this information on the blockchain. Other smart contracts can then query the oracle (usually paying a fee) to obtain this information.
For storing credentials or your PayPal balance this is obviously a bad solution. Here it would be better to use the second approach and give the balance as input to the smart contract. Here, you want of course the input to be 'validable' by the smart contract - otherwise you could hand over any value to the smart contract. To achieve this, what you can do is to require that the balance is signed by the third party (Paypal). The smart contract stores the public key of Paypal and checks the signature of the input before using it.

thanks for your answer

You are welcome. Please assess if the response answers your question and accept it as answer if it does.

@Jey what about SC where someone gets a reward when guesses a password?

@sloik You could store a commit to the password in the smart contract. This commit is a hash of the combination of the password and a random string. This random string needs to be a secret. Users push a guess onto the blockchain in a first step. The operator of the game then validates the guess. The commit makes sure that the users can verify that the operator of the game effectively rewards correct guesses.

What you are asking is commonly referred to as Oracles in the cryptoworld. Which is some way to interact with assets outside of the  blockchain, the problem with that is that since what is happening is impossible to verify by the blockchain. It can however work the other way, that the server which whom you wanted to communicates instead communicates with the blockchain, and immutably and publicly commits to whatever your smart contract does.
The blockchain cannot really contain secrets, since they would be visible for everyone, however what can be done is to "encrypt" the input to a smart contract, and at a later stage send proof that can unlock or recreate that value on the chain and proving that the value you sent now that is readable to everyone is actually the input that would recreate the encrypted value from before.
A real world example of this would to put a playing card face down on a table, everyone can see that there has been a card placed on the table, but the value is not visible (it's a secret). Later someone flips the card over and the value is visible to everyone (reveal). If you can demonstrate that the flipped card is indeed the same card that was put on the table face down and has not been replaced by another card (this would be equivalent to the cryptographic proof). Everyone can agree that the cards value is valid, and can be used to determine the outcome of the card game.

thanks for your answer!


text:
Daedalus fails to load wallet
Daedalus after 4.2.1 upgrade fails to load my wallet, the logs says the wallet was found, I can see some sqlite wallet files on my computer and cannot seem to find any information about anything being errorous, the only error I can spot in the logs are saying:
[34m[cardano-wallet.pools-engine:Info:1340][0m [2021-08-20 17:13:04.65 UTC] Fetching metadata with hash 7e10ed9d from https://smash.cardano-mainnet.iohk.io/api/v1/metadata/<bighexnumber>/<bighexnumber>
[33m[cardano-wallet.pools-engine:Warning:1340][0m [2021-08-20 17:13:04.81 UTC] Failed to fetch metadata with hash 7e10ed9d: There's no known metadata for this pool.

Can I somehow fix my wallet information without the seed phrase?

Please submit a support ticket within Daedalus.


text:
awaitTxConfirmed not returning
Under what conditions does awaitTxConfirmed not return?
It stopped returning since I updated my cabal.project file to make use of the latest plutus tag plutus-starter-devcontainer/v1.0.7. It worked with plutus-starter-devcontainer/v1.0.6.
The changes that had to be made were as trivial as changing ByteString to BuiltinByteString, mustForgeValue to mustMintValue etc.
The test output looks like:
...
Slot 00003: W1: TxSubmit: b7c6004fe8f4b8cdf94c9b4b3260f4bc60ae4c9fa6ec9d64e4b8f5e4e9c83c5b
Slot 00003: SlotAdd Slot 4
Slot 00004: SlotAdd Slot 5
...

can you post your code where you are actually using awaitTxConfirmed?

Your answer is found in the Plutus.Contract.Request module of plutus-contract.
It says that: "If the transaction is never added to the ledger then 'awaitTxConfirmed' never returns".

You are right about the comment, but it doesn't explain the reason why awaitTxConfirmed would not return

awaitTxConfirmed won't return because if loops indefinitely. If you look at the implementation, it stops looping only when the status of the tx is something other than Unknown.

This doesn't explain it, since the awaitTxConfirmed isn't recursive

You see the go function inside awaitTxConfirmed? It's recursive no?

Ok,  you are right about the recursion... But still, it doesn't tell why it may loop indefinitely :) I'd like to believe that the answer might have more to do with general blockchain documentation and not what can be discerned from code. I might be wrong though


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

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

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


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

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

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

And how to convert this address to bech32 in haskell?

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

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

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

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

module Test where

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

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

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

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

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

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

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

srlScript :: PlutusScript PlutusScriptV1
srlScript = PlutusScriptSerialised scriptShortBs

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

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

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

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

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

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

validatorHashHex :: String
validatorHashHex = show validatorHash

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

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

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

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

The header is in Base16 format (aka Hexadecimal)

-}
header :: String
header = "70"

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

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

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

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

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

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

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

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


text:
What tools do I have for building a Cardano Dapp right now?
I am building a Dapp in Cardano and I want it to build NFTs even if it's not possible right now, what tools can I use for it?
I know that there is a testnet where I can run Plutus contract. How can I access to it? Can I?
If it's not a good idea to write the contracts an Dapps, should I use testnet in a local PAB Plutus application back end, and wait till the testnet is available to everyone? Or would you recommend to do all what is possible with Cardano Cli? as far as I know there is no way to running smart contracts using Cardano Cli, is this true?
Thank you so much, I am following Plutus pioneer courses but it's hard to know what can I bring to life right now, and how.

+1 and welcome to our new community! Thank you so much for contributing your question here and we hope to see much more of you in the future!!! I would recommend though, that you try to split your question up into more focused questions, or to at least re-structure this post a bit, since currently there's multiple questions being asked in one post, which is usually not the best idea in the Stack Exchange network.

It is very possible to create an NFT on Cardano since the very second native tokens were supported, which was back in January. I advise you to provide lasting power and permanence to your NFTs by adhering to the CIP-721 metadata standard, so blockchain explorers (and eventually other dApps) will be interoperable with the NFTs that you issue.
Cardano will be the PREMIER blockchain for NFTs, due to the fact that all native tokens are first class citizens on Cardano and it is trivial to create a forging transaction and issue NFTs. You can define the supply (rarity) right in the monetary policy of the forging transaction.
There is already a thriving NFT community on Cardano.
To accomplish something similar on Ethereum you would need to create a ERC721 smart contract and program it to your needs. With Cardano, all you need is the Cardano wallet CLI and there is a great tutorial on how it works.
Now it is true that complex dApp logic with these NFTs won't be possible without smart contracts (swapping, auctioning off on DEXs etc.), but the act of creating an NFT on Cardano is as trivial as it could be!
Welcome aboard!

Thank you so much for your detailed answer, i will wait to see if anyone else can provide me a little more of insights regarding the testnet current state for making use of smarts contracts functionality, before accepting your answer.

Not NFT related, but SundaeSwap (DEX) completed the world's first swap using their smart contract deployed to the Cardano testnet. https://www.youtube.com/watch?v=cz-EDAjG3vk

Thank you so much... I think maybe I can see if in Cardano client.. is possible to send a tx  tx with a script

I have my doubts about Cardano NFTs vs Etherium tokens, i belive there are more option to exploit in Etherium tokens die to the intrinsic nature of the smart contracts in them.. for example Royalities.


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

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

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


text:
How does Ouroboros disincentivize bad behavior?
How does Ouroboros disincentivize bad behavior? For example, in ETH 2, poorly behaving nodes have their stake slashed. Does Ouroboros have a similar mechanism?

Here are three great videos on Ouroboros and Ouroboros Genesis that go into detail. They all give high-level dive into The Base Protocol and some of its upgrades.
Basically, they use game theory and math-based models on ensuring that honest SPOs flourish while dishonest ones have no incentive to be so.
When it comes to delegating on Cardano, A non-custodial form of delegation, ADA doesn't leave the delegator's wallet. They register a stake key with the network for ₳2 and the fee of the tx. Then they can pick any pool, usually a high performer to delegate.
This way no ADA is ever at risk of anything, even if the pool goes down. They can just delegate elsewhere without needing to reregister the staking key.
With that delegation system, Pools that are bad actors/performers can be abandoned and good pools can be chosen by ADA holders while never being at the mercy of stake pool operators.
This is why Education in the Cardano community is critical since informed delegators will pick the best pools as it's in their financial interest to do so.
As for ETH 2.0, Slashing isn't the only risk. Locking your ETH in for an indefinite period till the system is up is a risk.  If an admin of an ETH pool goes rouge or loses the private keys to the node, all ETH holders lose their coins.

How will a user be able to tell when a pool is misbehaving? I'd guess that the rewards for the delegators to that pool will lower which lowers the rewards of the users, is that right? If so, how does the system decide which pools are "bad" and thus should have their rewards lowered?

With a tool like https://pooltool.io/ A user would be looking out for performance more so behavior since the protocol accounts for the behavior of would-be attackers.
The less stake a pool has, the less they are likely to be selected to mint a block. So to be viable, a pool wants as much ADA as possible, and to attract it they need good fees and a pledge to the pool.

Pledge is an amount of ADA the SPO themselves decided on staking with the Pool and leaving it there so they also have skin in the game.
Pools with pledges are financially incentivized to maintain the pools uptime and its security, or they could lose their own ADA by losing their private keys. The Delegators are never at risk of this.
Pools that underperform just don't get picked to mint blocks at often or at all.

In Cardano, you cannot lose your stake. Instead, bad behavior is disincentivized by opportunity costs: if you misbehave (or if your delegated pool does), you will get lower rewards or none at all. It's better as it makes staking more secure from the viewpoint of the user, as the worst thing that could happen is that you get no reward.

How does the system "know" when a pool is misbehaving and thus lower it's rewards?

@PaymahnMaghadasian It depends how the SPO is misbehaving. For example, if it is just producing invalid blocks, those blocks are rejected as they are invalid, and thus the SPO gets no reward.

Great question! Ada is given as a reward to those nodes that dutifully complete their job as slot leaders.
Two epochs in advance, slot leaders are selected for a given epoch. The probability that a given stake pool will be selected is related to that pool's stake minus the difference between 1 and f, where f is a value determined by how good that node's behavior has been.
Every time a pool validates a transaction, it sends a verifiable random function (VRF) that takes as inputs its current state to the rest of the network. Each time this happens, the FVRF functionality is utilized. If a stake pool's node's VRF output is incorrect, the f parameter above is set to 1 for that round. Thus, if a node is adversarial, it will have no chance to participate as a slot leader and produce a block for the network. Failing to validate or "missing" blocks will have the same effect, and they will decreases the probability that a node will be selected to be the next slot leader. Thus, adversaries are unable to gain control over the network, and adversarial stake pools are punished because they will receive no rewards from staking.
Source: Ouroboros Praos


text:
Blockfrost, GrapgQL or any API for cardano help, working with javascript
I am building an MERN stack app cardano dex tool, I want to use Blockfrost.
I have installed the SDK in Node.js backend, but there are only very few examples on how to get any kind of data from it.
The Blockfrost documentation gives more info and I know how to use it with fetch, but only url based and don't know how to implement QUERY PARAMETERS into the url request. Here is an example.
function getAssets(){
        fetch(`https://cardano-mainnet.blockfrost.io/api/v0/assets`,{
            headers: {
                "project_id":'API KEY'
            },
        })
        .then(res=>res.json())
        .then(data=>{console.log(data)})
    }
    getAssets()

If there is someone that could explain me a bit how to start using Blockfrost the proper way with a Node.js backend and basically get any kind of information.
Or maybe there is a better solution to get all data from the Cardano network, I have an relay node running with GraphQL, but getting data from that is very difficult if you just starting to use it and I don't know if it will keep working after the Alonzo fork.
Please someone that can help me pointing the right direction would be awesome.

Using the Blockfrost SDK is pretty straight forward, as in this example:
import { BlockFrostAPI } from '../src/index';

async function run() {
  const API = new BlockFrostAPI({
    projectId: 'YOUR API KEY HERE', // see: https://blockfrost.io
  });

  try {
    const latestBlock = await API.blocksLatest();
    const latestEpoch = await API.epochsLatest();
    const health = await API.health();
    const address = await API.addresses(
      'addr1qxqs59lphg8g6qndelq8xwqn60ag3aeyfcp33c2kdp46a09re5df3pzwwmyq946axfcejy5n4x0y99wqpgtp2gd0k09qsgy6pz',
    );

    console.log('address', address);
    console.log('latestEpoch', latestEpoch);
    console.log('latestBlock', latestBlock);
    console.log('health', health);
  } catch (err) {
    console.log('error', err);
  }
}

run();

Basically you can use any of Blockfrost endpoints in the SDK as well, check out the list of available calls. I recommend you using an IDE such as codium as it will autofill these as you code.

Hey, thank you for the reply. Well you are right the wiki you show is very clear. Somehow I missed the right menu to get more specific info.


text:
how do I know if I should use cardano-cli or cardano-wallet
I'm new here and it's still a bit vague for me... In the developers' docs I often see that you can do the same thing with cardano-cli and cardano-wallet (receive payments, create metadata transactions, ...). So how do I know if I should use one or the other ?

The answer is it depends. The wallet provides a lot of high level automation, like coin selection for transactions, change addresses, etc... The CLI provides a bare bones I'm doing everything myself. In a production application, I'd recommend if you're not using the wallet, you use something like db-sync, graphql or rosetta to construct your transactions and handle the signing logic in your programming language of your choice rather executing cardano-cli from your code. That being said, I made my own single address wallet wrapping around CLI and cardano-addresses if you want to see an example of how you would utilize the CLI commands to build a simplified wallet here: https://github.com/input-output-hk/adawallet

Just like using the command line interface (CLI) on your computer exposes more capabilities as well as potential user errors, so does using the CLI on Cardano.
Unless you are very familiar with the CLI and the syntax, you are best off using the GUI Wallet software (Daedalus, Yoroi, ADALite, or....).


text:
How can I query the version of the node running a stake pool?
The version of the node running on the entire blockchain can be consulted in PoolTool.
I want to check the individual version of a stake pool. Thanks.

I believe PoolTool asks node operators to send them the data.
In bitcoin style nodes there is an RPC getpeerinfo and that shows peer info like major version, I dont think there is anything for cardano-node yet.
You could try looking thorough cardano-node logs and see if there is version data exchanged (I expect there is), you would then just need to manually configure mainnet-topology.json to point your node to the pool node.
Bear in mind this will only give the public relay version, not the block producer version.


text:
Slow settlement for safe wallet in Plutus
The problem I'm trying to solve -- I want to move my crypto off exchange, but I'm afraid I will be hacked or lose my keys.
Solution -- wallet that takes 1 day to settle every outgoing transaction. During that one day, it scans the blockchain for my public key to see if I cancelled the transaction. (You could set up notifications for every withdrawal, so you know if a hacker is trying to withdraw).
After 3 cancelled transactions or 1 year with no transactions (keys are lost), the wallet sends all its coins to another address (possibly in some custodial account, arbitration code, or a friend's account).
Usage -- keep 90% of money in safe wallet, and 10% in hot wallet to do stuff.

Your crypto is actually not stored in your wallet. It is stored on the blockchain. Having a wallet that is slow to figure out the state of the blockchain doesn't make your wallet any safer. Your crypto transactions move at the speed of the blockchain whether you want them to or not.
The way to ensure you're not hacked or lose your keys/mnemonics is to properly back them up and also utilize hardware wallets.
There's no possibility of slowing down the blockchain for individual users.


text:
Why do Binance run 62 pools if it is an exchange?
Enterprise addresses
Enterprise addresses carry no stake rights, so using these addresses means that you are opting out of participation in the proof-of-stake protocol.
Exchanges or other organizations that control large amounts of ada – but hold it on behalf of other users – may wish to follow a policy of not exercising stake rights. By using enterprise addresses, exchanges can demonstrate that they follow this policy. Since enterprise addresses are not associated with any staking key, they are automatically excluded from the mechanisms that influence the slot leadership schedule. Note that using addresses with no stake rights effectively decreases the total amount of stake, which plays into the hands of a potential adversary.
Source: https://docs.cardano.org/core-concepts/cardano-addresses#gatsby-focus-wrapper

From a tax point of view, in many countries you have to report staking and trading differently (DYOR). An exchange therefore does not have the right to stake users' coins without their consent. However, Binance offers a wide range of staking offers to their clients (including ADA staking) and it is only when the user subscribes to an ADA staking offer that the exchange stakes the ADA. With millions of users and millions of ADA, creating your own staking pools becomes a very profitable business for the exchange.
But staking your ADA on an exchange does not help secure Cardano, it is better to choose small independent pools to help the network with decentralization. By sending your ADA to a wallet like Daedalus or Yoroi, you can choose the pool to which you delegate your ADA.

It's their ADA, they can do what they want. This is why you should never stake your ADA with an exchange, no matter the return because, they lock your ADA for a time period and it doesn't help secure the Cardano network. Always stake with SPOs.
I stake with https://airadapool.com/ AADA because they belong to the Tech school, CareerDevs, I joined in 2016. They were the point in my life where someone sat me down and explained crypto. I've been in crypto since and that's why I stake with them and won't move till they are over 1M ADA.

Yes, I have no doubt...I am asking if exchanges can run a stake pool "entreprise address" should not allow them

Its an open system, they can do what they want.

Because it is profitable for them to do so. If they run 62 pools, they get approximately 32M * 62 * 0.05% a year, which is approximately 96M ADA. They would only change their mind if  it was bad for their image, but as people still stake with them, there is no reason for them to stop.


text:
Get wallet ID from Daedalus?
Some of the cardano-wallet API endpoints ask for 'walletId'. Does anyone know where to retrieve this value from Daedalus?  I only see wallet public key/wallet multi-sig public key.

cardano-wallet is able to create/store multiple wallets - https://input-output-hk.github.io/cardano-wallet/api/edge/#operation/listWallets
Daedalus wallet IDs have nothing in common with these - I think you need to re-create the wallet in cardano-wallet using either mnemonic words or using account xPub from Daedalus.
Also check out https://github.com/input-output-hk/cardano-addresses which contains examples of deriving various key types and addresses.

Alright that sounds good. Thank you!

As sorki replied you can indeed run a new cardano-node + cardano-wallet instance and restore the desired wallet by specifying its mnemonic sentence and copying the wallet_id shown in the API response.
Since Daedalus already runs cardano-node + cardano-wallet in the background you could perfectly query that API directly. If you're in a *nix system you could run Daedalus from the terminal like this
daedalus-mainnet 2>&1 | sed -u -n '/cardano-wallet/p' | sed -u -n 's/^.* --port \([0-9]*\) .*$/PORT: \1/p'

to get Daedalus cardano-wallet's port. Also since Daedalus' front-end communicates with Daedalus' back-end using a client certificate you'd have to use the very same one. Their location depends where did you install Daedalus, in my case they're located here
CLIENT_CRT='~/.local/share/Daedalus/mainnet/tls/client/client.crt'
CLIENT_KEY='~/.local/share/Daedalus/mainnet/tls/client/client.key'
CA_CRT='~/.local/share/Daedalus/mainnet/tls/client/ca.crt'

Then you can query the list of wallets and get the wallet_id
curl --cert "${CLIENT_CRT}" --key "${CLIENT_KEY}" --cacert "${CA_CRT}" https://localhost:<PORT_NUMBER>/v2/wallets


text:
Can someone who is familiar with Ouroboros explain its fault tolerance threshold?
Ouroboros claims to be <50% Byzantine fault tolerant with regards to persistence. I was wondering why is it that some other PoS systems settle for 33% (e.g. Casper), when 50% is provably achievable?
In the Ouroboros Classic paper, as referenced in this talk by Peter Gazi (https://www.youtube.com/watch?v=PoNaw-Mtxgo), it seems like all that is needed to achieve <50% fault tolerance is simply to have a sequence of random slot leaders create new blocks. That's all the forkability analysis and persistence/liveness conclusion with probabilistic finality seems to depend on (probability of forkability falls exponentially with length of the characteristic string with p = (1-e)/2). So why are some PoS chains out there still 33% BFT? Don't they all pretty much follow a slot leader system like Ouroboros, and thus should also have 50% BFT by this theorem?
I understand that in the Classic paper they assume synchrony. But this assumption is relaxed in Ouroboros Praos, with the same 50% BFT.
Does it have something to do with absolute finality vs probabilistic finality? I.e. does Casper achieve absolute finality, and in doing so have to sacrifice the fault tolerance somehow? Is there another factor?
Thank you!

Casper vs Praos
Casper protocol with its 33% fault tolerance is rather an economic finality type, than probabilistic one. It guarantees that at least 2/3 of validators sign some messages and the network verifies these messages. So it maintains the balance between finality time and decentralization.
With a lack of official IOHK documentation, I came to my own conclusion – probabilistic Ouroboros Praos with its < 50% simple byzantine fault tolerance (Simple BFT), means that approximately 2/3, but not lower than 1/2, of pool's validators sign some messages and the network approves these messages. This is a kind of trade-off between the speed, decentralization, Cardano's fault tolerance and protection against 51% attacks.
So the equation is as simple as that:
                50.001 % < consensus < 66.667 %
--------------------------------------------------------------------
        <--- dangerously               not effectively --->

Consensus can be reached in a case if more than 50% of the honest delegates find the block to be invalid, so the dishonest validator must be replaced and disincentivized.
If you need details on BFT you can find them in IOHK paper:
Practical BFT protocols
I don't think this story is about one protocol is better/worse than another, it's just about the fact that the developers have slightly different visions how their protocols should work.
Since in Cardano you have to wait for several minutes (after putting a block with your Tx into ledger), to be sure your Tx is deeper-and-deeper in blockchain, there's no thoughts about absolute finality at the moment:

Absolute finality refers to the type of finality provided by PBFT-based protocols (like Tendermint by Jae Kwon), in which a transaction is immediately considered finalized once it is included in a block and added to the blockchain. In this case, a leader will propose a block, and a sufficient fraction of a committee of validators will have to approve the block for it be committed.


text:
Unable to view images from ipfs.blockfrost.dev
I am unable to view images on ipfs.blockfrost.dev on my Mac. However, I can view them on my iPhone. I have tried Brave, Chrome, and Safari browsers.
Here is the error message I get when I click 'advance' in the security warning:
ipfs.blockfrost.dev normally uses encryption to protect your information. When Brave tried to connect to ipfs.blockfrost.dev this time, the website sent back unusual and incorrect credentials.

This has been solved internally by Blockfrost support.
The end user had configuration problem with his operating system when all the .dev domains were redirected to a different website.


text:
What does it mean that a UTxO sits at script address?
What does it mean that a "UTxO sits at a script address".
What is a script address?

UTxOs are always associated with some address or "public key".
Traditionally, on Bitcoin and Cardano that meant a wallet address. And someone could only spend a UTxO in a transaction signed by the private key of the associated address. When you send BTC or ADA to someone, you are really just creating new UTxOs that can only be spent by that person.
So, you could say that a UTxO exists or "sits" at a wallet address whose owner is allowed to spend it.

What does it mean that "utxo sits at script address". What script address?

Once smart contracts are enabled on Cardano, UTxOs can also be associated with "script addresses". Similar to wallet adresses, this is a way of determining when a UTxO can be spent. A "script" is just that, a piece of code that says "yes" or "no" when someone tries to spend a UTxO. (This is how smart contracts work on Cardano,  by combining different scripts to control the storage of value and data.)
So, you could say that a UTxO "sits" at the address of the script that determines when that UTxO can be spent.

Just how you think of your address that you receive all your ADA in, the address of the script is the way you can track and interact with a script.


text:
Hardware requirements for node
Would Raspberry Pi 4 with 4GB with Ubuntu 20.04 LTS. Is that enough to get started running the test mode?

As per the last release of cardano-node.
Minimum System Requirements:

An Intel or AMD x86 processor with two or more cores, at 1.6GHz or faster (2GHz or faster for a stake pool or relay)
16GB of RAM
120GB of free storage (200GB recommended for future growth)

However, you might get away with your setup, but do not be surprised if not :)

I run PGWAD pool on raspberrypi 4.
There is an alliance of pool operators running on raspberry pi.
You can find details here https://armada-alliance.com/
There are guides to help you setup pool.

I run a cardano-node 1.27.0 relay on a Pi4 8GB, and the RAM is often used at around 7-7.5GB.
My x86 relay is now compiled to cardano-node 1.29.0 and after 12 hours seems to be running around 5GB, so perhaps some memory optimizations are in there.
Try it.  If you are just missing enough RAM, maybe zRAM can help.


text:
Manual Calculation of Transaction Size and Fee
I realize that the CLI has commands for calculating a minimum fee based on a transaction size, but I'm wanting to do a calculation manually. The documentation states that the formula for calculating the transaction minimum fee is a * size(tx) + b where a & b are protocol parameters, and size(tx) is the transaction size in bytes.
Is there a way to calculate the transaction size if I know the number of consumed and output UTxOs? Also, are a and b in the genesis file?

there are two options that do come to my mind to calculate a transaction size:
starting from the fees
since we know that the fees are calulated as a * size(tx) + b == fees
using some simple algebra we can see that size(tx) == (fees - b) / a
this should be the most reliable way, but you need the fees in order to calculate the size, so it shouldn't fit you request
use the CBOR size
when builing a transaction using either cardano-cli transaction build or cardano-cli transaction build-raw you need to specify an --out-file which turns out to be a .json file with the following chema:
{
    "type": "Tx AlonzoEra",
    "description": "",
    "cborHex": "<some hex value>"
}

ultimately the cborHex value is what goes on-chain
that value is an hexadecimal string and represents the bytes of the CBOR message
since we know that each byte can have a value from 0 to 255 the hex representation must take 2 hexadecimal digits per byte
this way you could calculate the tx size in bytes as half the length of the cborHex string
in nodejs
"<some hex value>".length / 2

however, this approach returns usually a value smaller by ~400/~500 bytes in contrast to the first approach, so I might be missing some data
P.S. cardano-serialization-library
using the cardano-serialization-library it should be enough to use the Transaction.to_bytes() method and get the length
e.g.
myTx.to_bytes().length

The a and b fees parameters are protocol parameters, so you should probably check the current epoch, even they are unlikely to change suddenly.
$ curl -s  -H "project_id: $BLOCKFROST_PROJECT_ID" https://cardano-mainnet.blockfrost.io/api/v0/epochs/latest/parameters | jq '. | .min_fee_a, .min_fee_b'
44
155381

Then, all your need to do to calculate your fees is:
a × size (in bytes) + b

Read more on docs.cardano.org.

To get the exact size in bytes, you're going to want to build the transaction and include a dummy value for the fee even though you don't know it yet. Then you can get the exact number of bytes the transaction will take instead of doing estimates based on UTxO counts and such. Then, just calculate as @Marek showed and re-build the Tx a second time with the exact fees.

Thanks, you've both been helpful. I guess I probably also wasn't perfectly clear. I'm trying to figure out how to get the size(tx) value. I was wandering if I could do it without the CLI? I'm assuming its not the size of the ASCII characters in bytes but formatted differently. I couldn't find the exact info in the docs (although I'm sure its there somewhere).

Thanks Marek, I forgot to check the protocol parameters file. I was looking in the genesis files but of course it can change!

@nalyd88 The only way to get the size of the transaction without using cardano-cli is to build the cbor for everything yourself. I do this with my firehose project, but it's quite involved. Even cardano-cli doesn't give you exactly the minfee value. It just does a best guess estimate and pads it a bit. Things like stake vs enterprise output addresses can change the size of cbor and affect fees.

Here is my bash script
fee=$(cardano-cli transaction calculate-min-fee \
                    --tx-body-file tx.tmp \
                    --tx-in-count 1 \
                    --tx-out-count 1 \
                    --mainnet \
                    --witness-count 1 \
                    --byron-witness-count 0 \
                    --protocol-params-file protocol.json | awk '{ print $1 }') >> $log

In your case, it depends how many TX_in and TX_outs you will have.

tx.tmp will create it by :
cardano-cli transaction build-raw
--fee 200000
--tx-in ${tx_in}
--tx-out ${in_addr}+${utxo_balance}
--invalid-hereafter $(( ${currentSlot} + 2000))
--out-file tx.tmp >> $log