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

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

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

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

Thanks, Myles

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


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

You need to subtract the fee from $receiver_output.

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

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

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

receiver_output is balance of utxo spent in txin.

source: Stack Exchange

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

sort: votes


text:
cardano-db-sync table link diagram?
Is a diagram showing cardano-db-sync table links available?
i'm aware of the schema.md file, was after something more visual.

There is an Entity Relationship Diagram (ERD) here

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


text:
How should you properly mint multiple NFTs under same policy?
The minting guide say that you should set the policy to expire after certain slot to make sure that nobody can mint more of the same NFT. This kind of makes sense, but then how can you reuse the same policy to mint more of different NFTs?
I saw that most NFT projects share same policy ID, which makes perfect sense, you can verify that NFT really belongs to that same project and isn't forgery, but does it mean these projects didn't set expiry in their policy? Because if they did, how can they keep minting more and more NFTs over time and add them to their collection? What prevents them from adding two identical NFTs?

Can you give some examples? I don't think most projects will use the same policy ID, because it loses the meaning of NFT. If you see that a project is keeping minting, it should use different policy IDs, but just register all policy IDs here as the same project.

If a project has thousands of NFTs, the same policy will be used, but the NFTs will have unique names, and they will be unique (non fungible).
The purpose for the multiple policies in that list is to allow the policies to be time locked, so that the NFTs can be really unique (because the policy owned can still mint new NFTs with the same policy and the same name as long as the policy is not locked).

But they still want to be able to mint new NFTs with the same "Project ID", because registering a project on that github repository takes weeks, and this is why they register in a project multiple polict IDs with different timelock dates.

@George-APEXStakePool, you mentioned registering a project on github.  Can you say more about this, please? I'm planning an NFT campaign and am not aware of registering anything.  Thanks much

I think I found it.  Just leaving this here for posterity. https://github.com/Cardano-NFTs/policyIDs

Yes, that's the one.

You are right, some people consider a NFT being a real NFT only after the policy expires, so that you can be sure it is unique.
You can also mint multiple NFTs with one policy in one transaction.

OK, so that means most of current popular NFT projects don't do it right, because their policy doesn't seem to expire? (they keep minting more and more NFTs under same policy)

There are a couple different ways minters are doing this. First is they create a policy ID that expires 6-12 months in the future. This allows them to mint multiple collections under the same ID but the ID DOES eventually lock. As long as the ID locks at some point in the future, Pool.pm shows a lock icon.
Other artists choose to permanently have their ID unlocked. This allows them to mint collections under the same ID anytime in the future. As you noted, this makes it somewhat simpler for buyers to associate NFTs with the single ID, however, secondary marketplaces these days make it pretty straight forward to confirm NFTs are authentic even with multiple IDs so it's not a huge advantage.
The other reason an artist might choose to keep the ID open is if the NFT has future utility, such as workbench functionality, or some other feature where the artist might want to CHANGE the actual NFT that's in your wallet.

NFT projects tend to use a PolicyId to group NFTs into collections.
A PolicyId is tied to a minting wallet and may optionally contain an expiry date.
Once the expiry date passes, the minting wallet cannot mint or update NFTs tied to the PolicyId.
This gives buyers the assurance that a Collection with a expired policyId has not minted more than the stated supply and cannot change the minted asset's metadata.

The minting wallet can Mint two or more identical NFTs, but the NFTs will not technically be a NFT anymore (it becomes fungible).
NFT asset = PolicyId + AssetName
(If 2 Assets in the same PolicyId have the same AssetName, the block explorer will show a count of 2).
NFT buyers will usually check the total supply of NFTs in a PolicyId and that each NFT asset in that PolicyId is unique (non-fungible).

In my opinion of the English language, the token is fungible if it is possible to make more identical tokens.
One could include the splitting or changing of the token itself, but that is perhaps out of context if you regard the "token" to be the set of relevant unique identifiers.
Therefore if the policy is not locked, then the tokens are fungible.
Cases where another functionally identical token can be, but has not yet been made, are in the state of fungibility.
Of course various blockchain browsers can render and annotate data as they choose. Users beware.
I am not suggesting that non locked policies are inferior to locked policies.
There is obviously a lot of functionality to be obtained from burning tokens to create another with the relevant key hooks. Just don't confuse people, or mislead them into misconception.


text:
How to restore a wallet from root.prv file
I have a wallet for testnet that I was using for some experiments, I created it using cardano-wallet CLI, generated some recovery phrase that I thought I stored, but probably never did because it was of low importance on testnet and generated root.prv from that recovery phrase.
So, year later, now I am in a situation that I have this wallet on MacBook (I know its password), I don't have the recovery phrase and I want to also move it to another computer.
Daedalus only support recovery of wallet using recovery phrase, but I don't have that, I only have the root private key, which should be enough to regain full access to the wallet.
How can I "recover it"?
NOTE: I don't want to just transfer funds from there to a new wallet, this wallet is used as a testnet stake pool owner wallet, it would be too much work. Also this information could be useful to someone else in the future, so please try to answer the question instead of suggesting some workarounds or telling me it's a bad idea :-)

Does the root.prv file start with "root_xsk"?

You can copy the wallets directory in the Daedalus state directory of the old system to the new system. Daedalus Diagnostics in menu should have a link to where the state is on your operating system.

If the root.prv file is all you have, you could "recover" it by re-deriving the secret key files using cardano-address and cardano-cli (which you should get from the official sources (e.g. cardano-addresses github, etc.). Reminder to verify the binaries or source you build from).
Assuming you already have cardano-address and cardano-cli setup in your PATH. The commands could be something like this:
# Payment secret key from root.prv
cardano-address key child 1852H/1815H/0H/0/0 < root.prv > payment.xprv
cardano-cli key convert-cardano-address-key --shelley-payment-key --signing-key-file payment.xprv --out-file payment.skey

Note: you might need to update the derivation path accordingly if your wallet is a Byron-era wallet (e.g. 44H/1815H/0H/0/0).
From this point, you can derive your Verification Keys using cardano-cli if needed. Something like this:
cardano-cli key verification-key --signing-key-file payment.skey --verification-key-file payment.evkey
cardano-cli key non-extended-key --extended-verification-key-file payment.evkey --verification-key-file payment.vkey


text:
Cardano Balance While Staking
I am currently staking Cardano in Daedalus 4.6.0. When I started staking, my balance shows up as ***. Can someone please explain why? Thanks

You must have the "discreet" feature turned on - it is the little eyeball towards the top right of Daedalus, just to the left of the notification bell.
To view your balance, simply click the crossed out eyeball, it will uncross and you'll see your balance.

Thanks, that worked!


text:
How can I use cardano-serialization-lib in the browser to decode CBOR?
I'm building a simple website with pure HTML and JS (no React, Angular, etc.). I use Nami to connect to a Cardano wallet and use the Nami's cardano.getBalance() method to get the balance of the wallet.
This output (as most of the outputs of Nami) is CBOR encoded. I used https://cbor.me/ to decode it manually but I need to be able to do this in code to be able to work with the values.
Nami's README says to use the cardano-serialization-lib to do this. So I tried to use it but there is no documentation on how to actually use it.
Here's what I've done so far:
<html>
  <head>
    <!-- Cardano Serialization Lib -->
    <script
      type="module"
      src="https://cdn.jsdelivr.net/npm/@emurgo/cardano-serialization-lib-asmjs@9.1.2/cardano_serialization_lib_bg.min.js"
    ></script>
    <script
      type="module"
      src="https://cdn.jsdelivr.net/npm/@emurgo/cardano-serialization-lib-asmjs@9.1.2/cardano_serialization_lib.asm.min.js"
    ></script>
    <script
      type="module"
      src="https://cdn.jsdelivr.net/npm/@emurgo/cardano-serialization-lib-asmjs@9.1.2/cardano_serialization_lib.min.js"
    ></script>
  </head>
  <body>
    <script>
      function f() {
        window.cardano.enable().then((a) => {
          console.log(a);
          window.cardano.getBalance().then((b) => console.log(b));
        });
      }
      setTimeout(f, 1000); // wait for cardano object to be injected
    </script>
  </body>
</html>

I included the cardano-serialization-lib-browser using jsdelivr.com. Now the goal is to use this library to deserialize the output of cardano.getBalance().
My problems are:

I don't know how to call the library in my JS code.
I don't know what functions to use to deserialize CBOR as there is no documentation.

Any help would be highly appreciated.

With the help of Samuel's answer, I have been able to get it running.
Some important things I didn't know:

import from CDN has to be done with the full url.
The library has to be imported inside of my script, not in the <head>.

Here's the working example:
<html>
  <head>
    <!-- Cardano Serialization Lib -->
    <script
      type="module"
      src="https://cdn.jsdelivr.net/npm/@emurgo/cardano-serialization-lib-asmjs@9.1.2/cardano_serialization_lib_bg.min.js"
    ></script>
    <script
      type="module"
      src="https://cdn.jsdelivr.net/npm/@emurgo/cardano-serialization-lib-asmjs@9.1.2/cardano_serialization_lib.asm.min.js"
    ></script>
  </head>
  <body>
    <script type="module">
      import * as wasm from "https://cdn.jsdelivr.net/npm/@emurgo/cardano-serialization-lib-asmjs@9.1.2/cardano_serialization_lib.min.js";

      function hexToBytes(hex) {
        for (var bytes = [], c = 0; c < hex.length; c += 2)
          bytes.push(parseInt(hex.substr(c, 2), 16));
        return bytes;
      }

      function f() {
        console.log("hello");
        window.cardano.enable().then((a) => {
          console.log(a);
          window.cardano.getBalance().then((res) => {
            const balance = wasm.Value.from_bytes(hexToBytes(res));
            const lovelaces = balance.coin().to_str();

            console.log(lovelaces);
          });
        });
      }
      setTimeout(f, 1000);
    </script>
  </body>
</html>

CBOR is a serialization standard that's unrelated to the blockchain tooling itself. For nodejs, you can use something like https://github.com/paroga/cbor-js to encode/decode the CBOR.

I had a look at this library but it was last updated in 2015 and seems like it's not maintained anymore. And besides that I'll need some cardano specific functionality later like building transactions etc. Therefore I need to use cardano-serialization-lib.

Ah, your question didn't make it clear what you were trying to do. I thought you just wanted cbor.me equivalent in your code (which serialization lib doesn't provide). I'm not aware of any sort of balance object but for example the transaction class has a from_bytes method. See https://github.com/Emurgo/cardano-serialization-lib/blob/531e8cc2991c73edc19392558909ebb5a233b77d/rust/pkg/cardano_serialization_lib.js.flow#L4755

It's a Value type it returns. See https://cardano.stackexchange.com/questions/4112/nami-wallet-showing-getbalance-returning-a-nan which is a duplicate of this question.


text:
How do you install cardano-wallet on an Ubuntu server and get the http API set up and running?
Here's an example:
https://github.com/input-output-hk/cardano-wallet
wget https://raw.githubusercontent.com/input-output-hk/cardano-wallet/master/docker-compose.yml
NETWORK=testnet docker-compose up

Fantastic! The server is up-and-running, waiting for HTTP requests on localhost:8090/v2

No, it isn't. All that the above does is download a yml file.
I've also tried setting up a brand-new Ubuntu server on Digital Ocean, following the steps outlined here:
https://developers.cardano.org/docs/get-started/installing-cardano-wallet/
I've made sure to use the same git branches and tags that were listed, but running:
stack build --test --no-run-tests

takes a long time and then fails. I did figure out that sudo apt install libsodium-dev had been overlooked in the documentation, but I'm still stuck and haven't been able to find any solutions.

EDIT: I went through the whole process again, without installing libsodium-dev and it worked, so I'm not sure why that was the case for me before.

I've destroyed the server and set up a new one from scratch each time, worrying that there might be something I've done that could affect each tutorial. I've probably downloaded and installed and tried compiling (with cabal and stack) eight times.
So. What I'm trying to do is set up on a brand new droplet, cardano-wallet with the REST API, so I can make requests and get responses. Do I need to install cardano-node first? Do I need to set up a relay vs a node like a stake pool? (I have a stake pool set up, but I had to hire someone to do that because I wanted to make sure all the security patches were set up correctly, and that I didn't do something bone-headed)

You definitely need to have a local running cardano-node so the cardano-wallet server has something to talk to/query. Once you have that set up, the easiest thing is to download the latest pre-compiled cardano-wallet binaries from IOHK's github.
Extract the cardano-wallet binaries and place them in your bin folder. You should be able to run cardano-wallet -h from the CLI and get a help prompt. Once that works, make sure CARDANO_NODE_SOCKET_PATH environment variable is set appropriately in your ~/.bashrc folder. As long as cardano-node is up and running, you may now begin using cardano-wallet.
Follow the cardano-wallet user guide to begin. For a minimal setup, you can get started by running:
cardano-wallet serve \
  --mainnet \
  --node-socket CARDANO_NODE_SOCKET_PATH \
  --database <PATH_TO_WALLET_DB>

Hope this helps and let me know if you need further clarification!

But how do I get the http part working? I've asked on another question as well. https://cardano.stackexchange.com/questions/6058/how-do-i-get-the-http-endpoint-to-work-for-cardano-wallet

To build cardano-wallet from sources you need first to have cardano-node, as stated here:
https://developers.cardano.org/docs/get-started/installing-cardano-wallet/
This guide assumes you have installed cardano-node and cardano-cli into your system. If not you can refer to Installing cardano-node guide for instructions on how to do that.
You should have at least 8GB RAM, what is necessary for running cardano node, from first look seems your build fails because of insufficient resources.
I have build by myself cardano-node with cardano-wallet exactly on Digital Ocean(Even on same OS - Ubuntu) using following documentation what I updated quite recently, so it does work:
https://developers.cardano.org/docs/get-started/installing-cardano-node/
https://developers.cardano.org/docs/get-started/installing-cardano-wallet/
If you still have a problem building cardano-node or wallet. Please put logs and I will try to sort it out.
For wallet you just need to have cardano-node binaries that it. You can use prebuild or build by yourself.
P.S.
And this do work:
wget https://raw.githubusercontent.com/input-output-hk/cardano-wallet/master/docker-compose.yml
NETWORK=testnet docker-compose up

Seems you just don't have docker and docker-compose installed. So if you see that command docker-compose is not found then on Ubuntu/debian you need to run apt-get update && apt-get upgrade -y && apt-get install docker-compose -y and then it will work

I am reinstalling on a fresh droplet, following the installing-cardano-node instructions. I will post abbreviated logs if there are any problems. Thank you!

I was able to do it on an 8 GB instance, but I did have to log out and create a new session (and re-run the build both times).

Glad that you were able to build it. Cheers!


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

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

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

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


text:
How to new Cardano.Bip32PrivateKey from cborHex in file .skey generate by cardano-cli
I'm trying to new Cardano.Bip32PrivateKey from string cborHex which in file skey generate by cardano-cli
import * as Cardano from "@emurgo/cardano-serialization-lib-nodejs";

function genAccountKey(cborHex: string) {
    return Cardano.Bip32PrivateKey.from_bytes(Buffer.from(cborHex, "hex"))
        .derive(harden(1852)) // purpose
        .derive(harden(1815)) // coin type
        .derive(harden(0)); // account #0

}
genAccountKey("58204022747367deee69f601900e15ddc04fc8024753b6a1539ee2a8bed29832f420");

but I got this err (node:87994) UnhandledPromiseRejectionWarning: Invalid Secret Key size

Is it possible to use .skey(s) and .vkey(s) to construct transactions with the Cardano Serialisation Library? Based on your response it seems as though it is not possible since one cannot backwards derive the necessary privatekeys ...

Welcome aboard.  Your answer isn't an answer but it would make a good question.  Don't forget to check out the [tour] and read some of the pinned messages in the [help/dont-ask]

The CLI key you generate is not the same as Bip32PrivateKey associated with HD Wallet, the Root key you're considering is green box below - while the CLI key is red one. You can derive from parent key to child, but not the other way round.

You can derive a private key from skey CBOR using:
    // Sign with the backend wallet
    const signingKeyHexCBOR = 'THISISYUURKEYCBOR'
    const signingKey = this.S.PrivateKey.from_normal_bytes(Buffer.from(signingKeyHexCBOR,'hex'));

    const vkeyWitness2 = this.S.make_vkey_witness(txHash, signingKey);
    vkeysWitnesses.add(vkeyWitness);
    ```

do you know how to go the other way? Starting from a Bip32PrivateKey to a CBOR string that I can paste into an skey file that can be used to sign a transaction with cardano-cli?


text:
How to reuse data when updating Token using StateMachine
I'm currently creating a social network-like Dapp on plutus, and I've come across something I don't understand.
My Dapp, for example, is NFT(for own identity)->RFT(for sell own content)->NFT(for some other user)->MFT(NFT with some validator). In the case of this diagram, the transaction exists at the pointers between the various tokens.

What I want to do is to concatenate multiple MintingPolicies with different conditions in a one-way fashion while maintaining the data.
Most of sample code Lars written in the Plutus-Pioneer-Program has only one validator or MintingPolicy in each file.
When I create a transaction from off-chain, I want to bring in the data used in the previous MintingPolicy for the new MintingPolicy.
What is the best way to use StateMachine when I want to do this? For example, in the StateMachine.hs code, you can use

gameDatum :: TxOut -> (DatumHash -> Maybe Datum) -> Maybe GameDatum
gameDatum o f = do
    dh <- txOutDatum o
    Datum d <- f dh
    PlutusTx.fromData d

Do we need to repeat this process of searching for Datum I want to keep with the TxOut argument of a specific transaction?
I already know that UTxO is never rewritten, but rather that similar UTxOs are generated over and over again, so that it feels as if a single UTxO is being updated.
Lars says that StateMachine is in one (e)UTxO. So, is it like an empty bucket that can be injected with new data, deleted, or updated at its own time?
Or, when generating StateMachine, do I have to prepare in advance the data parameters that may be used in all processes?
Please tell me some information, Thanks.


text:
Are there papers (e.g. game theorie based) on how Ouroboros encourages decentralization of ADA among its users?
In Ouroboros, the more ADA you have the bigger the chance to get elected to mine the next block and get the rewards.
Apart from other parameters and up to the saturation level for a single poole this incentivizes high net worth entities to run several stake pools and/or to provide pledges.
At first sight this feels like it would incentivize centralization. I'm sure that's not the case but are there any papers about that? E.g. ones that simulate that via game theory?

After asking the great community in the Cardano Forum someone answered comprehensively and pointed me to a blog post with an abstract, a video and a link to the paper.

If you compare the proof of stake concept to that of proof of work, you still  end up with the "more money you have the more blocks you get." The difference being POW you buy graphics cards versus buying Cardano for POS.
Parameter k is an important factor for decentralization in Cardano. Currently k is set to 500 which sets the cap of a saturated pool at 64 million Ada. I believe the plan is to move k to 1000 next which will make 32 million Ada the saturation point. Changing that parameter will contribute to decentralizing the network even more, but you are right, high net worth entities are just going to make even more pools, which does centralize the network. However, single pool operators currently make up the biggest pool group of the network, which is great for decentralization. (How many of them are using the same cloud providers is a different discussion)
Currently Binance is the worst for creating multiple pools. Since they can stake other people's Ada to their own pools (not allowing competition) they currently have 42 fully saturated pools. They are making around 45 blocks per Epoch per pool or ~1,890 blocks per epoch. There are ~21,600 blocks per epoch, this mean that Binance is controlling 8.75% of the network. This is a lot but can easily be cut back by encouraging people to move their Ada from exchanges.
Here is a blog post from IOHK that you might find interesting on parameters such as k.
I hope this is helpful!

Thanks for the explanation! Unfortunately that doesn't fully answer my question. I understand that the K parameter allows for more pools. But the pools that will mostly mine blocks will still mainly be the ones that have the most stake already. This is why I wonder if there are any papers that show that wealth (ADA) doesn't get more concentrated over time.

I'll keep my eye out for papers. My guess, is that this largely depends on adoption and utility. Imo, to avoid hoarding of coins, there needs to be a lot of utility encouraging spending.

Not to be a snob, just wanted to mention that the pool saturation limit changes every epoch. The formula is given by: Saturation limit = Total circulating ADA / k. Since the total circulating supply rises every epoch, so too does the saturation limit, until k is increased. Right now, the pool saturation limit sits at over 67.5M ADA

High net-worth individuals running multiple stake pools is not necessarily a problem, as long as:

the initial distribution of ADA is sufficiently decentralized (done)
the aforementioned individuals' share of ADA is not growing at an exponential rate (done)

The market is still young, in that the big BIG money hasn't entered yet. During times of high volatility (in either direction), trading volume spikes, and overall distribution of ADA increases.

On Pool Splitting and Pledge
There are several network parameters that influence stake flow/aggregation. k (saturation limit) might be the most well known, but it is not enough alone. When k is increased, saturated pools are incentivized to evenly split, so a0 comes in to counterbalance the splitting incentive with a consolidation incentive.
a0 governs how much of an impact pledge has on max pool rewards. When a0 is increased, higher pledge mean higher rewards, which incentivizes would-be pool splitters to keep more of their ADA in a single pool.
At the time of this writing, there is a linear relationship between a0 and max pool rewards, such that higher pledge ~ higher rewards. However, CIP-7 is in the process of being finalized and, once implemented, will modify the formula to have an n-root curve. This will balance out the

On Economies of Scale
In PoW, economies of scale pose a much greater centralizing force than in PoS. Let's imagine a single GPU retails for $1000. If an average consumer wanted to buy one or two GPU's, they'd have to pay full retail price. However, if there was some big time player with $1 million to spare, they'd likely get a better deal than the average consumer, and they'd buy each GPU at a lower-than-retail rate. In PoS this is not the case; if we leave aside market manipulation, there are no discounts given to big-time buyers of cryptocurrencies. One ADA is one ADA. 1M ADA is 1M ADA. Period.
Additionally, if for whatever reason a new coin comes along that is more profitable to mine (even in the short term) than the current most-profitable PoW coin, there would be a massive incentive for miners to switch over to mining the new coin, compromising the decentralization of the original network. In PoS, this is not the nearly the case. Charles said it best in one of his AMA's: would you rather have Roman mercenaries guarding Rome, or Roman citizens guarding Rome? Probably the latter.

Sorry, no papers here, just some humble pontification :)


text:
Is it possible to specify metadata for native asset on-chain?
I know about token registry, which is off-chain, but I noticed that some tokens such as HOSKY are not in token registry and yet they have logo, description, URL and coin name visible on pool.pm.
Is it possible to add extra metadata when minting the coin, such as it's done with NFTs? Also https://developers.cardano.org/docs/native-tokens/minting describes only most basic policy:
vi minting-policy
{
  "keyHash": "your_key_hash",
  "type": "sig"
}

What other keys are accepted and how do they affect the policy? Is this described anywhere in detail?

HOSKY (very, very, loosely) follows the 721 NFT metadata spec to have onchain metadata, as you can see here:
{
  "721": {
    "a0028f350aaabe0545fdcb56b039bfb08e4bb4d8c4d7c3c7d481c235": {
      "HOSKY": {
        "HOSKY": {
          "website": "https://hosky.io"
        }
      }
    },
    "copyright": "HOSKY IO; all rights reserved",
    "publisher": [
      "hosky.io"
    ],
    "version": 1
  }
}

Though this doesn't include an image, I'm unsure how they got their logo on pool.pm, perhaps this is an ad-hoc thing they arranged with pool.pm. As you can see from the onchain metadata, they didn't include enough metadata on-chain for a logo (though you could use the "image" property in the NFT metadata to facilitate this.)
To answer your question about minting policies, this is completely separate to the metadata. The metadata is just supplied (as a file input to CLI or as raw JSON) to the minting TRANSACTION. It is not linked to the minting policy, they have used a  timeLocked + pubKey all policy for minting HOSKY tokens:
{
   all: [
      {
         pubKey: "421d2150828730433df35f93088bfc223f9ab3b74ad8333c160625f7"
      },
      {
         invalidAfter: 49428890
      }
   ]
}

oh, so the NFT metadata can be applied for non-NFT assets as well? is this a feature or a bug? :) also why is this called "721"? one more question - is this something you would recommend to do for non-NFT assets? Or is the registry preferred way? Or maybe combination of both?

Yeah technically you can put whatever you want in the metadata. You can choose to follow the spec if you want, since many apps will look for and interpret this metadata based off the standard. I think 721 is actually a historic reference to the Ethereum NFT metadata standard: https://eips.ethereum.org/EIPS/eip-721. I would say the registry is still the preferred way, but a combination of both isn't a bad idea IMO.

Is it possible to specify metadata for native asset on-chain?

Yes, you can add metadata for your fungible tokens.

yet they have logo, description, URL and coin name visible on pool.pm.

Not sure but maybe you're confusing HOSKY tokens:

Hoksy tokens, they don't have image, description, etc, therefore nothing is displayed on pool.pm. You can check here
Hoksy NFTs, they comply with the standard, therefore, they display an image on pool.pm. You can check here

If you see, they use different policies with different metadata.

What other keys are accepted and how do they affect the policy? Is this described anywhere in detail?

Regarding to policies, you can find more information here: Simple Scripts


text:
Generate list of payment addresses using CardanoCLI-JS
I am trying to generate a list of (unused) payment addresses with CardanoCLI-JS, but how to do it?
    const wallet = cardanocliJs.wallet("Main");
    const address = cardanocliJs.addressBuild("Main", {
      paymentVkey: wallet.payment.vkey,
      stakeVkey: wallet.stake.vkey,
    });

console.log(address);

This outputs the location of the vkey, which gets updated on execution, but contains the same address as before?
Is this something CardanoCLI-JS just can't do right now?
Cardano-Wallet-JS has wallet.getAddresses(), which returns an array of 20 addresses, but I'd really like to stick to one JS library...
(Can someone pls create the tags cardanocli-js and cardano-wallet-js? thanks...)

The cardano-cli (what the JS library wraps) has no notion of what a wallet is, how to derive addresses from mnemonic/public key, etc... cardano-wallet-js wraps the cardano-wallet process and can get information about a wallet and it's state on the network (which is required if you want to know unused addresses as a process needs to scrape entire chain to see if an address has been used or not). If you're looking for a simple library to derive addresses and don't care about state, there's a GHCJS build of cardano-addresses https://www.npmjs.com/package/cardano-addresses which provides the ability to derive addresses from a root key, account public key or your 24 word mnemonic for the wallet. However; to identify if an address was used or not, you would need a db-sync or explorer API (like graphql, blockfrost, rosetta, etc...) to check the state of the chain for that particular address.

Thanks for clearing this up... kinda confusing if you ask me. Why not work on ONE JS Library which can do it all?

Mainly because running js code is slow.


text:
Ensuring NFT collection uniqueness using counter as asset name?
I would like to be able to mint a collection of NFTs across different transactions that fall under the same policy id.
A method I would like to try is making a 'dummy' nft that holds a counter as its datum. Every time a new nft is minted, the policy checks that the asset name is the current_count + 1 and that the counter output is created again with the same dummy nft and incremented value. Would there be any ways of tampering with this and would it still be considered a valid NFT?
Thanks!

This should work. I don't see any obvious ways of tampering with it. As long as you are checking against the token name, not the currency symbol, these tokens would be non-fungible and unique.

To build this minting smart contract, I would write 2 scripts (and include a 3rd): a minting policy and a validator to hold the counter datum (and use Plutus.Contracts.Currency to build your "dummy" NFT).
The validator holds the "dummy" + datum and does all the logic you mentioned above:

Check that 1 token is minted of designated currency symbol
Check that the token name is the datum value + 1
Check that the dummy NFT is returned to the validator with the datum counter bumped

The minting policy just checks that the dummy NFT is included in the transaction.
It's organized this way because Minting Policies don't have datums for storing state (like your counter). It's a fairly common pattern in the Plutus examples. I've been calling it the "Access Control Token" pattern or variations on that. But "dummy NFT" works fine too :). I don't know what the core devs refer to it as.

Thanks, this answer was very helpful!


text:
Error while submitting Transaction through cardano-serialization-lib
I am trying to implement Martify contract using Cardano serialization lib. When I submit the transaction I get the following error. Can someone tell me what it mean?
transaction submit error ShelleyTxValidationError ShelleyBasedEraAlonzo (ApplyTxError [UtxowFailure (WrappedShelleyEraFailure (UtxoFailure (UtxosFailure (ValidationTagMismatch (IsValid True) (FailedUnexpectedly [PlutusFailure \"\\nThe 3 arg plutus script (PlutusScript ScriptHash \\\"a306c90d19adfd7302e6d0a452aed3bd1d7f08e5b291d1add3d8e4fb\\\") fails.\\nCekError An error has occurred:  User error:\\nThe provided Plutus code called 'error'.\\nThe data is: Constr 0 [B \\\"\\\",I 100000000,B \\\"B\\\\DLEGO\\\\251\\\\142\\\\170Lpz6u\\\\155Tf\\\\223\\\\208\\\\173X]\\\\237\\\\143X\\154%\\169\\n\",B \"\"]\nThe redeemer is: Constr 0 []\nThe context is:\nPurpose: Spending (TxOutRef {txOutRefId = 0ba3

I am  impressed since it appears that the shared repo is for submitting using cardano Cli! and Nami specs  don't match cardano-cli specs..but the error seems at a first look to be bassed on executing the plutus scripts... have you tried with this same transaction in the cli? to check if it is related to cardano serialization lib or to the contract perse?

I did try the same transaction through Cardano-cli which seems to be working perfectly fine. But when using Cardano-serialization-lib it keep on giving me this script failed eeror

ive read in Alessandro Twitter that Nami does not suport plutus contracts. But i am not sure why it is the case.. since is is a normal Tx  just with redemer and plutus scripts. so you took the plutus script, and used the cardano serialization lib to make the rest of the transaction?.. Maybe you should try to sign it using your prv keys in the library and send once int is signed.

I'm experiencing the same error. No idea what I'm doing wrong...

Lol I solved this issue. I was using a wrong tx id in my script utxo and the address in the datum was wrong too. Had to use ownerAddress.payment_cred().to_keyhash()?.to_bytes().

@Displee Can you share your implementation with me? And how did you identify these errors, did you use any debugging technique or just hit and try .

Sorry for the late reply @DawarEjaz. Here's the full code: https://pastebin.com/DEzY3vCi

I met the same issue when the plutus script is 10 bytes long. Do you meet that issue, and can you repost your code example to solve that? Tks so much

@Displee Can you please share your code as an aswer to this question? Thank you!

Here is the full code: https://gist.github.com/Displee/63ca898e991e61786825c78764371444


text:
Ambiguous type variable ‘e0’ arising from a use of ‘endpoints’
I'm writing emulator trace tests for the spacebudz contracts. Here is a minimum example:
{-# LANGUAGE DataKinds             #-}
{-# LANGUAGE FlexibleContexts      #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NoImplicitPrelude     #-}
{-# LANGUAGE OverloadedStrings     #-}
{-# LANGUAGE ScopedTypeVariables   #-}
{-# LANGUAGE TypeApplications      #-}
{-# LANGUAGE TypeFamilies          #-}
{-# LANGUAGE ExtendedDefaultRules  #-}

module Test.EmulatorTrace where

import           Control.Monad           hiding ( fmap )
import           Control.Monad.Freer.Extras    as Extras
import           Data.Default                   ( Default(..) )
import qualified Data.Map                      as Map
import           Ledger
import           Ledger.Ada                    as Ada
import           Ledger.TimeSlot
import           Ledger.Value
import           Plutus.Contract.Trace
import           Plutus.Trace.Emulator         as Emulator
import           PlutusTx.Prelude
import           Prelude                        ( IO
                                                , Show(..)
                                                )
import           Wallet.Emulator.Wallet

import           Contract

test :: IO ()
test = do
  test'

test' :: IO ()
test' = runEmulatorTraceIO' def def myTrace

myTrace :: EmulatorTrace ()
myTrace = do

  h1 <- activateContractWallet (Wallet 1) endpoints
  callEndpoint @"init" h1 ()

  void $ Emulator.waitNSlots 10

However, when trying to activate the wallets for the emulator, I get this error:
src/Test/EmulatorTrace.hs:45:43: error:
    • Ambiguous type variable ‘e0’ arising from a use of ‘endpoints’
      prevents the constraint ‘(Wallet.Types.AsContractError
                                  e0)’ from being solved.
      Probable fix: use a type annotation to specify what ‘e0’ should be.
      These potential instances exist:
        two instances involving out-of-scope types
        (use -fprint-potential-instances to see them all)
    • In the second argument of ‘activateContractWallet’, namely
        ‘endpoints’
      In a stmt of a 'do' block:
        h1 <- activateContractWallet (Wallet 1) endpoints
      In the expression:
        do h1 <- activateContractWallet (Wallet 1) endpoints
           callEndpoint @"init" h1 ()
           void $ waitNSlots 10
   |
45 |   h1 <- activateContractWallet (Wallet 1) endpoints

How is it possible, when every contract example has the same code?

Well, it's because you're not specifying where the endpoints variable comes from. So, basically the error is saying: You've various instances of endpoints variable, which of those is it?
Try to specify it on your imports, something like this:
import OffChainCode (endpoints)
And if your offchain code is in the Contract file, try to change the name of the module Contract, as it's a Plutus type.

This is changed in newer versions so you need to change:
h1 <- activateContractWallet (Wallet 1) endpoints

to
h1 <- activateContractWallet w1 (endpoints @ContractError)

For w1 you need to import Plutus.Contract.Test and for ContractError Wallet.Types

I think your endpoint looks something like this
endpoints :: forall  e. AsContractError e => Contract () yourSchema e ()

now in TraceMonad its confused what type should we put for variable e.
if you change your endpoint definition  to
endpoints :: Contract () yourSchema Text ()

This worked fine for me as now we are passing concrete types for endpoint.


text:
Couldn't match type ‘Either SomeCardanoApiTx Tx’ with ‘Tx’
I have this error when compiling Week01 from Pioneer Program:
error:
• Couldn't match type ‘Either SomeCardanoApiTx Tx’ with ‘Tx’
  Expected type: Tx
    Actual type: CardanoTx
• In the first argument of ‘txId’, namely ‘ledgerTx’
  In the second argument of ‘($)’, namely ‘txId ledgerTx’
  In the second argument of ‘($)’, namely
    ‘awaitTxConfirmed $ txId ledgerTx’

void $ awaitTxConfirmed $ txId ledgerTx

How to fix the error?

You must have built Plutus from the latest commit, some things have changed I believe. The reason is submitTxConstraintsWith returns a type of Contract w s e CardanoTx but txId requires the type Tx. Replace TxId with getCardanoTxId and it should work.
If you want to follow the Pioneer Program tutorials you need to build with the commit hash used in the lectures, for lesson 1 it is: ea0ca4e9f9821a9dbfc5255fa0f42b6f2b3887c4

But I want to use a recent version.

the getCardanoTxId fixed for me, thx!


text:
Check total ADA delegated to the pool with cardano-cli
I'm running the stake pool and want to know the delegators count and total amount of ADA delegated to my pool.
Is there a way to do that from my producer/relay node using cardano-cli?
I know this info can be obtained from resources like https://adapools.org/, but is there any internal statistics that provide such details (e.g. for my monitoring tools to fetch)

you can obtain a snapshot information using the cardano-cli:
cardano-cli query stake-snapshot --stake-pool-id POOL_ID --mainnet

which returns the following
{
"poolStakeGo": 12016106401607,
"activeStakeGo": 14925992640911949,
"activeStakeMark": 14854196369191645,
"poolStakeMark": 12021194972631,
"activeStakeSet": 14853022119978909,
"poolStakeSet": 12018867311903

}
Go - 2 epochs ago
Set - 1 epoch ago
Mark - snapshot for the current epoch
To get the more detailed information about the delegator count you'd need to query cardano-db-sync


text:
Selfish mining / denial of service on Cardano?
I just analysed the reasons for why my pool minted an orphaned block.
Here is the sequence of events:
My pool minted block No=1 in its allocated slot=28 at T=28.050 seconds.  This block propagated across the network and was received by other, not directly connected, relays within 1 second (ie. by T=29 seconds).
My pool and other relays received block No=0 which was generated in slot=0 at T=30s.  This block is 30 seconds delayed; it arrived 30 seconds after it was produced at T=30.  However, this block predates my block and contains transactions which my block included.  This results in the cardano node switching tip to this block No=0 and invalidating my block.
So here is the problem:
Lets say I wanted to increase my stake pool rewards.
Every time my pool is due to mint a block I could disconnect my relays from the block producer.  Then wait for the block to be minted and wait another 30 seconds or more.  Then connect my relays to the block producer.  The relays would then pull the freshly minted block and other connected nodes would in turn pull the minted block and it would propagate across the network.  The net result is a block delayed by 30 seconds or more.
Any other pools that mint a block during this 30 second or more window of time will get their blocks invalidated.
Thus selfish mining / denial of service on Cardano ??????????
Addition: 2012-12-17:
Timestamp seconds are actual values and last 2 digits of block and slot numbers are also actual values.
Logs:
...
xx:xx:45 cardano-node: TraceNodeIsLeader
xx:xx:45 cardano-node: block String "yyyy" Number 48 blockPrev "wwww"
xx:xx:45 cardano-node: Chain extended, new tip:yyyy at slot 74
xx:xx:45 cardano-node: TraceAdoptedBlock
xx:xx:45 cncli-sync: block 48 of 48, 100.00% synced
xx:xx:46 cardano-node: TraceNodeNotLeader
xx:xx:47 cardano-node: TraceNodeNotLeader
xx:xx:47 cardano-node: BlockFetchDecision SlotNo 45 blockPointHash = zzzz
xx:xx:47 cardano-node: Block fits onto some fork: xxxx at slot 45
xx:xx:47 cncli-sync rollback to slot 19
xx:xx:47 cardano-node: Valid candidate xxxx at slot 45
xx:xx:47 cardano-node: Switched to a fork, new tip xxxx at slot 45
xx:xx:47 cardano-node: Ignoring block already in DB: xxxx at slot 45
xx:xx:47 cncli-sync block 48 of 48, 100.00% synced
xx:xx:48 cardano-node: TraceNodeNotLeader
xx:xx:49 cardano-node: TraceNodeNotLeader
...

Note that my block was produced at time = 45 seconds for slot = 74.  The delayed block was produced 29 seconds before this (at time = 16 seconds) for slot = 45 but was received at time = 47 seconds.
Upon receiving this delayed block, the cardano-node rolls back to the block prior to this delayed block (block at slot = 19) and then adds the delayed block for slot = 45.
Now my block for slot 74 is invalid - presumably because it contains transactions that were in the delayed block and it has the same block number of 48.
Note: Cardano slots occur every 1 second.
Immediately after seeing these logs I did the following cncli query:
cncli validate --db db/cncli.db --hash yyyy

{
"status": "orphaned",
"block_number": "48",
"slot_number": "74",
"pool_id": "blahblah",
"hash": "xxxx",
"prev_hash": "wwww",
"leader_vrf": "blahblah"
}

My block is orphaned!
cncli database records:
select id, block_number, slot_number, hash, orphaned from chain where block_number > 40 and block_number < 52;

id|block_number|slot_number|hash|orphaned
35|          46|         xx|vvvv|0
36|          47|         19|wwww|0
37|          48|         74|yyyy|1
38|          48|         45|xxxx|0
39|          49|         xx|zzzz|0
40|          50|         xx|aaaa|0
41|          51|         xx|bbbb|0

Related? https://www.reddit.com/r/cardano/comments/re2e1b/two_years_after_reporting_a_problem_with_cardano/?utm_medium=android_app&utm_source=share

Update 12/13/2021:
My first question on Cardano Stack Exchange was What is the Penalty for Running 2 Block Producer Nodes? Which I was told, "Network can penalize." But I never received an answer as to what that penalty was, which I believe is because there is not a penalty.
With that said, I believe your question is a result of a pool running 2 block producing nodes with the same keys. When one of these pools is elected slot leader and creates a block they actually create 2 blocks. 1 of these 2 blocks will be orphaned, but damage could be done to other pools before that happens (like your case, I believe). With the 2 blocks propagating, it is possible that a pool, let's call it  pool A, creates their next block on the losing, bad block. If this happens, pool A is going to have their block orphaned when the chain is rolled back to fix the duplicate block issue. This is what I believe happened to you.
With that said, your comment about disconnecting the relays from your BP for 30 seconds still wouldn't work to cause this. If you wanted to cause this you would have to run 2 block producer nodes. Which I do not recommend, and as a community, we should figure out how we are going to penalize these pools.
Here is a reference: https://www.reddit.com/r/CardanoStakePools/comments/rdzbhq/two_years_after_reporting_a_problem_with_cardano/
Original Answer:
I believe this happened because you lost a slot leader battle. So basically the other pool you were competing with had a better overall propagation time and that is why your block was orphaned. From your point of view, it looks like your block had the better propagation time but that is because you are looking at the nodes you are connected to.
As far as waiting 30 seconds to try to cause a DoS attack, it wouldn't work and you would just orphan your block. This is because even if there isn't another slot leader to take that block, another block will be created in 20 seconds that will create the new longest chain.
I hope this is helpful!

No evidence of slot battle.  cncli validate says my block is orphaned.  Also the logs do not show another block for the same slot as my slot.  Instead the logs show that this earlier block arrived 30 seconds late which was 2 seconds after my block was minted.  Then the node switched tip to this earlier block, invalidated my block causing it to be orphaned.

Can you share the specific slot, block and logs you are looking at?

The logic in my question post seems correct.  Watch the NerdOut video by Andrew Westberg: https://youtu.be/4j_SymkuxfU

Re: Update 12/13/2021: I have checked the cncli database on my node and there was only 1 block produced by the previous block producer which was delayed 30 seconds.  My block producer produced its block when it should have (and I do only run 1).  The previous block producer's block arrived 30 seconds late which happened to be 2 seconds after my block was produced with the same block number.  Because this delayed block was for an earlier slot all the nodes in the network switched tip to this delayed block and invalidated my block.

Think about the logic:  If two blocks are produced with the same block number by two different stake pools the nodes will accept only the block for the earlier slot.  Therefore if a block producer deliberately delays his block this will invalidate a future block produced by another node.  Two blocks can't have the same block number in the chain (and there will be conflicting transactions).  The nodes will accept only the first block (the one for the earlier slot).

"To determine which chain to adopt, each party collects all valid chains and applies the Chain Selection Rule." "... Chain Selection Rule: pick the longest chain as long as it grows more quickly (is denser) in the slots following the last common block to both competing chains." So in the case of waiting 30 seconds, another pool will create a block and have 10 seconds to be denser. Link: https://developers.cardano.org/docs/stake-pool-course/introduction-to-cardano/

"The previous block producer's block arrived 30 seconds late which happened to be 2 seconds after my block was produced with the same block number. Because this delayed block was for an earlier slot all the nodes in the network switched tip to this delayed block and invalidated my block." It arrived late to you but that doesn't necessarily mean it was late, it just means that you created a block 2 seconds after theirs but didn't know it for 30 seconds (yours was also propagating). Not trying to argue with you, just trying to help :). Was hoping someone else would answer (why I added a bounty).

I appreciate the discussion.  I run relays on opposite sides of the world and all received this block approx 30 seconds late.  All relays part-take in topology updates via api.clio.one and have 20-24 outgoing connections and 10-20 incoming connections.  I was watching the logs at the time my node produced its block.  The block was produced and then 2 seconds later I saw the logs about switching tip and immediately investigated WTF just happened.  There didn't appear to be any time for a longest chain determination.  The nodes just switched tip to this delayed block (same block No) immediately.

I updated the question with logs and data from cncli database.


text:
Where is the Datum stored in PAB?
In utxo we store only the hash of the datum, so whenever you work with the Cardano cli to run a transaction - you should provide datum or its hash via tx-out-datum-embed-file, tx-in-datum-file, etc.
What about the PAB?
Did I understand correctly that original datum is stored in chainindex?
At what step is original Datum sent from PAB to the chainindex?
If the datum is stored in chaindex - does it mean that all PAB apps should be connected to the same chainindex in order to share datum with each other?
Are we going to have a global chainindex available for all PABs?
What if two PABs are connected to different chainindex servers, does it mean that the datum will not be shared between them?

Datum and redeemer (all required data for script execution) are stored on-chain as well so the node can optionally verify the script execution outcome when replaying the chain.
Since chainindex follows a chain using connection to cardano-node it receives all the executed scripts, datums and redeemers after they get committed on-chain.
Which means that even different chain-index servers will see the same script data.


text:
I'm getting ValueContainsLessThanMinAda error in Week01 of Plutus Pioneer Program
Here is a trace for wallet1:
[ Slot 1: 00000000-0000-4000-8000-000000000001 {Wallet W872c}:
            Contract instance started
, Slot 1: 00000000-0000-4000-8000-000000000001 {Wallet W872c}:
            Current requests (3):   Iteration 1 request ID 3
                                    Request: "{\"contents\":{\"aeMetadata\":null,\"aeDescriptio
              Iteration 1 request ID 2
              Request: "{\"contents\":{\"aeMetadata\":null,\"aeDescriptio
              Iteration 1 request ID 1
              Request: "{\"contents\":{\"aeMetadata\":null,\"aeDescriptio
, Slot 1: 00000000-0000-4000-8000-000000000001 {Wallet W872c}:
            No requests handled
, Slot 1: 00000000-0000-4000-8000-000000000001 {Wallet W872c}:
            Receive endpoint call on 'start' for Object (fromList [("contents",Array [Object (fromList [("getEndpointDescription",String "start")]),Object (fromList [("unEndpointValue",Object (fromList [("spCurrency",Object (fromList [("unCurrencySymbol",String "66")])),("spDeadline",Number 1.596059101e9),("spMinBid",Number 1.0e8),("spToken",Object (fromList [("unTokenName",String "T")]))]))])]),("tag",String "ExposeEndpointResp")])
, Slot 1: 00000000-0000-4000-8000-000000000001 {Wallet W872c}:
            Handled request:   Iteration 1 request ID 1
                               Response: "{\"contents\":[{\"getEndpointDescription\":\"star
, Slot 1: 00000000-0000-4000-8000-000000000001 {Wallet W872c}:
            Current requests (1):   Iteration 2 request ID 1
                                    Request: "{\"tag\":\"OwnPublicKeyHashReq\"}"
, Slot 1: 00000000-0000-4000-8000-000000000001 {Wallet W872c}:
            Handled request:   Iteration 2 request ID 1
                               Response: "{\"contents\":{\"getPubKeyHash\":\"a2c20c77887ace
, Slot 1: 00000000-0000-4000-8000-000000000001 {Wallet W872c}:
            Current requests (1):   Iteration 3 request ID 1
                                    Request: "{\"contents\":{\"unBalancedTxTx\":{\"txData\":[[\
, Slot 1: 00000000-0000-4000-8000-000000000001 {Wallet W872c}:
            Handled request:   Iteration 3 request ID 1
                               Response: "{\"contents\":{\"contents\":{\"contents\":{\"cont
, Slot 1: 00000000-0000-4000-8000-000000000001 {Wallet W872c}:
            Current requests (0):
, Slot 1: 00000000-0000-4000-8000-000000000001 {Wallet W872c}:
            Contract instance stopped with error: "WalletError (ValidationError (ValueContainsLessThanMinAda (Tx {txInputs = fromList [TxIn {txInRef = TxOutRef {txOutRefId = 183d5544f89d5e0a5cfcbd8330c73a5f629925ed5f076b5a1b06e60a35147d4c, txOutRefIdx = 2}, txInType = Just ConsumePublicKeyAddress}], txCollateral = fromList [], txOutputs = [TxOut {txOutAddress = Address {addressCredential = PubKeyCredential a2c20c77887ace1cd986193e4e75babd8993cfd56995cd5cfce609c2, addressStakingCredential = Nothing}, txOutValue = Value (Map [(,Map [(\"\",100000000000)])]), txOutDatumHash = Nothing},TxOut {txOutAddress = Address {addressCredential = ScriptCredential 8c770b7ff9ed4a5df36ca914d18723596df69556597678d9872e2158, addressStakingCredential = Nothing}, txOutValue = Value (Map [(66,Map [(\"T\",1)])]), txOutDatumHash = Just 50536f27f0948527e1df0489a97781d16155f92623b8559e00e7341f2fb0f24d}], txMint = Value (Map []), txFee = Value (Map []), txValidRange = Interval {ivFrom = LowerBound NegInf True, ivTo = UpperBound PosInf True}, txMintScripts = fromList [], txSignatures = fromList [(8d9de88fbf445b7f6c3875a14daba94caee2ffcbc9ac211c95aba0a2f5711853,b129c9922646ca3d0b1fb5349ce515d4b4aca392825794478df4479182f8e2d53c5157829cf1c72628bb7b419cafd131cfcab251188af2c9e9c5064e03045d08)], txRedeemers = fromList [], txData = fromList [(50536f27f0948527e1df0489a97781d16155f92623b8559e00e7341f2fb0f24d,Datum {getDatum = Constr 0 [Constr 0 [B \"\\162\\194\\fw\\136z\\206\\FS\\217\\134\\EM>Nu\\186\\189\\137\\147\\207\\213i\\149\\205\\\\\\252\\230\\t\\194\",I 1596059101,I 100000000,B \"f\",B \"T\"],Constr 1 []]})]}) (Lovelace {getLovelace = 2000000})))" ]

Why I am getting this error, how to avoid it?

The last line indicates the issue. It shows the transaction you build:
Tx {
  txInputs = fromList [
    TxIn {txInRef = TxOutRef {txOutRefId = 183d5..47d4c, txOutRefIdx = 2}, txInType = Just ConsumePublicKeyAddress}
  ],
  txCollateral = fromList [],
  txOutputs = [
      TxOut {
        txOutAddress = Address {addressCredential = PubKeyCredential a2c20c778..09c2, addressStakingCredential = Nothing},
        txOutValue = Value (Map [(,Map [(\"\",100000000000)])]),
        txOutDatumHash = Nothing
      },
      TxOut {
        txOutAddress = Address {addressCredential = ScriptCredential 8c770b7ff9..158, addressStakingCredential = Nothing},
        txOutValue = Value (Map [(66,Map [(\"T\",1)])]),
        txOutDatumHash = Just 50536f27f0948..2fb0f24d
      }
  ],
  txMint = Value (Map []),
  txFee = Value (Map []),
  txValidRange = Interval {ivFrom = LowerBound NegInf True, ivTo = UpperBound PosInf True},
  txMintScripts = fromList [],
  txSignatures = fromList [(8d9de8..711853, b129c992..e03045d08)],
  txRedeemers = fromList [],
  ...
}

You can see in the field txOutputs the second output value is txOutValue = Value (Map [(66,Map [(\"T\",1)])]). You are trying to put a native asset into a UTxO without also including Ada.
On Cardano, UTxO always need to include Ada. You cannot just send some tokens. You can find how much Ada is needed here in the documentation: minimum-ada-value-requirement

I was following the steps from the https://plutus-pioneer-program.readthedocs.io/en/latest/pioneer/week1.html
Yes, there was mention that I must include Adas to UTxO, OK. But I'm just a beginner. I wanted to test the smart contract.

I think it worked in the Plutus Pioneer Program because this restriction was not enforced. This probably changed.


text:
Query next epoch from postgresql
How can I get the next Epoch.No using Postgresql. If I use

'SELECT no FROM epoch ORDER BY no desc limit 1'

, it returned last epoch/currentEpoch, if I want to receive the next Epoch.No, what should I do? Thanks for your help

The epoch table is populated at the beginning of the epoch, actually more accurately at the first block received for that epoch. You can't get data that doesn't exist. If you're wondering what the next epoch is though, just take the result of that query and add 1.


text:
Can we check signatures of arbitrary data in plutus validators?
I am looking for a function with a type like this:
verifySignature :: Datum -> Signature -> PubKey -> Bool

which is also INLINABLE to use it inside validator.
I know that we can check if the whole transaction is signed by some pub key with this function, but this should be an arbitrary message signature, not transaction signature.

N.B. I want to store signed proof off-chain, so putting this Datum inside some output and singing it is not an option

I think PlutusTx.Builtins has what you need:
{-# INLINABLE verifySignature #-}
-- | Verify that the signature is a signature of the message by the public key.
verifySignature :: BuiltinByteString -> BuiltinByteString -> BuiltinByteString -> Bool

You can use verifySignature on-chain. If you do it on chain, then your signature and the PubKeyHash should be either some wrappers around BuiltinByteString or directly BuiltinByteString. Either way, there should be no problem getting the types needed for verifySignature.

There is also an oracle for signature verification here


text:
cardano_serialization_lib + GeneralTransactionMetadata error
help
const METADATA = {
[policy.id]: {
[name.slice(0,32)]: {
...inputData.metadata
}
}
}
const generalMetadata = Loader.Cardano.GeneralTransactionMetadata.new()
generalMetadata.insert(
Loader.Cardano.BigNum.from_str("721"),
Loader.Cardano.encode_json_str_to_metadatum(JSON.stringify(metadata))
)
console.log(generalMetadata)
_metadata = Loader.Cardano.TransactionMetadata.new(generalMetadata)
rawTxBody.set_metadata_hash(Loader.Cardano.hash_metadata(_metadata))
thank.

In the Alonzo update TransactionMetadata renamed to AuxiliaryData,
As you can see here
https://github.com/Emurgo/cardano-serialization-lib/releases
you should change this as well as some other definitions.
Good luck!


text:
Derive wallet ID from receive address
Although there is a related question about how this isn't possible with cardano-wallet, there is value in being able to get the wallet id from a receive address even if it requires another tool.
Does anyone know how to do this?

This cannot be done. The wallet ID is the hash of the public account key. If you have the public account key, you can derive the addresses belonging to it, but it doesn't work the other direction.


text:
Nami getBalance() returns wrong value compared to GUI Wallet
When I call cardano.getBalance() it does not show the same value as the Nami Wallet GUI shows.
The Nami Wallet shows ADA 99.73 and the getBalance() returns ADA 101.114713.

I think this chould help you out: https://cardano.stackexchange.com/a/4113/1045

In Nami Wallet GUI you can see the amount of ADA excluding the ADA locked with assets (in your case it is 1.37928 ADA). You can see the "Locked with assets" amount in the hint ⓘ to the right of your Nami Wallet ADA amount.


text:
Validator fails comparing two (assumed equivalent) PubKeyHashes
I have a simple validator script that checks if a transaction is signed by a specific public key with the hash: 12f2f3e44e6e310abc78802d7078ec1fd0fa220ff47ad1bdb43397e2
{-# INLINABLE getHolder #-}
getHolder :: PubKeyHash
getHolder = PubKeyHash "12f2f3e44e6e310abc78802d7078ec1fd0fa220ff47ad1bdb43397e2"

{-# INLINABLE mkValidator #-}
mkValidator :: BuiltinData -> BuiltinData -> ScriptContext -> Bool
mkValidator _ _ ctx = txSignedBy (scriptContextTxInfo ctx) getHolder

The validator always fails when attempting to spend an output with the correct key using the CLI, --required-signer is being used. The transaction is never built.

I attempt to log the txInfoSignatories in the validator using the following code:
{-# INLINABLE mkValidator #-}
mkValidator :: BuiltinData -> BuiltinData -> ScriptContext -> Bool
mkValidator _ _ ctx = traceError $ decodeUtf8 $ getPubKeyHash $ P.head signatories
    where
        info :: TxInfo
        info = scriptContextTxInfo ctx

        signatories :: [PubKeyHash]
        signatories = txInfoSignatories info

Even though the decoding function throws an error, I still get the following:
The provided Plutus code called 'error'.
Caused by: [
  (builtin decodeUtf8)
  (con bytestring #12f2f3e44e6e310abc78802d7078ec1fd0fa220ff47ad1bdb43397e2)
]

Which shows that the correct key hash is in the script context, but the way the hash is constructed by the script context is clearly not the same as the one I've made and I'm not sure how to proceed.
Thanks!
EDIT: In fact, this happens to any validator I try to use that compares scriptContextTxInfo with any compile time input I give it. The bytestrings that I hardcode are never seen as equal to the bytestrings in scriptContextTxInfo. The validator traces leave me completely in the dark as my code seems to be identical to other examples that apparently work.

I've ran into similar issue. You can try to use fromHex function form Ledger.Bytes module, which will return the pubkeyhash as bytes representation.
This answer helped me with this.

Thanks, this worked!


text:
Where can I find a good tutorial for PAB?
Up till now, I can't find any tutorial on how to use PAB on the Internet.  I really want to try it out to develop Cardano Dapp. Anybody find good ones?

Lecture #6 and #10 from Plutus Pioneer Program would be a good start although it might be a bit outdated because there has been many changes since the lectures were published, and PAB itself does not have an official stable release yet.
You can also check out PAB components in the repo's README.

The issue with the lectures from the Plutus Pioneer Program is that they do not show how to interact with the PAB in a realistic way. The newest Demo is more helpful. It can be found here: https://github.com/input-output-hk/plutus-apps/tree/main/plutus-pab/demo/pab-nami

Thanks for that. However the link shows 404. The PAB README is too far away from a tutorial. I don't have a clue how integrate with my contract after studying it.

Newest demo https://github.com/input-output-hk/plutus-apps/tree/main/plutus-pab-executables/demo/pab-nami


text:
How does one check a pool's delegation history?
How does one view addresses that were staking with a specific pool at a specific epoch boundary?
If there is any way to view a list of addresses that received staking rewards for a particular block, that could also do the trick.

If you need any kind of specific on chain information that isn't found on third party explorers like Cardanoscan, you'd have to use db-sync yourself. (It's what all the explorers use)
To quote directly from the db-sync github:
"
The purpose of Cardano DB Sync is to follow the Cardano chain and take information from the chain and an internally maintained copy of ledger state. Data is then extracted from the chain and inserted into a PostgreSQL database. SQL queries can then be written directly against the database schema or as queries embedded in any language with libraries for interacting with an SQL database.
Examples of what someone would be able to do via an SQL query against a Cardano DB Sync instance fully synced to a specific network is:

Look up any block, transaction, address, stake pool etc on that network, usually by the hash that identifies that item or the index into another table.
Look up the balance of any stake address for any Shelley or later epoch.
Look up the amount of ADA delegated to each pool for any Shelley or later epoch.
"

There are LOTS of examples in the interesting sql queries

Thanks a ton, especially for the examples link. This seems to be exactly what I've been looking for.

If you do not want to setup cardano-db-sync, try blockfrost.io with the /epochs/{number}/blocks/{pool_id} endpoint.

That's a great point about blockfrost. Checking it out has been on my TODO for several months.


text:
Validate Transaction with serialization lib from a Tx Hash
I want to validate Transactions to make sure they are actual Cardano txs with correct length, format etc.
I see that Transaction object in emurgo serialization library has an 'is_valid()' method that I guess returns if tx is valid or not.
The point is that I have the txHash (random example: 5ea96bdc7ab5e13c68838482eedf7b97382310f450bade5589bf500fed894ed7).
I am trying to convert from the txHash to the Transaction object, but library returns an error:
"Deserialization failed in Transaction because: Invalid cbor: not the right type, expected Array' byte received Bytes'"
This is what i am trying:
var txBytes = Buffer.from(txHash, 'hex');

const tx = WASM.Transaction.from_bytes(
    txBytes
);

isValid = tx.is_valid();

Any idea how can i get Transaction object from a txHash?
Thanks

It is impossible to go from hash to the object that generated the hash. But you can de-serialize the byte representation of a transaction for using in the WASM methods on it,with this:
 const transactionObjet = WASM.Transaction.from_bytes(
Buffer.from(CBORHextransaction, "hex")

);

Yes. That is what I was trying. But... what you call 'transactionHexString' is the same as the Transaction Hash? I guess not. I am getting transaction hashes, so, do i need to convert the hash to a hexString to be able to use it with the code above? Does emurgo serlization library has any method to do that?

No it is not the txHash... it is the CBOR hex-encoded whole transaction, you can not get the objet that generated the hash from the hash at a theoretical level .Thats the key concept of crypto. You can read more about the subject here: https://es.wikipedia.org/wiki/SHA-2#Funci%C3%B3n_hash .


text:
How to correctly build transaction using PubKeyHash or CurrencySymbol as Datum parameter in cardano-cli?
My validator script expects PubKeyHash and Currency symbol parameters in Datum.
I wrote a script that compiles validator script to plutus and also forms Datum JSON parameters, as well as Redeemer parameters.
In validator script:
data Datum = Datum
    { owner  :: PubKeyHash
    , symbol :: CurrencySymbol
    }

data Redeemer = ActionOne | ActionTwo

Compilation script uses this same Datum object structure imported from Validator, as well as Actions from Redeemer (note that I pass these values as parameters to this script and correctly form Datum object):
writePlutusScript :: Datum -> Redeemer -> Redeemer -> FilePath -> PlutusScript PlutusScriptV1 -> SBS.ShortByteString -> IO ()
writePlutusScript datum rOne rTwo filename scriptSerial scriptSBS =
  do
  case Plutus.defaultCostModelParams of
        Just m ->
          let
            pData = Plutus.toData datum
            (logout, e) = Plutus.evaluateScriptCounting Plutus.Verbose m scriptSBS
                              [ pData
                              , Plutus.toData ()
                              , Plutus.toData dummyContext ]
          in do print ("Log output" :: String) >> print logout
                case e of
                  Left evalErr -> print ("Eval Error" :: String) >> print evalErr
                  Right exbudget -> print ("Ex Budget" :: String) >> print exbudget
                let datumData = encode (scriptDataToJson ScriptDataJsonDetailedSchema $ fromPlutusData pData)
                print $ "Datum value: " <> datumData
                let rOneData = encode (scriptDataToJson ScriptDataJsonDetailedSchema $ fromPlutusData (PlutusTx.toData rOne))
                print $ "One redeemer value: " <> rOneData
                rTwoData = encode (scriptDataToJson ScriptDataJsonDetailedSchema $ fromPlutusData (PlutusTx.toData rTwo))
                print $ "Two redeemer value: " <> rTwoData

The output is like this for Datum:
{
"constructor":0,
"fields":[
{"bytes":"6137356337356661467362633764353365663731356436343734356137613031633263316637363533623261653936323431336163353231"},
{"bytes":"6266636539643063643512345635636537356632356632323835346161373635396239633766323733633866643666623238393235623563"}
]
}

And this for Redeemer:
{"constructor":1,"fields":[]}

But then I am trying to get Datum hash with Cardano-cli, using the very same JSON:
cardano-cli transaction hash-script-data --script-data-value INSERT_JSON_HERE

it fails with error:
Value out of range within the script data: INSERT_JSON_HERE
Byte strings in script data must consist of at most 64 bytes, but it consists of 112 bytes.

Then changing 'bytes' values to corresponding 'string' values, this datum hash command worked.
When I am trying to build the transaction using these values (providing  --tx-in-datum-value SAME_DATUM_JSON_VALUE, --tx-in-redeemer-value SAME_REDEEMER_JSON_VALUE) with cardano-cli transaction build, it fails with:
Command failed: transaction build  Error: The following scripts have execution failures:
the script for transaction input 0 (in the order of the TxIds) failed with The Plutus script evaluation failed: An error has occurred:  User error:
The provided Plutus code called 'error'.

The command I use:
cardano-cli transaction build --alonzo-era ${MAGIC} --tx-in SOMETHING --tx-in-script-file SOMETHING --tx-in-datum-value SOMETHING --tx-in-redeemer-value SOMETHING --tx-in-collateral SOMETHING --change-address SOMETHING --protocol-params-file pparams.json --out-file SOMETHING

THE QUESTION: Any ideas why is it failing to build, and maybe how to get clearer error message?

Check out my question I have made with similar problem.
My guess would be, you need to index redeemer as 0, instead of 1 and most important of all Datum bytes fields are too big. They take up 114 bytes of space while the most you can provide is 64!


text:
How do I create and submit a transaction using only Nami Wallet?
I'd like to create a transaction using pure JavaScript on browser using Nami Wallet.
The docs shows only cardano.signTx(tx, partialSign) and cardano.submitTx(tx), but don't explain very well how to build the Transaction object.
How can I create a full Transaction object, let's say, transfering a specific amount of ADA from one wallet to another?

Should you mark one of the answers as accepted?

On Cardano, a transaction consists of UTxOs spent and UTxOs produced. The Nami wallet has a function to extract its UTxOs:
cardano.getUtxos(amount?: Value, paginate?: {page: number, limit: number}) : [TransactionUnspentOutput]
These UTxOs and the recipient address (as well as some static variables of the mainnet like fees...) are theoretically all you need to construct the transaction that transfers funds from one wallet to the other. The construction is not trivial, however, and you would probably want to use a library like https://github.com/Emurgo/cardano-serialization-lib that does this for you.

I understand the concept, but would like more coding details of the implementation, because both Nami Wallet and cardano-serialization-lib documentation do not provide practical guidance to make this happen

@DanielCukier did you solve this? I'd encourage you to share your solution as the lack of documentation is indeed a problem. Cardano wont succeed unless all of us do a better job of getting people educated on these day-to-day-tasks.

If you are open to integrating with a wallet other than Nami, then Typhon Wallet integration is seamless which does not require you to fetch UTXOs and manually build a transaction.
The below snippet is all you need to build a transaction.
const paymentTransactionResponse = await typhon.paymentTransaction({
  outputs: [
    {
      address:
        "addr_test1qz7jw975stagnvs00wsjny6y6gpazn86yvwcm2vy02j3up7mt68vuzvz4nzgs00x0shrgywvy674v6r2zcs8fxvvq27qfjq8np",
      amount: "6000000", // In Lovelace
    },
  ],
});

More examples, https://docs.typhonwallet.io/examples/paymentTransaction.html

Unfortunately this does not answer the question at all.

Is a long and awful process, Check this example using version 10.4  for all function definitions check my repo https://github.com/alice1989123/vending_machine/blob/main/Cardano/Wallet/Wallet.js

Build the TransactionBody Inputs Outputs Fees, and more minting burning etc
Hash the body and Sign it attach the witnesses  to the  the transaction,
Send it

    async function sendAda(senderAddress, senderprvKeys, lovelaces, address) {
      const reciverAddress = wasm.Address.from_bech32(address);
      const wasmSender = wasm.Address.from_bech32(senderAddress);

      const outPutValue = wasm.Value.new(wasm.BigNum.from_str(`${lovelaces}`));

      const protocolParameters = await getProtocolParams();

      const output = wasm.TransactionOutput.new(reciverAddress, outPutValue);

      const txBuilder = InitTx(protocolParameters);
      txBuilder.add_output(output);
      const utoxs_ = await getUtxos(senderAddress);
      const utxos = wasm.TransactionUnspentOutputs.new();
      utoxs_.forEach((utxo) => utxos.add(utxo));
      txBuilder.add_inputs_from(utxos, 1);
      txBuilder.add_change_if_needed(wasmSender);
      const txBody = txBuilder.build();
      const tx = wasm.Transaction.new(txBody, wasm.TransactionWitnessSet.new());
      const hash = await SignAndSend(tx, senderprvKeys);
      return hash;
    }

I believe this won't work for my case, because I am using the browser wallet. I don't have access to the sender private key. What I want is to create a transaction and submit it to the user wallet, so the user can sign it before I submit the transaction to the blockchain


text:
how to build new transaction based on the UTXO with NFT token?
I'm using test net. Currently, I've got the UTXO with minted token made by the simple cardano-cli tool for that.
At first step it looked like:
cardano-cli transaction build --alonzo-era --testnet-magic 1097911063 --tx-in 4225e8c9f605c08765e1c99036dd4ab684f75634934062a7e82af16131d76cd9#0 --tx-in-collateral 4225e8c9f605c08765e1c99036dd4ab684f75634934062a7e82af16131d76cd9#0 --tx-out "addr_test1vqwvs32x3wg5ea2l5tr7t93hpta8arwxllr4ey96dhl5d7sytaf9n + 998275900 lovelace + 1 1b4dc8260cbaa66b1140fad4aaac052e2e18c8da508ba6bf4efaa067.TestTokenName" --tx-out-datum-hash 45b0cfc220ceec5b7c1c62c4d4193d38e4eba48e8815729ce75f9c0ab0e4c1c0 --change-address addr_test1vqwvs32x3wg5ea2l5tr7t93hpta8arwxllr4ey96dhl5d7sytaf9n --mint "1 1b4dc8260cbaa66b1140fad4aaac052e2e18c8da508ba6bf4efaa067.TestTokenName" --mint-script-file "mint-TestTokenName.plutus" --mint-redeemer-value [] --protocol-params-file testnet-protocol-parameters.json --out-file mint-tx.raw
cardano-cli result : b'Estimated transaction fee: Lovelace 351488\n'

 cardano-cli transaction sign --tx-body-file mint-tx.raw --signing-key-file /home/user/cardano_work/cardano-node-test1_config/keys/payment1.skey --testnet-magic 1097911063 --out-file mint-tx.signed

cardano-cli transaction submit --testnet-magic 1097911063 --tx-file mint-tx.signed
Transaction successfully submitted.

after checking address I got:
cardano-cli query utxo --address addr_test1vqwvs32x3wg5ea2l5tr7t93hpta8arwxllr4ey96dhl5d7sytaf9n --testnet-magic 1097911063
                           TxHash                                 TxIx        Amount
--------------------------------------------------------------------------------------
102d73bf6e52fb42848ce085d325c9835f3a955494928c2eebe41efd63482e2f     0        1310316 lovelace + 2 6b8d07d69639e9413dd637a1a815a7323c69c86abbafb66dbfdb1aa7 + TxOutDatumNone
275644c0d040ee371495a6a963dec167f5499936adf7fd6fbc8cc0bae94e2d40     0        1372612 lovelace + TxOutDatumNone
275644c0d040ee371495a6a963dec167f5499936adf7fd6fbc8cc0bae94e2d40     1        998275900 lovelace + 1 1b4dc8260cbaa66b1140fad4aaac052e2e18c8da508ba6bf4efaa067.TestTokenName + TxOutDatumHash ScriptDataInAlonzoEra "45b0cfc220ceec5b7c1c62c4d4193d38e4eba48e8815729ce75f9c0ab0e4c1c0"
a18485d41697e664ee9f99e2bbd42d2957b88c99e90a9ea27039293c31eec8ec     0        1310316 lovelace + 2 6b8d07d69639e9413dd637a1a815a7323c69c86abbafb66dbfdb1aa7 + TxOutDatumNone

After that, I'm trying to run the same script but with a different minting policy to mint another token:
policy_id : 378e458eff0ee31583e2f1eb31e04e75d09e92fba642be06a8a80100
left money : 998275900 lovelace+1 1b4dc8260cbaa66b1140fad4aaac052e2e18c8da508ba6bf4efaa067.TestTokenName
Prepared CMD:
 cardano-cli transaction build --alonzo-era --testnet-magic 1097911063 --tx-in 275644c0d040ee371495a6a963dec167f5499936adf7fd6fbc8cc0bae94e2d40#1 --tx-in-collateral 275644c0d040ee371495a6a963dec167f5499936adf7fd6fbc8cc0bae94e2d40#1 --tx-out "addr_test1vqwvs32x3wg5ea2l5tr7t93hpta8arwxllr4ey96dhl5d7sytaf9n + 998275900 lovelace+1 1b4dc8260cbaa66b1140fad4aaac052e2e18c8da508ba6bf4efaa067.TestTokenName + 1 378e458eff0ee31583e2f1eb31e04e75d09e92fba642be06a8a80100.TokenWithMeta" --tx-out-datum-hash 45b0cfc220ceec5b7c1c62c4d4193d38e4eba48e8815729ce75f9c0ab0e4c1c0 --change-address addr_test1vqwvs32x3wg5ea2l5tr7t93hpta8arwxllr4ey96dhl5d7sytaf9n --mint "1 378e458eff0ee31583e2f1eb31e04e75d09e92fba642be06a8a80100.TokenWithMeta" --mint-script-file "mint-TokenWithMeta.plutus" --mint-redeemer-value [] --metadata-json-file meta-TokenWithMeta.json --protocol-params-file testnet-protocol-parameters.json --out-file mint-tx-TokenWithMeta.raw
cardano-cli result : Command failed: transaction build  Error: The transaction does not balance in its use of ada. The net balance of the transaction is negative: Lovelace (-365986) lovelace. The usual solution is to provide more inputs, or inputs with more ada.

cost value: -365986
Prepared CMD:
 cardano-cli transaction build --alonzo-era --testnet-magic 1097911063 --tx-in 275644c0d040ee371495a6a963dec167f5499936adf7fd6fbc8cc0bae94e2d40#1 --tx-in-collateral 275644c0d040ee371495a6a963dec167f5499936adf7fd6fbc8cc0bae94e2d40#1 --tx-out "addr_test1vqwvs32x3wg5ea2l5tr7t93hpta8arwxllr4ey96dhl5d7sytaf9n + 997909914 lovelace+1 1b4dc8260cbaa66b1140fad4aaac052e2e18c8da508ba6bf4efaa067.TestTokenName + 1 378e458eff0ee31583e2f1eb31e04e75d09e92fba642be06a8a80100.TokenWithMeta" --tx-out-datum-hash 45b0cfc220ceec5b7c1c62c4d4193d38e4eba48e8815729ce75f9c0ab0e4c1c0 --change-address addr_test1vqwvs32x3wg5ea2l5tr7t93hpta8arwxllr4ey96dhl5d7sytaf9n --mint "1 378e458eff0ee31583e2f1eb31e04e75d09e92fba642be06a8a80100.TokenWithMeta" --mint-script-file "mint-TokenWithMeta.plutus" --mint-redeemer-value [] --protocol-params-file testnet-protocol-parameters.json --metadata-json-file meta-TokenWithMeta.json --out-file mint-tx-TokenWithMeta.raw
cardano-cli final result : Command failed: transaction build  Error: The transaction does balance in its use of ada, however the net balance does not meet the minimum UTxO threshold.
Balance: Lovelace 0
Offending output (change output): addr_test1vqwvs32x3wg5ea2l5tr7t93hpta8arwxllr4ey96dhl5d7sytaf9n +
Minimum UTxO threshold: Lovelace 999978
The usual solution is to provide more inputs, or inputs with more ada to meet the minimum UTxO threshold

Can anyone give a hint on how to construct a minting transaction based on UTXO with minted value?
Does it relate to this issue: https://github.com/input-output-hk/cardano-node/issues/3364?

It might help anyone else.

use cardano-node/cardano-cli 1.31.0 It supports multi asset
Token names in that version are hex strings(not programmatically can get by: https://codebeautify.org/hex-string-converter)

Example:
Initial state:
cardano-cli query utxo --address addr_test1vqwvs32x3wg5ea2l5tr7t93hpta8arwxllr4ey96dhl5d7sytaf9n --testnet-magic 1097911063
                           TxHash                                 TxIx        Amount
--------------------------------------------------------------------------------------
102d73bf6e52fb42848ce085d325c9835f3a955494928c2eebe41efd63482e2f     0        1310316 lovelace + 2 6b8d07d69639e9413dd637a1a815a7323c69c86abbafb66dbfdb1aa7 + TxOutDatumNone
275644c0d040ee371495a6a963dec167f5499936adf7fd6fbc8cc0bae94e2d40     0        1372612 lovelace + TxOutDatumNone
275644c0d040ee371495a6a963dec167f5499936adf7fd6fbc8cc0bae94e2d40     1        998275900 lovelace + 1 1b4dc8260cbaa66b1140fad4aaac052e2e18c8da508ba6bf4efaa067.54657374546f6b656e4e616d65 + TxOutDatumHash ScriptDataInAlonzoEra "45b0cfc220ceec5b7c1c62c4d4193d38e4eba48e8815729ce75f9c0ab0e4c1c0"
9dec871d095c5ec88dd727f0bdafc9d854a366593e0777dcf56b3ee776d51ffe     0        1000000000 lovelace + TxOutDatumNone
a18485d41697e664ee9f99e2bbd42d2957b88c99e90a9ea27039293c31eec8ec     0        1310316 lovelace + 2 6b8d07d69639e9413dd637a1a815a7323c69c86abbafb66dbfdb1aa7 + TxOutDatumNone

Build transaction with new minting:
cardano-cli transaction build --alonzo-era \
--testnet-magic 1097911063 \
--tx-in 275644c0d040ee371495a6a963dec167f5499936adf7fd6fbc8cc0bae94e2d40#1 \
--tx-in-collateral 275644c0d040ee371495a6a963dec167f5499936adf7fd6fbc8cc0bae94e2d40#1 \
--tx-out "addr_test1vqwvs32x3wg5ea2l5tr7t93hpta8arwxllr4ey96dhl5d7sytaf9n + 997909914 lovelace+1 1b4dc8260cbaa66b1140fad4aaac052e2e18c8da508ba6bf4efaa067.54657374546f6b656e4e616d65 + 1 378e458eff0ee31583e2f1eb31e04e75d09e92fba642be06a8a80100.546f6b656e576974684d657461" \
--tx-out-datum-hash 45b0cfc220ceec5b7c1c62c4d4193d38e4eba48e8815729ce75f9c0ab0e4c1c0 \
--change-address addr_test1vqwvs32x3wg5ea2l5tr7t93hpta8arwxllr4ey96dhl5d7sytaf9n \
--mint "1 378e458eff0ee31583e2f1eb31e04e75d09e92fba642be06a8a80100.546f6b656e576974684d657461" \
--mint-script-file "mint-TokenWithMeta.plutus" \
--mint-redeemer-value [] \
--protocol-params-file testnet-protocol-parameters.json \
--metadata-json-file meta-TokenWithMeta.json \
--out-file mint-tx-TokenWithMeta.raw
cardano-cli std out : Estimated transaction fee: Lovelace 365986

I've built a docker image that does this stuff automagically for you.
https://github.com/berlinpool/cnft-utxo


text:
Is there any risk in sharing my rewards address?
I want to test ẗhe Maladex Rewards calculator but they ask me to enter my rewards address. Is there any conceivable risk in doing so?

The only risks associated with sharing any kind of public/verification keys or addresses have to do with de-anonymization. If you are concerned with Maladex, your ISP, a traffic sniffer, or any other entity possibly linking your rewards address with your IP address, then you might have something to worry about. However, assuming you aren't massively evading taxes, living in an oppressive regime, or have some other target on your back, there is very little  risk to your funds when sharing your rewards address.
If however any of the above do apply to you, or you prefer to stay on the ultra-paranoid side, there are still options. You can use cardano-db-sync to query chain information from your own running node, including the reward history for a given stake address.
Another option is to learn how to access the internet in a truly anonymous fashion, and use third parties like Maladex that way. Warning: this is a deep dark rabbit hole, not for the faint of heart. If you are interested though, I'd recommend starting with The Hitchhiker’s Guide to Online Anonymity.


text:
Failed to build and install cardano-wallet on ubuntu
I'm trying to build and install cardano-wallet on ubuntu according to https://developers.cardano.org/docs/get-started/installing-cardano-wallet/#building-and-installing-the-node
But once I run the below command,
stack build --test --no-run-tests
I'm getting this error.
Received ExitFailure 128 when running
Raw command: /usr/bin/git reset --hard f827a4321e42f528e25f6079f7af3eb18f10d391
Run from: /tmp/with-repo8046/cloned
Standard error:

fatal: Could not parse object 'f827a4321e42f528e25f6079f7af3eb18f10d391'.

Any idea?

What is your ubuntu version?

Try maybe git fetch and then try one more time that command?

Seems something is broken. :) I will try to reach out developers. Seems cardano-ledger repository don't have necessary commit.

I'm getting exactly the same error here, at object f827a4321e42f528e25f6079f7af3eb18f10d391 (using Ubuntu 20.04.2)

i'm using Ubuntu-20.04 with WSL2 on Windows 10.

I retried today and it worked.

This commit was referencing a pull request branch of cardano-ledger that was closed: jc/benchmark/1-29-0-with-time. A new branch was pushed to resolve this called cardano-wallet/deps-for-node-1.30.1
This is a weird oddity with GitHub where it will refuse to give you an archive for a commit, even if it's aware of it if it's been orphaned and no longer exists in an open branch.