text:
Cardano Multi-Sig Mint BabbageOutputTooSmallUTxO
I’m trying to build a multi-sig transaction to mint an NFT. The transaction will take some input from users wallet via coin selection and add an additional NFT as output.
The problem begans, when the wallet have some ada but all of them are locked with some tokens. We all know that you can’t just send a token alone; there must be some ada attached to it.
Consider this UTXO, for example.
Hex:-
828258205abda375b18b2097b2011f22dbf2d14643ce5fd7478ba4df6b21c2b91d9fd1a70182583901c13c23461bf40f5e07e1a0a84759e8e6b75dc0c6f2364bfa52f0b45fe7230182c948c67dc319960f10910f8489818f6f85163f0deb83e6fc821a003be9eca5581c0445383201b56c4acedf544afa57cb88bfbc616c35b57e5b7dbad2d1a144505245531a000153d8581c5f4fa7ef47236a2b2a6b9455e7685b6d5993c925680d507fce3cd3eaa5504e6f7a6f6d69433152616e6b3331323801504e6f7a6f6d69433152616e6b3432383601504e6f7a6f6d69433152616e6b3533343201504e6f7a6f6d69433152616e6b3534373301504e6f7a6f6d69433152616e6b3534393601581c6eae3a98e41c11c85a1620357a1eeae0a8df772287d6cf71313ad311b1544e6f7a6f6d69436e66742050617373202330323401544e6f7a6f6d69436e66742050617373202330343301544e6f7a6f6d69436e66742050617373202330343601544e6f7a6f6d69436e66742050617373202330353801544e6f7a6f6d69436e66742050617373202330363001544e6f7a6f6d69436e66742050617373202330383401544e6f7a6f6d69436e66742050617373202330383601544e6f7a6f6d69436e66742050617373202330383801544e6f7a6f6d69436e66742050617373202330393201544e6f7a6f6d69436e66742050617373202330393501544e6f7a6f6d69436e66742050617373202330393701544e6f7a6f6d69436e66742050617373202331303201544e6f7a6f6d69436e66742050617373202331323001544e6f7a6f6d69436e66742050617373202331323401544e6f7a6f6d69436e66742050617373202331323901544e6f7a6f6d69436e66742050617373202331343301544e6f7a6f6d69436e66742050617373202331343801581c8b6e715851dead233ae5c4f8ed1f192e78461d2f64d0f4bb35b823cba153464643466f756e64657273506173733030373301581cf0ff48bbb7bbe9d59a40f1ce90e9e9d0ff5002ec48f232b49ca0fb9aa1496a696d742e6b69726b01

CSL JSON:-
{
  "address": "addr1q8qncg6xr06q7hs8uxs2s36earntwhwqcmervjl62tctghl8yvqc9j2gce7uxxvkpugfzruy3xqc7mu9zclsm6urum7qlau4pp",
  "amount": {
    "coin": "3926508",
    "multiasset": {
      "0445383201b56c4acedf544afa57cb88bfbc616c35b57e5b7dbad2d1": {
        "50524553": "87000"
      },
      "5f4fa7ef47236a2b2a6b9455e7685b6d5993c925680d507fce3cd3ea": {
        "4e6f7a6f6d69433152616e6b33313238": "1",
        "4e6f7a6f6d69433152616e6b34323836": "1",
        "4e6f7a6f6d69433152616e6b35333432": "1",
        "4e6f7a6f6d69433152616e6b35343733": "1",
        "4e6f7a6f6d69433152616e6b35343936": "1"
      },
      "6eae3a98e41c11c85a1620357a1eeae0a8df772287d6cf71313ad311": {
        "4e6f7a6f6d69436e667420506173732023303234": "1",
        "4e6f7a6f6d69436e667420506173732023303433": "1",
        "4e6f7a6f6d69436e667420506173732023303436": "1",
        "4e6f7a6f6d69436e667420506173732023303538": "1",
        "4e6f7a6f6d69436e667420506173732023303630": "1",
        "4e6f7a6f6d69436e667420506173732023303834": "1",
        "4e6f7a6f6d69436e667420506173732023303836": "1",
        "4e6f7a6f6d69436e667420506173732023303838": "1",
        "4e6f7a6f6d69436e667420506173732023303932": "1",
        "4e6f7a6f6d69436e667420506173732023303935": "1",
        "4e6f7a6f6d69436e667420506173732023303937": "1",
        "4e6f7a6f6d69436e667420506173732023313032": "1",
        "4e6f7a6f6d69436e667420506173732023313230": "1",
        "4e6f7a6f6d69436e667420506173732023313234": "1",
        "4e6f7a6f6d69436e667420506173732023313239": "1",
        "4e6f7a6f6d69436e667420506173732023313433": "1",
        "4e6f7a6f6d69436e667420506173732023313438": "1"
      },
      "8b6e715851dead233ae5c4f8ed1f192e78461d2f64d0f4bb35b823cb": {
        "464643466f756e646572735061737330303733": "1"
      },
      "f0ff48bbb7bbe9d59a40f1ce90e9e9d0ff5002ec48f232b49ca0fb9a": {
        "6a696d742e6b69726b": "1"
      }
    }
  },
  "plutus_data": null,
  "script_ref": null
}

This wallet has 3.92 ADA in it, more than enough to overcome the min utxo rules.
But all of these ADA are locked with the tokens of that utxo. Which means if we add another token, we also have to add some additional lovelace from another UTXO; otherwise, this will throw a BabbageOutputTooSmallUTxO error.
"transaction submit error ShelleyTxValidationError ShelleyBasedEraBabbage (ApplyTxError [UtxowFailure (UtxoFailure (BabbageOutputTooSmallUTxO [((Addr Mainnet (KeyHashObj (KeyHash \"c13c23461bf40f5e07e1a0a84759e8e6b75dc0c6f2364bfa52f0b45f\")) (StakeRefBase (KeyHashObj (KeyHash \"e7230182c948c67dc319960f10910f8489818f6f85163f0deb83e6fc\"))),Value 3671749 (fromList [(PolicyID {policyID = ScriptHash \"0445383201b56c4acedf544afa57cb88bfbc616c35b57e5b7dbad2d1\"},fromList [(50524553,87000)]),(PolicyID {policyID = ScriptHash \"5f4fa7ef47236a2b2a6b9455e7685b6d5993c925680d507fce3cd3ea\"},fromList [(4e6f7a6f6d69433152616e6b33313238,1),(4e6f7a6f6d69433152616e6b34323836,1),(4e6f7a6f6d69433152616e6b35333432,1),(4e6f7a6f6d69433152616e6b35343733,1),(4e6f7a6f6d69433152616e6b35343936,1)]),(PolicyID {policyID = ScriptHash \"6eae3a98e41c11c85a1620357a1eeae0a8df772287d6cf71313ad311\"},fromList [(4e6f7a6f6d69436e667420506173732023303234,1),(4e6f7a6f6d69436e667420506173732023303433,1),(4e6f7a6f6d69436e667420506173732023303436,1),(4e6f7a6f6d69436e667420506173732023303538,1),(4e6f7a6f6d69436e667420506173732023303630,1),(4e6f7a6f6d69436e667420506173732023303834,1),(4e6f7a6f6d69436e667420506173732023303836,1),(4e6f7a6f6d69436e667420506173732023303838,1),(4e6f7a6f6d69436e667420506173732023303932,1),(4e6f7a6f6d69436e667420506173732023303935,1),(4e6f7a6f6d69436e667420506173732023303937,1),(4e6f7a6f6d69436e667420506173732023313032,1),(4e6f7a6f6d69436e667420506173732023313230,1),(4e6f7a6f6d69436e667420506173732023313234,1),(4e6f7a6f6d69436e667420506173732023313239,1),(4e6f7a6f6d69436e667420506173732023313433,1),(4e6f7a6f6d69436e667420506173732023313438,1)]),(PolicyID {policyID = ScriptHash \"8b6e715851dead233ae5c4f8ed1f192e78461d2f64d0f4bb35b823cb\"},fromList [(464643466f756e646572735061737330303733,1)]),(PolicyID {policyID = ScriptHash \"9c241d1a9269da78a85a0e1269ecd5f56477641df28b2ce5ccd65188\"},fromList [(4e6f7a6f6d69436e667420506173732023303234,1)]),(PolicyID {policyID = ScriptHash \"f0ff48bbb7bbe9d59a40f1ce90e9e9d0ff5002ec48f232b49ca0fb9a\"},fromList [(6a696d742e6b69726b,1)])]),NoDatum,SNothing),Coin 4055710)]))])

I'm looking for a way to prevent this kind of coin selection. Is there a way to calculate how much ADA of a UTXo isn't locked with any assets?
Also, how do you calculate the minimum output amount that are required to avoid OutputTooSmall error?

Is there a way to calculate how much ADA of a UTxO isn't locked with any assets?

I am not sure I follow the question. All the ADA inside a UTxO is locked with all the tokens inside the UTxO, they are all in the same boat, you cannot consume only part of a UTxO, you either spend it as a whole (and return some change) or you don't spend it at all.
Maybe what you meant is "how to calculate how much ADA I can spend from a UTxO without raising a transaction error", in which case we come to your next question, which effectively the same.

how do you calculate the minimum output amount that are required to avoid OutputTooSmall error?

You can see a complete response in the Cardano documentation. In summary

minUTxoVal = (160 + sizeInBytes (TxOut)) * coinsPerUTxOByte

Some Cardano tools offer easy ways to calculate this value. In lucid, you can use the min_ada_required function. In PyCardano, you can use the min_lovelace function.

I think I got your point, but I am still unsure of one thing. Let's say I picked an UTXO with random improve method that contains 2 ADA. Then I added 20 NFT as output. As you might guess, adding 20 NFT will set the minUtxo way higher than 2 ADA as the tx size will be big.
But I can only get the sizeInBytes(TxOut) once I build the transaction. And if the transaction is already built, what's the point of retrieving minUTXOValue then? What should be the appropriate approach here?

"And if the transaction is already built, what's the point of retrieving minUTXOValue then?" In your case the point is to not have it raise an error. When we calculate what fees we need to pay, we do the same thing in the background, we first the transaction with an arbitrary amount for the fees and then we calculate it and change it. You would do the same thing, you first create the transaction and then calculate the min utxo value and change it in the transaction again, seems redundant, but in your case is what you need to do.

Unless somehow you already know how the new output UTxO will look like (what values it will contain), in which case you don't need to build the full transaction, you can simply use the sizeInBytes(TxOut) function and give it as an argument the output you expect

I think what you need to do is figure out what mph + token names you have in the utxos, and then craft an output that consolidates the separate UTXOs (with their own minting policy + token name) into one output.   I would recommend you checkout Helios which has coin selection algorithms that may be able to help with that.  You may also need to augment your own offchain code by examining the following code snippet from the helios.js library to help create this specific output.
https://github.com/Hyperion-BT/helios/blob/main/helios.js#L35660

Here is a related problem where I needed to find out the number of a specific tokens in the input UTXOs.  This is because when I minted more of them, I wanted the output to be both the amount of tokens in the input + the new minted ones.

Source code: https://github.com/lley154/littercoin/blob/preprod-6.33/app/pages/index.tsx

mph? Can you elaborate a little bit? I tried to google the term but nothing came up

sorry, I should have been more clear.   mph = minting policy hash.

If you want to see other helios examples, you can checkout my repo here: https://github.com/lley154/helios-examples  and book here: https://github.com/lley154/helios-examples/blob/main/docs/Cardano%20Smart%20Contracts%20with%20Helios.pdf


text:
plutus-apps nix-shell on Mac M2 segmentation fault
I'm unable to run nix-shell on my new M2 Macbook.
I read through the posts from last year on setting up M1 Macbooks with previous plutus-apps tags, but the same steps do not seem to work.
Environment: I'm using a new M2 Macbook and plutus-apps tag v1.1.0
I followed the plutus-community install steps for M1 from https://github.com/input-output-hk/plutus-community/blob/main/docs/Environment/Build/Mac_M1.md

only change to this was in substituters and trusted keys (see notes below for more detail)

I installed Rosetta 2 with
sudo softwareupdate --install-rosetta --agree-to-license

and installed nix package manager with
sh <(curl -L https://nixos.org/nix/install)

this is my nix.conf
build-users-group = nixbld

experimental-features = nix-command flakes

substituters = https://cache.iog.io https://cache.nixos.org https://digitallyinduced.cachix.org https://all-hies.cachix.org https://cache.zw3rk.com

trusted-public-keys = hydra.iohk.io:f/Ea+s+dFdN+3Y/G+FDgSq+a5NEWhJGzdjvKNGv0/EQ= cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY= digitallyinduced.cachix.org-1:y+wQvrnxQ+PdEsCt91rmvv39qRCYzEgGQaldK26hCKE= all-hies.cachix.org-1:JjrzAOEUsD9ZMt8fdFbzo3jNAyEWlPAwdVuHw4RD43k= loony-tools:pr9m4BkM/5/eSTZlkQyRt57Jz7OMBxNSUiMC4FkcNfk=

system = x86_64-darwin
extra-platforms = x86_64-darwin aarch64-darwin

sandbox = false
extra-sandbox-paths = /System/Library/Frameworks /System/Library/PrivateFrameworks /usr/lib /private/tmp /private/var/tmp /usr/bin/env

keep-outputs = true
keep-derivations = true

& with that conf when I try to spin up plutus-apps I was finally able to get
nix build -f default.nix docs.site
to run, and I got past the standard M1 error I was seeing people have.
(https://github.com/input-output-hk/plutus-apps/issues/632)
Once I got past that error (with the updated nix conf above), and nix build completes successfully, when I run nix-shell  I get this error
segmentation fault  nix-shell

not very insightful error at all, and I am out of ideas on what might be causing it
any ideas on what might be going on or what else I can try?
Some other notes:

The old posts/solutions include hydra as a substituter, but this repo was deprecated last year by IOG in a node upgrade, so I've removed it
I have a couple of other substituters and trusted keys in there from a separate repo I was trying out, but I doubt those are related to this issue.

After days of spelunking the internet, I found a comment in IOG ask-nix-os suggesting to use
GC_DONT_GC=1 nix-shell

and that solved the problem.
As of today, if you follow all the steps in my issue post, plus run your nix shell with the prefix above you should be able to successfully get nix working with an M1/M2 Macbook

source: Stack Exchange

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

sort: votes


text:
Changing Pledge amount on the stake pool
I would like to increase the pledged amount on my stake pool. I searched online and I learned that I need to generate a new pool.cert among other things and that the change will take effect in two epochs. My question is: If I generate and re-register my pool with the new pool  certificate and my pool is assigned to mint block with-in those two epochs, will it mint those blocks or do I lose them since they were assigned/associated to the old certificate?
Thanks

With a new pool registration certificate, you will change some of the parameters, like pledge in your case. It has no influence on the blocks the pool is minting. The only potential problem is that you wont't match the new pledge, if you increase it and there is not enough ADA in your wallet after 2 full epochs, but the blocks will still be minted and adopted, you just won't win rewards for them. Another potential problem is changing the VRF or COLD keys by mistake when submitting a new pool registration certificate. This should not happen.

If I generate and re-register my pool with the new pool certificate and my pool is assigned to mint block with-in those two epochs, will it mint those blocks or do I lose them since they were assigned/associated to the old certificate?

Correct. The new certificate you submit is not valid until 2 epochs after you submit it.

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


text:
How to create Policy Id using cardano serlization lib?
I was wondering how to create the policy Id/script for the cardano assets.
I am new to cardano blockchain but I have worked on Ethereum. I read the docs provided by the cardano officials but couldn't find any possible way on how to work with this lib. Moreover, there is no information provided by cardano on how to use this lib or possibly I could find it.
Please provide the information about how to use this lib.
Thank you..

You can find a full example here in the the /doc/getting-started folder of the serialization lib:
https://github.com/Emurgo/cardano-serialization-lib/blob/master/doc/getting-started/minting-nfts.md
You basically compose your script depending on your requirements, e.g. by creating a scripts object via NativeScripts.new(), adding the individual script components (timelock / pub key hash) to that and wrapping them in a new_script_all() script.
The "policy id" is a hex representation of the final script hash, received like this (from the example above):
const policyId = Buffer.from(mintScript.hash().to_bytes()).toString("hex");

console.log(`POLICY_ID: ${policyId}`);


text:
Sources of cardano rest api
While testing some  tangocrypto api , it is asking for "collection_id" which I don't know what is it.
So are there any Rest API providers other than (tangocrypto.com, blockFrost.com and opencnft.io)?

Firstly, here's the documentation for the Tangocrypto API:
https://www.tangocrypto.com/api-reference/#/operations/nft-collection
The collection_id here is just the ID of an NFT Collection that you can create on the platform. (You receive it in the response when you create one via the "Create NFT collection" endpoint or list your collections via "List NFT collections".)
If you're looking to find assets on the blockchain, e.g. via policy id you can look at this endpoint:
https://www.tangocrypto.com/api-reference/#/operations/get-asset-by-policy
Secondly, here's another alternative you could look at, if needed: https://dandelion.link/

but , How can I fetch all data of NFT's like buy Price , sold price . rarity, meta data through wallet address in one api ?

The metadata is there, but the others are marketplace specific. Haven't used it but looks like the one you mentioned, opencnft.io, has aggregated lots of data, eg floor prices, traits for rarity etc. You can try it out in their docs: https://api.opencnft.io/1/#/Policy/PublicController_getPolicyFloorPrice. To get them "by address" you'd have to use any of the other APIs to fetch assets sitting at it and then get the NFT data for each.

I am doing the same process as you mentioned above. I want to fetch NFT data through users wallet address, so for that I am using (cardano-mainnet.tangocrypto.com /{app_id}/v1/addresses/{address}/assets) and this gives me policy_id and asset name which I am using in (api.opencnft.io/1/asset{asset}, where asset is "policy_id + asset name") which gives me some data i want and another api (api.opencnft.io/1/asset{asset}/tx) also gives some useful data. Problem is that all these Processes are taking time

Ok, I don’t know of any API that can get you the data faster unfortunately. The fastest way is probably to run your own node, query the chain locally und monitor the marketplace contracts yourself. I don't have experience setting that up though.


text:
Is Plutus off-chain code relevant for testing?
It was mentioned in lecture 1 that in this fourth cohort of the PPP we won't need to learn to write off-chain code in Plutus/Haskell. Nevertheless it appears that testing uses the emulator and it seems to me that Plutus off-chain code might be relevant for writing testing scenarios. Is this correct?  Would knowing about the "contract monad" be useful for writing tests?

From Lars' answer in the Q&A:

First of all, you can still use Haskell in Kuber to do the off-chain part.
As a side note, it is likely that GeniusYield will soon release a PAB replacement that is also a Haskell library.
If you want to write tests in emulator traces, you still need Plutus-Apps and understand the "contract monad".  But there are alternatives, like Plutus simple model developed by MLabs.
Plutus simple model is also a Haskell library and is the one used in this course (PPP fourth cohort).  It doesn't use the contract monad and is easier to use than emulator traces.  A forthcoming lecture on testing will use "Plutus simple model" (as do the tests in the homeworks).
Admittedly emulator traces are still quite nice, but it is unfortunate that you need all the theory behind the contract monad (and for this reason they will not be covered in this course).


text:
How to differenciate between fungible token and NFT from their API data?
I am fetching assets stored in my wallet address. I want to seperate the fungible tokens and NFTs ,  on what basis I can differenciate both of them from data I am fetching from API (opencnft.io) like policy_id or fingerprint or any other factor which differenciates both of them?

The problem with the given approach of verifying the amount of tokens through the /assets/ endpoint like suggested is that it might guarantee you that it is an NFT currently, but it does not guarantee that it will always be an NFT.
For instance, it might be that the native script "owner" minted only one token currently, but he can still mint however many assets he wants in the future.
In order to actually enforce the policy is locked and guarantee that a specific token is an NFT an always will be, you will need to look at the policy of that script. To do that, block frost offers you the endpoint /script/{hash}/json
For example, in pre-prod, the endpoint https://cardano-preprod.blockfrost.io/api/v0/scripts/ee518da45e3ebe2858669e4eaf7c3c5a7f9be7733e47e0d48c596fd3/json will give you the output
{
    "json": {
        "type": "all",
        "scripts": [
            {
                "type": "sig",
                "keyHash": "87f96fd385bb6911a6f8eb47d97093ce2e3b5db2d884db7b238b0cec"
            },
            {
                "slot": 21561710,
                "type": "before"
            }
        ]
    }
}

Which tell us that this script is governed by two rules. First, it can only be minted by the user with the key 87f96fd385bb6911a6f8eb47d97093ce2e3b5db2d884db7b238b0cec, second that it cannot be minted after the slot 21561710. This second part is what is important for us. NFTs are only guaranteed to be NFTs forever if the this second argument is present and if our current slot is greater than whatever slot is in that script.

what is the script hash ?

@Yogesh it is the minting policy of the token

How can one retrieve script hash using policy_id or wallet address ?

@Yogesh It is the policy ID

I can't find the API for this to retrieve script hash using policy ID ?

@Yogesh The script hash is the same thing as the policy ID. There is no need for any API. It is a synonym. The only exception are minting policies which are not created by native scripts, but rather by a Plutus script, in which case the script hash is the has of that Plutus script itself. But it has not being widely used yet and most NFT projects still use native scripts.

The only way to know if a token is an NFT is to check the Minting Policy that was used to create it. There will be the rules used to validate its creation, and you will see if in the rules there are some checks to prevent this Minting Policy to run more than once and to allow only the mint of 1 unit of this token.
There are two kinds of Minting Policies. Old ones with Native Scripts and newer ones with Plutus Scripts.
If they were minted with Native Scripts you need to see in the code some validations like @Mateus explained, with the slot before check:
{
   "slot": 21561710,
   "type": "before"
}

That means that this particular Minting Policy can't run after that slot.
If they were minted with Plutus Scripts you will need to check if the Minting Policy is a parametrized one using an specific UTXO, that the policy is checking that this UTXO is used in the transaction and that the quantity of units of the token minted is 1.
The way to get the code of the Minting Policies is not so clear.
With the Currency Symbol of the token you can try to find it in the blockchain. Some times you will find it, most of the times, not....
Some blockchain explorers let developers upload the code of their minting Policies.
Summarizing, there is not a flawless way to probe if a token is a NFT or not.
As @Mateus explain also, one token could be a NFT now, but another copy could be done after, and it will not be a NFT anymore.
The only way to know that is going to be for ever a NFT is reading the code of the minting policy.
I needed to perform this check in a project I was working for, and I just relay in Blockfrost: https://docs.blockfrost.io/#tag/Cardano-Assets/paths/~1assets~1%7Basset%7D/get
There you can see the "quantity" and the "mint_or_burn_count". Just check if they are both 1. And at least for the moment you are sure that is a NFT.

After having a quick look at their API, it looks like it is not possible to find if the token is fungible or not.
You can try to fetch the quantity using the /assets/ Blockfrost's endpoint to see if is just one (NFT) or more (fungible).


text:
TypeError: a bytes-like object is required, not 'Transaction'
I am trying to use the https://github.com/Python-Cardano/pycardano/blob/main/examples/native_token.py with minor changes, like pointing to mainnet (have tried preview as well). I have updated the address to point to my actual wallet and trying to create an nft. I am getting the below error
File "\Desktop\CDrive\work\Python3.7\lib\site-packages\pycardano\backend\blockfrost.py", line 230, in submit_tx
self.api.transaction_submit(f.name)
File "\Desktop\CDrive\work\Python3.7\lib\site-packages\blockfrost\utils.py", line 63, in error_wrapper
raise ApiError(request_response)
blockfrost.utils.ApiError: {'error': 'Bad Request', 'message': '"transaction read error RawCborDecodeError [DecoderErrorDeserialiseFailure \"Byron Tx\" (DeserialiseFailure 1 \"Size mismatch when decoding TxAux.\\nExpected 2, but found 4.\"),DecoderErrorDeserialiseFailure \"Shelley Tx\" (DeserialiseFailure 1 \"Size mismatch when decoding \\nRecord RecD.\\nExpected 4, but found 3.\"),DecoderErrorDeserialiseFailure \"Shelley Tx\" (DeserialiseFailure 1 \"Size mismatch when decoding \\nRecord RecD.\\nExpected 4, but found 3.\"),DecoderErrorDeserialiseFailure \"Shelley Tx\" (DeserialiseFailure 1 \"Size mismatch when decoding \\nRecord RecD.\\nExpected 4, but found 3.\"),DecoderErrorDeserialiseFailure \"Shelley Tx\" (DeserialiseFailure 79 \"expected string\"),DecoderErrorDeserialiseFailure \"Shelley Tx\" (DeserialiseFailure 79 \"expected string\")]"', 'status_code': 400}
I am not sure what is wrong, would be of great help if anyone can guide me to get it working. The same code minor change has given have also faced "  File "\Desktop\CDrive\work\Python3.7\lib\tempfile.py", line 481, in func_wrapper
return func(*args, **kwargs)
TypeError: a bytes-like object is required, not 'Transaction'"
Below is the full python file
"""
This is a complete walk through of minting a NFT on Cardano blockchain in pure Python code.
This example is inspired by https://developers.cardano.org/docs/native-tokens/minting-nfts#crafting-the-transaction
import pathlib
from blockfrost import ApiUrls
from pycardano import *
Copy your BlockFrost project ID below. Go to https://blockfrost.io/ for more information.
BLOCK_FROST_PROJECT_ID = ""
NETWORK = Network.MAINNET
chain_context = BlockFrostChainContext(
project_id=BLOCK_FROST_PROJECT_ID,
base_url=ApiUrls.mainnet.value, #ApiUrls.preprod.value,
)
"""Preparation"""
Define the root directory where images and keys will be stored.
PROJECT_ROOT = "blockfrost"
root = pathlib.Path(PROJECT_ROOT)
print(PROJECT_ROOT)
Create the directory if it doesn't exist
root.mkdir(parents=True, exist_ok=True)
"""Generate keys"""
key_dir = root / "keys"
key_dir.mkdir(exist_ok=True)
Load payment keys or create them if they don't exist
def load_or_create_key_pair(base_dir, base_name):
skey_path = base_dir / f"{base_name}.skey"
vkey_path = base_dir / f"{base_name}.vkey"
if skey_path.exists():
    skey = PaymentSigningKey.load(str(skey_path))
    vkey = PaymentVerificationKey.from_signing_key(skey)
else:
    key_pair = PaymentKeyPair.generate()
    key_pair.signing_key.save(str(skey_path))
    key_pair.verification_key.save(str(vkey_path))
    skey = key_pair.signing_key
    vkey = key_pair.verification_key
return skey, vkey

Payment address. Send some ADA (~5 ADA is enough) to this address, so we can pay the minting fee later.
payment_skey, payment_vkey = load_or_create_key_pair(key_dir, "payment")
address = "<myWalletAddress"
address = Address(payment_vkey.hash(), network=NETWORK)
#"addr_test1qqxypmc96e3pska6ch2ucq4uv5d7uz6nhpgcne4ea4hgmemv40lpm3wmc3wqk5arjpgzrccm0m9k72puaqzwsgrj47asmp86u7" #Address(payment_vkey.hash(), network=NETWORK)

print(address)
Generate policy keys, which will be used when minting NFT
policy_skey, policy_vkey = load_or_create_key_pair(key_dir, "policy")
"""Create policy"""
A policy that requires a signature from the policy key we generated above
pub_key_policy = ScriptPubkey(policy_vkey.hash())
A time policy that disallows token minting after 10000 seconds from last block
must_before_slot = InvalidHereAfter(chain_context.last_block_slot + 10000)
Combine two policies using ScriptAll policy
policy = ScriptAll([pub_key_policy, must_before_slot])
Calculate policy ID, which is the hash of the policy
policy_id = policy.hash()
print(f"Policy ID: {policy_id}")
with open(root / "policy.id", "a+") as f:
f.truncate(0)
f.write(str(policy_id))
#******************************************************************************************************************************************
"""Define NFT"""
Create an asset container
my_asset = Asset()
Create names for our assets
nft1 = AssetName(b"MY_NFT_1")
nft2 = AssetName(b"MY_NFT_2")
Put assets into the asset container with a quantity of 1
my_asset[nft1] = 1
my_asset[nft2] = 1
Create a MultiAsset container
my_nft = MultiAsset()
Put assets into MultiAsset container. In this example, we only have one policy.
However, MultiAsset container can hold multiple different policies.
my_nft[policy_id] = my_asset
Create the final native script that will be attached to the transaction
native_scripts = [policy]
#******************************************************************************************************************************************
"""Define NFT (Alternative)"""
The nft definition above is somewhat verbose.
We can also directly create native assets from python primitives.
my_nft_alternative = MultiAsset.from_primitive(
{
policy_id.payload: {  # Use policy ID created from above. We can't use policy_id here because policy_id's type  # is ScriptHash, which is not a primitive type. Instead, we use policy_id.payload (bytes)
b"MY_NFT_1": 1,  # Name of our NFT1  # Quantity of this NFT
b"MY_NFT_2": 1,  # Name of our NFT2  # Quantity of this NFT
}
}
)
my_nft and my_nft_alternative are equivalent
assert my_nft == my_nft_alternative
#******************************************************************************************************************************************
"""Create metadata"""
We need to create a metadata for our NFTs, so they could be displayed correctly by blockchain explorer
metadata = {
721: {  # 721 refers to the metadata label registered for NFT standard here:
# https://github.com/cardano-foundation/CIPs/blob/master/CIP-0010/registry.json#L14-L17
policy_id.payload.hex(): {
"MY_NFT_1": {
"description": "This is my first NFT thanks to PyCardano",
"name": "PyCardano NFT example token 1",
"id": 1,
"image": "ipfs://QmRhTTbUrPYEw3mJGGhQqQST9k86v1DPBiTTWJGKDJsVFw",
},
"MY_NFT_2": {
"description": "This is my second NFT thanks to PyCardano",
"name": "PyCardano NFT example token 2",
"id": 2,
"image": "ipfs://QmRhTTbUrPYEw3mJGGhQqQST9k86v1DPBiTTWJGKDJsVFw",
},
}
}
}
Place metadata in AuxiliaryData, the format acceptable by a transaction.
auxiliary_data = AuxiliaryData(AlonzoMetadata(metadata=Metadata(metadata)))
"""Build transaction"""
Create a transaction builder
builder = TransactionBuilder(chain_context)
Add our own address as the input address
builder.add_input_address(address)
Since an InvalidHereAfter rule is included in the policy, we must specify time to live (ttl) for this transaction
builder.ttl = must_before_slot.after
Set nft we want to mint
builder.mint = my_nft
Set native script
builder.native_scripts = native_scripts
Set transaction metadata
builder.auxiliary_data = auxiliary_data
Calculate the minimum amount of lovelace that need to hold the NFT we are going to mint
min_val = min_lovelace(
chain_context, output=TransactionOutput(address, Value(0, my_nft))
)
Send the NFT to our own address
builder.add_output(TransactionOutput(address, Value(min_val, my_nft)))
Create final signed transaction
signed_tx = builder.build_and_sign([payment_skey], change_address=address)
signed_tx = builder.build_and_sign([payment_skey, policy_skey], change_address=address)
print("############### Transaction created ###############")
print("------------------------------Signed transaction------------------------------")
print(signed_tx)
print("-------------------------------------Signed to CBOR------------------------------")
print(signed_tx.to_cbor())
Submit signed transaction to the network
print("############### Submitting transaction ###############")
chain_context.submit_tx(signed_tx)

I believe the error stems from the chain_context.submit_tx(signed_tx) because the API expects CBOR encoded transaction (couple lines above).
You might want to try
chain_context.submit_tx(signed_tx.to_cbor())


text:
Cardano-cli minting gives FeeTooSmallUTxO error when no collateral
For minting some tokens I use this transaction:
cardano-cli transaction build
  --testnet-magic 2
  --tx-in-collateral 44ed21bc50eecc24e892a5bad4a98f2187b66d1f5074db22763cbc69fb5910b6#1
  --tx-in 44ed21bc50eecc24e892a5bad4a98f2187b66d1f5074db22763cbc69fb5910b6#1
  --tx-out "addr_test1vqffq45nzrdsprua0nakp8f44xp6mzvrscmpq8alg9w888s63fusl 2000000
                + 1 59f6d5ab2a1849c6080c05aa6fee05df34c4fcb1ba0f22eb4344405b.6a6176656c696e"
  --mint "1 59f6d5ab2a1849c6080c05aa6fee05df34c4fcb1ba0f22eb4344405b.6a6176656c696e"
  --change-address addr_test1vqffq45nzrdsprua0nakp8f44xp6mzvrscmpq8alg9w888s63fusl
  --protocol-params-file protocol-parameters.json
  --minting-script-file policy.script
  --babbage-era
  --out-file unsigned.json

It submits perfectly and a token gets minted:
Estimated transaction fee: Lovelace 179229
Transaction successfully submitted.

But when I remove the --tx-in-collateral line (thinking you don't really need it for simple tokens), and submitting this similar transaction ...
cardano-cli transaction build
  --testnet-magic 2
  --tx-in 53617a238110219e7d8dded048c6a497dc4ac253fa6e4bb80842bcb82b61bb93#1
  --tx-out "addr_test1vqffq45nzrdsprua0nakp8f44xp6mzvrscmpq8alg9w888s63fusl 2000000
                + 1 59f6d5ab2a1849c6080c05aa6fee05df34c4fcb1ba0f22eb4344405b.6a6176656c696e"
  --mint "1 59f6d5ab2a1849c6080c05aa6fee05df34c4fcb1ba0f22eb4344405b.6a6176656c696e"
  --change-address addr_test1vqffq45nzrdsprua0nakp8f44xp6mzvrscmpq8alg9w888s63fusl
  --protocol-params-file protocol-parameters.json
  --minting-script-file policy.script
  --babbage-era
  --out-file unsigned.json

I get this FeeTooSmallUTxO error (on submitting) :
Estimated transaction fee: Lovelace 170913
Command failed: transaction submit  Error: Error while submitting tx:
   ShelleyTxValidationError ShelleyBasedEraBabbage (ApplyTxError
     [UtxowFailure (UtxoFailure (FromAlonzoUtxoFail (FeeTooSmallUTxO (Coin 175181) (Coin 170913))))])

I wouldn't expect a FeeTooSmallUTxO error! Can this be a bug in cardano-cli ?
Or do I need need to add any other parameters? Or do simple tokens also need collateral?
(for ref: transactions executed on preview network with cardano-cli 1.35.5 - linux-x86_64 - ghc-8.10, the policy.script contains { "keyHash": "6c835e5..bcf986d0c", "type": "sig" } )

You don't need collateral unless evaluating a plutus script.  I cannot reproduce this, perhaps something has changed since. Would you mind trying node and cli 1.35.6?

It just occurred to me that you might be providing more than one signing key to witnesses this transaction (e.g. when using sign cmd). If that's the case you must override the number of witnesses during build using --witness-override. This is because the balancing algorithm won't know how many signatures are required and assuming just one would underestimate the fee as a result. Use of the collateral input would increase the calculated fee, which would explain why this error wasn't seen previously.

Cardano Node 1.35.5 is still tagged as the latest release on https://github.com/input-output-hk/cardano-node. Where do I get hold of 1.35.6? (without having to build it myself)

@james The --witness-override solved the issue!

Solution to this problem: add --witness-override to the transaction build.
Here are the transaction build/sign/submit statements:
cardano-cli transaction build
  --testnet-magic 2
  --tx-in 53617a238110219e7d8dded048c6a497dc4ac253fa6e4bb80842bcb82b61bb93#1
  --tx-out "addr_test1vqffq45nzrdsprua0nakp8f44xp6mzvrscmpq8alg9w888s63fusl 2000000
        + 1 59f6d5ab2a1849c6080c05aa6fee05df34c4fcb1ba0f22eb4344405b.6a6176656c696e"
  --mint "1 59f6d5ab2a1849c6080c05aa6fee05df34c4fcb1ba0f22eb4344405b.6a6176656c696e"
  --change-address addr_test1vqffq45nzrdsprua0nakp8f44xp6mzvrscmpq8alg9w888s63fusl
  --protocol-params-file protocol-parameters.json
  --minting-script-file policy.script
  --witness-override 2
  --babbage-era
  --out-file unsigned.json

cardano-cli transaction sign
  --testnet-magic 2
  --tx-body-file unsigned.json
  --signing-key-file javelin.skey
  --signing-key-file policy.skey
  --out-file signed.json

cardano-cli transaction submit
  --testnet-magic 2
  --tx-file signed.json

Estimated transaction fee: Lovelace 175357
Transaction successfully submitted.

When trying the above without the --override-witness, I got this error:
Estimated transaction fee: Lovelace 170913
Command failed: transaction submit  Error: Error while submitting tx: ShelleyTxValidationError ShelleyBasedEraBabbage
  (ApplyTxError [UtxowFailure (UtxoFailure
  (FromAlonzoUtxoFail (FeeTooSmallUTxO (Coin 175181) (Coin 170913))))])

(tested using 1.35.5)


text:
Comparing VALUES in a smart contract. How to know if they will be normalized or not?
I need to make VALUES comparisons on chain.
I realized that if a use the (==) operator from Plutus it is very inefficient in matter of memory and cpu steps needed to compute.
(https://github.com/input-output-hk/plutus/issues/5135)
I wrote another way of equality compare and I got better results.
But the best results I got was with the proposal here:
https://github.com/input-output-hk/hydra/pull/709
The problem is that this way of comparing is UNSAFE, witch means that it only work when VALUES are NORMALIZED (always with some ADA value, sorted lists, not repeated currency symbols or token names). That is why they call it exact equality operator.
Since memory in transactions executions is so limited, I really will be happy using the UNSAFE equality on my contracts, but... I really need to understand when and how VALUES that are not normalized can end up in the on-chain validation code.
Im building the transactions and creating the VALUES they are using (the off-chain code), in React with Lucid and Cardano Serialization Lib.
Then on chain, Im taking some of the INPUT VALUES, adding or deleting tokens in them with the built in operator <>, and comparing the resulting VALUES with the VALUES in the OUTPUT UTXOS.
In summary, I need to know...

Could Lucid and Cardano Serialization Lib build a transaction with a VALUE that is not NORMALIZED?
Could the <> operator on chain des-normalize a VALUE?

Can someone put some light here for me?
I need to feel safe using this UNSAFE operations.
Thank you so much


text:
Can I view a Plutus smart contract on the NFT marketplace?
Can I view a Plutus smart contract of an NFT from the marketplace like (JPG store) and what is PubKeyHash ?

You cannot view it directly on the chain.
The PubKeyHash is just the payment part of their contract address.
It is a good custom that the smart contract should be open source, in the case of jpg.store, their contract is released on github as contract-v2.


text:
Which API can give the buy price and sold price of NFT of cardano blockchain?
I am working on Cardano NFT tool kit, which basically shows the NFT's owned by a user. The tool kit shows the various information about NFT stored in wallet like (Buy Price, Sold Price, Rarity, Holding period, Floor price) apart from this some other data like (Policy Id, FingerPrint, Collection name, Asset name, Image IPFS link ). I have tried to get this data from Wallet address ...first using (https://cardano-mainnet.tangocrypto.com/{app_id}/v1/addresses/{address}/assets) which gives me policyId , fingerprint , asset name and these data from first API that i have got used in the all other API's. Second using (https://api.opencnft.io/1/asset/{asset}/tx), third using (https://api.opencnft.io/1/asset/{asset}) and **fourth using (https://api.opencnft.io/1/policy/{policy}/floor_price) which gives. But these all  process in taking too much time to fetch the data.
So, is there any particular api which can give all these data or any solution for this?

My first thought was to go to https://blockfrost.dev/. Here is their API documentation: https://docs.blockfrost.io/. You'll need an API key, but for limited use you can get one for free and test out your scenario.
You can initially get the asset history.
curl -H "project_id: 123456" https://cardano-mainnet.blockfrost.io/api/v0/assets/ad79da159614ff55130b3a28189fbe5c429c0dfc1c0aeaf94a1de95e4b6964646f7330373138/history
[{"tx_hash":"79b99a605b46603dbeefefab83bc72dfc241dafd1236504014732d6c3d3a5195","action":"minted","amount":"1"}]

Grab the transaction hash(s) and then run
curl -H "project_id: 123456" https://cardano-mainnet.blockfrost.io/api/v0/txs/79b99a605b46603dbeefefab83bc72dfc241dafd1236504014732d6c3d3a5195

That will give you a lot of details you won't need, but you can look at output amount:
    "output_amount": [
        {
            "unit": "lovelace",
            "quantity": "19809463"
        },
        {
            "unit": "ad79da159614ff55130b3a28189fbe5c429c0dfc1c0aeaf94a1de95e4b6964646f7330373138",
            "quantity": "1"
        }
    ],

Here you can see that 19809463 lovelace (or 19.8094630 ADA) was spent on unit ...330373138. This is the first transaction, so we might assume this was the purchase price. The same goes for the sold price. If you want the latest sold price, use the latest transaction hash from the /txs api call. Or loop over each to get the price history.
Use whichever language you want for the curl calls, and loop to process the transaction data. Here's a little javascript to grab the tx_hash.
fetch('https://cardano-mainnet.blockfrost.io/api/v0/assets/ad79da159614ff55130b3a28189fbe5c429c0dfc1c0aeaf94a1de95e4b6964646f7330373138/history', {
   headers: {
      'project_id': '123456'
   }
})
   .then(response => response.text())
   .then(text => console.log(JSON.parse(text)[0].tx_hash))


text:
Can't collect due to a non existent script
I'm following Plutus Pioneers Program, 4th Cohort, I'm at Week 2 on testnet
I'm struggling a bit collecting the gift, I have do a slightly modified version of Gift, creating it works as expect:
$ scripts/query-address.sh $(cat code/Week02/experiments/factoring.addr)
                           TxHash                                 TxIx        Amount
--------------------------------------------------------------------------------------
2d1604d8ba3128cd1526b6c68f94f8eddcd83b530dda4560dd327f25ad39164d     0        3000000 lovelace + TxOutDatumInline ReferenceTxInsScriptsInlineDatumsInBabbageEra (ScriptDataNumber 42)

However, with bob:
$ scripts/query-address.sh $(cat keys/bob.addr)
                           TxHash                                 TxIx        Amount
--------------------------------------------------------------------------------------
2e1fe0fe79677804a70bff96b249d9912143a3464f4788d7a42b1f772bfb2050     0        10000000000 lovelace + TxOutDatumNone

Building the transaction:
cardano-cli transaction build \
  --babbage-era \
  --testnet-magic 2 \
  --tx-in 2d1604d8ba3128cd1526b6c68f94f8eddcd83b530dda4560dd327f25ad39164d#0 \
  --tx-in-script-file /work/code/Week02/experiments/factoring.plutus \
  --tx-in-inline-datum-present \
  --tx-in-redeemer-file /work/code/Week02/experiments/wrong-redeemer.json \
  --tx-in-collateral 2e1fe0fe79677804a70bff96b249d9912143a3464f4788d7a42b1f772bfb2050#0 \
  --change-address addr_test1vqywcrjdxm0eehsgl5djnjg8pqeq48jhky8e3aht60ustkg6urjkr \
  --protocol-params-file /work/code/Week02/experiments/wrong-protocol-parameters.json \
  --out-file /work/code/Week02/experiments/wrong-collect-factoring.txbody

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 redeemer pointer: RdmrPtr Spend 0 points to a Plutus script that does not exist.
The pointers that can be resolved are: fromList [(RdmrPtr Spend 0,(Spending (TxIn (TxId {_unTxId = SafeHash "2d1604d8ba3128cd1526b6c68f94f8eddcd83b530dda4560dd327f25ad39164d"}) (TxIx 0)),Nothing,ScriptHash "c06d15e27842d0ccd6c825a13b84830a14215e01c98a93567f8cdbf8"))]

Have you any hints about the issue?
Thanks

This error means you're providing a different script to the one needed to witness the spend. Remember the script address will be different if the script is changed.

I did a breaking refactoring, which changed the address.


text:
Unable to convert BuiltinString to JSON
I would like to include a BuiltinString in a datum but am unable to do so as BuiltinString has neither a FromJSON nor a ToJSON instance. Is there an alternative to implementing these instances by hand?

BuiltinString has no ToData instance so it cannot be used as Datum. One option is to encodeUtf8 and use the BuiltinByteString. Not sure why you want to use JSON though.


text:
Mint the royalty token with pycardano
Good morning everyone,
I have a question regarding the royalty token. I've already read about this subject, and I understand that I need to mint a token with metadata like this:
{
    "777": {
        "rate": "0.1"
        "addr": [
            "addr1q8g3dv6ptkgsafh7k5muggrvfde2szzmc2mqkcxpxn7c63l9znc9e3xa82h",
            "pf39scc37tcu9ggy0l89gy2f9r2lf7husfvu8wh"
        ]
    }
}

however I don't understand how can I associate this token to a policy id if it is not identified anywhere.
The normal metadata has it's policy id after the "721" identifier and before the properties of each token. But for this royalty token, only the "777" identifier is defined.
I wrote a code to mint NFTs following the example in pycardano repository, and it runs smoothly, but I don't know how to mint the royalty token using pycardano.
Can someone help me?
I hope you all have an awesome day :)

From CIP27:

Process Flow

Create policy for planned assets.
Mint no name token with community standard royalties metadata.
Burn no name token to free up UTxO (recommended, but not required).
Mint planned assets using this same policy.

In the transaction you have to mint a token of the intended policy ID, with empty asset name. The policy is not referenced in the metadata.

yes, thank you a lot. what was being confused was the "no name token" part. Solved.


text:
Is cardano native token ADA is same as the ADA balance I have in the wallet?
Is the number of cardano native tokens ADA is same as the ADA balance I have in the wallet?

In what context?

if i have one ADA token then does it represent that i have 1 ADA as usable money in the wallet?

Yes.
In the image below there is 243 ADA in that account, and 243 ADA is available. There are ways to lock up your ADA, like liquidity pools, abnormal staking, UTXO (wallets usually have more than one, and NFT's have to have a certain amount associated with them), spending passwords, etc. However generally speaking, if your wallet says you have it, you can spend it.


text:
Rust off-chain solutions
I am interested in learning Rust and I thought a good idea of doing so would be to build something on Cardano. What libraries and resources would you recommend for someone like me? I am specially interested in building, balancing and evaluating transactions (including possibly smart contracts).

Naumachia is specifically designed to make off-chain code easy with Rust. It uses CML under the hood for actually deploying/transacting, but that's much too low-level for the average developer IMO, and Naumachia abstracts away a lot of the headache with declarative APIs. There are just a number of features that are still WIP.
Naumachia also comes with testing infrastructure for creating ScriptContexts for testing your On-Chain code, as well as mock chains for testing your contract as a whole. It also syncs with the trireme cli for managing your test environments/keys.
There are multiple "Sample dApps" which are functional examples of Naumachia here. A lot of progress has been made since the README was written, but everything on there is still relevant to get your started. I'm hoping to add more tutorials soon, and hopefully a Demeter template as well.

You can try Cardano Multiplatform Lib.
It can be deployed to multiple platforms (Rust crate would be what you are interested in) and it handles:

Serialization & deserialization of Cardano core data structures
Useful utility functions for DApps and wallets


text:
The Plutus script evaluation failed [Homework Week 02]
I'm a have problem unlocking the smart contracts of the homework of week 02.
The Plutus code:
{-# LANGUAGE DataKinds           #-}
{-# LANGUAGE ImportQualifiedPost #-}
{-# LANGUAGE NoImplicitPrelude   #-}
{-# LANGUAGE TemplateHaskell     #-}

module Homework1 where

import qualified Plutus.V2.Ledger.Api as PlutusV2
import           PlutusTx             (compile)
import qualified PlutusTx.Prelude     (Bool, (&&),BuiltinData, True)
import           Utilities            (wrap, writeValidatorToFile, writeDataToFile)
import           Prelude              (IO)

---------------------------------------------------------------------------------------------------
----------------------------------- ON-CHAIN / VALIDATOR ------------------------------------------

{-# INLINABLE mkValidator #-}
-- This should validate if and only if the two Booleans in the redeemer are True!
mkValidator :: () -> (PlutusTx.Prelude.Bool, PlutusTx.Prelude.Bool) -> PlutusV2.ScriptContext -> PlutusTx.Prelude.Bool
mkValidator _ (x,y) _ = (x && y)

wrappedVal :: PlutusTx.Prelude.BuiltinData -> PlutusTx.Prelude.BuiltinData -> PlutusTx.Prelude.BuiltinData -> ()
wrappedVal = wrap mkValidator

validator :: PlutusV2.Validator
validator = PlutusV2.mkValidatorScript $$(PlutusTx.compile [|| wrappedVal ||])

saveHM :: IO ()
saveHM = writeValidatorToFile "./Homework1.plutus" validator

The cardano-cli script:
cardano-cli transaction build \
    --babbage-era \
    --testnet-magic 2 \
    --tx-in "$txin" \
    --tx-in-script-file "$assets/Homework1.plutus" \
    --tx-in-inline-datum-present \
    --tx-in-redeemer-file "$assets/redeemer-success.json" \
    --tx-in-collateral "$collateral" \
    --change-address "$(cat "$keypath/$name.addr")" \
    --protocol-params-file "$pp" \
    --out-file "$body"

# Sign the transaction
cardano-cli transaction sign \
    --tx-body-file "$body" \
    --signing-key-file "$keypath/$name.skey" \
    --testnet-magic 2 \
    --out-file "$tx"

# Submit the transaction
cardano-cli transaction submit \
    --testnet-magic 2 \
    --tx-file "$tx"

And the redeemer that I generated using the writeDataToFile function of the utilities module. Both values are the serialization of the tuple (True,True)so the smart contract should be unlocking the funds:
{"constructor":0,"fields":[{"constructor":1,"fields":[]},{"constructor":1,"fields":[]}]}

The above raises me this problem when building the transanction:
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 machine terminated because of an error, either from a built-in function or from an explicit use of 'error'.
Caused by: [
  (builtin unConstrData)
  (con data #a24b636f6e7374727563746f7200466669656c647380)
]
Script debugging logs:

Command failed: transaction submit  Error: Error while submitting tx: ShelleyTxValidationError ShelleyBasedEraBabbage (ApplyTxError [UtxowFailure (UtxoFailure (AlonzoInBabbageUtxoPredFailure (ValueNotConservedUTxO (MaryValue 0 (fromList [])) (MaryValue 4799493069 (fromList []))))),UtxowFailure (UtxoFailure (AlonzoInBabbageUtxoPredFailure (BadInputsUTxO (fromList [TxIn (TxId {_unTxId = SafeHash "18af21838e2ae7b1f078caca222b5f1c992aeb08e38ccbade289458bc97e8225"}) (TxIx 1)]))))])

Thank you for your responses in forehand!

How is $txin defined? The error you're getting seems to be that there is a problem with the utxo in.

The txin is the utxo of the smart contract at id 0: e6bfde96d8c6e1c0fafca91bebca1d0bc35034183ed1a824753835e2630c26ad
you can see it here:
https://preview.cardanoscan.io/address/70919d457eac2f4e68d6835f8643852b51f7eecc7a2a9cd31d0944b24b

BadInputsUTxO means the input UTxO doesn't exist. It may have existed previosuly and has since been spent. Query the ledger state for current UTxOs and make sure to update your $txin accordingly.

I'm confuse because the $txin is of the smart contract and is this:
e6bfde96d8c6e1c0fafca91bebca1d0bc35034183ed1a824753835e2630c26ad#0
You can view it here:
https://preview.cardanoscan.io/address/70919d457eac2f4e68d6835f8643852b51f7eecc7a2a9cd31d0944b24b
So the tx does indeed exist i think or could be expent (?)

It's complaining about 18af21838e2ae7b1f078caca222b5f1c992aeb08e38ccbade289458bc97e8225#1 that I can confirm is not in the ledge state. Whats's $collateral?

Yes it is complaining about that utxo but the input was set with an id #0.
I did the bash script again with another inputs this time, and results in an error with either of the $txin locked in the contract:
a2a5f6a632d62bac847631b90749b11f43a2d861f8cd9c6bb3e7a4e0b7c64ca9#0
f3adbc5cd55a7473bfd12e944982f372282b12ba4611cf1293891b77f2b7a43a#0
and the collateral is:
a5ff5ca6ef0525dd1eb337f8a385dfbd4715288f5bc47a76e44ad28eba9caffd#0
And then is ix complaining about with the last utxo at index #1, and that utxo doesn't exist at #1 just at #0 :S (whatever of both txin I use as an input $txin):

(BadInputsUTxO .... SafeHash "f3adbc5cd55a7473bfd12e944982f372282b12ba4611cf1293891b77f2b7a43a"}) (TxIx 1)]))

Ah, one problem is the build cmd is failing so it won't produce txbody output. This means the sign and submit cmds are using some older txbody. The unConstrData failure means script data cannot be deserialised, that's either the datum, redeemer or script context. I think it's your inline datum. Your validator expects () so you want to store ScriptDataConstructor 0 [] at the script output not ScriptDataMap [(ScriptDataBytes "constructor",ScriptDataNumber 0),(ScriptDataBytes "fields",ScriptDataList [])]

Thank you very much for your Help :D Tomorrow I will take another look into this problem, I will let you know how it goes.


text:
Recover a Cardano wallet offline
Is there a way to recover or generate the addresses of my wallet (24 seed) without using external servers (JavaScript)? Just like we do with other blockchains?
Example: https://iancoleman.io/bip39/

My preference is to use a javascript library for this.
For example, use https://github.com/StricaHQ/bip32ed25519 to generate/convert the seed phrase to a private/public key.
Then use a javascript/typescript Tx builder library like Helios https://github.com/Hyperion-BT/helios to extract an address from a public key.  No servers involved.

Do you have a working example combining both libraries?

Yes.  Here is a working example using both libraries to do a multi-signature nft with a front-end browser wallet and an back-end private key.   https://github.com/lley154/helios-examples/blob/main/nft-multisig/pages/api/getSignature.ts

@enzo to generate offline addresses from mnemonic, you can use cardano-addresses https://github.com/input-output-hk/cardano-addresses

Can´t see a working example in JavaScript where I pass a mnemonic and I generate addresses with it.

You can do it using cardano-cli and cardano-address (or cardano-wallet instead of cardano-address, with the same parameters) using the script here:
https://gist.github.com/cardano-apexpool/99784308812bdf7aa01446fa95f47fd2
I've been using it a lot in the last year.

Yes. I used the Mnemonic Method detailed here:
https://www.coincashew.com/coins/overview-ada/guide-how-to-build-a-haskell-stakepool-node/part-iii-operation/setting-up-payment-and-stake-keys
You'll need cardano-wallet on an air-gapped machine.


text:
How to fetch data of sold nft from my NAMI wallet through api?
I am using "https://api.opencnft.io/1/asset/{asset}/tx" which gives the buy price and timestamp of an NFT, I have to fetch the data(Sold Price, Timestamp) of the NFT when it is sold then how can i do it?

I recently gave an example of this in another question here. The sold price will be the latest transaction for that asset.

so, through "https://api.opencnft.io/1/asset/{asset}/tx " which is giving me  " sold_at" timestamp and using "https://cardano-mainnet.blockfrost.io/api/v0/assets/{asset}/transactions" which  also gives timestamp and the immediate next block timestamp's hash  from previous  opencnft api .... so  could this give me the sold price of the nft when I sold it ?

Yes, though the api won't call it an obvious name like "sold_at." It will simply be the output_amount quantity in lovelace.


text:
Week02 Homework 1
I am getting type mismatch when I use traceIfFalse. What could be be reason? And how could I get this resolved. I also noticed that it didn't fail while I build lecture examples.

Couldn't match expected type PlutusTx.Builtins.Internal.BuiltinString' with actual type [ghc-prim-0.6.1:GHC.Types.Char]'

In the first argument of traceIfFalse', namely "expected boolean True"'
In the first argument of ($)', namely traceIfFalse "expected boolean True"'
In the expression:
traceIfFalse "expected boolean True" $ (boolx == True && boolx == booly)
|
19 | mkValidator _ (boolx, booly) _ = traceIfFalse "expected 42" $ (boolx == True && boolx == booly)

You need to use the OverloadedStrings Haskell extension.
Add {-# LANGUAGE OverloadedStrings #-} to the top of your file.


text:
Does nmkr.io provide public api?
Does nmkr.io provide free usable cardano apis for NFTS or do we have to mint the nfts and build a project on their platform something like that ...and then we can use their api because in their apis it (projectuid, nftuid)?

Can you elaborate on your question about what the API should do? What actions are you looking to execute and what data are you looking for?

basically I want to fetch the "sold price" and "timestamp" of that txn if a user sells his nft

You have to register on their site, then create a project. If you have an existing nft project, you'll need the policy keys and a wallet. The items labeled as projectuid and nftuid are custom IDs you get from nmkr.io. So while you don't need to mint with them, you need to do all these setup steps before using their API. At least, I'm assuming you're looking at /v2/UpdateMetadata/{projectuid}/{nftuid} since those are the two params you mentioned.

To figure out if an NFT has been transferred to another wallet, you have to check the transactions the NFT was involved in. You can get that information from the blockchain using for example the koios API.
You can get all transactions (with timestamp) using: https://api.koios.rest/#get-/asset_txs
If you need more information, e.g. the addresses involved, you can get this information from another API endpoint:
https://api.koios.rest/#post-/tx_utxos
There are also other options like Blockfrost or DB sync.


text:
Can I communicate with my local test net via REST/WebAPI
I am using this https://github.com/woofpool/cardano-private-testnet-setup to run my local testnet.
I was using this
const CardanocliJs = require('cardanocli-js');
const cardano = new CardanocliJs(options);
const txinds = cardano.queryUtxo(walletAddress);

But now I want my script to run on a different machine than the node and because cardanocli-js use cardano-cli and cardano-cli use cardano-node it's impossible
Note:
The script and the machine will not keep any private keys. The script will generate transactions based on some parameters.
In most protocols, Nodes have rest api, but I can't find anything like that in cardano.
Should I start this on the same machine as Cardano node in order to achieve my goal? https://github.com/input-output-hk/cardano-graphql
Or maybe some other tool from the cardano ecosystem?


text:
Can't collect utxo from the gift script address
I'm following Plutus Pioneers Program, 4th Cohort.
In the 2nd week we learned the smart contract Gift.hs
-- This validator always succeeds
mkGiftValidator :: BuiltinData -> BuiltinData -> BuiltinData -> ()
mkGiftValidator _ _ _ = ()

and used make-gift.sh and collect-gift.sh scripts for sending/receiving ada to/from Gift.addr script address addr_test1wqag3rt979nep9g2wtdwu8mr4gz6m4kjdpp5zp705km8wys6t2kla
This address has some UTXOs like this one
                           TxHash                                 TxIx        Amount
--------------------------------------------------------------------------------------

0f7262dba9374e8819a2170516a86b70e3857001f9c0dbe82ebaafcac1c3a676     0        1000000000 lovelace + TxOutDatumInline ReferenceTxInsScriptsInlineDatumsInBabbageEra (ScriptDataConstructor 0 [])

which looks correct from the smartcontract's point of view (has TxOutDatumInline, etc), but when I try to send the tx and collect this utxo I get the error
Command failed: transaction submit  Error: Error while submitting tx: ShelleyTxValidationError ShelleyBasedEraBabbage (ApplyTxError [UtxowFailure (FromAlonzoUtxowFail (WrappedShelleyEraFailure (ExtraneousScriptWitnessesUTXOW (fromList [ScriptHash "3a888d65f16790950a72daee1f63aa05add6d268434107cfa5b67712"]))))])

Could someone explain me please why this is happening? Shouldn't the smart contract validator always succeeds?

I'm using only --tx-in-script-file and having the same error. I noticed that if you include the script of the same smart contract, I'm obliged to reference the script rather than using --tx-in-script-file. I want to be able to use --tx-in-script-file even if the UTXO includes a reference to the same script. Any solution for that?

ExtraneousScriptWitnessesUTXOW means the script witness is being included in the txbody when it doesn't need to be because the witness requirement is already satisfied by a reference script.
Either include the script in the txbody OR reference the UTxO where the script has been stored when building a transaction. You are only allowed to do one or the other.

Thanks for your answer James, but I still don't fully understand... Does this mean that an error was made while creating the transaction 0f7262...c3a676 ? And now there is no way to collect this UTXO from the gift address?

No. It means the transaction you are currently building is including both. e.g.. with the cli you are using both --tx-in-script-file and --spending-tx-in-reference

That output you are spending has both the reference script and the inline datum. So because you need to reference the input for its datum you must also use the reference script and not provide the script file.

Thanks for your patience James, the solution finally dawned on me :) My mistake was that when I tried to create the UTXO like 0f7262...c3a676, I specified a vesting.plutus as tx-out-reference-script-file, just for testing. But it 'works' (the error ExtraneousScriptWitnessesUTXOW occurs) only with --tx-out-reference-script-file "$assets/gift.plutus". Probably, in the case when the scripts do not match each other, the offchain validation does not start at all

Unfortunately I can't mark your answer as correct, because It requires 15 reputation at least, but you've helped me a lot. Thank you very much!


text:
Daedalus synch problem
Not always, but very often the Daedalus wallet seems to synchronize completely again. Shouldn't the downloaded blockchain be permanently on the computer and then only the missing rest be synchronized?

I'm not sure what your specific use case is, and maybe you just want Daedalus, but I would recommend not using it. While being a full node, it doesn't serve much purpose for network integrity.

yes it should be as you said. But, if not closed in the proper way, Daedalus will scan its db for corrupted chunks.
Always let Daedalus run when starting up or closing down.


text:
Api for historical USD rates?
I want to fetch the historical USD rates from a timestamp, is there any api available for that could be used in javascript?

Coingecko is what comes to my mind. Checkout https://www.coingecko.com/en/api/documentation -> /coins/{id}/history


text:
Building a transaction that will require both payment and stake key signature using Cardano Serialization Lib
Usually, when a build a simple transaction such as making a payment, the transaction usually requires the buyer's payment key. Here is an example transaction I made with Cardano Serialization Lib.
// Payload from API user
const payload = {
    address: 'addr_test...',
    utxos: [...]
}

const whitelist = ['stake_test1...', 'stake12']
const paymentAddress = 'addr_test1';
const amount = 10 * 1000000

const buyerStakeAddress = RewardAddress.new(
    Address.from_bech32(payload.address).network_id(),
    BaseAddress.from_address(Address.from_bech32(payload.address)).stake_cred()
)

// Franken address will get pass this
if( !whitelist.includes(buyerStakeAddress.to_address().to_bech32()) )
    return false

const protocol_params = await this.get_protocol_parameters(NetworkInfo.testnet_preprod().network_id())
const linearFee = LinearFee.new(
    BigNum.from_str(protocol_params.min_fee_a.toString()),
    BigNum.from_str(protocol_params.min_fee_b.toString()),
)

const txBuilderCfg = TransactionBuilderConfigBuilder.new()
    .fee_algo(linearFee)
    .pool_deposit(BigNum.from_str(protocol_params.pool_deposit))
    .key_deposit(BigNum.from_str(protocol_params.key_deposit))
    .max_value_size(parseInt(protocol_params.max_val_size))
    .max_tx_size(protocol_params.max_tx_size)
    .coins_per_utxo_word(BigNum.from_str(protocol_params.coins_per_utxo_word))
    .build();

const txBuilder = TransactionBuilder.new(txBuilderCfg);
const inputs = TransactionUnspentOutputs.new()

payload.utxos.forEach(raw => {
    inputs.add(TransactionUnspentOutput.from_hex(raw))
})

txBuilder.add_output(TransactionOutput.new(
    Address.from_bech32(paymentAddress),
    Value.new( BigNum.from_str(amount.toString()) )
))

txBuilder.add_inputs_from(inputs, CoinSelectionStrategyCIP2.RandomImprove)
txBuilder.set_ttl(protocol_params.slot + 3600)
txBuilder.add_change_if_needed(Address.from_bech32(payload.address));

const body = txBuilder.build()
const witnesses = TransactionWitnessSet.new();
const auxFinal = AuxiliaryData.new()
const transaction: Transaction = Transaction.new( body, witnesses, auxFinal )

return transaction.to_hex()

Here you can see it's only asking for my payment key signature.

From the looks of it, there is nothing wrong with this. But the problem is that Franken address will easily get pass the whitelist check condition with a spoofed stake address.
I am wondering if it's possible to ask for both payment and stake key signature in a transaction (maybe without involving any actual staking activity, such as delegating to a pool) so that a franken wallet cannot sign the tx as they don't have a staking private key.
Any ideas?


text:
How to get total fees of a NFT transaction in cardano blockchain?
Is there any api for to get transaction fees of the NFTs when buy or sold and does the transaction fees includes Royalty fees ?

There are several ways to get transaction information. The most known API provider is probably blockfrost.io, but there are others like tangocrypto.com, or api.koios.rest.
You'll need to know the transaction hash and will be able to query information like the spent transaction fee.
The transaction fee applies for using the network and is enforced on protocol level. The concept of royalties does not exist in the protocol. Hence, they are not part of the transaction fee.
DApps/marketplaces need to make sure to handle royalties themselves. You might be interested in reading the CIP 27 (Cardano Improvement Proposal) describing a community standard for royalties.
I'd suggest you check out this resource as it includes a lot of great information and links to start with: https://developers.cardano.org/docs/get-started


text:
How to correctly identify NFTs and FTs?

Here are some tokens: how would I differentiate NFTs from FTs in this case?
I am confused as "AdaFarm860" seems to be a NFT but it has a quantity of "4". I am  having some trouble figuring this out. Could you please help me with this issue?

If you relay in the API data you can expect that a NFT has only 1 mint_transaction, with 1 mint_quantity, and as result only 1 in quantity.
But that is not flawless... some asset can be minted one time, have the look and feel of a NFT and then it can be minted again, and now it is not a NFT anymore.
The only way to known if an asses will be for ever unique is to known the minting policy that produce it. You know the hash of that minting code, is the currency symbol or policy_id. That hash belongs to a unique source code. Sometimes that code is upload in some blockchain explorer and you can look at it.
There are two types of policies to mint assets in Cardano. Native scripts and Plutus Scripts.
Native scripts are easy to read. They can have something like this:
{ "slot": 21561710, "type": "before" }
That means that after that slot they can't be used again.
Plutus Scripts are complex. To create policies with one use only they consume an specific utxo. Because utxo exists only once, after they are consumed to create the nft you can be sure they can't run and mint again.
I hope it helps!


text:
Minting with MESH - Error Missing key witness for: 1e101f14d
Having an issue trying to mint an NFT with my own policy. It's throwing the error below:
Missing key witness for: 1e101f14d07f203b01f8.....
I am not sure what to do here and any assistance would be appreciated. Long time developer, short time developing on Cardano.
Here is my code:
const nativeScript: NativeScript = {
  type: 'all',
  scripts:
  [
     {
      type: 'sig',
      keyHash: '1e101f14d07f203b01f89d1562831374f....'
    },
    {
      type: 'before',
      slot: '317614504'
    }

  ]
};

const forgingScript = ForgeScript.fromNativeScript(nativeScript);

const { wallet, connected } = useWallet();
const [txHash, setTxHash] = useState<string | null>(null);
const [loading, setLoading] = useState<boolean>(false);

 const wallet_for_mint = new AppWallet({
    networkId: 1,
    fetcher: blockchainProvider,
    submitter: blockchainProvider,
    key: {
      type: "mnemonic",
      words: [
    'tenant',
....
      ],
    },
  });

 const assetMetadata1: AssetMetadata = {
      name: "ASSETNAME",
      type: "TYPE1",
      item: "FLAG",
      image: "ipfs://Qmb18wvCu.....",
    };

    const asset1: Mint = {
      assetName: "TESTASSET",
      assetQuantity: "1",
      metadata: assetMetadata1,
      label: "721",
      recipient:

      "addr.........e",
    };

    const txMint = new Transaction({ initiator: wallet_for_mint });
    txMint.mintAsset(forgingScript, asset1);

    const unsignedTxMint = await txMint.build();
    const signedTxMint = await wallet_for_mint.signTx(unsignedTxMint);
    const txHash = await wallet_for_mint.submitTx(signedTxMint);

Is this all the code? Where do you set the witness count?

Hey. Thanks for the reply. That is all the code. I dont see in the sample code where the witness count is set.

It appears that you need to call one of the signature methods from ForgeScript. In most of the examples, they use ForgeScript.withOneSignature(address). However there are multiple options:

withOneSignature
withAtLeastNSignatures
withAnySignature
withAllSignatures

This looks like it needs to be done before your call to ForgeScript.fromNativeScript(nativeScript). This might set the witness count in some way.
"The --witness-count 1 basically tells cardano-cli that there will be only 1 signing key required for this transaction to be valid. Since the UTXO input involved in this transaction will only be coming from payment1 wallet, so that means we indeed only need 1 key to sign the transaction."
https://developers.cardano.org/docs/integrate-cardano/creating-wallet-faucet


text:
Can anyone provide an easy to understand script that sends ADA using the Cardano Serialization Lib?
new to coding here. (obviously)
I am looking to understand how this works, and I am sure if I physically see the code I will pick up on it quick.
I am looking for a very simple script that sends ADA to a specified address when a user clicks a send button, preferably in PHP. I already have connect to wallet working on my site, I am just incredibly lost on sending ADA.
Thanks in advance.

To get started with the Cardano Serialization Lib, have a look at their examples (with code) in the Cardano Developer Portal: https://developers.cardano.org/docs/get-started/cardano-serialization-lib/generating-transactions
That being said, there are more high level libraries nowadays that make building transactions a lot more simple than using the Cardano Serialization Lib.
Edit: You don't even need to have any backend (server side code like PHP) if you just want to send some ADA from the users wallet to some other address.
You could use a JavaScript library that gets the UTXOs from the wallet-connect API, builds the transaction and submits it using the wallet-connect API.
See for example this: https://developers.cardano.org/docs/get-started/cardano-serialization-lib/generating-transactions

Looking at: https://developers.cardano.org/docs/get-started/cardano-serialization-lib/generating-transactions
I need guidance on how to insert this into a php page, so the user clicks a button to make this transaction take place. The link is just code, there needs to be an action for this code to take place. Am I missing something?

PHP code is executed on the server. I'm not aware of any PHP port of the serialization lib. This simple use case of sending ADA from the user wallet to another address can be done completely in the browser (using JavaScript). Therefore I suggested that you could use MeshJS. You would import the library in your HTML and then you can add a button that calls a JavaScript function. This function creates the transaction and submits it through the wallet in the users brwoser.

"This simple use case of sending ADA from the user wallet to another address can be done completely in the browser (using JavaScript)." Can you show me an example of this code working in Javascript?

Some examples using the MeshJs library can be found here: https://developers.cardano.org/docs/get-started/mesh/transactions-basic


text:
setup a Plutus project use haskell.nix Error on Mac M1
I'm trying to set up a Plutus project with flake on my Macbook by IOHK document
I did the following steps:

create default.nix
enter command nix flake init --template templates#haskell-nix --impure
nix develop
and then I got error bellow:

error: a 'x86_64-linux' with features {} is required to build '/nix/store/n1aq309bp7jm9kkv7wi88jrxyjr09apa-cabal.project.drv', but I am a 'x86_64-darwin' with features {benchmark, big-parallel, nixos-test}
(use '--show-trace' to show detailed location information)

I'm a newbie, I'm learning how to create a project that is scalable, easy to test, and develop. if anyone can solve it please help me! Thanks!

Do you have nix installed? The best way of getting all Plutus features is building this repo https://github.com/input-output-hk/plutus-apps using nix.


text:
Denied Cabal Access to pictures. Now Getting error
Accidentally denied Cabal Access to pictures through a prompt given.  Now, when I try to cabal Init I get this message "User/******/Library/Application Support/MobileSync: getDirectoryContents:openDirStream: permission denied (Operation not permitted)"
Ive tried change permissions in the file with CHMOD and reinstalling Cabal without success. Can anyone help me solve this permissions issue?  Im using a MAC.

I wonder if you need to follow these steps. If Cabal isn't listed as an app, try terminal. https://support.apple.com/guide/mac-help/control-access-to-files-and-folders-on-mac-mchld5a35146/mac


text:
How can I access Haddock documentation for Plutus?
The link to the Plutus documentation - https://playground.plutus.iohkdev.io/doc/haddock/ - is broken. Is there another way to browse the haddock documentation for the latest version of Plutus?

The playground has been discontinued. Haddock can now be accessed at https://input-output-hk.github.io/plutus/master


text:
Can one see Redeemer value on Blockchain?
Redeem value is never revealed anywhere right? i mean on the BlockChain explorer i cant see someone's redeem passed?
It it sent to Validator to validate and that's it.

which explorer are you referring to?

The redeemer is stored in the transaction, so is visible onchain.
CardanoScan.io is one example of a blockchain explorer that displays the redeemer value for transactions that execute a plutus script (contract).


text:
Limit the number for each Token (AssetName) within one Currency Symbol (Policy ID)
is there any way to limit number for each tokens within one minting policy, in Plutus validator?
For example for policy ab12 I want to allow users minting tokens, in different transactions. Сan the validator reject minting if the user try to mint the Token ab12.A_1 but the token with name 'A_1' has already been minted (i.e. max number is 1)? It is assumed that the number in the name means the maximum possible number of tokens with this name. The names of the tokens are not known in advance, i.e. unfortunately it is impossible to determine the list of tokens and send it in datum or something like that. But I hope that maybe there is another way?

Is the space of names that you allow bounded? And if so, how large is this space?

It can be very large, 10K or even more

I think there are two approaches to this, the classical and the cryptographic way of doing this.
The classical method: In this method, you do the same as you would do on any computer. You store the list of minted names (in a UTxO). Given a new mint, the stateful minting policy would check that the new name is not in the list and makes sure the new state has it in its list. The problem with this design is that a blockchain is bound in transaction size. Currently, any transaction cannot exceed 16kb (more or less). So theoretically, the database cannot exceed this limit (note that this is the absolute upper bound, in practice it will be much lower).
Now you can also decide to shard the database captured by multiple UTxO's. For example, store all names that start with the letter "a" in one UTxO and the letters "b" in another. This method might work, since upon minting a new name, only the database of that letter is needed in a transaction. Now this is again limited since it might be the case that names that start with the letter "c" get minted a lot, rendering the database full at some point. So choosing a method how to shard is the key here, and this depends totally on your constraints on the name. But remember that this subdivision has to be deterministic, a validator should be able to decide if the appropriate database is used given a name!
The cryptographic method: Since space and time are bound on a blockchain, there are some clever ways to create bound algorithms that proof a statement. For example, using Merkle tree's you can prove that something is a member of a database in a relatively low-impact way. But these are involved from a dev perspective. Similarly, I found this paper that lets you prove that you correctly failed to prove membership of an element, effectively proving that it is not a member. The paper also has a nice non-interactive algorithm where a minting policy could probably act as the verifier. Note, however, that this paper leverage pairing curves, which won't be available until next HF (if we are optimistic!).
So to conclude, there are ways, but it depends on your specific application.

Thanx for the very detailed answer, Fermat! At first glance Zero-Knowledge Proofs of Non-Membership looks like exactly what I'm looking for. Well, it looks like I have to wait for the next (or for the next after next) HF :)


text:
Understanding a datum declaration in typescript
At the bottom of this post are lines 52-68 of file lucid-vesting of week 4 (PPP fourth iteration).  I am having a hard time understanding line 60:
const dtm: Datum = Data.to<VestingDatum>(datum,VestingDatum);

Why are there two instances of VestingDatum?  It seems that the command to is converting datum to VestingDatum, but datum had already been declared to be of type VestingDatum.
// Creating a datum with a beneficiary and deadline
const datum: VestingDatum = {
    beneficiary: beneficiaryPKH,
    deadline: deadlinePosIx,
};

// An asynchronous function that sends an amount of Lovelace to the script with the above datum.
async function vestFunds(amount: bigint): Promise<TxHash> {
    const dtm: Datum = Data.to<VestingDatum>(datum,VestingDatum);
    const tx = await lucid
      .newTx()
      .payToContract(vestingAddress, { inline: dtm }, { lovelace: amount })
      .complete();
    const signedTx = await tx.sign().complete();
    const txHash = await signedTx.submit();
    return txHash
}

Lucid also has a minimal example for typed data here.
The function Data.to has the following signature (as seen from here):
/**
 * Convert PlutusData to Cbor encoded data.\
 * Or apply a shape and convert the provided data struct to Cbor encoded data.
 */
function to<T = Data>(data: T, shape?: Json): Datum | Redeemer {

Where the type Data which is a wrapper around your usual Plutus primitives (see this).
Lucid defines higher types here which correspond to their serialized version as one would expect.
Now seeing the definition of function to from Lucid's source code, you'll realize that it first wants to obtain this Data (this line) and then convert it for corresponding plutus types (the serialize function) in Cardano Multiplatform Library.
Now either you can play with so called raw/untyped datum (like in this example) in which case your T above will simply be that Data or you can play at a bit higher type level (like you would do when writing Plutus contracts) where lucid helps you get this T using Data.Static as seen here. The second parameter as you would understand by now, is not at type level and is for this - the shape of your structure. Also Json is essentially any type.


text:
When is Genius Yield going to release its PAB?
I know that GeniusYield announced some time ago that they would make their PAB open-source.
Does somebody know when they are going to do it?

Looks like they just announce it! It's out now...more at https://atlas-app.io/


text:
Get Master Key from Mnemonic seed for Cardano Byron wallet
I have wallet in Infinito wallet. My mnemonic seed has 12 words and Yoroi, Daedalus Wallet does not support it.
I can get different Master Private key, address for Cardano Shelley, Byron wallet from mobile wallet app.
I am going to get them from code.
The master private key of Cardano Shelley can be gotten by following code.
const rootKey = CardanoWasm.Bip32PrivateKey.from_bip39_entropy(
  Buffer.from(entropy, 'hex'),
  Buffer.from(''),
);

Ref: https://developers.cardano.org/docs/get-started/cardano-serialization-lib/generating-keys#bip39-entropy
But I can't get the master private key of Cardano byron wallet.
How can I get the private key and address of Cardano byron wallet from mnemonic?

Can you share what error you are getting when you say you cannot get it with that function?

What prefix does your Byron wallet start with? Ae2 or  Dd?

I don't get any error. I am getting another private key which is different from wallet app. Its prefix is Ae2

Actually, I am getting same private key as Cardano Shelley. I want to know if there is another way to get private key for Cardano byron

did anyone manage to recover the Ada Byron from Infinito wallet?

Hi @u30004 and welcome to the Cardano StackExchange. If you have a question about a new topic, please open a new question instead of posting an answer on a related question. Otherwise people will probably not see it and the likelyhood of getting an answer is close to zero.

Your private key in infinito is the right one to use, you just have to find the correct deviation numbers. I was recently hired to recover a byron wallet from the same app (infinito-wallet), I'll be releasing the script publicly once I get permission.

I used Private key from infinito wallet, so I can manage to get wallet address. But when I submit transaction, I am getting error. https://cardano.stackexchange.com/questions/10994/transaction-submit-error-missingvkeywitnessesutxow. What do you think?

I can send you an invite to the private repository to view the copy of the script I made to recover the wallet (byron) from infinito. What's your github?

My github ID is heindrick17. Thank you

https://github.com/kcxyzxyz/restore-byron-ada-infinito-wallet made it public.

Update*****. Byron era cardano that is stuck in Infinito wallets can be accessed and moved with the Moonstake wallet app. Tested and works. You import your wallet with your byron private key that Infinito gives you. Thanks to Hazel from the Infinito helpdesk.
There is quite a few of us with cardano stuck in our infinito byron wallet. Late 2022, they added a warning to the app to move our byron to shelly or it would become inaccessible. I had to roll back infinito app to previous version and sideload app install.  Most of us have our 12 word passphrase, private key, and public address. My public address shows the correct ada on block elporers.  Daedalus, yoroi (previous version) browser extension, and a few other wallets like adalite.io will accept 12 key passphrase, but will generate diff keys. So our ada is as of right now inaccessible. Infinito discontinued suppot and do answer emails as far as i know.  If any savy cardano-cl guys could write a script allowing us to insert our private keys and move our ada to shelly...thatd be real nice. Also worth paying a fee to the creator of such a script.  Becuase it is frustrating to have ur crypto stuck even though you have passphrase, pvtkey and pubkeys. I havnt found a solution with any known wallet yet.  The previous versions of infinito no longer have connectivity to a node i suppose. So, I, and many others are currently stuck. Any help would be greatly appreciated.
Side note, I emailed IOHK and Yoroi for help, they both responded promptly. But their solutions were to restore with daedalus or lacy.io, neither worked for me.

The way you obtain the rootKey from the mnemonic is the same for both Shelley and Byron.
For Byron, you then have to do the following to get the right address:
const accountKey = rootKey
  .derive(harden(1852)) // purpose
  .derive(harden(1815)) // coin type
  .derive(harden(0)); // account #0

const utxoPubKey = accountKey
  .derive(0) // external
  .derive(0)
  .to_public();

const byronAddr = CardanoWasm.ByronAddress.icarus_from_key(
  utxoPubKey, // Ae2* style icarus address
 CardanoWasm.NetworkInfo.mainnet().protocol_magic()
);

You can have more information here.

I already tried it. But I am getting another byron address which is different from Infinito wallet address. I think Infinito wallet was using old way to get private key and wallet address. Is there any other way to get private key?

I am not familiar with Infinito wallet. Is it possible to ask their team on how they do it?


text:
Need to access documentation for Plutus.Contract.Oracle but not available in https://input-output-hk.github.io/plutus/master/
Playground is discontinued but the updated documentation seems to be lacking in components that I have been working with.
I did try to look up the other versions they have listed in their gh-pages repo here https://github.com/input-output-hk/plutus/tree/gh-pages but those pages also don't seem to have those
Any idea how I can access the old documentation I have tried the way back machine as well but it doesnt have those pages cached

If you're talking about the Haddock documentation, it moved here (for plutus-apss) and there (for plutus).
Some modules are still missing in the plutus-apps repo, we're working on it.

Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.


text:
Transaction submit error MissingVKeyWitnessesUTXOW
I am @emurgo/cardano-serialization-lib-nodejs to submit transaction in cardano.
I am getting following error.
Transaction 5c98317bc6caf027b91e807ed1cdd78571b8f9a791202b5feff5b32fa5f71f1f rejected,
message: "transaction submit error ShelleyTxValidationError ShelleyBasedEraBabbage
(ApplyTxError [UtxowFailure (FromAlonzoUtxowFail (WrappedShelleyEraFailure
(MissingVKeyWitnessesUTXOW (WitHashes (fromList [KeyHash
\"7afb7e3bfc4a25c9b5387657e8f71ae0c2d5f3b26142b51592785972\"])))))])"

I checked https://forum.cardano.org/t/blockfrostservererror-transaction-submit-error-shelleytxvalidationerror-shelleybasederababbage-applytxerror-utxowfailure-fromalonzoutxowfail-wrappedshelleyerafailure-missingvkeywitnessesutxow-withashes-fromlist-keyhash-b5cfe7a19bd626bd0d26657e/114662 and I am using utxoKey as signKey, but I am still getting above error.
How can I fix it?
Following is my code snippet to get signKey and address.
const accountKey = bipPrvKey
    .derive(harden(44)) // purpose
    .derive(harden(1815)) // coin type
    .derive(harden(0)); // account #

  const utxoKey = accountKey
    .derive(0) // external
    .derive(0);

  const utxoPubKey = utxoKey.to_public();

  const byronAddr = CardanoWasm.ByronAddress.icarus_from_key(
    utxoPubKey,
    CardanoWasm.NetworkInfo.mainnet().protocol_magic()
  );

  const address = byronAddr.to_base58();

  return { signKey: utxoKey.to_raw_key(), address: address };

You are missing a key when signing your transaction. Which kind of transaction are you trying to submit? Check that the key you are using is the right one and if it is a staking transaction for example, you need to sign it also with the staking key.

I am trying to send transfer transaction. I am using utxoKey as ref url. But I am still getting error.

I added my code snippet. Please check @Falcon Stakepool

Why are you using Byron? Try using Shelley. Byron is and old type of address Cardano used until July 2020.

Yes. I know, but I am using infinito wallet, and it is byron address. I am using above code.

I suggest you use this code instead (Shelley address, not Byron):
    const accountKey = rootKey
      .derive(harden(1852)) // purpose
      .derive(harden(1815)) // coin type
      .derive(harden(0)); // account #0

    const utxoPubKey = accountKey
      .derive(0) // external
      .derive(0)
      .to_public();

    const stakeKey = accountKey
      .derive(2) // chimeric
      .derive(0)
      .to_public();

const baseAddr = CardanoWasm.BaseAddress.new(
  CardanoWasm.NetworkInfo.mainnet().network_id(),
  CardanoWasm.StakeCredential.from_keyhash(utxoPubKey.to_raw_key().hash()),
  CardanoWasm.StakeCredential.from_keyhash(stakeKey.to_raw_key().hash()),
);

const address = baseAddress.to_address();

You can find more information about this here.

My address is Byron address, not Shelley address. So, I am using my above code. Do you see any issue?

Yes, I think you are not deriving the accountKey in the right way. See my answer and try that derivation instead.

I am sure, I am deriving account key correctly, because I got correct byron wallet address from private key.

If I use your method, I get wrong address which has no balance.

Do you have any idea? @Falcon Stakepool

If you are getting the right wallet from your private key then it seems the problem is in the way you are signing your transaction. Can you please share the code for how you are building and signing your transaction?


text:
Is it possible to obtain the cbor hex/script bytes from a bech32 script address?
I would like to get the script bytes from the bech32 address of a script. Is this possible?

While all answers are insightful, here is an example that makes it possible to entirely get the jpg.store script bytecode from just its script hash obtained from the bech32 address, using the pycardano and python-blockfrost libraries:
from pycardano import (
    BlockFrostChainContext,
    Address,
    PlutusV2Script
)
import cbor2
from blockfrost import ApiUrls

# ------- Chain context
chain_context = BlockFrostChainContext(
    project_id="mainnetslL7jFzg8p4Hxk8pcJCRIcWvcM6P6FZE",
    base_url=ApiUrls.mainnet.value
)
jpg_store_addr = Address.from_primitive("addr1zxgx3far7qygq0k6epa0zcvcvrevmn0ypsnfsue94nsn3tvpw288a4x0xf8pxgcntelxmyclq83s0ykeehchz2wtspks905plm")
script_hash = jpg_store_addr.payment_part
script_cbor = chain_context.api.script_cbor(str(script_hash)).cbor
script_bytes = PlutusV2Script(cbor2.loads(bytes.fromhex(script_cbor)))
print(script_bytes.hex())  # equals jpg.store script bytecode as shown on cardanoscan

From some indexer, yes as it is common to support fetching script's information from it's hash. Here is an API endpoint for Blockfrost.
To obtain script's hash from its bech32 encoded address, you would first need to decode this bech32 encoding and then remove the 1 byte header (see CIP-19).

To expand on the previous answer, you can use https://docs.blockfrost.io/#tag/Cardano-Scripts/paths/%7E1scripts%7E1%7Bscript_hash%7D/get endpoint and a TypeScript conversion function from here https://github.com/blockfrost/blockfrost-utils/blob/40964699913a54417371c63739e6d0c19712dca1/src/validation.ts#L220-L235

Thought I'd give some context for others who might come across this.
The short answer:
No, you cannot derive it directly because the script address only exposes the script hash.
You can however find it using tools like this Blockfrost endpoint
Long answer:
Cardano addresses are made up of 3 parts; a header, payment part, and a delegation part.
   addr1  zxgx3far7qygq0k6epa0zcvcvrevmn0ypsnfsue94nsn3tvpw  288a4x0xf8pxgcntelxmyclq83s0ykeehchz2wtspks905plm
| header |                  payment part                    |                 delegation part                 |

If you decode to Hex you get
    11     9068a7a3f008803edac87af1619860f2cdcde40c26987325ace138ad  81728e7ed4cf324e1323135e7e6d931f01e30792d9cdf17129cb806d
| header |                      payment part                       |                     delegation part                     |

The payment part in the above tells a node how to validate the transaction:

Either it is a pubkeyhash from a wallet, in which case the node checks for that wallets signature
Or it is the hash of a script, in which case the node checks for an attached script and executes it

This means that the only information you know from a script address is the hash of the script, and there is no way to directly derive the script bytes from this due to the nature of hashing
If you use a tool like the Blockfrost endpoint above to get the script, you must provide the script hash which you can get from the payment part of the HEX representation of the address.


text:
PlutusTx TxInfo Type Mismatch
I am building a PlutusTx V1 Smart Contract for NFT Royalty distribution. Part of that requires totaling up the amount of Lovelace sent to the contract from the most recent tx. I came up with the following function to try and accomplish this:
{-# LANGUAGE ImportQualifiedPost #-}
{-# LANGUAGE DeriveGeneric  #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE NamedFieldPuns #-}

import Prelude                        qualified as P

import PlutusTx                       (makeIsDataIndexed)
import PlutusTx.Prelude               as Tx hiding (Semigroup(..), unless)
import PlutusTx.Builtins

import Ledger                         hiding (singleton)
import Ledger.Constraints             qualified as Constraints
import Plutus.Script.Utils.V1.Scripts qualified as Scripts
import Ledger.Typed.Scripts
import Ledger.Ada                     as Ada
import Ledger.Value
import Plutus.V1.Ledger.Tx

import Plutus.Contract
import Data.Aeson
import GHC.Generics                   (Generic)

{-# OPTIONS_GHC -fno-warn-unused-imports #-}

totalAdaAmnt :: TxInfo -> Integer
totalAdaAmnt TxInfo{txInfoOutputs} =
    let valueSum = foldMap (Ledger.txOutValue . Ledger.TxOut) txInfoOutputs
    in valueOf valueSum Ada.adaSymbol Ada.adaToken

But when I try to compile, I get the following error:
error:
    • Couldn't match expected type ‘Ledger.Value.Value’
                  with actual type ‘cardano-api-1.35.4:Cardano.Api.Value.Lovelace’
    • In the first argument of ‘valueOf’, namely ‘valueSum’
      In the expression: valueOf valueSum Ada.adaSymbol Ada.adaToken
      In the expression:
        let valueSum = foldMap (Ledger.txOutValue . Ledger.TxOut) txInfoOutputs
        in valueOf valueSum Ada.adaSymbol Ada.adaToken
   |
42 |     in valueOf valueSum Ada.adaSymbol Ada.adaToken

This is my first contract and I really don't know how to resolve this error. Ledger is key to many different parts of my code, whereas I'm not using the Cardano-api package anywhere except for in this function. Is there a Ledger equivalent for getting Ada amounts from previous script Txs? Or vice versa?
I looked throughout the newly hosted Haddock docs for PlutusTx and couldn't find any work around, so any help is immensely appreciated!

Could you also mention your imports?

@Sourabh yes I'll edit the question to include them