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

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


text:
How much does it cost for stake-pools to mine 1 ADA?
More or less how much does it cost in terms of: electricity + hardware devaluation for the stake-pools to mine each ADA?

A fully-saturated pool, minting several dozen blocks per epoch costs the same to run as a pool with minimal pledge and delegation, which may not mint even one block per year.
The assignment of blocks is based on the delegated stake rather than on the processing power of the mining machines, as would be the case in a proof of work system.
It costs me a few hundred dollars per month to run my relays and my producer node, with a backup producer node but this is by no means the cheapest way to do it - some people run them on Raspberry Pis.
If you were minting 200 blocks per month in a fully-saturated pool, and it was costing you $200 per month to run the setup, that's about $1 per block. This block would then be rewarded by the system with a few hundred Ada, which would be distributed proportionally among the pool's delegators.
So, in some sense, you will have "mined" each Ada at a cost of less than a cent each. But, unlike a proof of work system, if you were to scale up the hardware in terms of electricity usage, it would make no difference to the number of Ada that were rewarded to the pool.

source: Stack Exchange

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

sort: votes


text:
Where are the private / public key files stored when creating them with cardano-cli?
I am using the cardano-cli for creating the signing / verification keys.
cardano-cli address key-gen --verification-key-file pay.vkey --signing-key-file pay.key

Does anybody know where these files are stored?
Thank you

They are located in the directory where you enter the command.
In the terminal, type in pwd and that will show you where your working on your system. Once you run the cardano-cli commands, type in ls  to view all folders and files in that directory.

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


text:
bech32 in Shelley addresses
I'm trying to write address validation in Python. According to the docs, Shelley addresses are encoded with bech32 and the first byte of the payload consists of header_type (4 bits) and network_tag (4 bits).
So, let's consider the following address:
addr1w8phkx6acpnf78fuvxn0mkew3l0fd058hzquvz7w36x4gtcyjy7wx
In [2]: bech32.bech32_decode("addr1w8phkx6acpnf78fuvxn0mkew3l0fd058hzquvz7w36x4gtcyjy7wx")
Out[2]:
('addr',
 [14,
  7,
  1,
  23,
  22,
  6,
[...]

The first byte of the payload is 14, which would mean network_tag = 14 and header_type = 0. However, (a) the HRP doesn't contain the _test suffix and (b) cardano-address reports different network tag than my result does:
$ echo addr1w8phkx6acpnf78fuvxn0mkew3l0fd058hzquvz7w36x4gtcyjy7wx | cardano-address address inspect
{
    "spending_shared_hash": "c37b1b5dc0669f1d3c61a6fddb2e8fde96be87b881c60bce8e8d542f",
    "stake_shared_hash_bech32": "stake_shared_vkh1cda3khwqv60360rp5m7akt50m6ttapacs8rqhn5w342z7p6v69g",
    "address_style": "Shelley",
    "network_tag": 1,
    "spending_shared_hash_bech32": "addr_shared_vkh1cda3khwqv60360rp5m7akt50m6ttapacs8rqhn5w342z70dxhec",
    "stake_reference": "none",
    "stake_shared_hash": "c37b1b5dc0669f1d3c61a6fddb2e8fde96be87b881c60bce8e8d542f"
}

I guess I'm making some stupid mistake, but where?

The problem stems from bech32 being a base5 encoding, which means that one character of address representation encodes only 5 bits of the actual address data.
The bech32_decode function from Python Reference Implementation leaves the decoded data as it is: every byte may have only 5 youngest bits used. Meanwhile the Cardano tools use converted notation, where bits are shifted left and "packed".
In the PRI you may add another step to get the packed data into payload var:
hrp, _payload32 = bech32_decode(address)
payload = convertbits(_payload32, 5, 8, False)

I would use the bech32 decoder tool available here:
https://github.com/input-output-hk/bech32
You can also find it in Daedalus in the binaries folder for your platform.
$ bech32 <<< addr1w8phkx6acpnf78fuvxn0mkew3l0fd058hzquvz7w36x4gtcyjy7wx
71c37b1b5dc0669f1d3c61a6fddb2e8fde96be87b881c60bce8e8d542f

This outputs the address in a hex format which is easier to understand as each 2 hex characters are one byte.
7# at the start means that it's a smart contract address, I believe. The 1 in 71 means a mainnet address. 70 would be a testnet address.
More info about addresses can be found here:
https://github.com/cardano-foundation/CIPs/blob/master/CIP-0019/CIP-0019.md

OK, it seems the bech32 implementations differ. Thank you for pointing out the IOHK source. Somehow I missed it.


text:
Is there any eth_sign equivalent signing method in plutus?
I want to use my private key to sign a message, and submit the message and signatures to third party server, the third party server can verify that signatures through plutus smartcontract.
In ethereum eth_sign can achieve this, the smartcontract side have a method to recover address related to the oringal signing private key:
pragma solidity ^0.4.25;

library ECDSA {

  /**
   * @dev Recover signer address from a message by using their signature
   * @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address.
   * @param signature bytes signature, the signature is generated using web3.eth.sign()
   */
  function recover(bytes32 hash, bytes signature)
    internal
    pure
    returns (address)
  {
    bytes32 r;
    bytes32 s;
    uint8 v;

    // Check the signature length
    if (signature.length != 65) {
      return (address(0));
    }

    // Divide the signature in r, s and v variables with inline assembly.
    assembly {
      r := mload(add(signature, 0x20))
      s := mload(add(signature, 0x40))
      v := byte(0, mload(add(signature, 0x60)))
    }

    // Version of signature should be 27 or 28, but 0 and 1 are also possible versions
    if (v < 27) {
      v += 27;
    }

    // If the version is correct return the signer address
    if (v != 27 && v != 28) {
      return (address(0));
    } else {
      // solium-disable-next-line arg-overflow
      return ecrecover(hash, v, r, s);
    }
  }

  /**
    * toEthSignedMessageHash
    * @dev prefix a bytes32 value with "\x19Ethereum Signed Message:"
    * and hash the result
    */
  function toEthSignedMessageHash(bytes32 hash)
    internal
    pure
    returns (bytes32)
  {
    return keccak256(
      abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)
    );
  }
}

You can find functions for message signing and signature checking in packacke plutus-ledger, module Ledger.Oracle.
Also, why whould you need a smart contract for this?


text:
Is on-chain voting limited to just the Cardano treasury?
I have an idea for a native asset where txn fees are sent to a treasury and token holders can vote on how to spend those funds. Exactly like how Cardano currently works, but for a different purpose (ex. A Miami coin where token holders can vote on proposed projects to improve the city).
Is it possible to build something like this?

I think what you're describing is basically a smart contract.
How you design a smart contract is not limited by anything other than your technical ability, then by your own imagination. You could design a smart contract where any transaction that occurs incurs a small transaction fee and the fee is stored in a designated address or "treasury" address where the UTXO can only be spent by having a vote by holders of the token.
The voting functionality would need an off-chain validator function confirming the person voting indeed has some of the correct native asset, and how much they have. Next you would create functions to submit proposals, which again check that the person submitting a proposal holds that specific native token.
So essentially the smart contract would handle the logic of submitting, voting on, and determining which proposal wins and becomes the future of the dApp/protocol/whatever.
This is what makes blockchain so exciting, it's simply up to your imagination. Look into the Uniswap smart contract for a more in-depth look into creating a smart contract with the functionality you defined.

This was a perfect answer, thank you so much :) My only follow-up question - is it not possible to have the voting occur on-chain?

Well, uhh.. that's essentially what's happening here. You can only execute a smart contract through a UTXO. Nothing happens on Cardano on it's own, it must be triggered by a UTXO which of course means everytime you interact with a smart contract and executing a function that's part of that contract you are "on-chain".

The on chain voting features coming with the Voltaire rollout will allow users to use those voting systems for other things because they are part of the base protocol. So incorporating voting on chain with a plutus contract will be possible.
just not right now.


text:
Implementing a nested state machine
I am trying to implement a nested state machine with plutus and I'm wondering if it is even a possibility.

What have you tried?

You can search the web for "nested state machine Haskell" and you should find quite a lot of information. Translating Haskell to Plutus should not be too difficult.

The answer is yes - qualified. It will eventually depend on what you have in mind.
The code that only runs off-chain is limited by the capabilities of Haskell.
But the part of the off-chain code that is executed on-chain (validator) is subject to the limitations of the Plutus Core language which is what runs on-chain. However, I don't know what they are in this case.


text:
Verifying user data sent to a smart contract
so i've got a fun idea to use an in game puzzle and the infinite solutions possible as a method to mine a coin. Essentially i want the gamer to create a system, and however long it runs for without falling apart will dictate how much currency is minted to reward the system. (kinda like earning in-game points, except i want it too be a crypto-token)
the slight catch is i'd like it too be a mobile game written in Unity, so i don't think i can verify the solution 'on-chain', but i also don't want someone to be able to just call a smart contract with "?duration=allTheTime" to mint all the monies fraudulently.
How would everyone else approach this? I've considered maybe a system of 'authorized accounts' that can do verification of submitted solutions, or somehow crowd sourcing the verification in a decentralized manner, but that stuff gets complicated fast. thoughts?
Edit: no idea why this question is being downvoted. I'd like to give a simpler example. giving out points in a game, and recording those on the blockchain.. "you chopped some wood, 2 points"... how to prevent fraud when the smart contract is publicly exposed to mint new points. store the private minting key IN-APP? (obviously not). help.


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

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

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

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

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

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

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

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


text:
How are transactions prioritized from memory?
I've been thinking on restrictions around concurrency of smart contracts given the deterministic nature of the EUTXO model, and I've had trouble finding an answer to how transactions are prioritized for a block in the case where multiple valid transactions exist
visible to a node redeeming a single UTXO. Is this left to the slot leader to decide?
This question also leads into another question I have, which is: Is network spam somehow a viable concurrency model since fees are not charged for simple validation failure? Like say you change the Uniswap implementation to allow for multiple liquidity pools of a given trading pair (thus multiple corresponding UTXOs) Would it be viable to submit multiple transactions redeeming overlapping UTXO's in the hope that only one transaction would go through?
Maybe this is still being thought about and maybe this question is ultimately silly, but I was hoping to hone in my thinking around this a bit.

We may need different models than what has been done in Uniswap, Keep in mind that Hyrda is coming and can get us around this problem. Unlike other L2 solutions for other blockchains, Plutus code runs with Hydra out of the box  so by then this may not be an issue.
Prof, Aggelos Kiayias explains here I recommend watching the whole video.

I understand that Hydra may render all this moot, but I'm still curious about what sort of tricks we'll have at our disposal for achieving something closer to concurrency at the base layer.


text:
Is there or will there be a way to request payment?
Is there any development going on with this? Or do I lack the understanding of how this works. I'm thinking something similar to Zelle or Venmo. Sorry if this has already been asked or is not possible, I'm brand new and trying to be involved.

Hi and welcome to the Cardano stack exchange. Currently it is not possible to request a payment from someone else using the official Yoroi or Daedalus wallets. I'm also unaware of any developments in this direction. Hope this answers your question.

Requesting payments is a third-party affair for the most part. In the world of “Don’t call us, we’ll call you”, it’s the other way round crypto/blockchain tech.  Every activity/transaction for the most part is executed by the user. Exceptions are contract-contract interactions.
In conclusion; third-party apps can be built to send notifications that request payments but that’s not a core aspect to blockchain tech AFAIK.

To add to my comment. In Yoroi you can generate a link that you can send to someone else. The other person must use Yoroi too to open the link. The link contains your address and the amount of ADA you request from the other person.
So it would be possible to create some sort of service that transmits this link to someone else. For now you have to manually send the link to someone else.


text:
How can we verify the 45B ada cap cannot be exceeded?
Is there a particular place in code that forbids exceeding this market cap? Should we be constantly keeping an eye on it after IOHK hands off the project to the community? Or is it somehow imbued in the chain's cryptography?

ADA can not be minted due to the parameter name of ADA in ledger and minting transaction validation being followed in Cardano.
In Detail.
Assets in Cardano is called as "Values" in eUTXO. Values can be ADA or any other Native tokens. In this respect, other user minted tokens also have equal status.  Tokens can be minted. Minting of ADA is not possible due to cleaver name settings. ADA was only minted in Genisis transaction and any additional minting is not possible. The reason is as follows.
Value is a Map of CurrencySymbol to a Map of Token Name to Integer. Every asset class is represented by Currency Symbol and Token Name. We cal also say that Asset Class is represented as a combination of CurrencySymbol and Token Name.
The ADA has a Currency Symbol and Token Symbol as empty Byte strings in the Ledger.
Transactions cannot create new assets. In the transaction, the input value has to be equal to the output value plus transaction fees.
We need a minting policy script to mint or burn tokens. The Hash of the minting script is the Currency Symbol.
Since no script Hashes to empty byte string, there is no way a minting transaction that mints ADA can be created.
The implementation in the Plutus repository and has been explained in a much better way in Plutus Pioneer Lecture #5 at around 15 minutes.
https://youtu.be/6VbhY162GQA


text:
How is the 'status' of a transaction shown in the wallet determined?
When you make a transaction with the wallet, the status shown for the transaction goes from Low -> Medium -> High. What does Low, Medium and High signify? How are these statuses calculated?

They mainly signify the number of block confirmations that have occurred since the transaction was sent. Block confirmations are metric used to determine the immutability of an entry(in this case, transaction).
Why is it important? Trust and assurance in a transaction. Different transactions usually require different levels of assurance. For example paying for a cup of coffee probably doesn’t need anything beyond 4-6 block confirmations, it’s coffee. However buying a car could require something like 20-50 confirmations because, well, it’s a car.
Hopefully this helps. More info regarding your question can be found here: https://iohk.zendesk.com/hc/en-us/articles/360033969174-Transaction-Assurance-Security-Level


text:
Are there any C# libraries to connect to a Cardano node/acting as a wrapper for cardano-cli?
There are a few libraries in other languages (Java, JavaScript, ...) that act as an abstraction layer between the Cardano node or the cardano-cli and your own code. I'm looking for a C# library that can do the same.
I found the following 2 libraries:

https://github.com/tugolukov/cardano (built on the old REST API of Daedalus I think)
https://github.com/KanLei/AdaSharp (seems like a rough prototype)

They both haven't been updated in 2 years and to me it doesn't look like they are in a usable state. So are there any other projects to connect to a Cardano node using C#? Or has anybody any experience with making calls to the cardano-cli from C#?

There is a new library called CardanoSharp.Wallet which can be used to generate mnemonics, create private and public keys, create addresses, build transactions and sign transactions.
As of now this seems to be the only C# library out there.

As of now, there is a feature JS library wrapping cardano-cli.
Link: https://github.com/Berry-Pool/cardanocli-js
Kindly refer to https://developers.cardano.org/tools for further information on tools available for developers.
There are plans for developing tools and wrappers for a variety of languages.
I will update this space in case any good community project pops up.


text:
Is there anyway to cancel payment or revert a payment
Recently I came across a situation: a payment was executed by a customer on a site but then the consumer changed his mind.
What levels of transaction revert of such activity can be done?
e.g. X invested a coin into a dubious looking site and now there is no response from the site or site is taken down and site owner disappeared. Now what next can be done?
Can a smart contract react to such situations where I put a timeline for response to revert payment back?

Your question as to what levels of transaction revert of such activity can be done is an a way the question: what provisions should be in a contract for this of business. Although there are plenty of ways to create an appropriate contract, it remains a contract between parties that are expected to handle in good faith. And that may not be necessarily the case with the example you mentioned.
That said: in the case of a ongoing investment on could envision a type of contract which remains active for the whole duration of the investment and which includes a provision for the investor to request a return of the funds, e.g. first into escrow in preparation of a timely return after an agreed period. Of course this assumes that there are funds there to be returned ...

i agree with you. thanks

There is no way to revert a payment. One of the core features of a blockchain is that it is immutable (unchangeable).
As for smart contracts, you could definitely write a script to hold the funds in escrow. This would allow the parties to verify that the goods were passed before the funds are handed over.
This still wouldn't be "revert"ing, but could protect the customer in a similar way.

thanks for response i understand, this will  be interesting if we could figure out over time human error is the biggest error to resolve... may be we can create a system where we have a settlement layer or something similar. may be reach the person using human genome code to find the unique individual :-)

In case the transaction is recorded to the ledger, under no circumstances the funds cannot be returned. A particular case in which funds may not be spent is a CLI command transaction forget. This command allows you to forget a pending transaction for a given wallet.
cardano-wallet transaction forget --port 8090 <WALLET_ID> <TX_ID>

A robust option when communicating with an unknown seller is always to use an escrow smart contract.


text:
Is KES rotation operation time sensitive? Does the datetime of the offline machine need to be set correctly?
Talking about key-gen-KES and issue-op-cert operations of cardano-cli.
Does the output of these functions depends on the machine clock?
They are part of rotating the KES process of which one of the steps if performed on an off-line machine, meaning no NTP time synchronization over the network. And if we combine that we no battery on the off-line machine that we get a date time that is far from current.
Hence my question. Do the KES rotating operation need to be performed on machines that have date and time set correctly? Can the offline machine clock be off by hours? days? months?
   cardano-cli node key-gen-KES \
        --verification-key-file kes.vkey \
        --signing-key-file kes.skey

and
cardano-cli node issue-op-cert \
    --kes-verification-key-file kes.vkey \
    --cold-signing-key-file $HOME/cold-keys/node.skey \
    --operational-certificate-issue-counter $HOME/cold-keys/node.counter \
    --kes-period <startKesPeriod> \
    --out-file node.cert

I did a quick search on the cardano-node Github repo for both
key-gen-KES and issue-op-cert but I am not familiarized with the cardano-node codebase enough to make any sense of it.

The notion of time is based on the input startKesPeriod, which is taken from the most current KES period of the blockchain.
You get the current KES period by dividing current slot number of the blockchain with the slotsPerKESPeriod parameter.
Hope that helps.

Thanks. Yes, obviously but this is an explicit input. I should have been more verbose in my question perhaps as it is the implicit inputs that I am concerned about. Not the explicit ones that users provide themselves. In other words, can you tell if the only datetime reference that is needed for either of these two operations is the kesperiod?

That's a great question. I've done some research, but without fully understanding the code behind cardano-cli, I can't say for sure. Hope someone from IOG will answer this.


text:
Is there a limit on how many distinct tokens can be sent in one transaction?
Let's say someone has 10'000 different tokens on one address. Each token is in a single UTxO. Would it be possible to send them all in one transaction to another address (or the same address), so they are all in one UTxO? Or is there a limit on how many distinct tokens one can send in a single transaction?

The maximum transaction size is specified in the genesis configuration of the chain. For reference, here is a genesis config for the Shelley Testnet.
The maxTxSize is set to 16384 (bytes, I assume).
"maxTxSize": 16384,

So. Yes, there is definitely a limit to how many different tokens you could include in a UTxO.
This doesn't answer the question on limits to the number of inputs for a transaction. Obviously these couldn't result in an output larger than maxTxSize, but I can't say if there are additional constraints on the number of inputs. I'm curious to know so I might keep looking. In the mean time, I hope that helps.

We can simulate this in the playground. I set up three tokens T1,T2 and T3 and gave one of each to Wallet 1 at the beginning.
Then I sent three separate transactions, sending each token in its own transaction to Wallet 2, resulting in 3 new UTxOs in Wallet 2, one for each token.
I then paid all the tokens back to Wallet 1 in a single transaction.
If you zoom in on the image, you can see that there are four inputs, which are the lovelace for fees plus one UTxO for each token. One of the outputs to Wallet 1 is a single UTxO with all three tokens included. The other output is the change given back to Wallet 2 after Lovelace fees are deducted.
As mentioned by Aoaddeola, there should be no theoretical limit to the number of tokens this can scale for.

To the best of my knowledge, there is no limit to the amount of tokens a transaction can contain.
A Value itself has the following Signature Map CurrencySymbol (Map TokenName Integer). Which literarily means an unlimited number of tokens, since Map poses no limit to the amount of elements it can contain.


text:
Does an unmet pledge prevent a pool producing blocks, or only prevent rewards?
If a pool does not meet its pledge, does that prevent it from producing blocks, or only prevent rewards being paid out?

The slots to make a block are pre-scheduled and the pool can make them even if the pledge is not fulfilled - but the pool will not get any rewards.
(It also means that all delegators do not get any rewards)


text:
403 Forbidden when trying to run nix-shell during setup for Plutus Pioneer Program
I've seen other questions similar to this about a 404 error, but this is different.
I have the IOHK Plutus cache set up as per the instructions.
Getting the following error:
trying https://bintray.com/joneshf/generic/download_file?file_path=purty-6.2.0-linux.tar.gz
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
curl: (22) The requested URL returned error: 403 Forbidden
error: cannot download download_file?file_path=purty-6.2.0-linux.tar.gz from any mirror
builder for '/nix/store/g0drypafpyzckkpwzplp9k9amx4bf7a4-download_file?file_path=purty-6.2.0-linux.tar.gz.drv' failed with exit code 1
building '/nix/store/m63hg37ygw5xkjkd429xds19qkffr6m3-easy-file-lib-easy-file-0.2.2-config.drv'...
cannot build derivation '/nix/store/wdgbj9xf3rz44xz5afw20m1ns0n8llpg-purty-6.2.0.drv': 1 dependencies couldn't be built
error: build of '/nix/store/05snx37ayscns4jfqq62v8ignps9izml-plutus-pab-generate-purs.drv', '/nix/store/08hhl408j6anygi2xf33xjdq4ciy2mxp-loch-th-lib-loch-th-0.2.2.drv', .....

I'm running on windows via WSL (Windows Subsystem for Linux) running Ubuntu

Please try the methods given https://cardano.stackexchange.com/questions/413/im-having-issues-with-nix-shell.

Yes, I've already tried those suggestions. Same result

The nix is trying to download from bintry which is outdated. Please update the question with details of your nix installation including version.

Ok thanks! I'll refresh my vm and try again

I'll update the question too

@raghu looks like I built on an incorrect branch initially, that caused problems later. Thanks for your help

So it looks like I initially built on the master branch by mistake. Switching to the correct branch and recompiling didn't help the situation.
I reset my WSL instance of Ubuntu and started again, more carefully this time. Everything worked as it should.


text:
Does Cardano suffer from MEV?
There's a lot of chatter lately in the cryptosphere about Miner Extractable Value (MEV) in Ethereum. As I understand it, MEV is a property of the Ethereum blockchain where miners can (re)order/frontrun transactions when mining blocks to their own advantage. It seems very much like the phenomenon of hedge funds trying to get their servers as geographically close as possible to exchanges in traditional finance.
Does/will Cardano suffer from MEV? If so, why? If not, why not? Is there any talk of preventing the problems of MEV at a protocol level (assuming ADA does/will suffer from the problem)? At a higher level, to UTXO based protocols suffer from MEV?

The simple answer is yes, a Cardano pool operator could front-run a transaction in the mempool to their advantage. They would need to customize the haskell code to allow their node to order the transactions in the mempool as they wanted them.
That being said, there is some risk to the pool operator by doing this. There is a 5% chance that any block made by the pool operator ends up in a slot battle. If they lose that slot battle, their transaction that was supposed to front run would instead be executed AFTER by the other pool which ordered the transactions naturally. This would be exactly what the operator didn't want to have happen.
There's also some natural protection from this because... haskell is hard.

"There's also some natural protection from this because... haskell is hard."
Not sure if your answer is correct but this would just be security by obscurity which would be horrible in a global, decentralized financial system.

Thanks for the great answer! A few followup questions: 1) I assume eventually there will be validators written in languages other than Haskell, right? 2) TIL about slot battles, any chance you have a doc I can read to learn more? 3) Do you know if there's a way at a protocol level to disincentivize MEV?

If you're rigging your local node, you could probably prevent your transaction from being sent to other nodes so it would only be processed in the case you made the block?

There’s a pretty good write-up here:
https://www.reddit.com/r/cardano/comments/n3jkp1/will_cardano_be_a_dark_forest/?utm_source=share&utm_medium=ios_app&utm_name=iossmf


text:
Ouroborous vs Tendermint
What are the relative advantages and disadvantages of Ouroborus (a Proof of Stake system) vs Tendermint (a BFT system)?
Some high level advantages of Tendermint I've seen so far (though I might be totally incorrect) are:

instant finality
faster settlement
lower fees (?)

And some advantages for Ouroborus:

formally verified
built in yield mechanism for validators (through staking)

I'm obviously a total novice here and would love to learn more about the cryptographic, economic, computational, etc properties of both systems and how they compare. I'm especially curious about the relative downside/risks of each system.

This question may not be appropriate for this site in its current form.  It should have a Cardano focus and be specific enough to lead to fact based answers.  General questions such as how does Bitcoin compare to Ethereum are not well handled by any StackExchange site.

Since this is such a broad question, I'll use this answer to collect info/data/ideas as I self educate.
Advantages of Tendermint

fast finality
lower fees
fast settlement
the network and consensus layer is decoupled from the application layer

Disadvantages of Tendermint

deterministic leader election - make DDoS attacks possible
validators much run Sentry nodes which makes the infra harder to maintain (can't run on just a raspberry pi)
Limited validator set (still have to learn more but it seems like there are some restrictions on who can become a validator)
if 1/3 of validators are dishonest, the system breaks
Results in Pareto like capital accumulation

Advantages of Ouroborus

Formally verified
Anyone can be a validator
Validator software can run with just a raspberry pi (which I think isn't possible with Tendermint)
will have an isomorphic layer 2

Disadvantages of Ouroborus

Can't bootstrap without a trusted entity (but I think the new Gensis paper will make PoS bootstrapping possible)
Slower block times
Slower finality
Results in Pareto like capital accumulation

Of course if anyone has more items to add to any of these lists (or has opinions on which should be removed) please comment and let me know!
EDIT: here's an interesting table comparing various PoS systems: https://docs.google.com/spreadsheets/d/1IZhx4Ix9xwFEUZFTihc_MBQcI43TK3jEhBjobhpiZbo/edit#gid=0 (I added a comment to see if we can get ADA included in the list)


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

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

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

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

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

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

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

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

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


text:
Daedalus is crashing my system. What can I do?
I have a problem with the Daedalus wallet crashing my system.
This happenes due to the Daedalus process increasing usage of RAM while trying to connect on startup. The problem started occuring some days ago and persists.
Windows error code is MEMORY_MANAGEMENT.
Didn't reinstall up to now, would be the next try if someone doesn't have another solution.
Thanks a lot!
My system: Windows 10, 8GB RAM, Ryzen 1200.

Do you have your seed phrase safely stored somewhere?

Do you have any other programs running at the same time as Daedalus?

The recommended requirements for Daedalus include:

8 GB of RAM
15 GB of free drive space

Your graphics card will not matter here.
Other processes on your Windows machine will influence how much memory will be left for daedalus, potentially resulting in that MEMORY_MANAGEMENT error. Also run diagnostics on your RAM.
Running daedalus after a fresh restart with little memory allocated to other processes might inform the next steps. That could include a reinstallation of daedalus (make sure you got your wallet info), a windows cleanup/reinstallation, upgrading of RAM and/or move to a different operating system such as Linux.

Thanks, after clearing some space on my harddrive and starting Daedalus right after startup just worked - but still driving the workload on my RAM very close to the maximum. Hard on ressources. Maybe it's time to upgrade! >:)

I installed Daedalus on a small business server, Windows 2012 and 8Gb RAM and nothing else running on the box. I don't run Daedalus continuously. It runs and synchronises, but only just: at peak the cardano-node process consumes nearly 6Gb on is own, with the other Daedalus processes consuming about 25Mb. The OS comes in at about 1.2Gb. I would say that on Windows it needs 10Gb minimum to have a bit of breathing space knowing how it can hog memory ...
I am at the beginning of my journey running cardano nodes and decided to give Daedalus a go on a Window box before moving to Linux.


text:
Are digital assets stored on personal devices or on the blockchain?
I keep my ADA on Daedalus. I keep my seed phrase on a piece of paper, stored somewhere at home. Say the computer where I have Daedalus suddenly dies tomorrow, and becomes inaccessible and irreparable. As long as I have my seed phrase, I would be able to restore my wallet and balance on another computer, right? So, a few questions came to mind:

Are digital assets (coins, native assets, NFTs) stored on the device where a wallet is installed, or on the blockchain?
Do wallets store digital assets, or just private keys (which can be used to prove ownership of an asset)?

Digital assets are stored on the blockchain. Your wallet is a window to the blockchain in that it allows for convenient functionality (e.g. filtering all transactions for transaction where your wallet-connected expenditure address is either receiver or sender).
Currently, Daedalus stores the entirety of the Cardano Blockchain on your device. But altering the data locally (such as past transactions and the digital assets they may hold) does not change the actual data. You can think of the local store of these assets as a cache. However you modify your local cache has no implications for the real world.
Notice that also most digital assets on Cardano currently just include metadata that links to an external resource (such as a Class Photo NFT of the Plutus Pioneers Program's first cohort with the actual data stored via ipfs).


text:
How do I properly derive a stake key from an address using Bech32?
I'm trying to get a stake address from a Shelley address in Python using this library: https://pypi.org/project/bech32/
I can convert an address from bech32 to hex without issue, but I'm getting stuck grabbing the staking part (final 56 bytes) and converting that to Bech32. I keep getting a staking address that doesn't actually exist:

address_words = bech32.bech32_decode("addr1qxdvcswn0exwc2vjfr6u6f6qndfhmk94xjrt5tztpelyk4yg83zn9d4vrrtzs98lcl5u5q6mv7ngmg829xxvy3g5ydls7c76wu")

address_hexlist = bech32.convertbits(address_words[1], 5, 16)

account = ''.join([f'{c:04x}' for c in address_hexlist])[-58:-2]

btr = bytes.fromhex(account)

stake_words = bech32.convertbits(btr, 8, 5)

stakeaddr = bech32.bech32_encode("addr", stake_words)
print(stakeaddr)

Using the above, I get the correct account = 883c4532b6ac18d62814ffc7e9ca035b67a68da0ea298cc24514237f
However, I get the wrong staking address at the end: stake13q7y2v4k4svdv2q5llr7njsrtdn6drdqag5cesj9zs3h7xjwn42
The correct staking address should be: stake1uxyrc3fjk6kp343gznlu06w2qddk0f5d5r4znrxzg52zxlclk0hlq
The annoying thing is, the wrong address I get is the same as what you get trying to use https://slowli.github.io/bech32-buffer/ which makes me think I'm missing something specific that cardano does differently to the bech32 spec.
I can't use the provided bech32.exe binary because it refuses to work (even if it did work, I'd still like to get it working in python).

Great first post, welcome aboard.

Credit to someone on Reddit who helped me with this:
Deriving the staking address requires you to manually update the header byte before bech32 encoding the hex account. All I needed to do was add e1 to the start of the account (1110 0001)

Maybe it is a bit late, but hope it helps.
You can use this python library PyCardano to derive the stake key.
Here is the code example:
>>> from pycardano import Address, Network

>>> addr = Address.from_primitive("addr1qxdvcswn0exwc2vjfr6u6f6qndfhmk94xjrt5tztpelyk4yg83zn9d4vrrtzs98lcl5u5q6mv7ngmg829xxvy3g5ydls7c76wu")
>>> addr2 = Address(staking_part=addr.staking_part, network=Network.MAINNET)
>>> addr2
stake1uxyrc3fjk6kp343gznlu06w2qddk0f5d5r4znrxzg52zxlclk0hlq

We first convert the address string to an Address object, addr. Then we use the staking part of the address to create a new stake address.


text:
How to spend two outputs of two different scripts
I've tried to implement a logic which can spend 2 outputs of 2 different scripts and create 2 new UTxOs:
lookups = Constraints.typedValidatorLookups instance1
          <> Constraints.otherScript script1
          <> Constraints.otherScript script2
          <> Constraints.unspentOutputs (Map.singleton txOutRef1 txOutTx1)
          <> Constraints.unspentOutputs (Map.singleton txOutRef2 txOutTx2)

tx = Constraints.mustPayToTheScript datum1 value1
          <> Constraints.mustSpendScriptOutput txOutRef1 redeemer
          <> Constraints.mustPayToOtherScript (validatorHash script2) (Datum $ PlutusTx.toData datum2) value2
          <> Constraints.mustSpendScriptOutput txOutRef2 redeemer

submitTxConstraintsWith lookups tx

But when I run the code, I'm faced with the error:
WalletError (ValidationError (ScriptFailure (EvaluationError [])))

What am I missing?

Can you also share the validator function for both scripts? One of the scripts is not letting spend the output

I've implemented on-chain function yet. I've implement off-chain first and tested it, so just having a validator return True value. I make sure this issue doesn't come to the validator

If I return false in the validator, the error is validator error message. But when I return true, the error above is presented. It's reason why I think the above error doesn't come from OnChain validator

It definitely looks as if the error happens in validation. Please share the code of both validators you are using - including the types you're using for datum and redeemer for both.


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

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

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

Can someone tell me why is this? Thanks

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

Is your Pi possibly running a 32 bit OS?

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

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

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


text:
plutus starter course
So I am trying to start a plutus project from scratch, as we are always just editing the .hs source files in the plutus pioneering program homeworks, wondering what are the bare necessary files needed in a repo, and how to set these up? ie cabal.project, hie.yaml, .cabal file, etc.
So far I see this starter. Does anyone have any other resources / tutorials that works on this repo? Would it make sense to have a short lecture on this in the future?

I was looking for a template like this when starting a personal project. I'm sure others will appreciate this too.

I asked Lars the same question in the Q&A, his answer was that your best bet is to copy one of the Plutus Pioneer Program lectures (preferably the last one), remove the unnecessary modules and create your own ones.
So the steps would be:

Chose the lecture you prefer (e.g. week06)
Copy the hash tag of this lecture and build the Plutus repository, as you would doing a lecture's homework

$ git checkout 8a20664f00d8f396920385947903761a9a897fe0
$ nix build -f default.nix plutus.haskell.packages.plutus-core

Copy the chosen lecture directory to your environment

$ cp ./plutus-pioneer-program/code/week06/ ./my-environment/

Rename what you want, remove the unnecessary modules (remember to remove it in your cabal file as well) and add your own ones (add it to the cabal file)

Just bear in mind that you may want to keep this framework in tune with the Plutus code by updating the Plutus commit in project.cabal. There is still a lot of flux in the code as we are still pre-life. It might be best to compare the project.cabal with one from a later Pioneer lecture.

Agreed, I mentioned week06, because that was the last one from the second cohort when I posted the answer

Okay but this limits the use case since tag version is lecture-specific. But I guess as @vcwebco mentions this will constantly be changing - would be good to have site where plutus tag->use case is continuously updated. For now, I take cabal.project from plutus-starter as-is and update .cabal depending on whats missing when I run cabal build. Afaik these are the only two files needed to build from scratch.


text:
Plutus Pioneer Week02: otherScript validator
In gift.hs, I do not understand the logic for why in the lookups for the grab contract there is Constraints.otherScript validator. The grabber is the consumer of the UTXO and thus the burden of providing the validator is on him, not the provider. It seems that the other is the provider who by definition does not have a validator.
grab :: forall w s e. AsContractError e => Contract w s e ()
grab = do
   utxos <- utxoAt scrAddress
   let orefs   = fst <$> Map.toList utxos
      lookups  = Constraints.unspentOutputs utxos      <>
                 Constraints.otherScript validator -- ###### THIS LINE #####
      tx :: TxConstraints Void Void
      tx       = mconcat [mustSpendScriptOutput oref $ Redeemer $ I 17 | oref <- orefs]
   ledgerTx <- submitTxConstraintsWith @Void lookups tx
   void $ awaitTxConfirmed $ txId ledgerTx
   logInfo @String $ "collected gifts"

The grabber is the consumer of the UTXO and thus the burden of providing the validator is on him, not the provider.

Correct! And I feel like this might be where your misunderstanding is.
You are right that "the burden of providing the validator" is on the grabber. The grab and give functions are called offchain to construct txs to perform those actions. So the line in question is in fact the code where the grabber "provid[es] the validator."
The Constraits are a way to declaratively specify

What kind of script and UTxOs you want to target with your tx (lookups)
What kind of tx you want to send (tx)

When we include
Constraints.otherScript validator

we are just saying that we want to target our validator with your tx. Or, it might be more accurate to say, we will need our validator in order to perform the tx.

Admittedly the name of the function as well as the documentation doesn't shed too much light on what it's doing:
-- | A script lookups value with a validator script
otherScript :: Validator -> ScriptLookups a
otherScript vl =
    let addr = Address.scriptAddress vl in
    mempty { slOtherScripts = Map.singleton addr vl }

So otherScript really means ourScript? This is very confusing.

That's not quite right. Maybe think of it as adding "another" script to the lookups. You could theoretically include multiple validators if you're spending outputs from different scripts in a single transaction. Remember, validators just check if you are allowed to spend outputs at a script address.

So it seems that in this particular case for grabbing, since there is only one grabber (at a time), there is just one validator. And hence there is no ambiguity in simply stating otherScript because there's just one script out there altogether for this particular transaction.


text:
Daedalus wallet 4.2.0 not syncing
I have a problem with wallet syncing. In fact, the wallet on my imac is not syncing at all. It's not connected to the network. I tried recommendations from a similar post, but nothing worked. I tried to even reinstall the wallet from scratch but it's just not syncing.
When I installed the very same version from the very same installation file on macbook, then there was no problem and the wallet started syncing immediately. But I can't keep the wallet on macbook due to the lack of space.
Any idea why the wallet on imac refuses to sync? It all started with an update to 4.1. version.
Many thanks for your help!


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

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

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


text:
cardano-cli verification key bech32 encoding
In the cardano-cli tool,
it is possible to accept both --payment-verification-key-file and --payment-verification-key when running cardano-cli address key-hash
From the docs, it seems that the --payment-verification-key is supposed to be bech32 encoded.
But it is unclear how that is achieved.
How can I convert from the key-file to the key-string?

So after some experiments, the answer is to
Remove the first 2 bytes (5820) from the cborhex and pipe the output to bech32 with addr_vk
For example
$ cat vkey
{
    "type": "PaymentVerificationKeyShelley_ed25519",
    "description": "Payment Verification Key",
    "cborHex": "5820ba6e94a603da493604a0e0d0e8c4f3465ba299a0d0967a1cafd4c0fa0ab882ad"
}

$ echo "ba6e94a603da493604a0e0d0e8c4f3465ba299a0d0967a1cafd4c0fa0ab882ad" | bech32 addr_vk > vkeystring

$ cardano-cli address key-hash --payment-verification-key $(cat vkeystring)
$ cardano-cli address key-hash --payment-verification-key-file vkey

Both key-hash should be the same.

thank you for the answer! What are the first 2 bytes?

As Alan has already answered this for himself I'd like to add that when using an extended verification key you can produce the non-extended key first and then bech32 encode it to produce the hash.
For example, produce non-extended verification key from extended one:
$ cat acct.vkey
  {
      "type": "PaymentExtendedVerificationKeyShelley_ed25519_bip32",
      "description": "Payment Verification Key",
      "cborHex": "58406d2d6c3e1bf46cfab0977279105a87bb89adb4c6dac3eb25ea2f300ef3e9aa0af720099909a8f7a871db0cb1b2158549cedd2019d60d7ac6c4891bf03cfdc652"
  }
$ cardano-cli key non-extended-key --extended-verification-key-file acct.vkey --verification-key-file acct_short.vkey
$ cat acct_short.vkey
  {
      "type": "PaymentVerificationKeyShelley_ed25519",
      "description": "",
      "cborHex": "58206d2d6c3e1bf46cfab0977279105a87bb89adb4c6dac3eb25ea2f300ef3e9aa0a"
  }

Remove first 2 bytes from non-extended key and produce valid encoded address (bech32 binary is included in wallet release bundle):
$ echo "6d2d6c3e1bf46cfab0977279105a87bb89adb4c6dac3eb25ea2f300ef3e9aa0a" | bech32 addr_vk
  addr_vk1d5kkc0sm73k04vyhwfu3qk58hwy6mdxxmtp7kf029ucqaulf4g9q8d6yzn

Produce key hashes and compare:
$ cardano-cli address key-hash --payment-verification-key addr_vk1d5kkc0sm73k04vyhwfu3qk58hwy6mdxxmtp7kf029ucqaulf4g9q8d6yzn
ad2704179252c6343d8e27708b725656ec30bc8a347dbb42bfd5509a
$ cardano-cli address key-hash --payment-verification-key-file acct.vkey
ad2704179252c6343d8e27708b725656ec30bc8a347dbb42bfd5509a


text:
Can the Validator ensure a certain Datum is sent by the Redeemer?
is it possible for a Validator to ensure that the redeemer pays some Value along with a certain Datum attached to it? Looking at the possible transaction methods on the ScriptContext, checks are only done on the Value and not the Datum. I see the DatumHash types but am not sure what it is used for.

Hope my answer was helpful. I'm not sure if you're overloading the term "Redeemer" (the redeemer data type vs the sender of that tx). I think I got what you were going for though. LMK if I can clarify.

The validator can ensure that a datum or multiple datums are included in the output.
Take the Uniswap clone in the plutus-use-cases for example:
The validateCreate method ensures that an updated Factory datum
Constraints.checkOwnOutputConstraint ctx (OutputConstraint (Factory $ lp : lps) $ unitValue usCoin)

and a new Pool datum
Constraints.checkOwnOutputConstraint ctx (OutputConstraint (Pool lp liquidity) $ valueOf lpCoinA outA <> valueOf lpCoinB outB <> unitValue c)

are included in the outputs.
Both of these are attached to some Value.

Oh gosh I didn't know there was a whole library on On-Chain Constraints. Thank you!
As for the term Redeemer, I believe the language used has been not-strict enough. So to my understanding, the person initiating the transaction is called the Redeemer, and he/she will supply a RedeemerType to the Validator to spend the underlying eUTXO.
Link to the On-Chain constraints library: [https://github.com/input-output-hk/plutus/blob/160d158c2679a72adfc8edf7a1c43a4b59189d99/plutus-ledger/src/Ledger/Constraints/OnChain.hs]

Yeah. The on-chain constraints are great and they compliment the off-chain constraints well. The more declarative the better :)


text:
How to permanently persist an arbitrary hash string in the blockchain?
I have an interesting use case for permanently storing an arbitrary hash string somewhere "reliable" publicly and, very important, with a trustworthy timestamp. For me, this sounds like a case for a blockchain application. As I feel a diffuse kind of sympathy for the Cardano project, i thought "why not start here". Let me explain a bit:
The idea is to create a strong hash (SHA2-256 or the like) of arbitrary data (text files, photos, combinations of these, ...). This part is easy. I don't need a blockchain for that and there are many well established standards for doing this. But now I also want to be able to reliably prove, forever, 'til eternity, that this specific hash existed at a certain time.
My first thought was, well, couldn't I just push this hash to a blockchain somehow? I mean, each transaction has a public timestamp that can't be messed with, right? Does Cardano allow for appending metadata like an arbitrary hash string to a transaction? Should I mint an NFT which holds this data? Then again, wouldn't that be overkill for my use case? What are the technical possibilities I could try to work with, here?
I am a developer, but my insights in blockchain technology are quite rudimentary. So I hope that someone can help me out by pointing me in the right direction. Thank you in advance!

Does Cardano allow for appending metadata like an arbitrary hash string to a transaction?

I believe you can do this without needing any tokens/NFTs by just making a transaction that has the metadata attached:
https://developers.cardano.org/docs/transaction-metadata/
This can be done using the --metadata-json-file switch when building the transaction:
cardano-cli transaction build-raw \
  --tx-in dfb99f8f103e56a856e04e087255dbaf402f3801acb71a6baf423a1054d3ccd5#0 \
  --tx-out $(cat payment.addr)+0 \
  --metadata-json-file metadata.json \
  --fee 0 \
  --out-file tx.draft

https://developers.cardano.org/docs/transaction-metadata/how-to-create-a-metadata-transaction-cli#submit-to-blockchain

This is great. TIL.

It really is! Thanks a lot! I wonder how I could miss this reading through the docs...

I'm sure there is more than one way to do this. Tokens can include metadata and depending on what behavior you want you could structure it different ways.
A couple of options come to mind:

Use the Cardano CLI to add hash string to the metadata of a token
Write a smart contract that owns an NFT with the hash string as data

I would first look at the Cardano CLI and see if creating a simple NFT would be good enough for you needs. It's been a minute since I dug into that stuff, so not positive if it will be enough.
If you wanted to do this with a Plutus smart contract, you could have an NFT containing the data owned by the script. This would allow other people, and in theory other smart contracts, to read the hash.
This could look similar to the Oracle Example from the Plutus Pioneers Program. Yours would be simpler because it wouldn't allow the creator to update the value like an oracle.
Essentially it will allow people to consume the hash data on the NFT as long as they return it in the same state they found it. This could also guarantee that you can always find it at the same place, rather than some NFT that could be transferred to different wallets.
Full discretion, this isn't trivial and you'd need to learn how to write/modify the smart contract as well as deploy it. Not to mention, smart contracts are only available on limited test networks as of writing this.
Hope this helps :)

Thank you for your answer, it was helpful in that it added some good ideas to the case. I think you'll understand I accepted the other answer for it's significantly smaller overhead, though :)


text:
Will Ouroborous work if a nontrivial portion of validators are on the moon?
Will Ouroborous work if a non trivial stake (say 5%) is delegated to validators on the moon? What about mars? How about one of the moons of Jupiter?
If not, why not? If yes, how does the consensus algorithm adapt to messaging delays because of large distances?
If 5% on the moon works, will 20%? What about 50%? If 5% doesn't work, what about 1%? Or 0.1%?
Are there well known theoretical limits of extraplanetary (ie: beyond earth) consensus?

The network protocol functions depend only on the propagation time of blocks with its peers. The physical location of the block producing node have an effect on the propagation delay. Likely propagation delay based on round trip time with locations mentioned in the questions are

Moon   - 3000ms
Mars   - 40 minutes.
Jupiter - 1 Hour and 50 minutes.

The recommended propagation delay for block producing node is less than 200 ms for the blocks to be accepted in the chain. Time synchronization with peers with such large dead time is not possible online.
The above is a shallow reason. Deep theoretical reason may come from an expert in  Ouroborous.

Amazing answer, thank you! Any chance you can link to a source claiming the 200ms propagation delay requirement?


text:
How can I check if my node is fully synced?
How can I check if my node is fully synced without resorting to
https://explorer.cardano-testnet.iohkdev.io/ ?

You can use a remote API such as blockfrost.io.

Since cardano-cli version 1.28.0, the syncProgress can be checked directly:

$ cardano-cli query tip --testnet-magic 2

{
    "epoch": 234,
    "hash": "f9eb71ac5de435b1e5c53d691cb03a4242c9cdc13f7782738e9a727a6a60aa73",
    "slot": 1684260,
    "block": 82557,
    "era": "Alonzo",
    "syncProgress": "100.00"
}

For future noobs (like me): to get the above response, enter the following your terminal:
cardano-cli query tip --testnet-magic 1097911063
(the testnet-magic number might have to be updated)


text:
Daedalus wallet recovery phrase to Cardano Wallet Backend mnemonic sentence + mnemonic second factor
Daedalus wallet recovery phrase is 24 words. Cardano Wallet Backend mnemonic sentence is 15 words and mnemonic second factor is 9 words, adding up to 24 words.
I tried restoring a wallet through Cardano Wallet Backend API by taking the first 15 words of the Daedalus wallet recovery phrase as an input for mnemonic_sentence and rest of the 9 words as an input for mnemonic_second_factor. Unfortunately, this does not work as the last word of the mnemonic_sentence produces an incorrect checksum.
Is there a way I can restore a wallet through the API knowing a Daedalus wallet recovery phrase?

The mnemonic_sentence can be between 15 and 24 words. The mnemonic_second_factor is optional. So you can simply pass all your 24 words in as mnemonic_sentence and don't set the mnemonic_second_factor and you should be able to restore your wallet.

Source: https://input-output-hk.github.io/cardano-wallet/api/edge/#operation/postWallet

I've tried this as well but using 15 words & I keep getting wallet_already_exists error. Does this mean I can't restore a wallet that was created by the cardano-wallet server in the past?


text:
Installing nix: where is shell profile - MacOS using zsh?
I am trying to install nix on my local iMac. I am following the following Guide to do that.  After executing
sh <(curl -L https://nixos.org/nix/install) --darwin-use-unencrypted-nix-store-volume

I get "Installing finished!" and I am requested to add the line:
. /Users/joeblogs/.nix-profile/etc/profile.d/nix.sh

"to your shell profile (e.g. ~/.profile)."
I am using a Mac (with zsh) and so what file is this shell profile referring to? For instance, i do not have a ~/.profile.

You'd have an easier time installing on a Linux machine. Try Linux mint.

So the following worked. Go to the following file:
/etc/zprofile

and add the following line:
. /Users/thanhdanhphan/.nix-profile/etc/profile.d/nix.sh

Close all your terminals and re-open a new one, try:
nix --version

and it should give you the latest nix version e.g (at the time of writing):
nix (Nix) 2.3.14

I had the same problem.  Try creating a file named .bash_profile in your user directory (/Users/joblogs/.bash_profile) and add the given line as it is written.  Restart the terminal and give it a go.

this does't work, maybe because i am using zsh


text:
illegal symbol `forall` in type, RankNTypes
I am trying to build Future.hs from plutus-use-case from scratch. I take two files from plutus-starter: cabal.project as is, and plutus-starter.cabal that I have to edit according to the imports in Future.hs. I get however these errors when I run cabal build:
src/Plutus/Contracts/Future.hs:574:8: error:
    Illegal symbol `forall' in type
    Perhaps you intended to use RankNTypes or a similar language
    extension to enable explicit-forall syntax: forall <tvs>. <type>

I also had to add several other modules e.g. Plutus.Contracts.Currency and for every .hs file with forall, do I have to add {-# LANGUAGE RankNTypes #-}?

Yes, the LANGUAGE pragmas are required, best practice is probably following Plutus code examples and having separate pragmas per-file as needed.
It is also possible to allow some extensions globally via .cabal file by using default-extensions, e.g.:
library
 default-extensions:
   DataKinds
   RankNTypes

but this should be done with care and can bite later as some extensions are not compatible.
Also instead of adding files locally, try adding plutus-use-cases to the list of your dependencies, then you can import Plutus.Contracts.Currency.

I never thought of adding plutus-use-cases thats helpful!


text:
Between the cardano-graphql and cardano-rosetta APIs, which one is recommended for apps and dapps integration?
From what I understand, cardano-graphql as well as cardano-rosetta APIs enable interaction with the Cardano blockchain. Which of these is recommended for developing apps/dapps that interact with Cardano? Will the Rosetta API be a more comprehensive solution given rosetta is a blockchain specific standard?

It really depends on your dApp.
Cardano Rosetta is build by and for exchanges and Cardano GraphQL is more universal.
Review both APIs to make the best decision.

You can also add Ogmios to the mix, as it's more reliable than Cardano GraphQL for some things, like submitting transactions.


text:
Metadata value limits (64 UTF bytes) - Use Arrays ? NFT image question
I'm currently setting up my minting software and noticed I get the error when assigning a CIDv1 hash as the image (CIDv0 works fine - it just fits)"Text string metadata value must consist of at most 64 UTF8 bytes"
I also noticed that someone got around this by splitting it up into a list of less than 64 bytes each.
eg.
{...image: [ "lessthan64string-0", "lessthan64string-1", "lessthan64string-2", "lessthan64string-3" ]...}
= lessthan64string-0lessthan64string-1lessthan64string-2lessthan64string-3
This seems very off standard for a NFT or am I wrong. Obviously you can recreate the string by joining, but I wouldn't think the chances of market places doing that is big.
I've had a look at - https://github.com/cardano-foundation/CIPs/pull/85, but I'm not sure about it.
If anyone could point me the the direction of what is the proper way to di this - It would be muchly appreciated
Thanks for your time
FYI: the reason for the CIDv1 is I am using https://nft.storage/ (as well as pinata) and I want the 2 hashes to match for longevity of the NFT for the images and they seem to only support CIDv1 - and it's going to have to be supported at some stage. The filecoin (nft.storage) one will be used as a backup

I would store the CIDv0 in the metadata. You should be able to convert from v1 to v0 if it's using v1 protocol buffer codec.
# If this outputs "protobuf" we can be reasonably certain we can convert
ipfs cid format -f "%c" -b base58btc bafybeiccuppnh2nh54jtubqo2jjmngzlnnmliejjq3xlswxzh24et2llu4
# Convert our CIDv1 to CIDv0 (returns "QmSpnYb3romJejsUqhRepYr6GBwuKUFj1kqrhtk1z2Hn8E")
ipfs cid format -f "%M" -b base58btc bafybeiccuppnh2nh54jtubqo2jjmngzlnnmliejjq3xlswxzh24et2llu4

Source: https://discuss.ipfs.io/t/make-cidv0-from-cidv1-using-cid-ipfs-io/10647/2

Thanks for the comment - I'll see what I can do :-)

Storing the longer image url as an array is also in-line with the CIP standard. If you use CIDv1 and store it as an ipfs url split in two, it should work and is supported by pool.pm and other NFT viewers out there.

@AndrewWestberg-BCSH can you elaborate on this pls? how is this done?

@rx2347 To store it as an array, just do
"image": [ "first part of the url", "second part of the url"]

@AndrewWestberg-BCSH so I just split the url string at a random character? thats so weird...

@rx2347 as long as each part is less than 64 chars, anybody implementing the NFT metadata spec just concatenates them together.


text:
I couldn't find the requested endpoint
When I try to construct a transaction by following the Cardano Wallet Backend API (v2021-06-11) (Transaction New section) by writing this code in TypeScript:
const resp: Response = await fetch(`http://localhost:1338/v2/wallets/${senderWalletId}/transactions-construct`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            payments: {
                address: sendToWalletAdress,
                amount: {
                    quantity: tADAToSend,
                    unit: "lovelace"
                }

            },
        })
    });

I got this response:
{
  message: "I couldn't find the requested endpoint. If the endpoint contains path parameters, please ensure they are well-formed, otherwise I won't be able to route them correctly.",
  code: 'not_found'
}

Is transactions-construct not yet implemented or am I doing something wrong?

Is the senderWalletId correctly formatted?

Yes, but it doesn't even get to that point because /transactions-construct part does not exist

The support for transactions-construct has been added just some days ago and is not released yet.


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

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

The tool in question is cardano-db-sync.


text:
Plutus tutorial similar to Ethereums "CryptoZombies"
Is anyone aware of a similar tutorial as Ethereum's "CryptoZombies" being built for Plutus on Cardano? I'm currently in the Pioneer program, and although we're incredibly lucky to have Lars as an instructor, it is much easier to scale a programming language learning curve through repetition and "DIY" (Lars even says this for himself). I found learning the initial foundations of Solidity through the "CryptoZombie" tutorial to be an EXCELLENT way to grasp the syntax and rudimentary design patterns to create smart contracts for Ethereum
A similar learning mechanism for Plutus would bring thousands of developers from the imperative language space into Cardano's ecosystem at scale

+1 Welcome to our community! However "Is anyone aware of a similar tutorial as Ethereum's "CryptoZombies" being built for Plutus on Cardano?" is not a very specific question, so I'm just warning that if you don't make some improvements to the question you might get canned by others (not me).

I am sure there is nothing like that at the moment. I would love to see this.

I don't believe anything like this exists yet. We're still a nascent community.
A tutorial like CryptoZombies would definitely be useful and well received, but I will point out that Plutus is still evolving quickly, and I think that is a big reason the PPP is being run the way it is (instead of a static course).
Open-sourcing a course like CryptoZombies might be a great way to go, since Plutus knowledge is still very disperse. I'm sure there are many developers that would pitch in, but it might be too early for it to be worth the upkeep.


text:
Is there any keyword to get the epoch details or stake-pool details in Plutus Smart Contract?
I am trying to write a smart contract where I can get the awards for delegators of a particular stake pool. I need to know if that is right now possible to do using Plutus, if yes, pls suggest me.

Hey Kuldeep. Welcome to the forum! I made an attempt to answer your questions, but I think I and the other contributors could answer better if you would be more specific with the type of epoch and stake-pool details you are looking for.

Okay. I think you are asking a couple different questions:

Is there any keyword to get the epoch details or stake-pool details in Plutus Smart Contract?

It really depends on what information you need. There are ways for a script to validate certain information about an epoch, e.g. check that the current slot is within a defined epoch.
For example, to check if you are past a deadline in a validator:
from slot `contains` posixTimeRangeToSlotRange (txInfoValidRange (scriptContextTxInfo ctx))

will return True if the transaction takes place after a specified slot. And there are ways to convert an epoch to a slot.
There is also limited staking information in the transaction context.

I am trying to write a smart contract where I can get the awards for delegators of a particular stake pool. I need to know if that is right now possible to do using Plutus

A smart contract can't withdraw awards on behalf of other delegators. The awarded ADA will be only be withdrawable by the wallets that have delegated the funds.
However, it is possible for a script to delegate its own funds. So, depending on the behavior you want, you could have a smart contract delegate on behalf of other delegators and get a similar behavior.
Hope that helps :)

Sorry if the question was put in a confusing way. Is there any way we can know how much a particular delegator earned (ADA) in an epoch from a particular staking pool. This is to be done using Plutus SC. I hope to be clearer this time.


text:
Staking functionality for Native Tokens?
Is it possible to have staking or reward functionalities, maybe minting, with your Native Tokens in Cardano?

This is not a native functionality on the Cardano blockchain. However, this will for sure be possible with a custom smart contract after the Alonzo release.
This form of "staking" would not require a staking-pool and would not produce any blocks or get rewards. It would be an independent system build by you with your own custom rules running on the Cardano blockchain.

To make my question now more specific: https://cardano.stackexchange.com/questions/2253/should-i-hold-ada-as-company-to-pay-fees-and-issue-native-tokens-for-my-game

No, that would be very bad for the platform, if any staking reward mechanisms on protocol are done based on native tokens which cost few seconds to mint and burn with no tangible outcomes, as they do not represent stake on cardano.
Having said that projects can certainly devise incentives based on history of holder, but such rules will not be at protocol level, possibly only at contract level or off-chain

To make my question now more specific: https://cardano.stackexchange.com/questions/2253/should-i-hold-ada-as-company-to-pay-fees-and-issue-native-tokens-for-my-game


text:
Plutus Pioneer Week 2 Smart Contracts
Do I need to run the cabal build for all the weekly modules? Will it do the following for all of the modules? Please confirm.
In order, the following will be built (use -v for more details):
 - plutus-core-0.1.0.0 (lib) (requires build)
 - plutus-tx-0.1.0.0 (lib) (requires build)
 - plutus-tx-plugin-0.1.0.0 (lib) (requires build)
 - plutus-ledger-api-0.1.0.0 (lib) (requires build)
 - cardano-ledger-alonzo-0.1.0.0 (lib) (requires build)
 - ouroboros-consensus-shelley-0.1.0.0 (lib) (requires build)
 - ouroboros-consensus-cardano-0.1.0.0 (lib) (requires build)
 - cardano-api-1.27.0 (lib) (requires build)
 - plutus-ledger-0.1.0.0 (lib) (requires build)
 - plutus-chain-index-0.1.0.0 (lib) (requires build)
 - plutus-contract-0.1.0.0 (lib) (requires build)
 - playground-common-0.1.0.0 (lib) (requires build)
 - plutus-pioneer-program-week02-0.1.0.0 (lib) (first run)
Starting     plutus-core-0.1.0.0 (lib)
Building     plutus-core-0.1.0.0 (lib)
Installing   plutus-core-0.1.0.0 (lib)
Completed    plutus-core-0.1.0.0 (lib)
Starting     plutus-tx-0.1.0.0 (lib)
Building     plutus-tx-0.1.0.0 (lib)
Installing   plutus-tx-0.1.0.0 (lib)
Completed    plutus-tx-0.1.0.0 (lib)
Starting     plutus-tx-plugin-0.1.0.0 (lib)
Starting     plutus-ledger-api-0.1.0.0 (lib)
Building     plutus-ledger-api-0.1.0.0 (lib)
Building     plutus-tx-plugin-0.1.0.0 (lib)
Installing   plutus-ledger-api-0.1.0.0 (lib)
Installing   plutus-tx-plugin-0.1.0.0 (lib)
Completed    plutus-tx-plugin-0.1.0.0 (lib)
Completed    plutus-ledger-api-0.1.0.0 (lib)
Starting     cardano-ledger-alonzo-0.1.0.0 (lib)
Building     cardano-ledger-alonzo-0.1.0.0 (lib)

Yes we need to run cabal build for all weekly modules to build it. It will download the packages which seems a repetitive process.

You can also use the Plutus Playground as well, which I personally found easier.

All the weekly modules need an update as they use the latest (and thus different) Plutus commits. I wouldn't know the exact files that require rebuilding as I use nix-shell followed by cabal and so update and rebuild is all done seamlessly.
The reason that such frequent updates are required is that there is still a lot of change taking place in the Plutus code base. This is expected to change once Plutus has gone live (September) and there is a stable live version.


text:
Should I hold ADA as company to pay fees and issue Native Tokens for my game?
As far I know Carano will allow to pay fees in Native Tokens, so fees will be on ADA + a reward. But I have questions about it after reading this blog post from IOHK.
If I'm running the economy of my game, for instance as premium currency Gems with ticker GEMS let's have in mind these transactions:
t1. Player buys GEMS in-game, so will pay 1.45$ for 1$ worth GEMS + Apple/Google commissions + blockchain fees.

Q1. Either including an external payment system or validating Apple/Google transaction, Where is coming the liquidity? Me, as Company, should I hold a bag of ADA to pay fees and issue the equivalent in GEMS?
Q2. How a staking pool decide to accept which Native Tokens?
Q3. Is the staking pool nodes getting ADA + GEMS with every transaction?

Thanks for the help!

What exactly do you mean with "pay fees in Native Tokens"? Are you referring to the transaction fees?

Yes, not sure if I understand it properly, you pay transaction fees in ADA and... you also send your native token to the pool?

Stake-pools don't do anything with native tokens. Everything a stake-pool does is done with ADA. ADA is delegated to the pool and rewards are paid in ADA. It's not possible to delegate native tokens to a stake-pool.

alright! thanks a lot

This blog post is (to my understanding) just a thought experiment. I haven't heard of any plans for Cardano to support something like the "Babel fees" described in the blog post.

Q1: In order to send some native tokens to another wallet, you need to have your own wallet with the native tokens and some ADA to cover transaction fees. There is a minimum amount of ADA that needs to be sent together with any native tokens (currently ~1.4 ADA). This amount will be transferred to the wallet of the player who buys your GEMS. Then you also have to cover the transaction fee of ~0.17 ADA.
Q2: There is no such feature in stake-pools as of now and to my best knowledge it is not planned to have such a feature. There are projects that do something called an ISO (initial stake pool offering). A company creates a stake-pool and takes all rewards as fees. Then they send some of their native tokens (e.g. GEMS) to the people who delegated their ADA to the pool. But this is not what you want I think.
Q3: No, stake-pools only receive rewards in ADA.


text:
How do I get my Native Token listed on an exchange?
What does it require to be able to list my Native Token in exchanges, so that users of my ecosystem can buy it?

This is a very broad question. In general any centralized exchange (Binance, Coinbase, ...) has strict screening and a process through which the issuers would be required to showcase the viability of the token and their business model. Not an easy task to get your coin listed for sure.
Listing a token on a DEX (decentralized exchange) on the other hand is pretty easy. Uniswap for example allows to trade any token by importing them. However, there needs to be someone that provides liquidity for your token against another token, otherwise it won't be tradeable.
Cardano currently doesn't have any DEX, but there are a few projects in the making that should launch shortly after Alonzo has been released.


text:
Cardano Development
I am a software developer. I wanted to learn Cardano development so for that where should I start and what technologies are required?

A great place to start is https://developers.cardano.org/.
The page provides a good overview about all Cardano development related topics.
Another great place to get started and learn is the cardano forum: https://forum.cardano.org/
And of course this StackExchange site.

You can join reddit channel for Cardano developers. You can also try to join the Plutus Pioneer Program but Haskell is must for it.


text:
Running Cardano Docker Node
I am working on running the Cardano Node with Docker. I Got it working (running cardano-cli version 1.27.0) but when i execute the following command cardano-cli query tip --mainnet I expect a block result in the era "shelley" bit it shows me I am in the "Byron" era. The epoch parameters returns 'null' instead of a value

How long did you wait before you run the query tip command after starting the node? Your local blockchain first needs to synchronize (download all the blocks). This happens in the order the blocks were produced and can last for several hours.

I waited about 10 seconds. After that it was loaded I think. Do I need to wait longer?

Yes, see my answer.

The behavior you describe is expected. After starting the Docker container, the cardano node will start downloading the whole blockchain. Depending on your system and internet connection it can take several hours to download the whole blockchain.
While the node downloads the blockchain, you can use the cardano-cli query tip --mainnet command to check on the progress. You can compare the current slot of your node with the latest slot (see https://explorer.cardano.org/) to see how much of the blockchain you already downloaded.
As soon as your node has downloaded the whole blockchain you can start to create transactions etc.

This explains it all! I see the block numbers are counting up so the download is working. The next time I run my node again I only have to download the remaining blocks and not the blockchain all over again?

Depends on where you stored the blockchain. Usually it should be stored in a mounted volume that is used by the docker container and is persisted on your drive. In that case you can continue where you left off. If you stored the blockchain data inside of the container, it is probably gone. A volume is mounted by using the -v argument of the docker run command.


text:
How to query cardano-graphql API to get the details of a transaction with the transaction id?
I am looking for a GraphQL query that will return transaction details as seen on the Cardano Blockchain Explorer when searched with txId.
For example,
https://explorer.cardano.org/en/transaction?id=f58152cafbd25e618433eae52f72bb419e00efe91b5cf7c74a93f8c29cbb2e7b
Can anyone provide a sample query which can also be tested on the Dandelion GraphQL playground?

Just came across this example on GitHub that aggregates inputs and outputs of a transaction.   https://github.com/input-output-hk/cardano-graphql/blob/master/packages/api-cardano-db-hasura/src/example_queries/transactions/aggregateDataWithinTransaction.graphql Could there be a more comprehensive query?

This is not related to GraphQL query, but if this could help you get the txn info https://github.com/input-output-hk/cardano-db-sync/blob/master/doc/interesting-queries.md#get-the-reward-history-for-a-specified-stake-address

To check exact query as explorer for GraphQL - in your browser, when viewing page from explorer - you can check Developer Tools > Network (tab). In the list, look for graphql POST requests where variable is your transaction ID - you would see the graphql query in Request Payload.
Thus, for the mentioned link in example , you'd see the request is:
{"query":"query searchById($id: Hash32Hex!) {\n  blocks(where: {hash: {_eq: $id}}) {\n    ...BlockDetails\n  }\n  transactions(where: {hash: {_eq: $id}}) {\n    ...TransactionDetails\n  }\n}\n\nfragment BlockDetails on Block {\n  ...BlockOverview\n  nextBlock {\n    hash\n    number\n  }\n  previousBlock {\n    hash\n    number\n  }\n  transactions(limit: 10, order_by: {fee: desc}) {\n    ...TransactionDetails\n  }\n}\n\nfragment BlockOverview on Block {\n  forgedAt\n  slotLeader {\n    description\n  }\n  epochNo\n  hash\n  number\n  size\n  slotNo\n  transactions_aggregate {\n    aggregate {\n      count\n      sum {\n        totalOutput\n      }\n    }\n  }\n}\n\nfragment TransactionDetails on Transaction {\n  block {\n    epochNo\n    hash\n    number\n    slotNo\n  }\n  deposit\n  fee\n  hash\n  includedAt\n  mint {\n    asset {\n      assetName\n      decimals\n      description\n      fingerprint\n      name\n      policyId\n      ticker\n    }\n    quantity\n  }\n  inputs {\n    address\n    sourceTxHash\n    sourceTxIndex\n    value\n    tokens {\n      asset {\n        assetName\n        decimals\n        description\n        fingerprint\n        name\n        policyId\n        ticker\n      }\n      quantity\n    }\n  }\n  metadata {\n    key\n    value\n  }\n  outputs {\n    address\n    index\n    value\n    tokens {\n      asset {\n        assetName\n        decimals\n        description\n        fingerprint\n        name\n        policyId\n        ticker\n      }\n      quantity\n    }\n  }\n  totalOutput\n  withdrawals {\n    address\n    amount\n  }\n}\n","variables":{"id":"f58152cafbd25e618433eae52f72bb419e00efe91b5cf7c74a93f8c29cbb2e7b"}}

Note that this is ofcourse a request payload sent to graphql endpoint, you can substitute \n and use/replace variable(s) as desired


text:
Are transaction fee's paid similarly to Bitcoin?
I understand the current staking rewards are a stepping stone to decentralization i.e. by incentivizing users to stake and pools to be set up to secure the Cardano blockchain with the left over Ada similar to the way miners are currently incentivized in Bitcoin with the remaining Btc and in both cases will transition to just Tx fee's in the future.
Currently most staking pools average out to around 5% rewards (equivalent to block reward in Btc). In Bitcoin though the transaction fee's are bundled with the reward and distributed to mining pools. Mining pools then have their own structure on how to distribute those fee's to miners with some distributing all to some keeping those fee's to themselves.
Once smart contracts are live with Cardano and fee's are being paid is the structure similar? Will staking pools have their own transaction fee payout structure? And if so will the busier the network equate to higher the staking rewards?

Once smart contracts are live with Cardano and fee's are being paid is the structure similar?

There are already fees today that have to be paid with every transaction. But there will probably be more transactions and therefore more fees when smart contracts are enabled with the Alonzo hard fork.
That being said, a stake-pool in Cardano works differently than a Bitcoin stake-pool. A Bitcoin stake pool usually lets miners connect to the pool and then everybody tries to find the right nonce for the same block. All the rewards go to the owners of the pool because they own the Bitcoin node that will submit the block when one of the miners has found it.
The proof of stake mechanism on Cardano doesn't require miners. A stake pool is just a single node that produces blocks when it is assigned a block by the network. No race for beeing the fastest to brute force some random number. As an ADA holder you can choose to delegate your ADA to one of the pools. The more ADA is delegated to one pool, the higher the chance that this pool will get a block assigned.
When a Cardano stake pool produces a block, it gets rewards. The rewards consist of the "remaining ADA" and the transaction fees of the transactions in this block. The rewards for this block are distributed among the wallets that are staking with this pool automatically. The pool owner can decide how big of a cut (fixed cost + margin fee) they will keep for themselves. The rest of the rewards are distributed among the delegators according to the size of their stake. This is all done as part of the Cardano protocol and the stake pool operator doesn't have control over the rewards of their delegators.

Will staking pools have their own transaction fee payout structure?

Some pools take 100% of the rewards. Those are called private pools. Binance runs pools like that for the people who want to stake directly from their exchange. The rewards then get distributed by Binance themselves to the accounts of their customers.
There are projects that do something called an ISO (initial stake pool offering) where they take 100% of the rewards and in return pay their delegators in some other token.

And if so will the busier the network equate to higher the staking rewards?

Yes. The more transaction fees a block contains, the higher the rewards.

Perfect answer thank you. I also didn't realize Binance "played middle man" with their stake pool.


text:
Understanding do notation with Monads in Plutus Pioneer Week 04
I have a question regarding a block of code from th Week04 Plutus Pioneer Program.  The block is in Writer.hs
foo'' :: Writer Int -> Writer Int -> Writer Int -> Writer Int
foo'' x y z = do
    s <- threeInts x y z
    tell ["sum: " ++ show s]
    return s

For reference,
threeInts :: Monad m => m Int -> m Int -> m Int -> m Int
threeInts mx my mz =
mx >>= \k ->
my >>= \l ->
mz >>= \m ->
let s = k + l + m in return s

tell :: [String] -> Writer ()
tell = Writer ()

instance Monad Writer where
    return a = Writer a []

number :: Int -> Writer Int
number n = Writer n $ ["number: " ++ show n]

Why does
foo'' (number 2) (number 3) (number 4)

return
Writer 9 ["number: 2","number: 3","number: 4","sum: 9"]

and not
Writer 9 []

Obviously there are holes in my understanding, but I read the do block as follows:

The result of threeInts x y z is Writer 9 ["number: 2","number: 3","number: 4"]
9 is extracted from this to the definition s
tell ["sum: " ++ show s] results in Writer () ["sum: 9"]
return s results in Writer 9 []

I know that return in Haskell is not the same as it is in an imperative language, but I'm failing miserably to grok how to read this block effectively.  The lambda version producing the same result is more explicit and makes sense to me.
bindWriter :: Writer a -> (a -> Writer b) -> Writer b
bindWriter (Writer a xs) f =
  let
    Writer b ys = f a
  in
    Writer b $ xs ++ ys

foo' :: Writer Int -> Writer Int -> Writer Int -> Writer Int
foo' x y z = x `bindWriter` \k ->
             y `bindWriter` \l ->
             z `bindWriter` \m ->
             let s = k + l + m
             in tell ["sum: " ++ show s] `bindWriter` \_ ->
                Writer s []

I read this backwards where (for my concrete example) Writer 9 [] is bound/combined with Writer () ["sum: 9"] which is then bound/combined with Writer 4 ["number: 4"], Writer 3 ["number: 3"] and Writer 2 ["number: 2"] where the Int values are discarded in the bind process and the "logs" are concatenated.
There is something implicit in the do notation that I'm overlooking or not reading correctly.  Any help appreciated.

The 'secret' is in the bindWriter function that drive the Writer monad.
instance Monad Writer where
    return a = Writer a []
    (>>=) = bindWriter

It is the bindWriter function that aggregates the string list of the Writers and this happens as part of the execution of the do block which is a list of monadic statements.
For instance, comment out the tell line and the do block in foo'' returns
Writer 9 ["number: 2","number: 3","number: 4"]

Rewriting the do block to
foo'' x y z = do
     threeInts x y z

returns the same result. Without return the do block returns the result of the last line (and the compiler complains when it isn't of the right type).
Adding a Writer line returns the Int from the Writer, but the full list of strings:
foo'' x y z = do
     threeInts x y z
     Writer 0 ["adding 0"]

return
Writer 0 ["number: 1","number: 2","number: 3","adding 0"]

The tell function causes a string list to be added ignoring the Int part. The threeInts result needs to be captured because it contains the Int result that needs to be returned (and the tell line needs it for the text line).
This monad allows the writing of functions that operate on the Ints and that can emit appropriate messages that are handled in the background.

This is what I was missing.  Much appreciated!


text:
What is the purpose of the Yoroi connector for dapps integration?
Based on my understanding of Cardano I would guess that the connector will serve much the same purpose at MetaMask. To allow Cardano dapps to connect with and use the funds in your Yoroi wallet. Is my understanding correct?

Yes.
The dApp connector code will inject a JavaScript object into the webpage that can be used to interact with the Yoroi wallet.
There is already a third party wallet that implements this and can be used on the mainnet. See: https://namiwallet.io


text:
Where is stored off-chain code?
As I understand, a smart contract in Cardano contains on-chain code and off-chain code.

On-chain code is executed by cardano nodes in order to validate transaction.
Off-chain code builds a transaction in the user wallet then submit it to the blockchain.

On-chain code is stored in the blockchain, but what about off-chain code if this is executed on user wallet. Where is this code stored?
I guess is in the blockchain too, but how does the user wallet get it?

I guess [the off-chain code] is in the blockchain too[?]

No. Actually. They mean it when they call it "off-chain" :).
Background:
Generally speaking, you want to minimize the amount of code you put on-chain because that code is expensive. For Plutus smart contracts, the role of on-chain code is simply to look at a transaction and say "yes" or "no".
There are two uses for the off-chain code:

Compile and submit the on-chain scripts
Create transactions that will be validated by the on-chain scripts

But as I mention in this other question's answer, there is nothing keeping someone from writing their own off-chain code to interact with the on-chain script. This is important for a smart-contract writer to understand when thinking about the security of the on-chain validation.
Answer:

Where is stored off-chain code?

There is nothing binding the on-chain code to a singular off-chain code. So there is no correct answer.

How does the user wallet get it?

From what I understand, there will be options. It could be stored in a repo by the SC writer where you could download it, or perhaps hosted on a website where your wallet can access it (similar to how Metamask works on Uniswap or other Ethereum sites), or you could write it yourself in an attempt to exploit the contract.
As a SC creator, it will be your responsibility to make your off-chain code available to consumers so they can interact with your contract in your intended way.

Also, I imagine a central repository similar to what we have for tokens metadata will be ran by the Cardano Foundation.

This. I imagine at some point there could be a dApp browser of sorts. As we’ve seen with the Plutus Playground, the endpoints interface can be used auto-generate a UI. This could help lower the barrier to entry for dApp writers so they don’t need to build a UI themselves. If you can get your SC onto the registry then anyone can find it and use it.