text:
How to generate script address from plutus script cborhex
I want to generate the address from the plutus script's cborhex value, but so far without much luck. I am using the alwayssucceeds.plutus contract as an example for which the cborhex value is 4E4D01000033222220051200120011 and the for which the address is known to be addr_test1wpnlxv2xv9a9ucvnvzqakwepzl9ltx7jzgm53av2e9ncv4sysemm8. What i want to do is derive the same address from the cboxhex by using the cardano-serialization-lib
Why not use the cardano-cli for this by running cardano-cli address build --payment-script-file alwayssucceeds.plutus --testnet-magic 1097911063 --out-file script.addr ?
Well, if it can be done in the cardano-serialization-lib then it means it can be done in the client's front end which is faster and requires less wiring to the backend. cardano-serialization-lib is already used for a lot of the interaction with the wallet and submitting transactions, so it is a natural place to derive the address from the cborhex
This is my code, but it does not produce the correct address
// cborhex of the alwayssucceeds.plutus
const cborhex = "4E4D01000033222220051200120011";
const cbor = Buffer.from(cborhex, "hex");
const blake2bhash = blake.blake2b(cbor, 0, 28); //blake2b-224 -> 28 bytes
const scripthash = ScriptHash.from_bytes(blake2bhash);
const cred = StakeCredential.from_scripthash(scripthash);
const networkId = NetworkInfo.testnet().network_id();
const baseAddr = EnterpriseAddress.new(networkId, cred);
const addr = baseAddr.to_address();
const addrBech32 = addr.to_bech32();

// hash of the address generated from script
console.log(Buffer.from(addr.to_bytes(), "utf8").toString("hex"))

// hash of the address generated using cardano-cli
const ScriptAddress = Address.from_bech32("addr_test1wpnlxv2xv9a9ucvnvzqakwepzl9ltx7jzgm53av2e9ncv4sysemm8");
console.log(Buffer.from(ScriptAddress.to_bytes(), "utf8").toString("hex"))

And the hex outputs are:
geneated from cborhex: 70d4e0f6e402a19e086f2fb9914124604ece088db0fa5906fb0f66fc07
generated by cardano-cli: 7067f33146617a5e61936081db3b2117cbf59bd2123748f58ac9678656
The corresponding bech32 addresses are:
geneated from cborhex: addr_test1wpnlxv2xv9a9ucvnvzqakwepzl9ltx7jzgm53av2e9ncv4sysemm8
generated by cardano-cli: addr_test1wr2wpahyq2seuzr097uezsfyvp8vuzydkra9jphmpan0cpczfflxx
The blake package is npm install blakejs
Similar question has been raised in the below 2 links, without an adequate answer so far:
Link1
Link2

Typically the CBOR hex would have a prefix of number of bytes and the data after that prefix.
So for example the CBOR hex 4E4D01000033222220051200120011 would have 4E bytes (14 bytes) after the prefix 4E namely 4D01000033222220051200120011 (use https://cbor.me to decode the cbor).
This might possibly be throwing off your blake2B hash  output?

I have since implemented this in a git repo:
https://github.com/dynamicstrategies/cardano-wallet-connector

I've answered this here, but as a reference I'll copy my answer below:

Plutus-Core script bytes are wrapped twice in a CBOR bytearray.
Use the following steps to calculate the script address:

unwrap one layer of CBOR
prepend a byte representing the PlutusScript version: 0x01 for PlutusScriptV1, 0x02 for PlutusScriptV2
calculate the 28-byte (224-bit) blake2b digest to get the payment part of the address
form the full script address using CIP19 (so for script addresses without a staking part simply prepend 0x70 to the digest)
encode the script address bytes using bech32 ("addr_test" prefix for testnet, "addr" prefix for mainnet)

The pseudo code of these steps would look as follows: encodeBech32("addr_test", prepend(hashBlake2b224(prepend(unwrapCborBytes(hexToBytes(cborHex)), 0x01)), 0x70))
As an example consider the commonly used AlwaysSucceeds script. It has
the following hexadecimal representation:
"4e4d01000033222220051200120011".

Unwrapping one layer of CBOR bytearray would give: "4d01000033222220051200120011".
Prepend 0x01: "014d01000033222220051200120011"
Blake2b 28-byte digest: "67f33146617a5e61936081db3b2117cbf59bd2123748f58ac9678656"
Prepend 0x70: "7067f33146617a5e61936081db3b2117cbf59bd2123748f58ac9678656"
Bech32 encoding of testnet address: "addr_test1wpnlxv2xv9a9ucvnvzqakwepzl9ltx7jzgm53av2e9ncv4sysemm8"

Don't ask me why Plutus-Core scripts are wrapped twice in CBOR, and
then unwrapped once to calculate the address. Some smart guys
somewhere must have a good reason.
If you'd like to do these calculations in Javascript without some
complicated Rust/Haskell dependencies check out the Helios Lang
library. The library is UNLICENSEd so you can copy the relevant
functionality as you please.


text:
Ensure a unique policy ID for a "time before" type minting policy
Let's suppose I am starting an NFT project, and I choose to use a time-lock based policy script.  For example, the policy is enabled until some slot in the future.
E.g, here's the Hosky Cash Grab NFT script, which is open until slot 112500819.
{
  "type": "all",
  "scripts": [
    {
      "keyHash": "4d04380dcb9fbad5aff8e2f4e19394ef4e5e11b37932838f01984a12",
      "type": "sig"
    },
    {
      "slot": 112500819,
      "type": "before"
    }
  ]
}

When you calculate the Blake2B hash of the policy script serialized to bytes, you get a policy ID, e.g. a5bb0e5bb275a573d744a021f9b3bff73595468e002755b447e01559.
If another project happens to choose the same slot for their required-time-before policy and generates the same script or they simply choose to use the same script, won't they also have the same policy ID? This seems like a bad outcome, since I assume that querying the NFT assets minted under the policy ID could potentially show NFTs from another project.  Am I correct about this?
As a related question, I understand that projects may register a policy ID for their project in a github repo Cardano-NFTs/policyIDs.  What protection or value does registering offer?

They will also have to come up with the same keyHash to have the same policy ID, and that is virtually impossible.

source: Stack Exchange

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

sort: votes


text:
cardano-cli submit error: ScriptWitnessNotValidatingUTXOW
I have a problem when submitting a transaction using cardano-cli 1.33.
This is my transaction:
cardano-cli transaction build-raw
--tx-in 0e2a21444b1aeeba7cb10f21d221ae7ff844f0b4f8c444e557cd8d4fd1396cc2#1
--tx-in e4dcdfd68ea1cbf52425f775c92a83404652f9be9b24b6c8d9cf53d9ba563d90#0
--tx-out addr1q96x3lat2putrufnr4nml4dpaeflmk9f0necnwags593fyczhes4kfnypptyuqsm824w5mhx4p4venlcc4l8w6rlsdzskzcvwu+21793799+"1 7ed6bfc18a525bac4b0891c5fc106e8cf06ccfcf2926bf58a35b55e4.005400490054004f0030003200350030"
--mint="1 7ed6bfc18a525bac4b0891c5fc106e8cf06ccfcf2926bf58a35b55e4.005400490054004f0030003200350030"
--minting-script-file /home/node/Desktop/test/src/utilities/../keys/tmp/script_4wtn6rz8h.json
--metadata-json-file /home/node/Desktop/test/src/utilities/../keys/tmp/metadata_fab5bmmo5.json
--invalid-hereafter 82089724
--invalid-before 0
--fee 206201
--out-file /home/node/Desktop/test/src/utilities/../keys/tmp/tx_d9ns8yg52.raw
This is my mint script:
{
"type": "all",
"scripts": [
{
"slot": 82089724,
"type": "before"
},
{
"keyHash": "c4aae7aca5e060793f24fbf860f6538fce187fe28675d7d43481d93d",
"type": "sig"
}
]
}
and this is the error that i get:
Error: Error while submitting tx: ShelleyTxValidationError ShelleyBasedEraAlonzo (ApplyTxError [UtxowFailure (WrappedShelleyEraFailure (ScriptWitnessNotValidatingUTXOW (fromList [ScriptHash "7ed6bfc18a525bac4b0891c5fc106e8cf06ccfcf2926bf58a35b55e4"])))])
Any idea? Let me know if you need more info.
Thank you a lot!

Would need your signing command to be able to fully assess what you're doing wrong.

Without seeing your signing command it's difficult to discern what you're doing wrong. Can you confirm you are referencing the policy skey in your signing command? --signing-key-file keys/policy.skey

Try to follow the transaction pattern found here toward the end of the page. It worked for me.
You need to add
--mainnet \
--alonzo-era \
--witness-override 2 \

You can probably drop the --invalid-hereafter, unless you think you specifically need that. Remove the --fee. Also, make sure your invalid-hereafter is in the future. You may only need 1 tx-in as long as that utxo has enough to cover your transaction.

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


text:
How to retrieve an addresses transaction history inside a plutus contract
I am trying to implement so logic to ensure smart contract (SC) validation upon certain conditions - which are derived from the end-users transaction history.
If I parameterise the SC and take the users address or public key hash (pkh) how can I look up the last N transactions to/sent from that address.
I need to be able to do this within the mkValidator logic.
Example:
mkValidator :: pkh -> () -> () -> () -> Bool
mkValidator pkh _ _ _
| pkh last transaction was to the specified user = True
| otherwise = False
I am attempting to make some free and opensource code for the community that tackle a fundamental problem in the Cardano protocol (i.e. it scales with the number of users) so I am attempting to stay away from blockfrost and other paid API services.

The current state of Plutus makes this impossible to do. Instead, you have to try and use a custom DB-sync server, and then construct the off-chain code in such a way that it passes the looked-up values to the Haskell program.
Note that you will have to use lifting to ensure that the values passed by the Haskell code, can configure the Plutus app.
The state of Plutus mentioned here is everything available on and before  Feb 22 2022.


text:
Why is String being interpreted as a type?
According type applications, this extension allows to give explicit type arguments to a polymorphic function.
type VestingSchema =
             Endpoint "give" GiveParams
         .\/ Endpoint "grab" ()
-- ...
endpoints :: Contract () VestingSchema Text ()
endpoints = awaitPromise (give' `select` grab') >> endpoints
   where
     give' = endpoint @"give" give
     grab' = endpoint @"grab" $ const grab

This does not allows to give values to a polymorphic function, so I have figured out that actually those "strings" at @"give" and @"grab" are actually something similar to types, because the type Endpoint has this type/kind signature:
type Endpoint :: ghc-prim-0.6.1:GHC.Types.Symbol
                 -> * -> row-types-1.0.1.2:Data.Row.Internal.Row *
type Endpoint l a =
  l
  row-types-1.0.1.2:Data.Row.Internal..== (Wallet.Types.EndpointValue
                                             a,
                                           Plutus.Contract.Effects.ActiveEndpoint)
  :: row-types-1.0.1.2:Data.Row.Internal.Row *
        -- Defined in ‘Plutus.Contract.Request

So that l has kind Symbol. Why this is working with TypeApplications? Can I use this "give" and "grab" as type and/or type constructors anywhere in my code?

The extension that you are after is not TypeAplications, but DataKinds. I liked the explanations here: https://stackoverflow.com/questions/20558648/what-is-the-datakinds-extension-of-haskell

DataKinds explains why Endpoint can receive a type as argument and return a concret type, but it does not explain why I am allowed to use "give" and "grab" as type references on @ operator argument

No, because of DataKinds you can use "give" as a type, both in Endpoint and in the type application. Because of the DataKindsextension, String becomes a kind and the values of type String become types of kind String.

Also see the example Lars gave in the lecture https://youtu.be/qoUfgaHs1CI?list=PLNEK_Ejlx3x230-g-U02issX5BiWAgmSi&t=855:

type application allows us to disambiguate the type of callEndpoint
data kinds allows us to use type-level strings


text:
Royalities CIP 27
I followed the  CIP 27 for implementing royalities:
https://cardanoupdates.com/commits/facb8aa0ad9aa41f1a047b2000674fdea2162e71
Mint no name token with the policy then burn it wit the metadata incluiding royalities info:
for example:
https://testnet.cardanoscan.io/transaction/2471b2b3092744b21ee7eb45f68e37f753f834ab911567219d9127e399f4ba9a?tab=metadata
   {
   addr: [
      "addr1q88604np2z4hkl9a78dhuxasnssrxzk5kz497yvw4wq7jjp7vt8s8tygau8",
      "fl40vg3t7gxdzkq7uxl8sqmaqqkdxca0sg9y"
   ],
       rate: "0.1"
}

then I burn the token.
My doubt is if should I add the same data that I added in the initial mint/burn as a field in the standard 721 metadata? so  the marketplace can fetch this field, or if it is not needed, i am guessing it should not be needed otherwise the initial mint/burn mechanism would be not needed, right?

No, don't add your 721 data here. The above example is all you should have, and then burn the token.

Thank you, may I ask how do you know this is the right way to do it?

Because I run Cardano minting vending machines for artists and have done it dozens of times.. :)
I've also spoken with the person who initially wrote the 777 CIP proposal. You can find the details here:
https://github.com/cardano-foundation/CIPs/pull/116/files


text:
Calculation cpu and memory exUnits on transaction submit is different then on transaction build?
I am trying to build a non-optimized script and during the cardano-cli build transaction I got an error:
Command failed: transaction build  Error: The following scripts have execution failures:
the script for transaction input 2 (in the order of the TxIds) failed with:
The Plutus script evaluation failed: An error has occurred:  User error:
The budget was overspent. Final negative state: ({ cpu: 3356097790
| mem: -240
})
Script debugging logs:
the script for transaction input 3 (in the order of the TxIds) failed with:
The Plutus script evaluation failed: An error has occurred:  User error:
The budget was overspent. Final negative state: ({ cpu: 3356097790
| mem: -240
})
Script debugging logs:
the script for transaction input 4 (in the order of the TxIds) failed with:
The Plutus script evaluation failed: An error has occurred:  User error:
The budget was overspent. Final negative state: ({ cpu: 3356097790
| mem: -240
})

After optimization (BuiltinData -> BuiltinData -> BuiltinData -> () and custom ScriptContext)  build succeeded but then submit started to report error:
Command failed: transaction submit  Error: Error while submitting tx: ShelleyTxValidationError ShelleyBasedEraAlonzo (ApplyTxError [UtxowFailure (WrappedShelleyEraFailure (UtxoFailure (ExUnitsTooBigUTxO (WrapExUnits {unWrapExUnits = ExUnits' {exUnitsMem' = 16000000, exUnitsSteps' = 10000000000}}) (WrapExUnits {unWrapExUnits = ExUnits' {exUnitsMem' = 18581638, exUnitsSteps' = 6410063947}}))))])

Why does this happen? Shouldn't calculations be the same for build and submit so if it passes build it should pass also submit?


text:
How to search for a token by name on Cardano.io?
Is there any way that I can get a token name on cardano explorer(cardano.io) like we can on other blockchains?  For example, Ethereum(etherscan.com) or Binance(bscscan.com)?
Why is it that almost all tokens on the Cardano Blockchain are not found in the CMC site?
I am looking for a token called "FLANO" but can't find it

Try using this explorer to find tokens (1), it can find the FLANO token (2).


text:
Where is the actual NFT data stored
I'd like to create a unique set of NFTs of super high definition images. However they require sizable memories.  These images must reside on a server so will transactions just point to this server address for the actual images if queried about the data? and if one of these NFT is consumed, does the data move to the buyer's server? And if so how is this resolved?
Also an idea. Would it be possible to have the data (image) scrambled and the only one it renders to is the owner (signed by the previous owner?)? And likewise, if owner desires to relinquish ownership he signs it to the buyer and he'll never be able to view it again. It also implies anyone can have a copy of the scrambled image if wishes.
Has this been done?
How does it work with current NFTs?

These images must reside on a server so will transactions just point
to this server address for the actual images if queried about the
data?

Yes, the standard is to store those images in IPFS

and if one of these NFT is consumed, does the data move to the buyer's
server?

No

Would it be possible to have the data (image) scrambled and the only
one it renders to is the owner (signed by the previous owner?)?

I don't know if I understand your idea, but maybe the NFT owner encrypted the image with his cryptographic keys and then decrypted them when he wanted to load the image. I don't see how this would be useful, though, since most of NFT owners just want to show their tokens to other people.

And likewise, if owner desires to relinquish ownership he signs it to
the buyer and he'll never be able to view it again.

No because he could store a copy of the image from once he was able to see it.

How does it work with current NFTs?

Take a look here, for example, if you pay attention, you'll see that the metadata has a series of information from the token, including an "image" key that points to an IPFS url.
So, basically, in Cardano, policies can have expire dates, so that, after this date, no more tokens with that policy can be minted. So to mint an NFT, you set this to, say, 2 hours from now, and only mint one token until this deadline. The image of the NFT is defined by the metadata, following this CIP, which is embedded in the transaction that mints the NFT.


text:
Allowing for a weaker on-chain constraint. Week 05 Homework 2
In HW 2 of Week 5, we need to write a script that mints a token with empty ByteString.  The minting policy code on the on-chain part (mkPolicy) could ensure that the token name is empty by defining
    checkMintedAmount :: Bool
    checkMintedAmount = case flattenValue (txInfoMint info) of
      [(_, tn, amt)] -> tn == (TokenName emptyByteString) && amt == 1
      _              -> False

I claim that that the weaker constraint
    checkMintedAmount :: Bool
    checkMintedAmount = case flattenValue (txInfoMint info) of
      [(_, _, amt)] -> amt == 1
      _             -> False

is good enough, since the off-chain part of the code will make sure that the token name is the empty string.  I ran the experiment and it seems to work.
Generalizing, it seems that the constraints on the on-chain script can be less stringent than the off-chain constraints if the transaction is going to be initiated by the wallet that owns the UTxO where the script resides.  Is this claim correct?

This question was answered by Lars during the Q&A.
In summary, you can't rely on an attacker using your offchain code. An attacker could write their own off chain code that uses a non empty Token name.
Perhaps if you are sure that you are the only person able to use the minting policy (eg you check that the transaction is signed by a specific user), you could make such assumptions.


text:
How to Start a New Project
Let's say I have downloaded all the necessary things needed to start developing on Cardano and I just opened up the terminal. I want to start building a new project. What are the commands I run.
Example -- If I was going to do this for React I would run the following command and start coding.
npx create-react-app my-app
cd my-app
npm start

What is the equivalent of that for Plutus.

Please take a look at this post https://cardano.stackexchange.com/a/9648/2335

There is no npx create-react-app my-app on cardano unfortunately, but there is a helpful repository that has the project structure necessary to start working with plutus.
So, first, you need to nix-shell inside the plutus-apps repo:
$ git clone https://github.com/input-output-hk/plutus-apps # if you haven't already
$ cd plutus-apps
$ git checkout <current-tag>
$ nix-shell

The git checkout part just need's to be done in the first time you run this or whenever you change the cabal.project file. "<current-tag>" can be found inside cabal.project file (in this case it would be plutus-starter-devcontainer/v1.0.14)
So, assuming you are already on a nix-shell, it would look like this:
$ git clone https://github.com/input-output-hk/plutus-starter.git
$ cd plutus-starter
$ cabal update
$ cabal repl

Way longer than the create-react-app one, but that's mainly because of nix-shell, after a while you get used to it.

Why do we need to do the command git checkout  ? I am following the plutus-pionner-program and I have to do this for every week's folder too. Why cant we just run nix-shell and start up the client ?

Because plutus-apps is being constantly developed and so some syntax / features change from lecture to lecture

If your app is fairly simple and all you need is to be able to send transactions to an address, send transactions to a smart contract or redeem assets from a smart contract then there is a create-react-app to get you started here:
Create React App on Cardano Developer Portal

inside the terminal you would be able to make a custom directory (or folder tree) using the commands mkdir and cd which make a folder and change the current folder your in respectively.
Doing this will separate your project files from the plutus files, but by running nix-shell your environment would still be the one required to compile plutus smart contracts.
To use this with vscode from the terminal navigate to your project directory and run code .. This should port your nix-shell environment into the vscode one, if it doesn't you may have to change some settings in vscode.
Between this and @Mateus answer your good to go.


text:
Smart contract fees paid from another wallet
When using smart contract and creating transaction, current wallet/user pays for fees.
Example of transaction:

burn NFT
min NFT
burn native assets

In my situation, my customers have their own wallet (nami #whatever) but is there any chance I can use a company wallet to pay fees instead of them?
Naive idea:

customers should have some ADA: unfortunately I cannot go forward with it
granting customers some ADA will allow them to spend them on something else!~

Basically I would have love the idea to have several wallet involve in a single transaction (multisig) but I do not find any relevant solution.
Maybe a different pattern should be think of?
Thanks.

It is definitively possible, provided every paying wallet sign the transaction. To do this with cardano-cli, you have to build the raw transaction as usual, involving the use of different UtxO coming from different wallets.
cardano-cli transaction build ... -> tx.raw
Then, every involved wallet has to sign separately. For this you have to use
cardano-cli transaction witness --tx-body-file tx.raw ... -> tx.wit_x
And finally you have to collect all individually signed tx.wit_x parts and assemble them into a single transaction
cardano-cli transaction assemble --witness-file tx.wit_0 --witness-file tx.wit_1 ...

Thanks.
Interesting, if I told you I really want to use smart contract with PAB and Nami would you say it is a dead end (at least for now)?

I never tried to go for multi-sig with Nami (or ccvault, or others), so I'm not completely sure. However, the CIP 30 that defines the standard API to interface with them (https://cips.cardano.org/cips/cip30/) seems to allow that thanks to partial signature. The difficult part will then to setup the required protocol to collect all the partials and to reassemble them into a single final transaction. You will need to use the cardano serialization lib for that purpose. So, definitively not a dead end.


text:
how to get public key of nami wallet
wondering whats the simplest way to get the pkh for nami-wallet? Is it possible through the webapp?

I would be interested in getting the holdings of that pkh as a list after getting the pkh, but I think this is a user input type of deal.
I don't think you can get the pkh for a random wallet on nami without other information such as the wallet address (I mean how is it gonna know which address your requesting the pkh for?).
Also if your using smart contracts, I think whatever the solution is would work any address on the chain regardless of which wallet they are using.

maybe not the pkh or public key of any specific address, but an account-level public key should be an option

Hi @zhekson can you please clarify what you mean by account level pk and how this differs from the pk of an address?

Scroll down to the "HD Sequential wallets (à la BIP-44)" here

Thanks Ill take a look at it

The easiest way I can think of (so far) is:

Grab your bech32 address from the Nami wallet interface (e.g. addr_***)
Inspect that address with the cardano-address tool with this command:

echo <YOUR_ADDRESS_HERE addr_...> | cardano-address address inspect

You should be able to find the hex hash in the output under the property spending_key_hash

ALTERNATIVELY, there's another easy way where you dont need to download cardano-address. By using the cardano-address demo here Cardano Address Inspector.

Unfortunately they have disabled the hex output option, not sure why
But I realized that they do print the cardano-address output into the console... So if you open the browser inspect tool and hit Inspect again, you should be able to find the hex hash with the key spending_key_hash


text:
How do Endpoints work?
and cant figure out what Endpoint do (why are they in the code) and most important of all how should I code them. What are the best practices?

In Plutus apps, the mechanism for requesting inputs is called "endpoints".
All endpoints that an app wants to use must be declared as part of the type of the app. The set of all endpoints of an app is called the schema of the app. The schema is defined as a Haskell type. You can build a schema using the Endpoint type family to construct individual endpoint types, and the .\/ operator to combine them.
I suggest you design your Plutus app based on the idea that endpoints are the only possible way to interact with the smart contract from a user perspective.


text:
How to PreSign a transaction
im trying to figure out how to sign a smart contract (SC) and have it put on-chain, where it waits until its validation logic returns True.
Edit 1:
To clarify what I mean by signing is the private key signature. The purpose would be to have the user sign the contract once and after X years the contract is activated. The user should not be able to Sign again after this point as the user is believed to have died and the address locked. At this point, the contract act as a last will and testament, sending the ada balance to the beneficiary.

what do you mean by "sign" a smart contract?

When you use nami or another wallet the user should input their password only once. If its correct the private key signature is applied. this should only happen once as the validation logic of the contract is initially False, and only becomes True once the contract should be run. This means that the contract will also stay on chain.

Scripts on the ledger are passive, they do not act unless a party sends a transaction that propagates the state of the script.
If I understand correctly, you want a vesting scheme, this is possible. Have a look at (1).


text:
Stream/Query transaction price history of an asset
Is it possible to get the transaction incl. price history of an asset e.g. (SundaeSwap) using blockfrost or cardano-db-sync?
If yes, is it also possible to stream this value from block to block?

No, as this information is not directly on-chain.


text:
How Do you generate the Cabal and Nix files for a new project?
I built the plutus-apps repo from iohk, and then made a different folder to orgenise my projects. I want to know how to have the nix files needed to make the environment generated in the new project folder and the same with the cabal files.
I have used cabal init but get the following output:

I don't really understand what this means nor can I figure out how to generate the files needed for nix-shell to work in this project.
Please help me figure out how to do this.
Thankyou.

Once inside the nix-shell, it assumes that the correct dependencies have already been loaded especially if you have built it on top of the newly cloned plutus-apps repo.  The nix files necessary are therefore already available for any new project that you would compile or run inside the nix shell.
In the Plutus Pioneer Program, there is an instruction to have to update (checkout) to the proper github commit tag of the plutus-apps repo that the current week's source codes is using.  Follow this intruction, then enter the nix shell.  Once inside the nix shell, you will be able to successfully compile and run the projects of the current week.
For a new project to work, there is an option to set a file as an executable in the cabal project file.  You may want to watch a part of the Plutus Pioneer Program - Iteration #3 Week #4 Lecture #2 video.  At time 09:55, Lars made an example on how to execute his source code using cabal run command, and he also explained afterwards the needed changes in the cabal project file if you want to use that command.

Thanks for the answer but i think it is answering the wrong question. The question is can I generate these files into a separate folder from a terminal command to upload them to GitHub along with my code for a new project.

@KryptoKing Okay, I was assuming that the files you want to generate are files of the nix shell, which in my opinion don't have to be specified as part of your new code, and therefore no need to include in Github upload.  I am not an expert in nix OS or shell, so I guess later somebody else knowledgeable might shed light about your intended result for your project.

Thanks for the help. I appreciate you trying to help me out. Can I ask why you don't believe they belong in the repo? Arnt they required to reproduce the effective env?

In Lars' lectures, we only clone the source files. I believe there are no nix files in his source repo.
I didn't encounter problems loading the PPP source files while inside the nix-shell,
and it successfully compiles and run. The nix-shell already managed the environment by referencing
the right plutus-apps and cabal files, thus, with the correct environment, you only need to clone
the source codes (and the cabal project file), no nix files needed just like what Lars did in his repo.


text:
How do you deploy ready made AI on chain
I have made a bunch of trading bots using python and tensorflow. How do I deploy this stuff on the chain with Plutus?
Is this the approach taken by Dr Ben Goetzel at SingularityNet or do they run it locally and only use the smart contracts for payment?

I have done that as well for Kucoin Binance etc python is great for backend data analisis... Well.. BlockChain are just transactions...  you should be able to do a BlockChain a transaction from your backend current running bot and give data to your bot from a service like Blockfrost... also.. what you buy and sell should be locked funds in smart contracts, for exqample liquidity pools from sundae Swap...  :)  the buy and sell transactions should be tx with smart contract interactions.

I am not very knowledgeable when it comes to AI, but I'm pretty sure right now it's impossible to have one on-chain for two reasons. First, it would be too computationally heavy, so the current CPU and transactions size limits would be reached. Second, there are no modules that allow this on-chain.
Plutus has a very limited number of types and functions allowed inside the on-chain validator, which certainly doesn't include tensor-flow or any AI related libraries.
Personally, I don't know how Singularity Net is doing, but I suppose they are doing this work off-chain and using oracles to communicate the results on-chain.
If you want to learn about oracles and how to deploy plutus smart-contracts, the best resource right now is the Plutus Pioneers Program. The third cohort already started, but you can watch the lectures on youtube and do the homework cloning the github repository.

Im already in the 3rd cohort but they don't seem to cover this.

They talk about oracles in week06, at least they did in the second cohort

Thanks that should be this Thursday then


text:
How to log/trace/print messages from within the contract ON-chain code, while using cardano-cli?
I'm wondering how to log/print/trace any message during the execution of a contract when submitted to the blockchain via cardano-cli.
So basically I hoped this very simple test script would show me something:
mkValidator :: ContractInfo -> () -> () -> ScriptContext -> Bool
mkValidator _ _ _ _ = (traceIfFalse "Test" False) || True

However, when submitting a transaction with this script to cardano-cli, it gets executed without printing anything.

Your validator is basically False || True, which will always return True. The value from traceIfFalse is only passed to the user if the final result of the validator is False.
So if you are using the most recent version of cardano-cli the error should appear once you try to build a transaction removing the || True part. If you want, however, to log an error even when the validation succeeds, this is impossible with Plutus, at least on-chain.


text:
Is it possible to use recursion in onchain code?
I originally asked Working with BuiltinByteString
One of the suggested solutions defined a recursive function in the on chain code.
This did not work however and I've since been trying to determine if onchain code can contain any recursive function. I've tried to define the simplest validator function that uses recursion but the Plutus compiler always errors on:
GHC Core to PLC plugin: E042:Error: Unsupported feature: Use of Haskell Integer equality, possibly via the Haskell Eq typeclass

Here is my simple example:
{-# INLINABLE mkPolicy #-}
mkPolicy :: TxOutRef -> () -> ScriptContext -> Bool
mkPolicy oref () ctx = (fact 2) == (2 :: Integer)
  where
    fact :: Integer -> Integer
    fact 1 = 1
    fact n = multiplyInteger n  (fact (subtractInteger n 1))

I used this code as a template, and just replaced the mkPolicy function: https://github.com/input-output-hk/plutus-pioneer-program/blob/main/code/week05/src/Week05/NFT.hs
This is the first few lines of the error I get:
GHC Core to PLC plugin: E042:Error: Unsupported feature: Use of Haskell Integer equality, possibly via the Haskell Eq typeclass
Context: Compiling expr: GHC.Integer.Type.eqInteger#
Context: Compiling expr: GHC.Integer.Type.eqInteger# ds_d1hoe
Context: Compiling expr: GHC.Integer.Type.eqInteger# ds_d1hoe 1
Context: Compiling expr: case GHC.Integer.Type.eqInteger# ds_d1hoe 1
                         of wild [Occ=Once]
                         { __DEFAULT ->
                         GHC.Prim.tagToEnum# @ GHC.Types.Bool wild
                         }
Context: Compiling expr: case case GHC.Integer.Type.eqInteger# ds_d1hoe 1
                              of wild [Occ=Once]
                              { __DEFAULT ->
                              GHC.Prim.tagToEnum# @ GHC.Types.Bool wild
                              }
                         of {
                           GHC.Types.False ->
                             PlutusTx.Builtins.Internal.multiplyInteger
                               ds_d1hoe
                               (fact (PlutusTx.Builtins.Internal.subtractInteger ds_d1hoe 1));
                           GHC.Types.True -> 1
                         }
Context: Compiling expr: \ (ds_d1hoe :: GHC.Integer.Type.Integer) ->
                           case case GHC.Integer.Type.eqInteger# ds_d1hoe 1 of wild [Occ=Once]
                                { __DEFAULT ->
                                GHC.Prim.tagToEnum# @ GHC.Types.Bool wild
                                }
                           of {
                             GHC.Types.False ->
                               PlutusTx.Builtins.Internal.multiplyInteger
                                 ds_d1hoe
                                 (fact (PlutusTx.Builtins.Internal.subtractInteger ds_d1hoe 1));
                             GHC.Types.True -> 1
                           }

I was able to get something that works, but I couldn't explain why. It has to do with the way Template Haskell is generated:
{-# INLINABLE mkPolicy #-}
mkPolicy :: TxOutRef -> () -> ScriptContext -> Bool
mkPolicy oref () ctx = fact 2 == (2 :: Integer)
  where

    fact :: Integer -> Integer
    fact n
      | n == 1 = 1
      | otherwise = n * fact (n - 1)

As you see, the problem is not recursion. Perhaps you should open an issue on the Plutus issue tracker and discuss with the people there whether this is a bug or a feature.


text:
How can I configure and send a transaction to the Cardano chain using python
I have written some plutus contracts, but they use parameterisation and the params are gained through a REST API.
I am using python3 to interface with the API, but would like to be able to script an automatic process that converts the data into the params structure, and then submit the plutus code/contract with the params to the blockchain.
I can do the conversion between the REST data and the params, but how do I package the code and submit it to the chain via python 3.

Checkout PyCardano. It is able to serialize python objects to datum and redeemers. Maybe this test example can help: https://github.com/cffls/pycardano/blob/main/integration-test/test/test_all.py#L217 It implements all off-chain code of forty-two example in Plutus-pioneer-program.
Update:
I polished the test into a concrete example with more details here: https://github.com/cffls/pycardano/tree/main/examples/plutus/forty_two

Do you have any examples of more complex datums being used? I am getting some errors when I try some more complex structures

@Mateus Checkout this unit test: https://github.com/cffls/pycardano/blob/7ac73501ff3093b1b467b51c685ded3336cdc526/test/pycardano/test_plutus.py#L56 It covers different data structures, e.g. list, map.

Thanks @Jerry, my attempt was a plutus data instance with a map as one of the attributes that has another plutus data instance as the key of that map. Very specific scenario, but it fails for some reason. It says that cborTag cannot be hashable

Hey @Mateus, we have a discord server. Do you want to discuss the issue you encountered over there: https://discord.gg/qT9Mn9xjgz ?


text:
Non-INLINABLE functions Error
I mark the function as inlinable but get the error that the function cannot be made inlinable. This does not appear to make sense as the function is known to be inlinable.

This was a problem with the Haskell compiler interfering with the code before it reached the Plutus compiler. The changes made in the Haskell compiler made it impossible to compile in Plutus.
This means the plugin doesn’t have access to implementation of the function, which it needs to be able to compile the function to Plutus Core. Some things you can do to fix it:
Make sure to add {-# INLINABLE functionname #-} to your function.
If there’s an extra $c in front of the function name in the error, GHC has generated a specialised version of your function, which prevents the plugin from accessing it. You can turn off specialisation with {-# OPTIONS_GHC -fno-specialise #-}
Other compiler options that can help:
{-# OPTIONS_GHC -fno-strictness #-}
{-# OPTIONS_GHC -fno-ignore-interface-pragmas #-}
{-# OPTIONS_GHC -fno-omit-interface-pragmas #-}
{-# OPTIONS_GHC -fobject-code #-}


text:
Unable to send funds from a Byron-era wallet created with Daedalus back in 2017
This is not a situation that happened to me personally, so I am sorry upfront if I can't provide all the necessary information, but I am trying to help recover money from a wallet that has been generated with a very early version of Daedalus. The recovery phrase related to that wallet does not appear to be correct, thus the wallet can't be recovered through any wallet or the cardano-wallet CLI tool. (bad entropy, check the last word error). Since it was made with an old version of Daedalus, I am unsure of where the key files are stored. Nothing that I have ever gotten from Cardano-CLI/-wallet in the Daedalus folder (maybe it's stored somewhere else, or a different format back then?)
The main issue here is that Daedalus isn't able to send any transactions out, because the node is not letting the transaction through. Here is the error:
renderer.js:34 [2022-02-20T09:08:54.788Z] [daedalus.mainnet:error:ipcRenderer] {
    "msg": "AdaApi::createTransaction error",
    "data": {
        "error": {
            "code": "created_invalid_transaction",
            "message": "The submitted transaction was rejected by the local node. Here's an error message that may help with debugging: TxValidationErrorInMode (ShelleyTxValidationError ShelleyBasedEraAlonzo (ApplyTxError [UtxowFailure (WrappedShelleyEraFailure (MissingVKeyWitnessesUTXOW (WitHashes (fromList [KeyHash "ffea5f425e909556d3190f446ba1058609d2f459fe442932b93d2232"]))))])) AlonzoEraInCardanoMode"
        }
    }
}

Would it be in any way possible to recover the funds from that wallet? Alternatively, do you think there's any way to at least get the wallet key in a format that cardano-cli and cardano-wallet can work with? Maybe manually constructing a transaction could work in this case?
Thank you!

There are two types. Seed phrase or wallet created with cardano-cli. (I'm pretty sure you can still create a wallet with cli that uses seed phrases)
If the wallet was created using cardano-cli then you likely also need the verification key (.vkey) to build transactions and you need the signing key (.skey) to sign the transaction.
If you don't have either the correct seed phrases or the verification and signing key, you may not be able to recover these funds.

You can generate the verification key from the signing key with cardano-cli.


text:
Plutus function TxSIgnedBy - transaction build Error: The Plutus script evaluation failed
I'm trying to use Plutus function txSignedBy with a transaction involving the usage of cardano-cli
I first sent some UtxO to my script address, with a datum whose structure is like this:
data TradeDetail = TradeDetail
    { tradeOwner        :: !PubKeyHash
    } deriving (Generic, ToJSON, FromJSON)

data TradeDatum = TradeDatum TradeDetail
    deriving (Generic, ToJSON, FromJSON)

To build the datum,

I first generated the public key hash from my verificaiton key like this:
cardano-cli address key-hash --payment-verification-key-file mykey.vkey
and got 59b07e6d2500c82f6325ac18d7624cfbdb83a92e061c31068e6b03f9

Then I created the Datum JSON file encapsulating the public key hash

{
   "fields":[
      {
         "fields":[
            {
               "bytes":"59b07e6d2500c82f6325ac18d7624cfbdb83a92e061c31068e6b03f9"
            }
         ],
         "constructor":0
      }
   ],
   "constructor":0
}

My problem happens when I try to retrieve the UtxO from the script, providing the datum.
The validator sub-function where the error happens, in the ON-chain code, is like this:
{-# INLINABLE getback #-}
getback :: ContractInfo -> TradeDetail -> ScriptContext -> Bool
getback ci details context =

    traceIfFalse message $
        (scriptContextTxInfo context) `txSignedBy` (tradeOwner details)

    where

        message :: BuiltinString
        message = "Tx has to be signed by the item owner " `appendString` decodeUtf8 (getPubKeyHash (tradeOwner details))

When using cardano-cli to get back the UtxO, signing with mykey.skey,  I get the error:
Command failed: transaction build  Error: The following scripts have execution failures:
the script for transaction input 0 (in the order of the TxIds) failed with:
The Plutus script evaluation failed: An error has occurred:  User error:
The provided Plutus code called 'error'.
Caused by: [
  (builtin decodeUtf8)
  (con bytestring #59b07e6d2500c82f6325ac18d7624cfbdb83a92e061c31068e6b03f9)
]

I don't know why my error message is not well formatted, but at least the public key hash is correctly displayed.
This shows that, at the minimum, the datum is unpacked correctly and the public key hash is extracted.
But the question is, why function txSignedBy returns false ?

I finally found the answer myself. It is kind of obvious but easy to forget :-)
When using the command cardano-cli transaction build, the script gets executed although the transaction has not been signed yet. So the Plutus function txSignedBy is doomed to fail.
The trick simply consists in specifying that you will sign it later on with the required key, thanks to the option --required-signer-hash.
As usual, the problem was where I didn't expected to be...


text:
Adding Smart Contract to Existing Native Coin
A native coin was created prior to smart contract functionality availability on the platform.  Originally, it was thought that the native coin functionality was enough.  But recently we determined that we might benefit more from using a smart contract.
Can we update a native coin to include a smart contract, or must we "cancel" the old coin, and reissue under the smart contract?  Also, would there be any issues with reusing the coin symbol if the coin is cancelled and reissued?
Lastly, are coin symbols unique or can there be multiples?
Thanks for the help!

Should be two separate questions so that searching works better.  Add smart-contract capability?  Coins symbols unique?

Are you using "coin" when you should be using "token"?


text:
How can I download transaction history of any public address as CSV?
How can I download transaction history of any public address as CSV? Use case: For some 'lost' wallets (lost seed phrase) I need to get the transaction history for Tax Software. Cannot figure out a way to do this using the available blockchain explorers... but this should be relatively easy IMO.

The data you need is in a fully synced instance of cardano-db-sync. All you need is the correct SQL query.

I do not how you could do it as CSV, i guess you must adapt  the data you get from Blockfrost, you can use this endpoint
https://docs.blockfrost.io/#tag/Cardano-Addresses/paths/~1addresses~1{address}~1transactions/get
:) The API usage is pretty straight foward using NodeJs.. but they have support for more languagues like Haskell or Python ... Any how i think there might arise complications from the fact that some wallet uses more than one address for your data analysis tool

This tool does exactly that (based on a set of staking addresses) using the blockfrost.io API, as a CSV or XLSX.
It also can graph the asset balance over time.
https://github.com/pixelsoup42/cardano_account_pandas_dumper


text:
Is it posible to know if two different address came from the same wallet- prvKeys?
I am wondering if is there is a way I can check if two different addresess belong to the same prvKey (wallet, person)... since there is a hash function involved in the process from getting the Address from the prvKey, I am guessing it is not posible, given two addresses know for sure if they were generated from the same prvKeys.. But I find hard to make a less intiuitive argument, any help?

You can look up and use the stake address to determine this. Stake address is unique to wallet and linked back to all payment addresses. Here is an example (use CardanoScan or other method to expose stake address). Two wallet addresses:
addr1q87xqs5duasp4ehuec9gasy9qptt7zhweg046gh9pa7nmax6yxvvxd5qhurea4rvlj6a8c35twc0654l48avkn79z3mq46yfdm
addr1q9rmevy4rsnvzmhj0xfljdqhm9u2zmr9y34rqeytd3qky5k6yxvvxd5qhurea4rvlj6a8c35twc0654l48avkn79z3mq8kpjld
Have the same stake address:
stake1u8dzrxxrx6qt7pu763k0edwnug69hv8a22l6n7ktflz3gaspch4jv

Note: stake addresses and payment addresses are not necessarily derived from the same master seed. Most wallet software will do this by default, so the above example can work in linking addresses that share the same stake key. However, a shelley address can be built from payment and stake keys that live on completely different merkle trees. If you have more than one stake address, or non-shelley addresses, you would need to use cardano-db-sync

what if there is no stake address?

@DaveStrider then this method also would not work. I think the best way to do this would be to list all transactions associated with a wallet's extended account key (beginning in acct_xvk.....) using a wallet software like cardano-wallet


text:
How to start a instance of a SC with PAB and Nami wallet?
I am runnin a PAB server in mainnet but now I am struggling to run it with a external wallet (Nami)
I start the instance of the SC with the following command
curl --location --request POST 'http://localhost:9080/api/contract/activate' \ --header 'Content-Type: application/json' \ --data-raw '{ "caID": "nameOfContract", "caWallet":{"getWalletId":"WhereDoIGetThis?"} }'
How do I get the walletId of an external Wallet?

walletId is an identification of a wallet within PAB, so there is no way to provide it with an id outside the system.
To list you current wallets, run:
> curl -H "content-type: application/json" -XPOST \
  -d @testnet/restore-wallet.json \
  localhost:8090/v2/wallets


text:
Referencing between scripts and application to state machines
(This is not related to CIP-33.)
I want a validator to ensure another validator is also run.
Naively I could construct one, get the hash, and hard code it into the other.
Presumably two validators can't mutually reference each other. How do people get around this/ What is the canonical way to handle this?
Same question with minting policies and validators.
The plutus API provide a forwardToValidator minting policy.
I want a validator to then know its 'canonical' currency symbol,
but as far as I can see ownCurrencySymbol is vacuous in the context of a validator.
This started by trying to establish how a state machine knows its state token is an NFT. As far as I can see, it doesn't. If an untrusted party initialized a machine, it would be down to a curious user to verify the statetoken is an NFT.
I'm surely not the first person to encounter this but trawling SE and discord didn't shed light on this.

If you want to ensure that a validator A run alongside another validator B, you need to check that the validator hash is present by the other in a transaction. This can be done by indexing if an output is spent with that hash as a credential (1).
On the problem of mutually referencing in plutus scripts, you need to later inject this data in the script via, for example, by referencing an input that contains the validator/minting hash of both the scripts. So scripts can mutually reference each other, but you cannot hard-code this in each script at the same time.
The forwardValidator that you provided is an example of a minting policy that checks whether a certain validator/minting script is present. As you stated, a validator is not a minting script and thus has no ownCurrencySymbol, this also has to be injected via another way, like a referencing script. If this minting policy is the result of a validator that you run alongside the validation of this script, you could create the minting policy first and hard-code its policy ID in the validator script. It all depends on what you are trying to achieve.


text:
Exception from validator is not shown when using cardano-serialization-lib
I have this simple validator:
newtype BreedConfig = BreedConfig
    { feeAddr  :: PubKeyHash
    } deriving (Generic, ToJSON, FromJSON)

PlutusTx.makeIsDataIndexed ''BreedConfig [('BreedConfig, 0)]
PlutusTx.makeLift ''BreedConfig

data BreedDatum = BreedDatum
    { owner       :: !PubKeyHash
    , deadline    :: !POSIXTime
    , currency1   :: !CurrencySymbol
    , token1      :: !TokenName
    , currency2   :: !CurrencySymbol
    , token2      :: !TokenName
    , serviceFee  :: !Plutus.Integer
    , serviceDFee :: !Plutus.Integer
    } deriving (Generic, ToJSON, FromJSON)

instance Eq BreedDatum where
    {-# INLINABLE (==) #-}
    a == b = (owner    a == owner    b) &&
             (deadline     a == deadline     b) &&
             (currency1    a == currency1  b) &&
             (token1       a == token1     b) &&
             (currency2    a == currency2  b) &&
             (token2       a == token2  b) &&
             (serviceFee   a == serviceFee  b) &&
             (serviceDFee  a == serviceDFee  b)

PlutusTx.makeIsDataIndexed ''BreedDatum [('BreedDatum, 0)]
PlutusTx.makeLift ''BreedDatum

data BreedAction = Claim | Cancel
    deriving Show

PlutusTx.makeIsDataIndexed ''BreedAction [('Claim, 0), ('Cancel, 1)]
PlutusTx.makeLift ''BreedAction

{-# INLINABLE breedDatum #-}
breedDatum :: TxOut -> (DatumHash -> Maybe Datum) -> Maybe BreedDatum
breedDatum o f = do
    dh <- txOutDatum o
    Datum d <- f dh
    PlutusTx.fromBuiltinData d

{-# INLINABLE mkbreedValidator #-}
mkbreedValidator :: BreedConfig -> BreedDatum -> BreedAction -> ScriptContext -> Bool
mkbreedValidator cfg breedDat r ctx = case r of
        Claim    -> traceIfFalse "No rights to perform this action (claim)" (txSignedBy (scriptContextTxInfo ctx) (owner breedDat)) &&
                    traceIfFalse "Fee not paid" (checkFee (serviceFee breedDat)) &&
                    traceIfFalse "deadline not reached" deadlineReached
        Cancel  -> traceIfFalse "No rights to perform this action" (txSignedBy (scriptContextTxInfo ctx) (owner breedDat))

  where
    info :: TxInfo
    info = scriptContextTxInfo ctx

    sig :: PubKeyHash
    sig = case txInfoSignatories info of
            [pubKeyHash] -> pubKeyHash

    deadlineReached :: Bool
    deadlineReached = contains (from $ deadline breedDat) $ txInfoValidRange info

    checkFee :: Integer -> Bool
    checkFee srvfee = fromInteger (Ada.getLovelace (Ada.fromValue (valuePaidTo info $ feeAddr cfg))) == fromInteger srvfee

data Breed
instance Scripts.ValidatorTypes Breed where
    type instance DatumType Breed    = BreedDatum
    type instance RedeemerType Breed = BreedAction

typedBreedValidator :: BreedConfig -> Scripts.TypedValidator Breed
typedBreedValidator bc = Scripts.mkTypedValidator @Breed
    ($$(PlutusTx.compile [|| mkbreedValidator ||]) `PlutusTx.applyCode` PlutusTx.liftCode bc)
    $$(PlutusTx.compile [|| wrap ||])
  where
    wrap = Scripts.wrapValidator @BreedDatum @BreedAction

breedValidator :: BreedConfig -> Validator
breedValidator = Scripts.validatorScript . typedBreedValidator

breedValidatorHash :: BreedConfig -> ValidatorHash
breedValidatorHash = validatorHash . breedValidator

breedScript :: BreedConfig -> Plutus.Script
breedScript = Ledger.unValidatorScript . breedValidator

breedScriptAsShortBs :: BreedConfig -> SBS.ShortByteString
breedScriptAsShortBs = SBS.toShort . LB.toStrict . serialise . breedScript

apiBreedScript :: BreedConfig -> PlutusScript PlutusScriptV1
apiBreedScript = PlutusScriptSerialised . breedScriptAsShortBs

When I test it using cardano-cli everything works, so when I try to retrieve tokens before deadline I'm getting exception from validator.
When I use the same smart contract code from webpage I'm not getting the expected error "deadline not reached"
In the webpage I take latest block and from it I extract time and add to it 5 minutes and use this as parameter deadline in datum
const deadline = (await getLatestPosixTime()) + 300000;
breedingParams.deadline = deadline.toString();

Next if I try to retrieve the locked tokens before five minutes have elapsed I'm not seeing nice CEK exception "deadline not reached" that should be raised from validator.
Instead I'm seeing:
  ""transaction submit error ShelleyTxValidationError ShelleyBasedEraAlonzo (ApplyTxError [UtxowFailure (WrappedShelleyEraFailure (UtxoFailure (UtxosFailure (ValidationTagMismatch (IsValid True) (FailedUnexpectedly [PlutusFailure \"\\nThe 3 arg plutus script (PlutusScript PlutusV1 ScriptHash \\\"0b71d943b18479d4742ea625e06e249a79cadcb4fa8c5dcf86ae64b4\\\") fails.\\nCekError An error has occurred:  User error:\\nThe provided Plutus code called 'error'.\\n
The data is: Constr 0 [B \\\"_\\\\SYN\\\\DC4\\\\153C\\\\217\\\\132\\\\182\\\\228\\\\158\\\\169\\\\149\\\\193R\\\\230z3\\\\a\\\\DC1\\\\SO\\\\219q\\\\190\\\\ACK\\\\131\\\\221\\\\167^\\\",I 1645699355000,B \\\"\\\\230\\\\ESC\\\\252\\\\DLEc8\\\\237J\\\\235\\\\169\\\\&062O\\\\190\\\\168\\\\NAK\\\\SI\\\\217u\\\\SI\\\\207\\\\252\\\\161\\\\205\\\\159\\\\SUB\\\\EM\\\",B \\\"DinoSavior00537\\\",B \\\"\\\\230\\\\ESC\\\\252\\\\DLEc8\\\\237J\\\\235\\\\169\\\\&062O\\\\190\\\\168\\\\NAK\\\\SI\\\\217u\\\\SI\\\\207\\\\252\\\\161\\\\205\\\\159\\\\SUB\\\\EM\\\",B \\\"DinoSavior01301\\\",I 10000000,I 1000]\\nThe redeemer is: Constr 0 []\\nThe context is:\\n
Purpose: Spending (TxOutRef {txOutRefId = 7117be7c6ce8ec60e5833c3c710326f9b42c00b45bd45bd2fdce3a8024a1e290, txOutRefIdx = 0})\\nTxInfo:\\n  TxId: ae79dfa4ab0a987942bc281ce40fd22b4c2aee58eb564e439974c40856e83a2f\\n  Inputs: [ 7117be7c6ce8ec60e5833c3c710326f9b42c00b45bd45bd2fdce3a8024a1e290!0 -> - Value (Map [(,Map [(\\\"\\\",13000000)]),(e61bfc106338ed4aeba93036324fbea8150fd9750fcffca1cd9f1a19,Map [(\\\"DinoSavior00537\\\",1),(\\\"DinoSavior01301\\\",1)])]) addressed to\\n                                                                                ScriptCredential: 0b71d943b18479d4742ea625e06e249a79cadcb4fa8c5dcf86ae64b4 (no staking credential)\\n          , 7117be7c6ce8ec60e5833c3c710326f9b42c00b45bd45bd2fdce3a8024a1e290!1 -> - Value (Map [(,Map [(\\\"\\\",29337196)]),
(e61bfc106338ed4aeba93036324fbea8150fd9750fcffca1cd9f1a19,Map [(\\\"DinoSavior04792\\\",1),(\\\"DinoSavior05352\\\",1),(\\\"DinoSavior07962\\\",1),(\\\"DinoSavior08352\\\",1),(\\\"DinoSavior09109\\\",1)]),(ee8e37676f6ebb8e031dff493f88ff711d24aa68666a09d61f1d3fb3,Map [(\\\"Cryptodino02704\\\",1),(\\\"Cryptodino05426\\\",1),(\\\"Cryptodino05943\\\",1),(\\\"Cryptodino06553\\\",1),(\\\"Cryptodino06853\\\",1)])]) addressed to\\n                                                                                PubKeyCredential: 5f16149943d984b6e49ea995c152e67a3307110edb71be0683dda75e (StakingHash PubKeyCredential: 309275ebc497184c163de20271e1af63d6e7b1e03f4b6cea0af3fd4a) ]\\n  Outputs: [ - Value (Map [(,Map [(\\\"\\\",3000000)]),
(e61bfc106338ed4aeba93036324fbea8150fd9750fcffca1cd9f1a19,Map [(\\\"DinoSavior00537\\\",1),(\\\"DinoSavior01301\\\",1)])]) addressed to\\n               PubKeyCredential: 5f16149943d984b6e49ea995c152e67a3307110edb71be0683dda75e (StakingHash PubKeyCredential: 309275ebc497184c163de20271e1af63d6e7b1e03f4b6cea0af3fd4a)\\n           , - Value (Map [(,Map [(\\\"\\\",10000000)])]) addressed to\\n               PubKeyCredential: e2a206cf1f33c8bb90722b6fd92f747911485954f0562faae0b16bc0 (StakingHash PubKeyCredential: d55b8648692398368392f24ad16d56235d1b514ed616b09cdb7281b2)\\n           , - Value (Map [(,Map [(\\\"\\\",28294183)]),(e61bfc106338ed4aeba93036324fbea8150fd9750fcffca1cd9f1a19,Map [(\\\"DinoSavior04792\\\",1),(\\\"DinoSavior05352\\\",1),(\\\"DinoSavior07962\\\",1),(\\\"DinoSavior08352\\\",1),(\\\"DinoSavior09109\\\",1)]),(ee8e37676f6ebb8e031dff493f88ff711d24aa68666a09d61f1d3fb3,Map [(\\\"Cryptodino02704\\\",1),(\\\"Cryptodino05426\\\",1),(\\\"Cryptodino05943\\\",1),(\\\"Cryptodino06553\\\",1),(\\\"Cryptodino06853\\\",1)])]) addressed to\\n               PubKeyCredential: 5f16149943d984b6e49ea995c152e67a3307110edb71be0683dda75e (StakingHash PubKeyCredential: 309275ebc497184c163de20271e1af63d6e7b1e03f4b6cea0af3fd4a) ]\\n  Fee: Value (Map [(,Map [(\\\"\\\",1043013)])])\\n  Value minted: Value (Map [])\\n  DCerts: []\\n  Wdrl: []\\n  Valid range: [ POSIXTime 1645699329000 , +\\8734)\\n  Signatories:
[5f16149943d984b6e49ea995c152e67a3307110edb71be0683dda75e]\\n  Datums: [ ( 1dbcbc38286af4f5f77fea28a01a76c7c53dc4eaaa27f2b1197e183d0741350c\\n          , <\\\"_\\\\SYN\\\\DC4\\\\153C\\\\217\\\\132\\\\182\\\\228\\\\158\\\\169\\\\149\\\\193R\\\\230z3\\\\a\\\\DC1\\\\SO\\\\219q\\\\190\\\\ACK\\\\131\\\\221\\\\167^\\\",\\n          1645699355000,\\n          \\\"\\\\230\\\\ESC\\\\252\\\\DLEc8\\\\237J\\\\235\\\\169\\\\&062O\\\\190\\\\168\\\\NAK\\\\SI\\\\217u\\\\SI\\\\207\\\\252\\\\161\\\\205\\\\159\\\\SUB\\\\EM\\\",\\n          \\\"DinoSavior00537\\\",\\n          \\\"\\\\230\\\\ESC\\\\252\\\\DLEc8\\\\237J\\\\235\\\\169\\\\&062O\\\\190\\\\168\\\\NAK\\\\SI\\\\217u\\\\SI\\\\207\\\\252\\\\161\\\\205\\\\159\\\\SUB\\\\EM\\\",\\n          \\\"DinoSavior01301\\\",\\n          10000000,\\n          1000> ) ]\\n\" \"some very long string - maybe transaction body

However using the same code in the webpage if I try to redeem my tokens after 5 minutes everything works, I'm able to retrieve them from smart contract.
I'm passing the deadline as an integer to the Datum.


text:
How to format a JSON value in the cardano-cli
I started creating this python library with most of the Plutus types represented as classes. I get their values by calling the json method, which returns the JSON equivalent of this type so it can be passed to cardano-cli, like the following:
class PubKeyHash(object):
    ...
    def json(self):
        return json.dumps({
            "bytes": self.__pkh
        })

This worked well while I was writing these values to files and passing the files path to cardano-cli, but since I'm using ssh to connect to the node and writing files all the time is not very performant, I think it would be great to, instead, pass the JSON values directly.
When I try to do this using the --mint-redeemer-value argument, though, it returns me a weird error Exception: option --mint-redeemer-value: Failed reading: not a valid json value, which makes me assume my JSON is not formatted correctly.
This is the command I'm running:
...
--mint-redeemer-value {"constructor":0,"fields":[{"constructor":0,"fields":[{"bytes":"
02fbd1c6934d888ec6575de3ec2f87dd75aec2891f20e0dc38fa7440e47a3803"}]},{"int":0}]} \
...

If it is the case that my JSON is formatted incorrectly, how should I format it? If it is not, can anyone bring me some light on why I'm running into this error?

Checking the man page for cardano-cli transaction build, I see:
  --mint-redeemer-value JSON VALUE
                           The JSON value for the script data. Supported JSON
                           data types: string, number, object & array.

This is expecting a basic JSON value (no schema).
Since you are providing JSON that follows the schema for script data, you will need to write your JSON to a file and use --mint-redeemer-file instead:

cardano-cli transaction build \
--mint-redeemer-file my-file.json
...


text:
Plutus: Integer->Value?
I give to Integer via an endpoint function, multiply them and give them to
Constraints.mustPayToTheScript. For this I need the result to be converted into an Value. Does Anyone know how to do this?
 buy =  endpoint @"buy" @BuyParams $ \ (BuyParams fst scd ) -> do
    let amt = fst*scd
    let tx         = Constraints.mustPayToTheScript (hashString fst) amt
    void (submitTxConstraints gameInstance tx)

Is ADA what you want to pay to the script?

Supposing that you want to pay ADA to the script, you can use lovelaceValueOf :: Integer -> Value from Plutus.V1.Ledger.Ada as follows:
import qualified Plutus.V1.Ledger.Ada as Ada

buy = endpoint @"buy" @BuyParams $ \ (BuyParams fst scd ) -> do
   let amt = fst*scd
       val = Ada.lovelaceValueOf amt
       tx  = Constraints.mustPayToTheScript (hashString fst) val
   void (submitTxConstraints gameInstance tx)

Hope this will be useful.

Yes! Solved it thanks :)

@John_Bones more than welcome!


text:
Get public key into PubKeyHash and use it in mustBeSignedBy
A user provides me with his wallet pub key as BultinByteString (or Haskell string, fine either way). From that, I need to get the PubKeyHash, but I am not sure how to hash it or if I need to hash it at all.
Then, I need to use it in the PubKeyHash in Ledger.Constraints.MustBeSignedBy in my state machine. Kinda like that:
Constraints.mustBeSignedBy "35dedd2982a03cf39e7dce03c839994ffdec2ec6b04f1cf2d40e61a3"

or
Constraints.mustBeSignedBy PubKeyHash { getPubKeyHash = "35dedd2982a03cf39e7dce03c839994ffdec2ec6b04f1cf2d40e61a3" }

The problem is when I put some PubKeyHash in the constraint (like above), the compiler spits out 5000 long error starting with:
GHC Core to PLC plugin: E042:Error: Unsupported feature: Use of fromString on type other than builtin strings or bytestrings: Plutus.V1.Ledger.Crypto.PubKeyHash
Context: Compiling expr: Data.String.fromString
                           @ Plutus.V1.Ledger.Crypto.PubKeyHash
                           Plutus.V1.Ledger.Crypto.$fIsStringPubKeyHash
                           (GHC.CString.unpackCString#
                              "a2c20c77887ace1cd986193e4e75babd8993cfd56995cd5cfce609c2"#)

Can the string be translated into the PubKeyHash? Can it be somehow fixed? Is it me, or is it a Plutus bug?
Edit:
Tried new code:
Constraints.mustBeSignedBy $ pubKeyHash (PubKey {
                            getPubKey = LedgerBytes {
                                    getLedgerBytes = "35dedd2982a03cf39e7dce03c839994ffdec2ec6b04f1cf2d40e61a3"
                                }
                        })

Got new error:
 GHC Core to PLC plugin: E042:Error: Unsupported feature: Type constructor: GHC.Prim.Char#
Context: Compiling type: GHC.Prim.Char#
Context: Compiling data constructor type: GHC.Types.C#
Context: Compiling type: GHC.Types.Char
Context: Compiling type: GHC.Base.String
Context: Compiling type: GHC.Base.String
                         -> Plutus.V1.Ledger.Bytes.LedgerBytes
Context: Compiling definition of: Plutus.V1.Ledger.Bytes.$fIsStringLedgerBytes_$cfromString
Context: Compiling expr: Plutus.V1.Ledger.Bytes.$fIsStringLedgerBytes_$cfromString
Context: Compiling expr: Plutus.V1.Ledger.Bytes.$fIsStringLedgerBytes_$cfromString
...

Did you add OverloadedStrings pragma?

Yes, I do have that pragma at the beginning of my file. No other issues with strings occurred in my state machine contract.

It's an issue with Plutus core. Even though PubKeyHash is part of IsString type class, we can't use OverloadedStrings mechanism in on-chain code for certain types. Basically, the problem is this:

Unfortunately, due to the technical reasons plutus plugin doesn't
support OverloadedStrings with newtypes.

Please, check this issue.
https://github.com/input-output-hk/plutus/issues/4404
Same thing apply for PubKeyHash and LedgerBytes.
A solution might be to have a parameterized validator script with PubKeyHash. This way, you can build PubkeyHash offchain using OverloadedStrings and pass it to the validator.

Thank you! Parameterized validator script with PubKeyHash works like a charm. Indeed a fascinating issue.

@MartinDrozdík You’re welcome. glad to help!


text:
Is it possible to link multiple addresses built from different stake key pairs but one payment key pair?
Say I generate 10 stake key pairs and 1 payment key pair. Then, I generate 10 unique shelley addresses accordingly (same payment key pair for all 10, but different staking keys).
Is it possible to correlate those addresses as having one owner (or, is it possible to link them all as being constructed from the same payment key pair?).
If so, how would one go about linking the addresses? (I assume there would be some kind of cardano-db-sync query that can do this).

You can bech32 decode an address to check the address in raw form (for a given payment address, assume first 58 chars will be the same).
Thus:
echo addr1q8hsff3uwtphx7dtya7unjwjwug52e5jvqp09je6pwqx8k4jvuxrw2x5rr7e258a33yzkrhhlrrc5ezvd2z7qtdq0gasme44c9 | bech32 | cut -b -58
# 01ef04a63c72c37379ab277dc9c9d277114566926002f2cb3a0b8063da

Now, to "query a chain" , let's assume you're using dbsync. You would be able to query tx_out table for all values in address_raw field that start with 01ef04a63c72c37379ab277dc9c9d277114566926002f2cb3a0b8063da as below:
select address_raw from tx_out where ENCODE(address_raw,'hex') LIKE '01ef04a63c72c37379ab277dc9c9d277114566926002f2cb3a0b8063da%';

#                                                      address_raw
# ----------------------------------------------------------------------------------------------------------------------
#  \x01ef04a63c72c37379ab277dc9c9d277114566926002f2cb3a0b8063dab2670c3728d418fd9550fd8c482b0ef7f8c78a644c6a85e02da07a3b
#  \x01ef04a63c72c37379ab277dc9c9d277114566926002f2cb3a0b8063dab2670c3728d418fd9550fd8c482b0ef7f8c78a644c6a85e02da07a3b
#  \x01ef04a63c72c37379ab277dc9c9d277114566926002f2cb3a0b8063dab2670c3728d418fd9550fd8c482b0ef7f8c78a644c6a85e02da07a3b
#  \x01ef04a63c72c37379ab277dc9c9d277114566926002f2cb3a0b8063dab2670c3728d418fd9550fd8c482b0ef7f8c78a644c6a85e02da07a3b
#  \x01ef04a63c72c37379ab277dc9c9d277114566926002f2cb3a0b8063dab2670c3728d418fd9550fd8c482b0ef7f8c78a644c6a85e02da07a3b
#  \x01ef04a63c72c37379ab277dc9c9d277114566926002f2cb3a0b8063dab2670c3728d418fd9550fd8c482b0ef7f8c78a644c6a85e02da07a3b
#  \x01ef04a63c72c37379ab277dc9c9d277114566926002f2cb3a0b8063dab2670c3728d418fd9550fd8c482b0ef7f8c78a644c6a85e02da07a3b
#  \x01ef04a63c72c37379ab277dc9c9d277114566926002f2cb3a0b8063dab2670c3728d418fd9550fd8c482b0ef7f8c78a644c6a85e02da07a3b
#  \x01ef04a63c72c37379ab277dc9c9d277114566926002f2cb3a0b8063dab2670c3728d418fd9550fd8c482b0ef7f8c78a644c6a85e02da07a3b
#  \x01ef04a63c72c37379ab277dc9c9d277114566926002f2cb3a0b8063dab2670c3728d418fd9550fd8c482b0ef7f8c78a644c6a85e02da07a3b
#  \x01ef04a63c72c37379ab277dc9c9d277114566926002f2cb3a0b8063dab2670c3728d418fd9550fd8c482b0ef7f8c78a644c6a85e02da07a3b
#  \x01ef04a63c72c37379ab277dc9c9d277114566926002f2cb3a0b8063dab2670c3728d418fd9550fd8c482b0ef7f8c78a644c6a85e02da07a3b
#  \x01ef04a63c72c37379ab277dc9c9d277114566926002f2cb3a0b8063dab2670c3728d418fd9550fd8c482b0ef7f8c78a644c6a85e02da07a3b
#  \x01ef04a63c72c37379ab277dc9c9d277114566926002f2cb3a0b8063dab2670c3728d418fd9550fd8c482b0ef7f8c78a644c6a85e02da07a3b
# (14 rows)
#
# Time: 10639.159 ms (00:10.639)
#

PS: Note that this is a list of all used addresses on chain that use the mentioned payment key (as ofcourse - just creating an address can have unlimited possibilities off-chain).

It sounds like you want to do the opposite of what's done purposely.
Usually you can query multiple addresses associated with the same stake key.
In any case, what you described might be possible. So far I've tested creating different addresses using different stake keys and 1 single payment key.
Last part that is partially unknown to me is querying addresses by public key hash. You can generate the pubkeyhash of your payment address and I noticed that that information pops up in both addresses but Im currently unsure if there is a way to do a query by pubkeyhash.
These 2 addresses were created with the different stake keys. I didnt register the stake keys but you can see that the first half of the hash below the addresses are the same.

addr1q9z5hhekqyyxlwqdgv2j3u58dk0678z0wkatvd02v6v2dr5s70tn8q48pzvv6dnxz5ha224x2ptkapxas7x0y08dxeesgudlpu

view on cardanoscan

addr1q9z5hhekqyyxlwqdgv2j3u58dk0678z0wkatvd02v6v2drkysuuv8huyu7q3k7e7mxdgkvjm4ftg7n5dm358jw0ngyeq9jl7z8

view on cardanoscan

In your example, you already suspect two addresses as sharing the same payment key (prior knowledge) because you created them. I am wondering more along the lines of querying the chain for any and all addresses constructed from a given payment key, without already having a list of potential addresses.


text:
Failed to build Diff-0.4.0 (why?)
   |
18 | import Data.Monoid (mappend)
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
/usr/bin/ld.gold: error: cannot find -lgmp
collect2: error: ld returned 1 exit status
`gcc' failed in phase `Linker'. (Exit code: 1)
cabal: Failed to build Diff-0.4.0 (which is required by
test:cardano-cli-golden from cardano-cli-1.33.0).

What versions of ghc and cabal are you using? Have you run cabal update ? How much RAM does your machine have?

I am facing the same problem and am stuck. [nix-shell:~/cardano-src/cardano-node]$ cat /home/wims/.cabal/logs/ghc-8.10.7/dependent-sum-0.7.1.0-a9b93f488664d838e88fc29667167f9b0174f527c76ea1751582c678600794a8.log
Configuring library for dependent-sum-0.7.1.0..
Preprocessing library for dependent-sum-0.7.1.0..
Building library for dependent-sum-0.7.1.0..
[1 of 1] Compiling Data.Dependent.Sum ( src/Data/Dependent/Sum.hs, dist/build/Data/Dependent/Sum.o, dist/build/Data/Dependent/Sum.dyn_o )
/nix/store/f0rrfmf8kh5bsiql5bbq7m4h3xgihpnx-binutils-2.38/bin/ld.gold: error: cannot find -lgmp
collect2: e

This does not really answer the question. If you have a different question, you can ask it by clicking Ask Question. To get notified when this question gets new answers, you can follow this question. Once you have enough reputation, you can also add a bounty to draw more attention to this question. - From Review

Found the same issue when executing :
cabal build cardano-node cardano-cli
following steps in https://developers.cardano.org/docs/get-started/installing-cardano-node/
I'm using Ubuntu on Virtual box with 2GB RAM


text:
Error when minting with CLI
I tried to follow Lars' instructions on minting with CLI and I get the error below. I did not modify cabal.project. Any idea what goes wrong?
./mint-token-cli.sh f8a3850921711b4d8ad1e467f38640000a7d1ad99e076a286d0b3999450b86b1#0 123456 PPP testnet/01.addr testnet/01.skey
oref: f8a3850921711b4d8ad1e467f38640000a7d1ad99e076a286d0b3999450b86b1#0
amt: 123456
tn: PPP
address file: testnet/01.addr
signing key file: testnet/01.skey
cabal: Error parsing project file
/home/mcodescu/repos/Plutus/plutus-pioneer-program/code/week06/cabal.project:46:
"<eitherParsec>" (line 2, column 1):
unexpected 'p'
expecting space or end of input

cabal: Error parsing project file
/home/mcodescu/repos/Plutus/plutus-pioneer-program/code/week06/cabal.project:46:
"<eitherParsec>" (line 2, column 1):
unexpected 'p'
expecting space or end of input

currency symbol: 15a3588ebd4ab3ef669bca21021836e3914fb0c6f3ba0c34ace0b4a4
token name (hex):
minted value: 123456 15a3588ebd4ab3ef669bca21021836e3914fb0c6f3ba0c34ace0b4a4.
address: addr_test1vr0g9yze75lahhygqs5kg7x8m4as0tnj6k2gpe9ng8vlp0q9wdl2v
Command failed: transaction build  Error: The following scripts have execution failures:
the script for policyId 0 (in the order of the PolicyIds) failed with:
The Plutus script evaluation failed: An error has occurred:  User error:
The provided Plutus code called 'error'.
Script debugging logs: wrong amount minted
PT5

Command failed: transaction sign  Error: testnet/tx.unsigned: testnet/tx.unsigned: openBinaryFile: does not exist (No such file or directory)
Command failed: transaction submit  Error: testnet/tx.signed: testnet/tx.signed: openBinaryFile: does not exist (No such file or directory)

Ah, my bad, you have to do this from the nix shell.


text:
Difference between `PlutusTx.TH.compile` and `PlutusTx.compile`?
I've been reading the official Plutus docs and saw that in the explanation about Template Haskell, there is information about PlutusTx.TH.compile, to use it for producing the quoted Plutus Core program.
And in Plutus-Pioneers examples there is PlutusTx.compile being used, instead of the 'TH' version.
Can this two imported functions be used interchangeably? Their type looks the same in ghci, so I'm a bit confused.
Thanks in advance!

Hi man Lars answered this in the 7th Q&A video of the Plutus pioneers program cohort 3.
If you don't want to watch the video the long and short of it is that the PlutusTx.TH.compile module is just an Exported version of the  PlutusTx.compile module. This is done to make it easier for people to use, but the PlutusTx.compile is really all you need and you should learn it just in case at some point the PlutusTx.compile module has some functionality that has yet to be exported to the PlutusTx.TH.compile module.


text:
Error Reading metadata while trying to mint token
I am trying to mint the token using this command. to testnet.
cardano-cli transaction build-raw \
> --fee 188865 \
> --tx-in 540f0a1e27b64da69059d8b5ff22c542a53d31d5f01fedc6a0094879efb7152d#0 \
> --tx-out $(cat payment.addr)+4811135+"1000 $(cat policy/tokens/policy.id).eduladderTestCoin"+"1000" \
> --mint="1000 $(cat policy/tokens/policy.id).eduladderTestCoin"+"1000" \
> --minting-script-file policy/tokens/token_policy.script \
> --metadata-json-file policy/tokens/token_meta.json \
> --out-file token_tx.raw

When I am trying to do that I am getting this error.
Command failed: transaction build-raw  Error: Error reading metadata at: "policy/tokens/token_meta.json" Value out of range within the metadata item 721: {"c5edbeaed052fa6e3e3f1ced8e39fdb9900b910622ead746ee938cff":{"eduladderTestCoin":{"name":"eduladderTestCoin","image":"ipfs://bafkreifuidzqzsol7lcf7km6od7723qln2aw7xlf4xyvx2t2bgwnbf2wum"}}} Text string metadata value must consist of at most 64 UTF8 bytes, but it consists of 66 bytes.
What does this means and how will i debug the same?

As the error says:

Text string metadata value must consist of at most 64 UTF8 bytes

You can't use more than 64 UTF8 bytes in a value in the metadata.
In this case the problem is because your IPFS CID is V1, instead of V0. Take a look in the Identifiers formats.
So in this case you've some options:

Use an array to specify the image if you continue using V1.
Generate a CID V0, which is shorter
Use another storage solution with a shorter URI

Either way, try to follow the NFT Metadata standard, which defines that the metadata should specify the URI, that means, don't remove the ipfs:// part.
Anyway, it'll be stored in the blockchain, that doesn't matter, but maybe some websites won't display correctly your asset.

Removing ipfs from this has solved the problem.
"image":"ipfs://bafkreifuidzqzsol7lcf7km6od7723qln2aw7xlf4xyvx2t2bgwnbf2wum"}}}

The result is:"image":"bafkreifuidzqzsol7lcf7km6od7723qln2aw7xlf4xyvx2t2bgwnbf2wum"}}}

That's not right.. You have something else wrong if that patched your problem as it should not have been required to remove that. If you want to paste the full metadata contents in I can help sort out what's going on.

please paste the full metadata which is given above in the question.

I am having a very similar issue although with a different erorr.

Text string metadata value must consist of at most 64 UTF8 bytes, but
it consists of 70 bytes.

It makes complete sense why removing the first "ipfs://" from that string allows it to work. It's just a coincidence that the string becomes less than 64 characters, allowing it to work.
I've tested this out with multiple fields in the metadata, and all it always works so long as the string is not greater than 64 characters.
This is obviously an issue as most ipfs links are longer than 64 characters.
Any ideas on a solution?

in pool.pm the image is shown after i removing the ipfs part too but i am wondering will this work correctly in block chain or not in live server?


text:
About Fees in the Plutus Playground
I had been reviewing sample codes that can be run in the Plutus Playground, particularly the Vesting.hs code in Cohort #3 Week #3 of PPP.  So while trying several cases in the simulation, I sometimes encounter errors related to fees, so therefore it generated my curiosity on the following questions about fees:

The 10 lovelaces fees charged during the "Give" operation (Vesting.hs), is this a standard fee when sending ada via smart contracts?  Or this setting is intended only for Plutus Playground?  If so, where is this setting defined for Plutus Playground?

I also noticed that the playground throws an error for any value less than 2,000,000 lovelaces that I try to send for simulation of Vesting.hs. So similar to question #1, is this setting a standard for Cardano smart contracts?  Was it set differently from the Mainnet Network?  (I understand that the minimum Ada value in Mainnet is 1,000,000 lovelaces)  If so, where is this setting for Plutus Playground defined?

In the "Grab" operation (Vesting.hs), I noticed that the fee charged to the beneficiary is considerably higher. (When I tried, it is roughly 4,500 lovelaces).  Again, what is the basis of this fee setting?  Where is it defined?

I executed "Give" several times and it made several UTxOs for the beneficiary.  After I performed the "Grab", it charged the beneficiary lovelaces apparently for each UTxO that was created, so it means it charged the beneficiary considerably higher fees.  Is this expected for a Smart Contract operation?  Will this be same expectations when executed in Mainnet?

The default Playground fees are very unrealistic. In reality it starts around 160000 lovelace for a simple tx https://testnets.cardano.org/en/testnets/cardano/tools/plutus-fee-estimator/


text:
Command failed: transaction submit Error: Error while submitting tx
I have minted a token to the testnet and now i want to sent it to deadalus testnet wallet but i am getting error. And the steps which i am following is this.
Make a transaction
cardano-cli transaction build-raw  --fee 177381  --tx-in 8e6ece3c2fde93fb741bee62ececb886c1108d3a1c287ab29cc6a887c33b757e#0 --tx-out addr_test1qp62uukdt5q588ggeu0j7hwe2jdjrqecmvt6mc4hy4luvlvvdm7hkdy4dtdmsvxg3gc0ddg52etkffmf0sx4rl5zwv7sg5vcyv+"2 $(cat policy/tokens/policy.id).eduladderTestCoin"  --tx-out $(cat payment.addr)+"998 $(cat policy/tokens/policy.id).eduladderTestCoin" --out-file token_tx.raw
Create the protocol.
cardano-cli  query protocol-parameters \ --testnet-magic 1097911063 \ --out-file protocol.json
Get the fee.
cardano-cli transaction calculate-min-fee \ --tx-body-file token_tx.raw \ --tx-in-count 1 \ --tx-out-count 1 \ --witness-count 1 \ --byron-witness-count 0 \ --testnet-magic 1097911063  \ --protocol-params-file protocol.json
Again with the updated fee.
cardano-cli transaction build-raw  --fee 177381  --tx-in 8e6ece3c2fde93fb741bee62ececb886c1108d3a1c287ab29cc6a887c33b757e#0 --tx-out addr_test1qp62uukdt5q588ggeu0j7hwe2jdjrqecmvt6mc4hy4luvlvvdm7hkdy4dtdmsvxg3gc0ddg52etkffmf0sx4rl5zwv7sg5vcyv+"2 $(cat policy/tokens/policy.id).eduladderTestCoin"  --tx-out $(cat payment.addr)+"998 $(cat policy/tokens/policy.id).eduladderTestCoin" --out-file token_tx.raw
Now sign the transaction.
cardano-cli transaction sign \ --signing-key-file payment.skey \ --signing-key-file policy/policy.skey \ --testnet-magic 1097911063 \ --tx-body-file alien_babies_tx.raw \ --out-file token_tx.raw.signed
Now sent the same
cardano-cli transaction submit \ --tx-file  token_tx.raw.signed \ --testnet-magic 1097911063
But i am getting the following error.
Command failed: transaction submit  Error: Error while submitting tx: ShelleyTxValidationError ShelleyBasedEraAlonzo (ApplyTxError [UtxowFailure (WrappedShelleyEraFailure (UtxoFailure (OutputTooSmallUTxO [(Addr Testnet (KeyHashObj (KeyHash "74ae72cd5d01439d08cf1f2f5dd9549b218338db17ade2b7257fc67d")) (StakeRefBase (KeyHashObj (KeyHash "8c6efd7b34956adbb830c88a30f6b514565764a7697c0d51fe82733d"))),Value 0 (fromList [(PolicyID {policyID = ScriptHash "c5edbeaed052fa6e3e3f1ced8e39fdb9900b910622ead746ee938cff"},fromList [("eduladderTestCoin",2)])]),SNothing),(Addr Testnet (KeyHashObj (KeyHash "6baa0d059efc68aefaf4d30c639d62a894b2568b874e06d4f5a39c15")) StakeRefNull,Value 0 (fromList [(PolicyID {policyID = ScriptHash "c5edbeaed052fa6e3e3f1ced8e39fdb9900b910622ead746ee938cff"},fromList [("eduladderTestCoin",998)])]),SNothing)]))),UtxowFailure (WrappedShelleyEraFailure (UtxoFailure (ValueNotConservedUTxO (Value 9811135 (fromList [(PolicyID {policyID = ScriptHash "c5edbeaed052fa6e3e3f1ced8e39fdb9900b910622ead746ee938cff"},fromList [("eduladderTestCoin",1000)])])) (Value 188865 (fromList [(PolicyID {policyID = ScriptHash "c5edbeaed052fa6e3e3f1ced8e39fdb9900b910622ead746ee938cff"},fromList [("eduladderTestCoin",1000)])])))))])
How do i debug this? What wrong is going on?

The issue here is probably you're missing the minimum amount of Ada required to be sent along with any tokens.By design this is required to limit the overall size of the ledger.
See more info on this here:
https://docs.cardano.org/native-tokens/minimum-ada-value-requirement

It is impossible to make outputs containing only custom tokens

Requiring some amount of ada to be included in every UTXO (where that
amount is based on the size of the UTXO, in bytes), limits the maximum
total size taken up by UTXO entries on the ledger at any given time.

I have tried with ada in it as well. But that also not working attaching the command below cardano-cli transaction build-raw  --fee 177381  --tx-in 8e6ece3c2fde93fb741bee62ececb886c1108d3a1c287ab29cc6a887c33b757e#0 --tx-out addr_test1qp62uukdt5q588ggeu0j7hwe2jdjrqecmvt6mc4hy4luvlvvdm7hkdy4dtdmsvxg3gc0ddg52etkffmf0sx4rl5zwv7sg5vcyv+2+"2 $(cat policy/tokens/policy.id).eduladderTestCoin"  --tx-out $(cat payment.addr)+9633752+"998 $(cat policy/tokens/policy.id).eduladderTestCoin" --out-file token_tx.raw

the "2" for the ada in your first output probably needs to be "2000000" because it's in lovelace

It is not in ada it is in lovelace.

okay right, but 2 lovelace is too little then - you'll need to send a minimum of around ~1.6 Ada - which is 1600000 lovelace - together with the token

Okey. The transaction was successfull.


text:
How to define the return type of `callEndPoint` appropriately?
In homework of week4, I refactored my solution:
payTrace :: Integer -> Integer -> EmulatorTrace ()
payTrace payment1 payment2 =  do
contract1 <- activateContractWallet (knownWallet 1) payContract
let pkh2 = mockWalletPaymentPubKeyHash $ knownWallet 2
callEndpoint @"pay" contract1 $ PayParams
   {
       ppRecipient = pkh2
   ,   ppLovelace = payment1
   }
void $ Emulator.waitNSlots 1
callEndpoint @"pay" contract1 $ PayParams
   {
       ppRecipient = pkh2
   ,   ppLovelace = payment2
   }
void $ Emulator.waitNSlots 1

to:
payTrace :: Integer -> Integer -> EmulatorTrace ()
payTrace payment1 payment2 =  do
contract1 <- activateContractWallet (knownWallet 1) payContract
let pkh2 = mockWalletPaymentPubKeyHash $ knownWallet 2
    payTo :: (Member RunContract effs) => PaymentPubKeyHash -> Integer -> Eff effs ()
    payTo pkh amount = callEndpoint @"pay" contract1 $ PayParams
       {
           ppRecipient = pkh
       ,   ppLovelace = amount
       }
payTo pkh2 payment1
void $ Emulator.waitNSlots 1
payTo pkh2 payment2
void $ Emulator.waitNSlots 1

(https://gitlab.com/moment-4/courses/plutus-pioneer/plutus-pioneer-program/-/blob/week04/code/week04/src/Week04/Homework.hs)
However, there are still 2 things I don't like about my current solution:

I'd prefer to put the payTo function in the where clause, but that doesn't seem to work properly (although I think I'm close thanks to Luis (https://discord.com/channels/826816523368005654/834340082273878046/942064349831381042). How would one define it in the where clause? (The solution of Luis put me on the right track, but I still can't get it right)

I still get compiler warnings about the type. How to define the type of the function properly, so I can get rid of the warnings as well?

src/Week04/Homework.hs:46:18: warning: [-Wsimplifiable-class-constraints]
    • The constraint ‘Member RunContract effs’ matches
        instance (Data.OpenUnion.Internal.FindElem t r,
                  Data.OpenUnion.Internal.IfNotFound t r r) =>
                 Member t r
          -- Defined in ‘Data.OpenUnion.Internal’
      This makes type inference for inner bindings fragile;
        either use MonoLocalBinds, or simplify it using the instance
    • In the type signature:
        payTo :: (Member RunContract effs) =>
                 PaymentPubKeyHash -> Integer -> Eff effs ()
      In the expression:
        do contract1 <- activateContractWallet (knownWallet 1) payContract
           let pkh2 = mockWalletPaymentPubKeyHash $ knownWallet 2
               payTo ::
                 (Member RunContract effs) =>
                 PaymentPubKeyHash -> Integer -> Eff effs ()
               ....
           payTo pkh2 payment1
           void $ Emulator.waitNSlots 1
           ....
      In an equation for ‘payTrace’:
          payTrace payment1 payment2
            = do contract1 <- activateContractWallet
                                (knownWallet 1) payContract
                 let pkh2 = ...
                     ....
                 payTo pkh2 payment1
                 ....
   |
46 |         payTo :: (Member RunContract effs) => PaymentPubKeyHash -> Integer -> Eff effs ()
   |                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Ok, 8 modules loaded.

Thanks!

I don't know if this is what you expect but there are three ways to get rid of warnings:

add {-# LANGUAGE MonoLocalBinds     #-}, like the warning hints
don't give a type for payTo and let Haskell infer it
if things worked before, the body of payTo was fine in the EmulatorTrace monad, so you could go for payTo :: PaymentPubKeyHash -> Integer -> EmulatorTrace ()

I'm not particularly fond of the idea of moving the function in a where clause if it depends on something you obtain in the body of the bigger function. You could consider adding another parameter and passing contract1 as an argument, and then you can move it to where.

Allright, thanks. Well, I just wanted to get rid of the warning and understand why it's there. So, seeing your solutions: 1. what does it mean (MonoLocalBinds)? 2. I try to understand the types passed everywhere. Is there no way I can give the right type signature? 3. The body was fine, but moving it to the where, makes in different (it's a different type in the do-bindings vs in the were clause.
That being said, it makes more sense to keep in the let-binding? (Just trying to figure out the Haskell type system and monads and do-bindings)

a Haskell extension meant to infer less polymorphic types. Details here: https://ghc.gitlab.haskell.org/ghc/doc/users_guide/exts/let_generalisation.html. 2. I'd say using EmulatorTrace () for the result is the right type signature. The type you use is more general: (Member RunContract effs) => ... -> Eff effs () can be specialized to Eff '[StartContract, RunContract, Assert, Waiting, EmulatorControl, EmulatedWalletAPI, LogMsg String, Error EmulatorRuntimeError] (), which is EmulatorTrace (), because RunContract is in the list of effects for EmulatorTrace thus the condition holds.

And 3, you use contract1 in the body of payTo and if you move payTo to the where clause, contract1 is no longer in scope, as it is local to the body of payTrace. Either leave payTo in the let-binding or make payTo :: ContractHandle w s e -> PaymentPubKeyHash -> Integer -> EmulatorTrace (), move it to where and add contract1 to the calls of payTo in the body of payTrace.


text:
How to keep ADA in Yoroi wallet without staking?
Hi I send some ADA to my Yoroi wallet but it staked into the pool automatically, I want to keep some ADA in the wallet so I can claim coins from Drip Drops, how do I  do it?

On Cardano, you are staking with your wallet. It locks a 2ADA deposit that you will get back when you unstake.
So you are free to claim your tokens from Drip Dropz or spend the ADA even when you are staking.

Staking on Cardano is non-custodial and you can use the staked Ada anytime.
Once you register you wallet to stake to a stake pool, all future Ada added to the wallet is automatically staked to the same pool.
The 2 Ada staking deposit is refunded when you choose to de-register from the stake pool and stop staking.

You can claim the staking rewards without de-registering
You can switch pools without de-registering

These will cost a transaction fee (~0.17ada at this time)

Registering with a stake pool (2 Ada refundable)
De-registering
Changing stake pool
Claiming stake rewards

if you dont want to stake your ada from yoroi, there is an option in the main area "withdraw".
when you click there, there is another question you received -either to keep registered - or to deregister.
Deregistering means this key will no longer receive rewards until you re-register the staking key (usually by delegating to a pool again).
but we will recommend you to have a small research what exactly CArdano is, Proof of Stake, and why this "stake" help the network, ADA and more specific your asset.
if you have any further questions, please never hesitate to contact us.
Cardano is a great huge Community, and we are all happy to assist.
have a nice Sun-day.
pool operator for TTS17
theTokenSquare17
PS.
based on my understanding and research, i can see only a reason someone who doesnt want to Stake, only in case of Taxes, and this "income" he receives (rewards).


text:
How do Validators work
How do validators work when there are multiple inputs does the validator check one input at a time or does it require them all to be validated for a transaction to pass.

All components of a transaction need to be valid for the whole tx to be valid.


text:
How to decode output of cardano-cli query ledger-state?
Running cardano-cli query ledger-state --mainnet --out-file out produces a binary file.
What format is it in?
How can I decode it?
I cannot use the command without --out-file out because of memory limitations.
UPDATE
I tried:
pip install cbor2
cat ledger-state.cbor | python -m cbor2.tool --pretty > ledger-state.json

which gave me:
[
    320,
    {
        "\u0000\u0000\u00006\\xd5\u0015\\xe1.\u0018\\xcd<\\x88\\xc7O\t\\xa6y\\x84\\xc2\\xc2y\\xa5)j\\xa9n\\xfe\\x89": 58,
        "\u0000\u0000\u0000\\xf6n(\\xb0\\xf1\\x8a\\xef U_LIT#N2p߻\\xdc\\xc1?T\\xe7\\x99": 57,
[...]
    }
]

which does not seem to be decoded properly.

Pretty sure the binary format is CBOR and yes, the ledger state is HUGE.
I think that if you drop the --out-file command line option the output goes to stdout in JSON format but again the output on mainnet is so huge that for me cardano-cli is killed by the OOM killer on a machine with 16G of RAM.
Using the command you use, the output file is 1.4 Gigabytes (much more compact than the in-memory representation).
There is already a Github issue about that which is almost a year old.

Thanks for the relevant information.

If you're looking to create a readable snapshot of the Cardano ledger as of a given slot, might I suggest using ogmios.dev as a simpler solution.  Ogmios allows one to read the entire state of the ledger via the chain sync mini-protocol.  The ledger is exposed as a websocket api, reducing integration complexity.

I am planning on using Ogmios but was hoping for a quick and easy way to do a few inspections of the ledger from the commandline with jq.


text:
Referencing an external plutus script
I would like to understand how one can reference an external plutus script in one transaction. In  solidity (for the other script), one can import the contract interface into their script, create an object using the smart contract address and then call the visible functions of the other script (as below).
address token = 0xE592427A0AEce92De3Edee1F18E0157C05861564;
IERC20(token).totalSupply();

I presume to achieve a similar effect in plutus, you would need to perform this all in the off-chain Contract code? And in order to do all of this you would need both the code for the other script as well as the address?

Reference Scripts, the ability for a transaction to reference scripts from a prior transaction is scheduled to be available later this year, sometime in June I believe. https://github.com/cardano-foundation/CIPs/pull/161
However, I'm not sure this will be what you're looking for.  In Solidity, smart contracts are like recipes: do X, then do Y, and then do Z.  On Cardano, a validator (smart contract) is a function that return a boolean representing whether the provided transaction may spend the funds may, yes or no?
Because of this difference, contract composition will look different.  Composability on Solidity resembles a micro service architecture, each service (contract) can synchronously call other services (contracts) via an exposed api.  Composability on Cardano, on the other hand, will more closely resemble an event driven ecosystem (or FRP).  Services will emit events that can be consumed to trigger downstream events.

Thanks for the response Matt! So let's say (in the current cardano environment), one of the parameters to my validator function is the total supply of a native asset, are you saying that it is not possible to query the total supply of this native asset from it's policy script? Apologies if my initial question was not quite clear.

Composability on Cardano, on the other hand, will more closely resemble an event driven ecosystem Can you please elaborate?