text:
Obscure error while trying to unlock funds from a script from the CLI
I have been trying to interact with a simple script I created using the CLI, and I am getting an error that I don't understand:
This is the error:
The Plutus script evaluation failed: An error has occurred:  User error:
The provided Plutus code called 'error'.
Caused by: [ (builtin unConstrData) (con data #80) ]

This is the script:
{-|
Module      : Horrocubes.Counter.
Description : Plutus script that keeps track of an internal counter.
License     : Apache-2.0
Maintainer  : angel.castillo@horrocubes.io
Stability   : experimental

This script keeps a counter and increases it everytime the eUTXO is spent.
-}

-- LANGUAGE EXTENSIONS --------------------------------------------------------

{-# LANGUAGE DataKinds                  #-}
{-# LANGUAGE DeriveAnyClass             #-}
{-# LANGUAGE DeriveGeneric              #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE FlexibleContexts           #-}
{-# LANGUAGE MultiParamTypeClasses      #-}
{-# LANGUAGE NoImplicitPrelude          #-}
{-# LANGUAGE OverloadedStrings          #-}
{-# LANGUAGE ScopedTypeVariables        #-}
{-# LANGUAGE TemplateHaskell            #-}
{-# LANGUAGE TypeApplications           #-}
{-# LANGUAGE TypeFamilies               #-}
{-# LANGUAGE TypeOperators              #-}
{-# LANGUAGE DerivingStrategies         #-}
{-# LANGUAGE LambdaCase                 #-}
{-# LANGUAGE NamedFieldPuns             #-}
{-# LANGUAGE ViewPatterns               #-}

-- MODULE DEFINITION ----------------------------------------------------------

module Horrocubes.Counter
(
  counterScript,
  counterScriptShortBs,
  CounterParameter(..)
) where

-- IMPORTS --------------------------------------------------------------------

import           Cardano.Api.Shelley      (PlutusScript (..), PlutusScriptV1)
import           Codec.Serialise
import qualified Data.ByteString.Lazy     as LBS
import qualified Data.ByteString.Short    as SBS
import           Ledger                   hiding (singleton)
import qualified Ledger.Typed.Scripts     as Scripts
import           Ledger.Value             as Value
import qualified PlutusTx
import           PlutusTx.Prelude         as P hiding (Semigroup (..), unless)
import           Data.Aeson               (FromJSON, ToJSON)
import           GHC.Generics             (Generic)
import qualified Ledger.Contexts          as Validation
import           Text.Show
import           PlutusTx.Builtins

-- DATA TYPES -----------------------------------------------------------------

-- | The parameters for the counter contract.
data CounterParameter = CounterParameter {
        ownerPkh    :: !PubKeyHash, -- ^ The transaction that spends this output must be signed by the private key
        identityNft :: !AssetClass  -- ^ The NFT that identifies the correct eUTXO.
    } deriving (Show, Generic, FromJSON, ToJSON)

PlutusTx.makeLift ''CounterParameter

-- PlutusTx.unstableMakeIsData ''CounterDatum

-- | The Counter script type. Sets the Redeemer and Datum types for this script.
data Counter
instance Scripts.ValidatorTypes Counter where
    type instance DatumType Counter = BuiltinData
    type instance RedeemerType Counter = ()

-- DEFINITIONS ----------------------------------------------------------------

-- | Maybe gets the datum from the transatcion output.
{-# INLINABLE counterDatum #-}
counterDatum :: TxOut -> (DatumHash -> Maybe Datum) -> Maybe Integer
counterDatum o f = do
    dh      <- txOutDatum o
    Datum d <- f dh
    PlutusTx.fromBuiltinData d

-- | Checks that the identity NFT is locked again in the contract.
{-# INLINABLE isIdentityNftRelocked #-}
isIdentityNftRelocked:: CounterParameter -> Value -> Bool
isIdentityNftRelocked params valueLockedByScript = assetClassValueOf valueLockedByScript (identityNft params) == 1

-- | Creates the validator script for the outputs on this contract.
{-# INLINABLE mkCounterValidator #-}
mkCounterValidator :: CounterParameter -> BuiltinData -> () -> ScriptContext -> Bool
mkCounterValidator parameters oldDatum _ ctx =
    let oldCounterValue        = oldDatumIntegerValue
        isRightNexCounterValue = (newDatumValue == (oldCounterValue + 1))
    in traceIfFalse "Wrong counter value"           isRightNexCounterValue
    where
        info :: TxInfo
        info = scriptContextTxInfo ctx

        ownOutput :: TxOut
        ownOutput = case getContinuingOutputs ctx of
            [o] -> o
            _   -> traceError "Expected exactly one output"

        newDatumValue :: Integer
        newDatumValue = case counterDatum ownOutput (`findDatum` info) of
            Nothing -> traceError "Counter output datum not found"
            Just datum  -> datum

        oldDatumIntegerValue :: Integer
        oldDatumIntegerValue = case PlutusTx.fromBuiltinData oldDatum of
            Nothing -> traceError "Counter output datum not found"
            Just datum  -> datum

        valueLockedByScript :: Value
        valueLockedByScript = Validation.valueLockedBy info (Validation.ownHash ctx)

        isTransactionSignedByOwner :: Bool
        isTransactionSignedByOwner = txSignedBy info (ownerPkh parameters)

-- | The script instance of the counter. It contains the mkCounterValidator function
--   compiled to a Plutus core validator script.
counterInstance :: CounterParameter -> Scripts.TypedValidator Counter
counterInstance counter = Scripts.mkTypedValidator @Counter
    ($$(PlutusTx.compile [|| mkCounterValidator ||]) `PlutusTx.applyCode` PlutusTx.liftCode counter) $$(PlutusTx.compile [|| wrap ||])
    where
        wrap = Scripts.wrapValidator @BuiltinData @()

-- | Gets the counter validator script that matches the given parameters.
counterValidator :: CounterParameter -> Validator
counterValidator params = Scripts.validatorScript . counterInstance $ params

-- | Generates the plutus script.
counterPlutusScript :: CounterParameter -> Script
counterPlutusScript params = unValidatorScript $ counterValidator params

-- | Serializes the contract in CBOR format.
counterScriptShortBs :: CounterParameter -> SBS.ShortByteString
counterScriptShortBs params = SBS.toShort . LBS.toStrict $ serialise $ counterPlutusScript params

-- | Gets a serizlized plutus script from the given parameters.
counterScript :: PubKeyHash -> AssetClass -> PlutusScript PlutusScriptV1
counterScript pkh ac = PlutusScriptSerialised $ counterScriptShortBs $ CounterParameter { ownerPkh = pkh,  identityNft = ac }

This is how I am creating the transaction:
cardano-cli transaction build --alonzo-era --testnet-magic 1097911063  --change-address $(cat counter/payment.addr) --tx-in-collateral 7d65ca46aca44532d94da57ec6b7297efdda2e523626f90bbdc780f3767202f2#0 --tx-in 0be3e055fa3e51b34baa1cc5589397520ee79670dbf2428f7884713ba0066f4f#1 --tx-in-script-file ./counter/out2.plutus --tx-in-datum-file ./datum_0.json --tx-in-redeemer-value [] --tx-out "addr_test1vpfvmwfl8eucm8rnsej9pehzh7628k53raczagz4uvzzm2csx7sfl+1000000" --tx-out-datum-embed-file ./datum_1.json  --protocol-params-file protocol.json --out-file tx-script2.build

I have been trying to find the root cause of the error to no avail. It seems it is related to one of the Datum inputs, but I don't the error on the script or the datum data.
This is what is on the datum.json files:
datum_0.json
{"constructor":0,"fields":[{"int":0}]}

datum_1.json
{"constructor":0,"fields":[{"int":1}]}

I finally made it work, I will leave it here in case anyone encounters the same issue.
The problem was the redeemer. You have to be careful with the encoding of the datums and the redeemer (even if you are not using the redeemer), this one took me a really long time, as I didn’t understand why I was getting some constructor error for a built-in type, I thought there was something wrong with the datums, it turned out to be the redeemer, I was using [] as a dummy value, but in reality, you have to pass a valid value as it will try to construct a value for the redeemer even if you only defined it as unit ().

What was the value you used for ()? I've been stuck on that for a bit now.

I just used the same as I was using for the datum "{"constructor":0,"fields":[{"int":0}]}", I also had to use it as a file "--tx-in-redeemer-file"


text:
Ledger wallet initial setup in Daedalus versus restore
What are the differences when a brand new Ledger HW wallet is paired with Daedalus as compared to when a Ledger HW wallet is restored?  The reason I ask is that after the Ledger is initially configured, the wallet only has options for changing the wallet name, viewing the public address and deleting the wallet. After a wallet is deleted and restored there are additional options to change the spending password and to confirm the wallet recovery seed.

Is it possible to get back to the original wallet configuration where there is no spending password?
Is the recovery phrase stored in Daedalus and if not, why is the option to confirm the wallet recovery seed not available before the wallet is restored?

I'm paranoid but I don't even like the fact that I typed in a wallet recovery seed on a computer that could have been monitored in some way.

I think you're confusing creating a wallet within Daedalus (using create/restore by mnemonic) with using a hardware wallet. With restoration of a hardware wallet (whether it be a new one or existing), Daedalus never needs the recovery seed or a spending password. The device itself requires a pin to send funds, and Daedalus only gets the public account key of the hardware wallet so the wallet can identify utxos associated with that wallet and generate new unused addresses.

source: Stack Exchange

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

sort: votes


text:
Tutorial for Haskell Restful-API Webserver
Using free and open source Haskell and with minimal or ideally no external libraries, I need to build a very simple RESTful-API/database server and a CLI to manage it. I need to use it for serving up webpages, text files, or selected lines of json from a text file. After this is done, I would like to give it a GUI. My problem is I can't find any tutorials that explain how to do any of this.
Does anyone know of any tutorials that fit these requirements?
Much thanks

There are at least 3 web frameworks in the Haskell ecosystem, from simplest to most complex; Scotty, Yesod and Snap.
A google search shows up a bunch of tutorials: https://www.google.com/search?client=firefox-b-d&q=haskell+rest+web+server+howto

Thank you @ErikdeCastroLopo. I had been searching and searching but never thought to use the keyword howto. That was the charm.

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


text:
Official IOG Cardano Node Course Documentation Error - Node Won't Start
I am following along with the new Official IOG Cardano Node Course:
https://cardano-course.gitbook.io/cardano-course/

I am stuck at Video 3 at 6 minutes and 8 seconds in.
https://youtu.be/YlUljmlCPYs?t=368

I started with a new WSL setup with Ubuntu 22.04.
I used the nix setup method shown in video 2.
There was no indication of any problems.
Then I ran the following command to start the node.
js@LAPTOP-NGQPLDGT:~/preview$ cardano-node run --topology topology.json --database-path db --socket-path node.socket --port 3001 --config config.json

This produced the following error message:
cardano-node: FatalError {fatalErrorMessage = "Cardano.Node.Run.handleSimpleNodeP2P.readTopologyFile: Is your topology file formatted correctly? Expecting P2P Topology file format. The port and valency fields should be numerical. If you specified the correct topology file make sure that you correctly setup EnableP2P configuration flag. Error in $: key "LocalRoots" not found"}

It should work if I followed the directions exactly because I used the topology file that was supplied with the course. I am reporting the issue here because if I followed the directions accurately then there is an issue with the course materials which must be fixed.
I am curious to know if there is anyone else using Windows Subsystem for Linux setup with Ubuntu 22.04 who has followed video 2 in the series and what was the result?
Any ideas?
Much thanks.

The following is the contents of the topology file. It was retrieved using the following command as per course instructions found at this link here.

wget https://book.world.dev.cardano.org/environments/preview/topology.json

{
  "localRoots": [
    {
      "accessPoints": [],
      "advertise": false,
      "valency": 1
    }
  ],
  "publicRoots": [
    {
      "accessPoints": [
        {
          "address": "preview-node.world.dev.cardano.org",
          "port": 30002
        }
      ],
      "advertise": false
    }
  ],
  "useLedgerAfterSlot": 322000
}

This appears to be your topology file. You're probably running the p2p enabled config, but using the old topology format. Edit config.json and set "EnableP2P": false, or remove the parameter totally. If that's not enabled, post your topology file (hiding your IPs), so we can look at it. Your p2p local roots needs to look like the following:
  "localRoots": [{
    "accessPoints": [
      {"address": "your blockproducer/relay IP or domain name", "port": 6000}
    ],
    "advertise": false,
    "valency": 1
  },{
   "accessPoints": [
     {"address": "if you have a second relay", "port": 6000}
   ],
   "advertise": false,
   "valency": 1
  }],

If you're certain P2P is not enabled in your config, then you could try the old format (and by old I mean about 2 weeks old now and is still used by the majority).
{
  "Producers": [
    {
      "addr": "BP/Relay IP or domain name",
      "port": 6000,
      "valency": 1
    },
    {
      "addr": "If you have a second",
      "port": 6000,
      "valency": 1
    }
  ]
}

Thanks @PREEB, I didn't see anything about EnableP2P. I posted the contents of the topology file in the body of my original question. Thanks for having a look.

@JohnShearing I updated my answer above. Looks like you're using the "preview" version of the config.json, which in fact does have   "EnableP2P": true,

Ultimately the following text in the topology.json file worked when setting EnableP2P": false in the config.json file all as @PREEB suggested.
{
  "Producers": [
    {
      "addr": "preview-node.world.dev.cardano.org",
      "port": 30002,
      "valency": 1
    }
  ]
}

The URL to use was found here and it had to be pasted into a file of the format suggested by @PREEB
So I followed the directions in the course correctly but the file topology.json file I was directed to use was not correct and the P2P setting in the config.json file was set to true when it must be set to false.
I hope this can be corrected in the documentation so that others will not have the same problem when working through the course. Otherwise I am really enjoying the course and learning a lot.
I see the GitHub repository is here.
I will reach out to the creator.
Much thanks.


text:
NFT Support For Marlowe
A Marlowe contract for a bank loan is linked here:
This was homework for Marlowe Pioneers - Lesson 4.
If you run the contract in the Marlowe Playground you will see that if the borrower makes all the payments on time then the bank returns all the ADA to the borrower and the contract ends. Returning the money to the borrower seems to simulate the bank is giving the borrower a title to a property. I am wondering if giving an NFT to represent the property deed is already possible using Marlowe. If not, then I am wondering when NFT support is going to be added to Marlowe.
I think that it may be possible to do this now or in the future because of the stackexchange post linked here. Is this something that should be added to the ACTUS demos?
Is it possible to expand the Marlow contract linked above to deliver an NFT representing a property deed if the borrower makes all the payments on time? If so, will we be taught this skill?
Much thanks

Thanks to Hernan Rajchert, the contract linked above now uses a native token as seen in his solution below.

Marlowe already has the notion of MultiValue asset, which is what you need to trade custom tokens. Instead of using the ADA token, use one that represent your deed.
The minting of that NFT is done outside of Marlowe, but after you have it, you can put it into a Marlowe contract with a Deposit.

Useful link: https://docs.cardano.org/native-tokens/learn


text:
ScriptWitnessNotValidatingUTXOW while minting an NFT
I'm currently trying to create a minting process with lucid (v. 0.8.9) using Blockfrost on Mainnet.
Minting policy:
const mintingPolicy: MintingPolicy = lucid.utils.nativeScriptFromJson({
    type: "any",
    scripts: [{
        scripts: [{
            keyHash: "ccb1d97578fe819d6df11095a74a96803e5a50460b5cf895aaf40c0d",
            type: "sig"
        }],
        type: "all"
    }, {
        scripts: [{
            keyHash: "66f9337a3873f06478d394058ec7fda75909b359df883b8aaf8ba79d",
            type: "sig"
        }],
        type: "all"
    }, {
        scripts: [{
            keyHash: "6c70c3fc4f73e5bbb54cc87bdf943fad2213da692b260e12749bcc10",
            type: "sig"
        }],
        type: "all"
    }]
});

Mint function:
export async function mintNFT(name ? : string, ): Promise < TxHash > {
    try {
        const unit: Unit = policyId2;
        const tx = await lucid.newTx().mintAssets({
            [unit]: 1n
        }).attachMintingPolicy(mintingPolicy).validTo(Date.now() + 100_000).complete();
        const signedTx = await tx.sign().complete();
        const txHash = await signedTx.submit();
        console.log(txHash) return txHash;
    } catch (e: any) {
        console.log('Error occured:');
        console.log(e.message);
        return e.message;
    }
}

Error:
"transaction submit error ShelleyTxValidationError ShelleyBasedEraBabbage (ApplyTxError [UtxowFailure (FromAlonzoUtxowFail (WrappedShelleyEraFailure (ScriptWitnessNotValidatingUTXOW (fromList [ScriptHash \"f188522db566255b029de7c30e1e5cc14c30ba6649356d9b1ae8ebb5\"]))))])"

Where f188522db566255b029de7c30e1e5cc14c30ba6649356d9b1ae8ebb5 is a policyId.
I'm not entirely sure, but the error seems to be fixable by adding invalid-hereafter parameter to a raw transaction in cli OR by signing a transaction with both skey and vkey (I think that currently lucid only signs with vkey), but I didn't find a way to do it properly.

I messed up the keyHashes in the minting policy and was trying to mint with a different wallet.
This was extremely useful.

I'm not sure if this will help, but I have an example that includes both on-chain and off-chain code for minting a multi-sig NFT using Helios.
https://github.com/lley154/helios-examples/tree/main/nft-multisig


text:
What means this line of script
What this means on cardano token time lock?
all: [
      {
         invalidAfter: 99336691

The script cannot be used to mint assets once slot 99336691 has passed.

Only can not mint? Or can not transter assets?

A simple script can be used for: locking utxos at an address where all spending conditions are defined by the script, and the same conditions can also be applied to restrict minting/burning of tokens under a common policy. Have a read of https://github.com/input-output-hk/cardano-node-wiki/wiki/simple-scripts


text:
how to use ownPubKey and RedeemerType and DatumType
My code is here.
{-# LANGUAGE DeriveAnyClass        #-}
{-# LANGUAGE DataKinds             #-}
{-# LANGUAGE DeriveGeneric         #-}
{-# LANGUAGE ScopedTypeVariables   #-}
{-# LANGUAGE TemplateHaskell       #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeOperators         #-}

module MarketState (
  createMarket
)where

import Plutus.Contract as Contract
import Control.Monad (void)
import Control.Applicative
import Data.Aeson (ToJSON, FromJSON)
import GHC.Generics (Generic)
import Schema (ToSchema)
import Data.String (String)
import Data.Text (Text)
import qualified PlutusTx
import Ledger (PubKeyHash(..))
import qualified Plutus.V1.Ledger.Ada as Ada
import Ledger.Constraints (TxConstraints)
import Ledger.Contexts (ScriptContext)
import Ledger.Typed.Scripts (DatumType, RedeemerType)

-- Define the market parameters
data MarketParams = MarketParams {
  event :: String,
  outcomes :: [String],
  fees :: Integer
} deriving (Generic, ToJSON, FromJSON, ToSchema)

PlutusTx.makeLift ''MarketParams

-- Define the smart contract logic
data Market = Market {
  params :: MarketParams,
  creator :: PubKeyHash
} deriving (Generic, ToJSON, FromJSON, ToSchema)

PlutusTx.makeLift ''Market

-- Create a function to deploy the smart contract
createMarket :: MarketParams -> Contract w s Text ()
createMarket params = do
  pk <- PubKeyHash <$> ownPubKey
  let market = Market params pk
  void $ submitTxConstraints (marketConstraints market) (tx market)
  logInfo $ "Market deployed at " <> show (address market)

-- Define the market constraints
marketConstraints :: Market -> TxConstraints (RedeemerType -> ScriptContext -> Bool)(DatumType, ())
marketConstraints market = mustValidateIn (to $ scriptAddress market)

-- Define the transaction logic
tx :: Market -> TxConstraints () ()
tx market = mustSpendScriptOutput (scriptTxOut $ market) (Redeemer $ PlutusTx.toBuiltinData BuyShares)
         <> mustPayToPubKey (creator market) (Ada.lovelaceValueOf $ fees $ params market)

I am a Plutus Smart Contract beginner. I don't sure how to fix this error. Please help me to fix the error.
src/MarketState.hs:58:47: error:
    • Expecting one more argument to ‘RedeemerType’
      Expected a type, but ‘RedeemerType’ has kind ‘* -> *’
    • In the first argument of ‘TxConstraints’, namely
        ‘(RedeemerType -> ScriptContext -> Bool)’
      In the type signature:
        marketConstraints :: Market
                             -> TxConstraints (RedeemerType
                                               -> ScriptContext -> Bool) (DatumType, ())
   |
58 | marketConstraints :: Market -> TxConstraints (RedeemerType -> ScriptContext -> Bool) (DatumType, ())
   |                                               ^^^^^^^^^^^^

src/MarketState.hs:58:87: error:
    • Expecting one more argument to ‘DatumType’
      Expected a type, but ‘DatumType’ has kind ‘* -> *’
    • In the second argument of ‘TxConstraints’, namely
        ‘(DatumType, ())’
      In the type signature:
        marketConstraints :: Market
                             -> TxConstraints (RedeemerType
                                               -> ScriptContext -> Bool) (DatumType, ())
   |
58 | marketConstraints :: Market -> TxConstraints (RedeemerType -> ScriptContext -> Bool) (DatumType, ())

RedeemerType and DatumType both require the data type to be specified, e.g. RedeemerType Integer.
If you use AllowAmbiguousTypes language extension you can do, e.g. RedeemerType a.


text:
Create a Native token for voting & burn afterwards
I am looking to issue voting Tokens.
The basic idea is that I will send something like 100 tokens to 10 people. Then there will be three wallets that act as ballot box.
In order to incentivise the people to vote within a certain timeframe I wan’t to burn the tokens after a certain period of time.
Am I right that I can do so by burning the tokens as token issuer?
And when burning, what will happen to the ADA used during token minting?

First of all, there might be better ways to build a voting system than to use native assets as "votes" in the future when we have smart contracts on Cardano. But of course your proposal would be possible.
Once the tokens have left your wallet, you won't be able to burn them. That can only be done by the owners of the tokens. There is this question where you can find more info on how token burning works: What does it mean to "burn" a token?
The ADA used to mint the tokens is used to "pay" for the minting process. This has nothing to do with the burning of tokens.

OK thnx.
I am aware that this way of voting is suboptimal, but I'am looking for a voting mechanism which works prior to smart contracts release.


text:
What is a Redeemer?
So I am currently on lecture 1 on the Plutus Pioneer Program. In the lecture they said the redeemer is the input information that the script uses to decide if a specific UTxO can be spent. I watched a video that was made two years ago that said the redeemer is used to decide if a wallet can receive Ada from a smart contract. The person in that video did say that these things might change because things are still under development. Can someone clear this up for me? What exactly is a redeemer as of right now? What is a redeemer's role in sending transaction and in smart contracts?

From https://iohk.io/en/blog/posts/2021/04/13/plutus-what-you-need-to-know/:

When validating an address, the script will access the data being
carried by the output, the transaction being validated, and some
additional pieces of data called redeemers, which the transaction
provides for every input. By looking up all this information, the
script has enough context to give a ‘yes’ or ‘no’ answer in what can
be highly complex situations and use cases.

In lecture 1 of the current plutus pioneers program, you find a redeemer on the auction validation script. When making a bid, there are essentially five cases to check. All these five cases need to pass or the transaction will not be even committed to the blockchain (which is good, because you're saving on fees for something that won't succeed anyway):

Is the bid sufficient (the bid is >= the minimum valid bid)
The auction hasn't closed

The three other cases also do data checks (output datum/value, bid refund).
The redeemer (in the auction example) itself is a simple data type that we can define (AuctionAction) to do data validation (particularly on inputs).

That was a great explanation.Thanks.

Thank you. If you're happy with the explanation, make sure to mark the answer as a solution to your question as it helps other StackExchange users to see what questions have/haven't been answered sufficiently.

In simple terms, redeemer is the data that the user of the smart contract provides to the smart contract.
In the simple UTxO model, redeemer is your signature. By providing your signature, you prove that you own the UTxO and in return you are allowed to spend that UTxO.
EUTxO takes this one step further. How are you going to spend an EUTxO? You have to provide all the data that EUTxO needs and depending on the data you provide, you are allowed to spend it or not.

Before (E)UTxO - There Was UTxO
Understanding how a UTxO model works (such as BTC) may help you understand the implementation of (E)UTxO in Cardano.
The UTxO Model
A UTxO model, meaning: unspent transaction outputs from previous transactions1 will typically implement a validator and a redeemer for any given new transaction (at least, this is the case in BTC).
Validators and Redeemers
The validators job is to return a boolean value as to whether the UTxO can be spent or not. In BTC the validator is implemented in BitCoin Script and is about as simple as it could be. It does, however, take a redeemer (which in the case of BTC is a representation of transactional digital signatures); and the validator uses the redeemer to either allow the UTxO to be spent or not.
Cardano | The (E)UTxO Model
Within Cardano we use scripts to evaluate whether or not a given (E)UTxO may or may not be spent. An address in Cardano points to a script - the script contains arbitrary logic and takes a redeemer as its input/parameter(s) - which are now also more general in nature, as they need to satisfy the constraints provided by the arbitrary logic within the script.
By triggering the script (attempting to create a new transaction), the redeemer will be passed to the script, the script will be executed and will determine whether or not the (E)UTxO can be spent or not.
Summary
A redeemer is used as input to an (E)UTxO script in order to determine whether or not the extended unspent transaction output may or may not be consumed, given the arbitrary logic provided within the script.
FYI: Cardano addresses point to scripts, the script may be simple or extremely complex.
I found this video by Michael Peyton Jones to be pretty informative and perhaps a little more intuitive than the first lecture presented within the Plutus Pioneer Program:
https://youtu.be/usMPt8KpBeI
However, it may be a little outdated? I'm still working my way through the second cohort.

Footnotes:

Think of an unspent transaction as the change you're given in a shop when you hand a $20 bill for a $5 item, the $15 change is YOUR UTxO and is secured using public-private key cryptography.

In Bitcoin, both the "validator" and "redeemer" is Bitcoin Script. The output of the redeemer is given as input to the validator. In Bitcoin's implementation this amounts to the validator script being executed against the stack produced by the redeemer script. The validator script will then determine if the redeemer is valid based on the stack it leaves behind.

There is an interesting example in one of the Pioneer lectures which implements Uniswap on Cardano.
A redeemer is not only used to justify that a UTxO can be spent, but also the manner in which it will be spent. The validation script will then place the necessary constraints on the creation of the transaciton based on who is trying to spend it and how they are trying to spend it.
In the screenshot attached from lecture 10 of the first iteration of the Plutus Pioneer Program, the blue lines represent the redeemer as an input to the UTxO's validation script (represented by the blue and red circles) which, in this case, is validating the consumption of  a UTxO which represents a liquidity pool.
You can see four different labels on four of the blue lines - Create, Swap, Add and Remove. These represent different constructors for the redeemer data type being used and tell the script what action the user is trying to take.
For further details of exactly what each redeemer does, you can read more and find a link to the video here.


text:
Automatically connect to wallet if website is whitelisted
I am currently connecting to a cardano wallet like this.
  const [walletApiKey, setWalletApiKey] = useState(null);

  const connectCardanoWallets = async (selectedWallet) => {
    const walletFound = !!window?.cardano?.[selectedWallet];
    if (walletFound) {
      try {
        let walletApi;
        walletApi = await window.cardano[selectedWallet].enable();
        setWalletApiKey(walletApi);
      } catch (err) {
        console.log(err);
      }
    } else {
      toast('Wallet not found');
    }
  };

If they have previously connected to our website before , when I envoke the method .enable() we get the API key automatically without the user putting in their password to whitelist us again. Right now I am using a useEffect hook like this to connect to their wallet.
  useEffect(() => {
    connectCardanoWallets('nami');
  }, []);

How do I check if our website is whitelisted so i can automatically connect to their wallet and don't automatically envoke the .enable() method if my website is not whitelisted?

The simplest solution I had is to use a cookie which you set once you grants you permission. Then, as a user visits your page, you just read the cookie and get the selected wallet.

Above simple solution will work, but you could expand it more like:

check if the window.cardano API is available
loop through all wallets to check if they are installed
check if they are enabled, there is a isEnabled() function which can be used.

With this feedback you can give the end-user a dropdown where you list all wallets and enable/highlight the ones that are available.


text:
Programmatically Send Transactions From a Wallet Using Javascript
I am building an application that has a hot wallet that stores ADA that my user has deposited. After some business logic is met, I want to transfer funds from my hot wallet to another address. How do I programmatically send ADA from my wallet to another user? I am currently using the Cardano-serialization-library but it prompts you to enter your password into your wallet extension for the transactions to go through. How do I programmatically send transactions from my wallet to my user without putting in a password in my wallet extension? My application is built on MERN stack so it needs to be in JavaScript.

If you already hold access to wallet private keys, you dont need to "interact" with a wallet extension, you already have all you need to derive the keys, addresses, fetch inputs from query layer of your choice and then construct/submit transaction.
If - instead - you're interacting via extension to access user's wallet, doing it without user prompt should NOT be possible unless using an insecure wallet with bad practices (i.e. either does not care about user security to authorize transactions OR allows bulk mode of transactions to be allowed at once, both of which can be easy targets for scam).


text:
Listing all UTXOs spend by a script as well as the public key it came from
How do I list all Utxos that is in my script as well as the public key addresses that it came from.I am using the result as a parameter for a different function.I want to know if a public key address has already send a transaction to this script , if they have then do something , and if they have not then do something else.

Scripts do not spend utxos, transactions do. Do you mean all outputs that belong to the script at any given time?, including or excluding current unsuspended outputs?

Yep, like outputs that belong to the script.

sorry can you please be more specific?
what exactly do you mean "ist all Utxos that were consumed by my script " ?
do you need a list of UTXOs for a specific address?
and additionally, do you need the address from the sender of this UTXOs?
if yes, please see below.
find all UTXOs
fullUtxo=/fullUtxo.out
myAddr=addr1qljkdlgamadjnlh8xmgxln4535kj5j3lgl9mawrr99nkrt2meqa2z
cardano-cli query utxo --address $myAddr --mainnet > $fullUtxo

find sender
        in_addr=$(curl -H 'project_id: MainnetBlockfrostProjectNameID' https://cardano-mainnet.blockfrost.io/api/v0/txs/${tx_hash}/utxos | jq '.inputs' | jq '.[0]' | jq '.address' | sed 's/^.//;s/.$//')

if that helps you, would be great if you vote for my answer and give me some credits :)
have a nice day mate,
pool operator for TTS17

Yep, i wanted a list of UTXOs for a specific address and the address from the sender of this UTXOs.How can i also get the amount of times an address has send UTXOs to a script.

i dont understand what is your goal, because either i need to sell / send something to everyone for each transaction..... or i can send back tokens to many addresses ,who sent transactions, in the same transaction i send. - - - - if you want to know "how many times " of something, you can create a txt file with one line for each transaction and then execute this commands to find the number of lines "wc -l fileName.txt"   -#-#-#-#-

I want to see how many times an address has send UTXOs to a script. I am going to use that value as parameters for the script. I want to create a logic like if this public address has send UTXOs to this script once before , something happens.

like i said, i would add create a new file txt will all the tx you have currently "echo ${tx_in} >> $txsin" and better for your case, add tx there based on the sender....here you can see what i do, maybe related... if that helps you


text:
How to get a base 16 hex BuiltinString from getTxId
I am trying to find a way to inspect the base16 hash from a Tx on-chain using plutus.
I get a BuiltinByteString from the txInputs here:
getTxIdBBS :: TxInInfo -> BuiltinByteString
getTxIdBBS txInfo' = getTxId(txOutRefId (txInInfoOutRef txInfo'))

but then I need to get the base16 representation so I can compare and inspect the hex digits.

Ideally, I would like to use a function similar to below, but this only works off-chain (due to conversion to non-builtin).
import qualified Data.ByteString.Base16 as B16 (encode)

txId    = getTxIdBBS (txInfo)
txId'   = fromBuiltin(txId)
txIdHex = toBuiltin(B16.encode txId')

I've also tried the following, but this does not work either.
import Data.Text.Encoding qualified as E
import PlutusTx.Builtins.Internal qualified as BI

{-# INLINABLE txEncodeUtf16 #-}
txEncodeUtf16 :: BI.BuiltinString -> BI.BuiltinByteString
txEncodeUtf16 (BI.BuiltinString s) = BI.BuiltinByteString $ E.encodeUtf16BE s

txHash = txEncodeUtf16(decodeUtf8(txId))

I am not able to use decodeUtf8 on a BuiltinByteString generated by sha2_256 and get the following error:
decodeUtf8*** Exception: Cannot decode byte '\xc6': Data.Text.Internal.Encoding.decodeUtf8: Invalid UTF-8 stream

I also can’t use encodeUtf16BE due to the following compiler error:
GHC Core to PLC plugin: E042:Error: Unsupported feature: Type constructor: GHC.Prim.ByteArray#

Any help or suggestions on how to convert the BuiltinByteString from getTxId into a BuiltinString  "on-chain" where I can inspect the hex digits would be awesome.
Thanks,
Lawrence

What is BuiltinByteString ?

I was able to resolve this issue by converting (encoding) the BuiltinByteString from getTxId into a hex format.   From there I was able to inpsect the hex digits.   Below is an onchain encodeHex function that I used (thanks Minswap!).
-- Convert from a byte string to its hex (base16) representation. Example: [2, 14, 255] => "020eff"
{-# INLINEABLE encodeHex #-}
encodeHex :: BuiltinByteString -> BuiltinByteString
encodeHex input = go 0
  where
    len = lengthOfByteString input
    go :: Integer -> BuiltinByteString
    go i
      | i == len = emptyByteString
      | otherwise =
        consByteString (toChar $ byte `quotient` 16) $
          consByteString (toChar $ byte `remainder` 16) (go $ i + 1)
      where
        byte = indexByteString input i

        toChar :: Integer -> Integer
        toChar x
          -- 48 is ASCII code for '0'
          | x < 10 = x + 48
          -- 97 is ASCII code for 'a'
          -- x - 10 + 97 = x + 87
          | otherwise = x + 87

but then I need to get the base16 representation so I can compare and
inspect the hex digits.

Not sure this is correct, I was able to inspect the txId directly with getTxId, take a look at the following code
import           Data.Aeson           hiding (Value)
import           GHC.Generics
import           Ledger               hiding (singleton)
import           Ledger.Scripts
import           Ledger.Typed.Scripts as Scripts
import           Ledger.Value
import           Plutus.ChainIndex
import qualified PlutusTx
import PlutusTx.Builtins
import qualified PlutusTx.AssocMap    as PlutusMap
import           PlutusTx.Prelude
import qualified PlutusTx.Ratio       as R
import qualified Prelude

...

{-# INLINEABLE mkNFTPolicy #-}
mkNFTPolicy :: Integer -> TxOutRef -> ScriptContext -> Bool
mkNFTPolicy size oref ctx =
    nftPolicyTraceIfFalse "UTxO not consumed" hasUTxO &&
    nftPolicyTraceIfFalse "Invalid token name or amount" validMinting
  where
    refId :: BuiltinByteString
    refId = case intToBuiltinByteString $ txOutRefIdx oref of
        bbs | lengthOfByteString bbs == 1 -> "0" `appendByteString` bbs
            | lengthOfByteString bbs == 2 -> bbs
        _ -> nftPolicyTraceError "Invalid ref id"

    ...

    validTokenName :: TokenName -> Bool
    validTokenName (TokenName bs) = sliceByteString 0 (size + 2) bs == expected
      where
        expected :: BuiltinByteString
        expected = sliceByteString 0 size (getTxId $ txOutRefId oref) `appendByteString` refId
    ...

Thanks Mateus.  I was able to resolve the issue, I needed to convert (encode) the onchain reprentation proivded by getTxId into a hex format.   From there I was able to look at each of the hex digits.   I'll post the encodeHex function on the main thread.

You might just need to use the fromBuiltin fn to get a ByteString:
...
import Data.ByteString.Char8 as C
import Prelude as Haskell
...

converted :: BuiltinByteString -> BuiltinString
converted bbs' = let b = C.unpack( fromBuiltin bbs' ) :: Haskell.String
                              -- in toBuiltin b
                              in stringToBuiltinString b

Update: I'm not sure I've figured out how to set up the toBuiltin fn. It's not compiling in my test project.
Update: the actual fn is stringToBuiltinString

This does not work on-chain

@Mateus  is correct, this doesn't work onchain. I'll add another answer with what I've found.


text:
GHC error when adding TokenName to NFTMint params
I get the following GHC error for code that I am trying to update to Plutus V2.   I can reproduce the error using the plutus-scripts below.   Is this a bug with Plutus V2 or can anyone explain how to resolve it.   I don’t have this issue with Plutus V1.
Thank you.
Steps to reproduce
Git clone https://github.com/james-iohk/plutus-scripts.git
Git clone https://github.com/input-output-hk/plutus-apps.git
Go into plutus-apps directory and checkout 87b647b05902a7cef37340fda9acb175f962f354
Type nix-shell --extra-experimental-features flakes
Cd ../plutus-scripts/src
Make the following changes 1,2,3,4 below

vi NFTMint.hs

     53 data NFTParams = NFTParams --  doesn't need more than the TxOutRef
     54     {  mpTokenName :: !PlutusV2.TokenName  -- << 1. uncommented code here
     55     , mpAmount   :: !Integer
     56     , mpTxOutRef :: !PlutusV2.TxOutRef
     57     --, mpPubKeyHs  :: !Plutus.PubKeyHash
     58     } deriving Show
     59
     60 PlutusTx.makeLift ''NFTParams
     61 PlutusTx.unstableMakeIsData ''NFTParams
     62
     63 tn :: PlutusV2.TokenName  -- << 2. added helper function definition
     64 tn = PlutusV2.TokenName "test" -- << 3. and here function body
     65
     66 redeemer :: NFTParams
     67 redeemer = NFTParams { mpTokenName = tn,  -- << 4. added tn to param
     68                        mpAmount = 1,
     69                        mpTxOutRef = PlutusV2.TxOutRef {txOutRefId = "82669eddc629c8ce5cc3cb908cec6de339281bb0a0ec111880ff0936132ac8b0", txOutRefIdx = 0}
     70                      }

This will generate the following error when running cabal build from the plutus-scripts directory.
GHC Core to PLC plugin: E042:Error: Unsupported feature: Type constructor: GHC.Prim.Addr#
Context: Compiling type: GHC.Prim.Addr#
Context: Compiling data constructor type: Data.ByteString.Internal.PS
Context: Compiling type: Data.ByteString.Internal.ByteString
Context: Compiling data constructor type: NFTMint.NFTParams
Context: Compiling type: NFTMint.NFTParams
Context: Compiling expr: \ (mp' [Occ=OnceL1] :: NFTMint.NFTParams) ->
                           PlutusTx.Base.$
                             @ (PlutusTx.Builtins.Internal.BuiltinData
                                -> Plutus.V2.Ledger.Contexts.ScriptContext -> GHC.Types.Bool)
                             @ Plutus.Script.Utils.V1.Typed.Scripts.MonetaryPolicies.UntypedMintingPolicy
                             (Plutus.Script.Utils.V2.Typed.Scripts.MonetaryPolicies.mkUntypedMintingPolicy
                                @ PlutusTx.Builtins.Internal.BuiltinData
                                PlutusTx.IsData.Class.$fUnsafeFromDataBuiltinData)
                             (\ _ [Occ=Dead] (ctx :: Plutus.V2.Ledger.Contexts.ScriptContext) ->
                                let {
                                  info :: Plutus.V2.Ledger.Contexts.TxInfo
                                  [LclId,
                                   Unf=Unf{Src=<vanilla>, TopLvl=False, Value=False, ConLike=False,
                                           WorkFree=False, Expandable=True, Guidance=IF_ARGS [] 20 0}]
                                  info = Plutus.V2.Ledger.Contexts.scriptContextTxInfo ctx } in
                                PlutusTx.Bool.&&
                                  (PlutusTx.Trace.traceIfFalse
                                     (Data.String.fromString
                                        @ PlutusTx.Builtins.Internal.BuiltinString
                                        PlutusTx.Builtins.Class.$fIsStringBuiltinString
                                        (GHC.CString.unpackCString# "UTxO not consumed"#))
                                     (PlutusTx.Base.$
                                        @ [Plutus.V2.Ledger.Contexts.TxInInfo]
                                        @ GHC.Types.Bool
                                        (PlutusTx.Foldable.any
                                           @ []
                                           @ Plutus.V2.Ledger.Contexts.TxInInfo
                                           PlutusTx.Foldable.$fFoldable[]
                                           (\ (i [Occ=Once1] :: Plutus.V2.Ledger.Contexts.TxInInfo) ->
                                              PlutusTx.Eq.==
                                                @ Plutus.V1.Ledger.Tx.TxOutRef
                                                Plutus.V1.Ledger.Tx.$fEqTxOutRef
                                                (Plutus.V2.Ledger.Contexts.txInInfoOutRef i)
                                                (NFTMint.mpTxOutRef mp')))
                                        (Plutus.V2.Ledger.Contexts.txInfoInputs info)))
                                  (PlutusTx.Trace.traceIfFalse
                                     (Data.String.fromString
                                        @ PlutusTx.Builtins.Internal.BuiltinString
                                        PlutusTx.Builtins.Class.$fIsStringBuiltinString
                                        (GHC.CString.unpackCString# "wrong amount minted"#))
                                     (join {
                                        fail_dCmD [Occ=Once2!T[1]] :: GHC.Prim.Void# -> GHC.Types.Bool
                                        [LclId[JoinId(1)],
                                         Arity=1,
                                         Str=<L,U>,
                                         Unf=Unf{Src=<vanilla>, TopLvl=False, Value=True, ConLike=True,
                                                 WorkFree=True, Expandable=True,
                                                 Guidance=ALWAYS_IF(arity=1,unsat_ok=True,boring_ok=True)}]
                                        fail_dCmD _ [Occ=Dead, OS=OneShot] = GHC.Types.False } in
                                      case Plutus.V1.Ledger.Value.flattenValue
                                             (Plutus.V2.Ledger.Contexts.txInfoMint info)
                                      of {
                                        [] -> jump fail_dCmD GHC.Prim.void#;
                                        : ds_dCmB [Occ=Once1!] ds_dCmC [Occ=Once1!] ->
                                          case ds_dCmB of
                                          { (cs [Occ=Once1], tn' [Occ=Once1], amt [Occ=Once1]) ->
                                          case ds_dCmC of {
                                            [] ->
                                              PlutusTx.Bool.&&
                                                (PlutusTx.Eq.==
                                                   @ Plutus.V1.Ledger.Value.CurrencySymbol
                                                   Plutus.V1.Ledger.Value.$fEqCurrencySymbol0
                                                   cs
                                                   (Plutus.V2.Ledger.Contexts.ownCurrencySymbol ctx))
                                                (PlutusTx.Bool.&&
                                                   (PlutusTx.Eq.==
                                                      @ Plutus.V1.Ledger.Value.TokenName
                                                      Plutus.V1.Ledger.Value.$fEqTokenName0
                                                      tn'
                                                      ((Data.String.fromString
                                                          @ PlutusTx.Builtins.Internal.BuiltinByteString
                                                          PlutusTx.Builtins.Class.$fIsStringBuiltinByteString
                                                          (GHC.Types.[] @ GHC.Types.Char))
                                                       `cast` (Sym (Plutus.V1.Ledger.Value.N:TokenName[0])
                                                               :: GHC.Types.Coercible
                                                                    PlutusTx.Builtins.Internal.BuiltinByteString
                                                                    Plutus.V1.Ledger.Value.TokenName)))
                                                   (PlutusTx.Eq.==
                                                      @ GHC.Integer.Type.Integer
                                                      PlutusTx.Eq.$fEqInteger
                                                      amt
                                                      1));
                                            : _ [Occ=Dead] _ [Occ=Dead] -> jump fail_dCmD GHC.Prim.void#
                                          }
                                          }
                                      })))
Context: Compiling expr at "plutus-script-0.1.0.0-inplace:NFTMint:(98,8)-(98,37)"

The issue is not with the Plutus version but the compiler. You need to remove ! from where mpTokenName is defined. This should be fixed in the near future.

Thanks James, greatly appreciated.  This will work for now but had to remove other ! references in custom datatypes I have used in my code to get it to work.   Let me know if there is a bug logged for this.

My pleasure @lley154! This bug has been reopened with reference to this question: https://github.com/input-output-hk/plutus/issues/4193

Great - thanks James.


text:
plutus example of interacting with wallet on testnet using haskell
Can anyone proivde an example of how to create a wallet that can be used in the Main.hs file when connected to the testnet?   I have working code for Emulator and Simulator, but all examples against testnet are done via the REST API call to invoke a a contract instance with a wallet.   Here is the code fragment that I need to work for testnet, and I know the wallet ID in advance, but I don't know how to create a Wallet instance that can replace the defaultWallet below.
Simulator code:
main :: IO ()
main = void $ Simulator.runSimulationWith handlers $ do
Simulator.logString @(Builtin StarterContracts) "Starting plutus-starter PAB webserver on port 8080. Press enter to exit."
shutdown <- PAB.Server.startServerDebug
cidInit <- Simulator.activateContract defaultWallet InitContract
adminPkh <- Simulator.handleAgentThread defaultWallet ownPubKeyHash

...
Run code:
main :: IO ()
main = do
runWith (Builtin.handleBuiltin @StarterContracts)
shutdown <- PAB.Server.startServerDebug
cidInit <- Core.activateContract (Wallet ???) InitContract
adminPkh <- Core.handleAgentThread (Wallet ???)  ownPubKeyHash


text:
On-chain and off-chain for Plutus SCs
Hi I am currently at lecture 5 of the Plutus Pioneers Programm and I was wondering which part of the code is on chain and which is offchain. I know that the valididation script is onchain but the whole code is in one file, so how can later on some of that run offchain? And can maybe someone explain how this is handled in Ethereum?

I'm noob when it comes to plutus but i was curious to one thing: Where is the off-chain code stored? is this stored on-chain to be executed off-chain? or does it not work in that way?

I know that the valididation script is onchain but the whole code is in one file, so how can later on some of that run offchain?

Technically, everything you see in the file is off-chain code.
It is specifically the code that gets compiled into Plutus code that will be executed on-chain. And, yes this includes Validators and Policies. You can see how the monetary policy is compiled in the NFT code for lesson 5 here.
Everything else is used to either

Submit the compiled code on-chain, or
Interact with the submitted code

It's worth noting, people could write whatever off-chain code they want to interact with the on-chain code as long as the hashed policy address is the same here. It's the job of the policy writer to keep people from abusing that freedom.
It's nice having everything in one file/project so things can share types. It all starts as Haskell after all :).

The on chain part is basically every piece of code that runs when the nodes perform validations on whether you have the rights to spend UTOXs or you can mint or burn currencies (validator script and monetary policies). The term "On chain" I guess refers to the execution context of said code and since this validations are performed by the blockchain, that "on chain code" term was coined.
However, if I understand it correctly, these scripts do not actually live on the blockchain, but only the hash of the validator script does (along with the value and the current Datum of the UTXO), and is the spending transaction the one that must provide the right script for the nodes to validate (along with the new Datum and the Redeemer). Of course this script must match the script hash on the UTXO.
It works similar to the pay to script hash transactions in bitcoin, but adds the concepts of Datum and Redeemer and provide access to all inputs and outputs of the transaction so more sophisticated validations can be made.
So to summarize:
On chain code: All code that is executed by the nodes at validation time (UTXO validator script or monetary policy).
Off chain code: All code that is run by the wallet before sending the transaction. This code will construct the valid (or invalid) transaction to be send.

Thanks I think this helps

Mitchel Turner is right but for myself in the beginning i tried to think of things a little "simpler"
The validators basically run "on chain"
and the contracts (everything that result in the type -> Contract) runs in your(the users wallet) wallet.
So what that i took away from that.

the contracts just create/build a transaction from ground up in your wallet or "hidden" in the user interface that you create ... and will the be submitted to the chain

"the chain" will then use your validator to well validate this created transaction

the offchain code does the "heavy lifting" in setting every thing up ...

the validator is just there to say okay this transaction is okay or not

this "mindset" helped me in the beginning to start understand things ... and im still in the process of getting the whole picture ;)

On-chain part refers to all things compiled to the Plutus core. This compilation is driven by Haskell template engine and the code is wrapped in a Haskell data structure.
Off-chain part interacts indireclty with the ledger. In fact this part runs in a sandbox called PAB (Plutus application backend) which is capable of interacting with the Cardano passive node (entry point to the Cardano blockchain)
Off-chain part can lock (e)UTxOs or spend them.
When it comes to spending the transaction created by the off-chain part besides providing inputs and outputs needs only to provide hashes (hash for script and hash for datum). Those hashes can be computed by taking before compiled Plutus script (wrapped by some Haskell data structure) and performing some computation (calling function)
For spending however the transction being submited needs to contain the script, all required datum and of course redeemers as a wittneses.
To summarize the whole code related to the smart contract is sitting in a PAB. The on-chain part is generated during compilation by Haskell template engine and wrapped in Haskell data structue. Off-chain part when needed  unwraps the Plutus from underlying data structure and submit it as a part of a transaction.


text:
What does it mean for a contract to "stop"?
I'm working through the week 4 homework for the Plutus Pioneer program. I've found an answer to the homework problem and now I'm trying to get a deeper understanding of the code. I've noticed that the payContract returns itself (I'm still learning Haskell so that terminology might not be correct).
I find that if I comment out this line of code, then the second invocation of callEndpoint doesn't do anything. I also notice that the logs of payTest1 say Contract Stopped:
Prelude Week04.Solution> payTest1
Slot 00000: TxnValidate 0636250aef275497b4f3807d661a299e34e53e5ad3bc1110e43d1f3420bc8fae
Slot 00000: SlotAdd Slot 1
Slot 00001: 00000000-0000-4000-8000-000000000000 {Contract instance for wallet 1}:
  Contract instance started
Slot 00001: 00000000-0000-4000-8000-000000000000 {Contract instance for wallet 1}:
  Receive endpoint call on 'pay' for Object (fromList [("contents",Array [Object (fromList [("getEndpointDescription",String "pay")]),Object (fromList [("unEndpointValue",Object (fromList [("ppLovelace",Number 1000000.0),("ppRecipient",Object (fromList [("getPubKeyHash",String "977efb35ab621d39dbeb7274ec7795a34708ff4d25a01a1df04c1f27")]))]))])]),("tag",String "ExposeEndpointResp")])
Slot 00001: W1: TxSubmit: 66b88e2673c2d50a5de7603fb28c71ac56963d88dda4c69dc529e2d26638b294
Slot 00001: 00000000-0000-4000-8000-000000000000 {Contract instance for wallet 1}:
  Contract instance stopped (no errors)
Slot 00001: TxnValidate 66b88e2673c2d50a5de7603fb28c71ac56963d88dda4c69dc529e2d26638b294
Slot 00001: SlotAdd Slot 2
Slot 00002: SlotAdd Slot 3
Slot 00003: SlotAdd Slot 4

I feel like I can intuit what Contract Stopped means but I'd like to understand on a more technical level what this means and under which conditions this happens.

The line of interest is:
pp <- endpoint @"pay"

Which is essentially blocking until someone hits the "pay" endpoint and then returning whatever PayParams the caller included (see PaySchema).
In the case where you include the recursive payContract function call, you are essentially saying, "after running payContract, wait for someone else to hit the "pay" endpoint."
In the case that the recursive payContract function call is removed, the Contract monad will exit, since it isn't blocked on any endpoints or anything.
Hope that helps :)


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

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

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

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

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


text:
How do I `:reload` in `ghci`
I copied the plutus-starter template: https://github.com/input-output-hk/plutus-starter and created a file BasicPlutusTx.hs (and added it under exposed-modules in the .cabal file).
Then I started copying over all the code from the introductory tutorial: https://plutus.readthedocs.io/en/latest/plutus/tutorials/plutus-tx.html
As I work with the tutorial, I like being able to make changes to the code and then see how that affects things in ghci. I usually use stack and hpack and run ghci with stack ghci. When I do this, I can just type :reload in ghci and it recompiles any changes I've made. But that doesn't seem to work here. Even if I run cabal build in a separate tab, it doesn't. It seems like I have to quit ghci, run cabal build, and then re-run ghci and re-import everything again. Is there a better way?

cabal repl loads the necessary context or something so that :reload works as expected

Other answer was deleted because it was not an answer.  It was a suggestion if "something to try".  It should have been a comment.  This is also not an acceptable answer according to: [answer]

As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

It answered the question. It probably would have been appropriate to suggest an improvement, rather than deleting it. This site will be most successful when people feel comfortable participating.


text:
Metadata '721' error on pool.pm
Hello and thank you beforehand for your time! I read a lot before posting and could not find a solution to this.
Pool.pm is complaining about the metadata '721' throwing an error: "Expecting an OBJECT with a field named 721"
I first thought I made the transaction using a different policy id than the metadata like in this post: NFT Image not Displaying in Pool.pm after using the 721 Metadata Standard
But as you can see from https://cardanoscan.io/transaction/c02c4db6bc9b2b9f3adcac930559368f7c2a4f00a2a53fc8661fae3b5ce844b2?tab=metadata the policy id matches the one on the metadata. The metadata I used is:
{
  "777": {
    "prc": "0.5",
    "addr": [
      "addr1q8pfw723tpkt8hl7q4wxx7h9seqt4cy22zrqk4axmhmcglwykt772jcyu6u",
      "9pv84nktsmpefeh7w9y6hdr87a65a93ysut2t0r"
    ]
  },

  "721": {
    "3e3a9f39933d04bd854527801f615d35d1cbe1b0344d482af20343ae": {
      "ShaveandTattooed": {
        "Name": "Shave and Tattooed",
        "Artist": "Marvin Lunas",
        "Image": "QmRTJUU8MUw5rUzES6XJd5RiA55K9seVAWU3tTkS8UoQYi",
        "mediaType": "image/png",
        "Description": "Description",
        "files": [
          {
            "mediaType": "image/png",
            "src": "QmUhgW6c8MKmzZKMNtr8Sfvb8UjqM3bgCh6X1upDCNAgHH",
            "Name": "Shave and Tattooed"
          }
        ],
        "ID": "1",
        "Minting Platform": "https://adamagic.io"
      }
    },
    "Version": "1.0"
  }
}

I have no idea what is causing this issue because I did use the same template before and it was all good.
It also has a problem while loading the thumbnail and at this point, I think the problem is on me.
Once again, thank you all for your time and effort!
Cheers

When I tried I did not get a 721 error from pool.pm. The assets show correctly with the correct policy ID eg https://pool.pm/asset1xpdk028mq57te9dkg62rvy79nv2mhl4zr78xgn and https://pool.pm/asset1qlmcztdqq3w8fu5jfxrmsel40yn0y652hhs9ap . The policy shows ok https://pool.pm/policy/3e3a9f39933d04bd854527801f615d35d1cbe1b0344d482af20343ae .
But the policy when searched shows 'no match found' using
https://pool.pm/tokens/3e3a9f39933d04bd854527801f615d35d1cbe1b0344d482af20343ae - I think pool.pm only shows 'recent' minted or transferred NFTs as there are so many.

It's showing up for me alright on pool.pm: https://pool.pm/asset1xpdk028mq57te9dkg62rvy79nv2mhl4zr78xgn
Might have been just a temporary issue while data was populating?
There's a testing tool here, that you can use to verify it works: https://pool.pm/test/metadata
Here it's populated with your metadata: Link
When you remove or rename the "721" object you'll see your exact error show up: "Expecting an OBJECT with a field named 721".
So if this is the place you're seeing it, there might be just a simple syntax error in the json you're putting in here.
Just some potential minor improvements to the metadata:
According to the spec at https://cips.cardano.org/cips/cip25/#specification you should use lowercase attribute names like "name" and "image" instead of "Name" or "Image".
And for the image hashes I'd add "ipfs://" as a prefix to make it more clear where to look for them, but it does usually work fine without.
Anyways looks like it all works fine on my side as is


text:
Issue with Lucid and sending tokens
Any ideas of why this isn't working? I obviously removed the Blockfrost ID and address, and I have enough tokens to send. For some reason it keeps saying Inputs Exhausted. Any help appreciated.
import { Blockfrost, Lucid } from "/mod.js";

const lucid = await Lucid.new(
  new Blockfrost("https://cardano-mainnet.blockfrost.io/api/v0", "mainnet...")
);

// Assumes you are in a browser environment
const api = await window.cardano.nami.enable();
lucid.selectWallet(api);

const policyId = "2b28c81dbba6d67e4b5a997c6be1212cba9d60d33f82444ab8b1f218";

const tx = await lucid.newTx()
  .payToAddress("addr1...", { [policyId]: 100n })
  .complete();

const signedTx = await tx.sign().complete();

const txHash = await signedTx.submit();

console.log(txHash);

A token has two components, it's name & corresponding policy-id. Thus, instead of .payToAddress("addr1...", { [policyId]: 100n }) you need to do .payToAddress("addr1...", { [token]: 100n }) where token is defined as concatenation of policy-id & name, like const token = policyId + tokenName.

I'm sorry, I am not following.
Can you write out the full script so I can try and understand what you are trying to correct?

Let's say that the name of the token you wish to send is "BTC" (const tokenName = "BTC"). So  as mentioned in this answer, you need to update payToAddress like payToAddress("addr1...", { [policyId + fromText(tokenName)]: 100n }). You can import "fromText" from "/mod.js" itself.


text:
How to properly start a new Plutus project, from scratch
I'm from ETH's ecosystem and recently just decided to get into Cardano development, specifically Plutus dev work thanks to Demeter.Run, and after going through the Plutus starters on there, I noticed there weren't any guides on how to start a fresh project from scratch. I did a speedrun through the latest iteration of the Plutus Pioneer course and found out that most of the work was either done in the Playground, the Repl, or built from the top of an existing project(which still doesn't add up to me).
Tried moving some sample .hs code from Plutus-apps and Alonzo-testnet repos hoping to compile and submit them for my own experience and only ended up fighting with GHC and Cabal errors because the sample code used other dependencies and structures different from the secondhand project I was guided to build on top of.
I don't want to start a project by piggybacking on some already existing files and .cabal and .project configs with specs I don't know/understand.
If I was starting a NodeJs project I'd begin with npm init then go from there
My question is, how can I start a new Plutus project from scratch such that I know

how to setup my .cabal file dependencies
how to setup what's needed for the .project file
where to input my fresh code (or borrowed code from Plutus-apps samples to test) because there's the "main.hs" in the app folder which I learned from Haskell but Plutus samples put their .hs code files in the "src" folder, the "main.hs" in the app folder contains something completely different.
how to compile my .hs to .plutus

Everything that comes after these 4 steps i.e. submitting that new .plutus file to the chain (serialised) and building Tx's I know how to do.
I am using Demeter.Run and working from the Terminal and Cardano-CLI from the workspaces, I am under the impression every dependency from IOHK/IOG is setup. I don't know nix and the plutus starter samples didn't need that so hope to progress that way.
I have very minimal Haskell but learning the basics hasn't been tough but I'm good with front-end Javascript and some Solidity.
Please be as detailed/technical as you like, thank you.
Note: I went through the previous questions posed in the links below but still did not get it.
Starting a new Plutus Project
How to Start a New Project

This is a great question. It would be great if there is a guide that show every step from zero to a working dapp on testnet. Plutus Pioneer Program doesn't provide the complete picture. Plutus Playground doesn't compile most of the time. I previously thought it's just me.

A well formatted question deserves a well formatted answer! I will go into some depths, but also keep some things at a “magical” level. This is a long read so take your time!
Before we start, it is good to note that most of the Cardano stack is written in Haskell, and thus, managing a Plutus project is just managing a Haskell project. There are multiple ways of doing this, just a plain Cabal project or one of the many Nix ways of building (cabal2nix, Haskell.nix and many others). Now there are good reason to use these Nixs ways (most notably reproducibility and caching), but in this answer I will focus on a more understandable way of just using GHC + cabal on Ubuntu 22.04 (not the minimal install).
A disclaimer, building everything yourself requires lots of ram (you can also re-run the cabal run command if you run out of memory mid-process). The good thing, however, once build you have these Haskell artifact locally prebuilt in your ~/.cabal/ folder.
The dependencies
Before we can even build a general all-purpose Haskell/plutus project, we need some basic building tools necessary to even start compiling! These mainly consist of the following tools,

OS dependent dependencies
GHC and Cabal
A special version of libsodium
A special version of libsecp256k1

OS dependent dependencies
To build everything, you at least need these dependencies
sudo apt-get update -y && sudo apt-get upgrade -y
sudo apt-get install automake build-essential pkg-config libffi-dev libgmp-dev libssl-dev libtinfo-dev libsystemd-dev zlib1g-dev make g++ tmux git jq wget libncursesw5 curl libtool postgresql libpq-dev autoconf -y

Note that translating these OS dependent dependencies to other operating systems is hard and out of the scope of this post (this is why you might want nix). They may also change in the future as the project might add new dependencies.
GHC and Cabal
It is recommended by IOG to use GHC version 8.10.7 and Cabal version 3.6.2.0. These can be installed via GHCUP via,
curl --proto '=https' --tlsv1.2 -sSf https://get-ghcup.haskell.org | sh

You can press enter for all question the installer asks. Then reload your terminal (to make ghcup appear in your path) and,
ghcup install ghc 8.10.7
ghcup set ghc 8.10.7
ghcup install cabal 3.6.2.0
ghcup set cabal 3.6.2.0

Reload your terminal again to make these appear in your path and set
cabal configure --with-compiler=ghc-8.10.7

A special version of libsodium
Libsodium is a tool chain (written for performance) for cryptographic derivatives, for example you can create signatures and hashes with it. We require a particular version of it that adds VRF cryptography to it (used for the Cardano consensus mechanism). Installing this can be done via,
git clone https://github.com/input-output-hk/libsodium
cd libsodium
git checkout 66f017f1
./autogen.sh
./configure
make
sudo make install

In addition to this add the following to your ~/.bashrc and reload your terminal again to add it to your path
export LD_LIBRARY_PATH="/usr/local/lib:$LD_LIBRARY_PATH"
export PKG_CONFIG_PATH="/usr/local/lib/pkgconfig:$PKG_CONFIG_PATH"

A special version of libsecp256k1
Since the Vasil hard fork Cardano has the secp256K1 signature scheme available in plutus. This allows for the validation of Bitcoin signatures and will make it easier to build bridges. Bitcoin is not the only blockchain that use this signature scheme, many others do. So to install this library (again a particular audited version) you use,
git clone https://github.com/bitcoin-core/secp256k1
cd secp256k1
git checkout ac83be33
./autogen.sh
./configure --enable-module-schnorrsig --enable-experimental
make
make check
sudo make install

A preconfigure project
We are ready to build a Plutus project! Before I tell how you can set up such a project, I want to share an already set up example. This so that you can test that you correctly installed the dependencies above. To run this example you use
git clone https://github.com/perturbing/example-project-basic.git
cd example-project-basic
cabal update
cabal run

I would like to reiterate, if you do not have sufficient ram available, for example because you run this example in a VM, you can cabal run again if your memory overflows. This example ran for me in a vm with 10gb ram.
Now how is this project setup?
This project and its structure is not constructed arbitrarily. It is namely derived from the latest release of the plutus-apps repository. This repository and its management of dependencies is chosen because it imports and exposes almost all important Haskell packages written for Cardano.
Now, how to concretely set up and copy the essential bits of this repo? It consists of the following steps.
To start we execute
mkdir my-plutus-project
cd my-plutus-project
cabal init
touch cabal.project

You could also use the flag --interactive for a more detailed set up with cabal init.
Next, we copy the cabal.project file of plutus-apps from its latest release (do not pick the main branch, consider this is unstable). Currently, the latest version of this file is this. Next, we need to adjust some pieces of this file to make it work for us.
The first thing to change, this cabal.project file does not import the plutus-apps repo (since it was part of the original one). So, we need to add that by changing the code that declared the to build packages of the plutus-apps repo. It also does not declare our new build artifacts of our cabal project, we have to change the exposed packages it has to build. Both can be achieved by changing,
packages: cardano-streaming
          doc
          freer-extras
          marconi
          marconi-mamba
          playground-common
          pab-blockfrost
          plutus-chain-index
          plutus-chain-index-core
          plutus-contract
          plutus-contract-certification
          plutus-example
          plutus-ledger
          plutus-ledger-constraints
          plutus-pab
          plutus-pab-executables
          plutus-script-utils
          plutus-tx-constraints
          plutus-use-cases
          rewindable-index

to
packages: ./

source-repository-package
    type: git
    location: https://github.com/input-output-hk/plutus-apps
    tag: the_latest_release_tag_used_here_CHANGE_ME!!!
    subdir:
          cardano-streaming
          doc
          freer-extras
          marconi
          marconi-mamba
          playground-common
          pab-blockfrost
          plutus-chain-index
          plutus-chain-index-core
          plutus-contract
          plutus-contract-certification
          plutus-example
          plutus-ledger
          plutus-ledger-constraints
          plutus-pab
          plutus-pab-executables
          plutus-script-utils
          plutus-tx-constraints
          plutus-use-cases
          rewindable-index

Next up, we can add to our executables and/or libraries on which modules they depend. For example, we might add to our my-plutus-project.cabal file that the executable depends on
    build-depends:    base ^>=4.14.3.0
                    , aeson
                    , bytestring
                    , containers
                    , cardano-api
                    , data-default
                    , plutus-ledger
                    , plutus-ledger-api
                    , plutus-ledger-constraints
                    , plutus-script-utils
                    , plutus-tx-plugin
                    , plutus-tx
                    , text
                    , serialise

And lastly, we can write our app/Main.hs file to execute some functions for us. A simple cabal update and a cabal run will execute your Main.hs executable.
Some last words
This is a long answer, and in no way is complete. I advise anyone who is eager to learn more about Haskell to take the Haskell course from IOG (it also covers cabal!). I hope this gets you started!

Since this question was posted Plutus-alternatives have been developed by the community that allow doing DApp development in JavaScript only. One such library is https://github.com/hyperion-bt/Helios
https://www.hyperion-bt.org/Helios-Book/api/picoswap/index.html is a step-by-step guide on how to implement a simple marketplace. The example code can be found here, and a demo is hosted here

Helios seems very interesting, although my confidence in the project decline the second I saw they chose to build Helios in JavaScript.

There isn't really an alternative for javascript if you want to build pure client-side DApps

The fact that the Helios compiler uses javascript to compile to plutus untyped core is a huge advantage and allows for the dynamic compiling to plutus core on any architecture that supports javascript  (browser, mobile devices, etc).   The helios language itself is a functional programming language, so you get all the benefits of a strongly typed functional programming language for writing your smart contracts, but you can compile it almost anywhere.

doesn't answer the question

People who are struggling with Plutus should know there are easier alternatives

You can start with cloning https://github.com/input-output-hk/plutus-starter
and follow the readme in that repo


text:
How to hide API keys when using Lucid-Cardano
Lucid-Cardano requires me to expose my api key on my client side of my app. How can I go around hiding this. I have tried to call my express backend to make a blockfrost request so that I can keep my api key on the backend. It works for connecting to the wallets but it doesn't work for signing transactions. How can I go around this. I am using express backend and react front end. How can I go about this?
//This is where I try to sign the transaction on my client side

import { Lucid, Blockfrost } from "https://unpkg.com/lucid-cardano@0.7.7/web/mod.js"
import axios from 'axios'

async function connect(){
  const data = await axios.get('http://localhost:4000/blockfrost').then((res) => {
  }).catch((err) => {
    console.log(err)
  })

  const lucid = await Lucid.new(data,
    "Testnet",
   );

    const api = await window.cardano.nami.enable();
    lucid.selectWallet(api);

    const tx = await lucid.newTx()
    .payToAddress("addr...", { lovelace: 5000000n })
    .complete();

    const signedTx = await tx.sign().complete();

    const txHash = await signedTx.submit();

    console.log(txHash);

}

//This is where i connect to blockfrost

const axios = require('axios')
require('dotenv').config()

axios.defaults.headers.common = {
    "project_id": process.env.BLOCKFROST_KEY,
  };

async function connect(){
    const data = await axios.get('https://cardano-testnet.blockfrost.io/api/v0')
    return data.data
}

module.exports = {connect}

export default connect

//This is the error I get
mod.js:2 Uncaught (in promise) Error: expected instance of u_
    at c (mod.js:2:535)
    at j_.new (mod.js:2:157455)
    at new cn (mod.js:4:35867)
    at ln.newTx (mod.js:4:52734)
    at connect (makeTransaction.js:20:1)

In the README.md file of lucid, their is a blockfrost proxy example, illustrating how you could implement a proxy api call.


text:
Call Martify Smart contract by cardano-cli
I call the martify smart contract by cardano-cli but I've seen the error Command failed: transaction build  Error: The following scripts have execution failures:
the script for transaction input 1 (in the order of the TxIds) failed with:
The redeemer pointer: RdmrPtr Spend 1 points to a Plutus script that does not exist.
The pointers that can be resolved are:
fromList [(RdmrPtr Spend 1,(Spending (TxIn (TxId {_unTxId = SafeHash "c502c6f0929e9eb7562097592a71d9e4aaae01033c7c5cb685c2103c9fee070c"}) (TxIx 1)),Nothing,ScriptHash "74d2a2a31173aad514c66551190f4ca4d6eedcdd71776a04ba263de5"))]

The command of building the transaction:
cardano-cli transaction build \
    --testnet-magic 1 \
    --tx-in c1ca2d6e65360e2acc78485ea93803e6119af1864872ff8cbdd6fcdf2044d7e5#0 \
    --tx-in-collateral c1ca2d6e65360e2acc78485ea93803e6119af1864872ff8cbdd6fcdf2044d7e5#0 \
    --tx-in c502c6f0929e9eb7562097592a71d9e4aaae01033c7c5cb685c2103c9fee070c#1 \
    --tx-in-script-file marketplace.plutus \
    --tx-in-datum-file datum.json \
    --tx-in-redeemer-file buy.json \
    --required-signer ./../../common/payment3.skey \
    --tx-out "$(cat ./../../common/payment3.addr) + 9982422778 + 1 d8375cb8ece93f752c57981c7978a6b3f9e06cee44c464dd3b7b7d2b.53706f7265734e46545f33" \
    --tx-out "$(cat script.addr) + 2000000" \
    --tx-out "$(cat ./../../common/payment4.addr) + 6000000" \
    --change-address $(cat ./../../common/payment3.addr) \
    --protocol-params-file testnet-protocol-parameters.json \
    --out-file buy.draft

Which: the payment3.addr is the buyer, the payment4.addr is the seller, and script.addr is the marketplace.

Two questions:

What's the datum-hash of datum.json ?
(output of cardano-cli transaction hash-script-data --script-data-file datum.json )

I assume this is the address on which your contract is: addr_test1wp6d9g4rz9e644g5cej4zxg0fjjddmkum4chw6syhgnrmegk8l8yj
(correct me if wrong)

The PT5 error exhibit the validator func return the error code in Onchain.hs file. So I put wrong pkh code in datum. By set correct value on datum, and its work.
Here is the code I used for making transaction via cardano-cli:
# Hash the datum

cardano-cli transaction hash-script-data --script-data-file datum.json >> dhash

# PUT ON SALE

cardano-cli transaction build \
    --alonzo-era \
    --testnet-magic 1 \
    --tx-in 8b076a7b96a24af1aec65213a45636b1e45c6acfe62e368f29e6e5119e368091#1 \
    --tx-out "$(cat script.addr) + 1800000 lovelace + 1 33700cf3c3d4aa6c84d9fd8a506c6c5482e4249abe78e37829913caa.53706f7265734e46545f33" \
    --tx-out-datum-hash $(cat dhash) \
    --change-address addr_test1vqquurd5cglaqfnnusnsfy3w0u6r20hpa4hf9x75evnmhxgwcrdas \
    --protocol-params-file testnet-protocol-parameters.json \
    --out-file tx.02

cardano-cli transaction sign \
    --tx-body-file tx.02 \
    --signing-key-file ./../../common/payment4.skey \
    --testnet-magic 1 \
    --out-file tx-2.02

cardano-cli transaction submit --tx-file tx-2.02 --testnet-magic 1

# BUY NFT

cardano-cli transaction build \
    --babbage-era \
    --testnet-magic 1 \
    --tx-in c1ca2d6e65360e2acc78485ea93803e6119af1864872ff8cbdd6fcdf2044d7e5#0 \
    --tx-in-collateral c1ca2d6e65360e2acc78485ea93803e6119af1864872ff8cbdd6fcdf2044d7e5#0 \
    --tx-in f2134f93278707a37a1ef03abac76e7fc38dd9796c1143f25953448efbd3fdca#1 \
    --tx-in-script-file marketplace.plutus \
    --tx-in-datum-file datum.json \
    --tx-in-redeemer-file buy.json \
    --tx-out "$(cat ./../../common/payment3.addr) + 9982422778 + 1 33700cf3c3d4aa6c84d9fd8a506c6c5482e4249abe78e37829913caa.53706f7265734e46545f33" \
    --tx-out "$(cat ./../../common/payment4.addr) + 6000000" \
    --required-signer ./../../common/payment3.skey \
    --change-address $(cat ./../../common/payment3.addr) \
    --protocol-params-file testnet-protocol-parameters.json \
    --out-file tx.04

cardano-cli transaction sign \
    --tx-body-file tx.04 \
    --signing-key-file ./../../common/payment3.skey \
    --testnet-magic 1 \
    --out-file tx-2.04

cardano-cli transaction submit --tx-file tx-2.04 --testnet-magic 1

Link to check on preprod cardanoscan: https://preprod.cardanoscan.io/address/6001ce0db4c23fd02673e42704922e7f34353ee1ed6e929bd4cb27bb99


text:
Error occurs in simple request to blockfrost.io for multiple wallets
This is a screenshot of console log for my problem
    export const deriveStakeAddress = async ( rewardAddress: string ):
       Promise<string> => {

           const endPoint = `addresses/${rewardAddress}`;
           const request: string = 'https://cardano-mainnet.blockfrost.io/api/v0/' + endPoint
           console.log("Request:", request);
           const response = await fetch(request, {
             //@ts-ignore
             headers: {
                "Content-Type": "application/json",
                 project_id: process.env.REACT_APP_BLOCKFROST_KEY
             },
             method: "GET",
          });
          const result = await response.json();
          console.log("Stake address: ", result);
          return result.stake_address;
       };

    export const findAssets = async (networkId: number, stakeAddress: string) =>
         {

          const endPoint = `accounts/${stakeAddress}/addresses/assets`;
          const request: string = 'https://cardano-mainnet.blockfrost.io/api/v0/' + endPoint;
          console.log("Request:", request);
          const response = await fetch(request, {
             //@ts-ignore
             headers: {
                "Content-Type": "application/json",
                 project_id: process.env.REACT_APP_BLOCKFROST_KEY
             },
             method: "GET",
          });
          const result = await response.json();
          console.log("Assets: ", result);
          return result;
    };

And then I called above functions as following.
const walletAddress: string = 'addr1qxzpuc....6vexzc';
const stakeAddress: string = await deriveStakeAddress( walletAddress );
const assets = await findAssets( stakeAddress );

But I faced errors for some wallets such as Yoroi, Eternl.
On the other hand, there was no errors for Nami wallet. (here)

The first error happens because there are no transactions for the address you try to query on the blockchain. If the address was never used, this endpoint returns a 404 error.
The second error seems to happen because you pass in 'undefined' instead of an actual stake key when building the URL.


text:
Validator always accepts and Mints (but it shouldn't)
Hey I have this simple stupid validator:
validator {
  fn nft(datum: Datum, _redeemer: Void, context: ScriptContext) {
    let ScriptContext { transaction, purpose } = context
    when purpose is {
      Mint(policy_id) -> False
      _ -> False
    }
  }
}

Now when performing a call to this validator to Mint it still returns True for the transaction and the native token is minted. I'm confused, how can this be?

That is because the interface of the source you have is for a spending validator, and NOT for a minting policy.
Let me explain.
for the chain there is not difference between spending validators and minting policies, it is all just UPLC.
on top of that, the node considers any script that doesn't fail (aka. never evaluates an error) to be correct.
so when you run a script you apply a bunch of data and then you only check if it throws an error or not.
now, the key difference is that a spending validator expects 3 pieces of data ( datum, redeemer, context );
all the others (minting policies, staking validators, etc) expect only 2 pieces of data ( redeemer and context )
when you use your source ( that takes 3 inputs ) as a minting policy ( which expects 2 inputs ) the node only passes 2 of the 3 inputs.
now applying those two inputs is equivalent to a partial function application.
so the result of the application is a new function, and it is a totally valid evaluation because no error is evaluated!
basically, when applying only two inputs (as in this case) the evaluation always succeeds.

NOTE: behind the scenes aiken (and also plu-ts and many other languages) are wrapping your contract that returns a boolean in a simple "if then else" that evaluates an error if the condition is false!

Been trying so many different thinks... Also had with a redeemer datum and context only but also got an error. Seems like I must have forgotten to compile or something. It works now at least thank you


text:
How can I convert Key Hash to bech32 in Cardano serialization lib?
I generate my Key Hash Using the Following Function
const getAddressKeyHash = (address) => {
  return toHex(
    Cardano.Instance.BaseAddress.from_address(
      Cardano.Instance.Address.from_bech32(address)
    )
      .payment_cred()
      .to_keyhash()
      .to_bytes()
  );
};

Now i need to revert this back to Bech32. Can someone help?

Hashing is a one way function; the purpose of it is to verify the authenticity of data, not to encrypt data.
If you hash a piece of data, it should be impossible to revert the hash back to it's original form; this is a key operating principle of any hash function.
Generally, when a key-hash is used there should be a point in the process where an associated public/private key is supplied, and is used in combination with the key-hash to perform some sort of true/false evaluation.


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

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

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

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

Is something like this available in golang?


text:
Building nodes on computers in a local network
How may I add the public IP address of a relay node to a block producer?
I have set both machines at home so they share the same public IP address if I am not wrong.

The relay node needs to know the IP of the block producer. If they are in the same network, you can use the local IP for this. Only the relay node needs to be accessible from outside of your local network (using your public IP).
When running the nodes at home you also need to make sure that you have a static public IP address or use some sort of DynDNS service. However, DynDNS might cause your nodes to be temporary unavailable which could lead to missing blocks.


text:
How eUTXO is more scalable than the account model?
There is this beautiful eUTXO handbook which state scalability as one of the main advantage of the eUTXO accounting model.
How and why is that essentially?

Besides what @Eddex stated, there is a more fundamental reason why an UTxO model scales better than an account model base blockchain.
TLDR: A UTxO model is more concurrent due to the atomic nature of unspent outputs.
In a UTxO model, state (that which describes a system) is localized in the form of an unspent output. Propagation of such a state is the consumption of it. Here, the collective/global state of the chain is described by all the outputs together. In the account model, state is always global. There is no subdivision of smaller units like UTxO's.
Why are smaller units important for scalability? Given that each block a set of transactions mutate the state, we could have that smaller sections of the state and their propagation do not intersect. Since these transactions do not intersect, you know for sure that they do not influence each other. This means that the validation of such a collection of non-intersecting transactions can be validated separately, or more specific, concurrently. This allows for protocols like Hydra more naturally, this is a protocol for off chain handling of an isolated set of outputs between parties. Since these are isolated, multiple Hydra heads can concurrently propagate the set of outputs.
Now of course an account model can also create state channels, but the problem there is that they have global state! This means that for an account model, we first have to decide how to cut up the global state onchain to concurrently validate its propagation (how do you decide such a thing? It's not a trivial task if it's an interconnected web of codependent state).
Now with all good comes some bad, by starting with local state (the utxo model) Cardano gains scalability, but has trouble creating global state. We saw that with the testnet launch of the initial Minswap dex. It just means that the protocol designs on Cardano are harder when global state is involved.
By starting with global state, you gain easy and straightforward coding of protocols, but lack scalability. This is why Ethereum is so focused on sharding (the process of cutting up their global state into smaller pieces) for their scaling plan, though again, this is no trivial task.

The scalability of the eUTxO model is simply the ability to include multiple transactions in one transaction.
For example: A company wants to send salaries to all its employees. Instead of creating 1 transaction for each employee, they can craft 1 transaction that contains 1 or many input UTxOs and many output UTxOs that are sent to the wallets of the employees.
These transactions can also contain smart contracts in addition to simple transactions and are only limited by the maximum size of one transaction.
A beautiful visualization of this can be found here: https://eutxo.org/


text:
How to get transaction info of a public key hash in a plutus smart contract?
Given a PubKeyHash (pkh) how can I get the history of that pkh's transactions from within a plutus smart contract?

Plutus only validates a pending transaction given a datum, redeemer and script context, which includes tx inputs. The only way you could potentially provide that kind of information is through the datum or maybe reference inputs.

Turns out plutus does not support this yet (if your reading this in the future it might be out of date -> please check the timestamp).


text:
Signs for the trustworthiness of the SundaeSwap project?
I would like to know, what are known signs about the trustworthiness of the project SudaeSwap?
What could be technically achievable black swan scenarios?
Is it a project that is connected with Cardano?

This question seems to be opinion based, which may cause it to be closed. For instance, in my opinion Sundaeswap is a trustworthy project but not everyone shares this opinion. I would recommend changing your question.

It's a bit fishy the whole 'come stake at our pool with 100% fees and then we'll give you tokens when we launch', what's to stop them from disappearing and not releasing anything while keeping all the ADA rewards minted all that time?

Opinion based questions are better asked in Reddit's Cardano subreddit

As much as I'm voting to close this question as it is opinion based, I'm going to provide my insight as it can save people money.
For me, they are not trustworthy because:

The initial team and most of the team is anonymous
They have no track record of previous projects
They have a plan to take millions of dollars from the community but they do not have a value-offering by having at least a whitepaper. Several dates promising the whitepaper has been posted but later deleted by the team
They are banning people raising concerns from their twitter and discord, censoring discussion
They have no skills to even run their own pool and are trying to outsource it, which is a basic technical skill when you try to build on Cardano

Several highly trusted community members have already warned about the red flags, for example Sebastien.

Charles Hoskinson has posted on Twitter that he has a meeting with SundaeSwap's team sometime soon and will advise on his feedback about the project. It is not clear when the meeting will take place but my best guess is that it will be within the next 30 days.


text:
Verify that Token is NFT
I was wondering how it is possible to actually validate if a certain Token is an NFT without having to inspect the code of the script which mints that Token? Only by checking if the current quantity is 1 will certainly not ensure that it won't be possible to mint more of that Token.

You can check the token policy for that. For most NFT projects you can look it up on https://pool.pm
A token policy can look like this:
{
  "scripts": [
    {
      "keyHash": "66833acfcf26d87e56bc829aa7bcef13295d4eee4d8b442175bd67a9",
      "type": "sig"
    },
    {
      "slot": 31882046,
      "type": "before"
    }
  ],
  "type": "all"
}

You can see the "slot": 31882046 and "type": "before" values which means tokens with this policy can only be minted before slot 31882046. To be sure that your NFT is unique, you can check that the quantity is 1 and the current slot of the blockchain is later than the one mentioned in the policy.
This policy is from the following NFT: https://pool.pm/1131301ad4b3cb7deaddbc8f03f77189082a5738c0167e1772233097.CardanoBits1947

How do you check the quantity?

You can see the quantity on https://pool.pm on the asset or on https://cardanoscan.io/ when searching for the policy id. These are just 2 of many options.

How to check quantity using CLI? :)

Hi @sloik, I'd recommend you create a new question for this.

@eddex https://cardano.stackexchange.com/questions/2348/how-to-check-using-cli-that-toke-is-a-nft done :)


text:
When are the snapshots for the active stake in an epoch taken?
A stake pool always has an "active stake" and a "live stake". "Active stake" refers to the amount of ADA that is used for rewards calculation in the current epoch. "Live stake" is all ADA that is delegated to the pool, also counting ADA that was delegated/undelegated after the "active stake" snapshot for the current epoch.
At which point is the snapshot for the "active stake" taken? Is it right when the new epoch starts? And will this happen at the exact same moment for all stake pools?

I suggest you break this into two separate questions:  "When are staking snapshots performed?" and "How are staking snapshots performed?"

@gRebel I removed the "how" part from the question.

Staking snapshots are taken at the beginning of each epoch and a stakepool's active stake is whatever was delegated to it at the beginning of the prior epoch or during the epoch before that.
Any new or changed stakepool delegations take effect at the beginning of the next (1st) epoch after they are made (they become part of a stakepool's live stake).
In the (2nd) epoch after that the delegation is used to determine the stakepool's probability of rewards and is part of the stakepool's active stake.
In the next (3rd) epoch since delegation rewards are calculated based on the number of times the pool became a slot leader.
In the last (4th) epoch rewards are distributed to the delegator.
In summary

Delegation changed
Snapshot taken
Slot leaders chosen based on delegation
Rewards calculated
Rewards distributed

"Cardano Staking: Practical Information" provides a more detailed explanation

Great article you linked, thanks!

That linked article[1] is really clear!
[1] https://cardanians-io.medium.com/cardano-staking-practical-information-3c86cbc73bd4