text:
How to specify the new output datum value (not hash) using the CLI
I have written a script that basically keeps a counter and every time it is spent increases said counter, the way it guarantees that the counter was increased is by checking the current datum of the output and making sure the new datum is current datum + 1 (The script has some additional preconditions which are not important right now):
{-|
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

-- 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

-- | This Datum represents the state of the counter.
data CounterDatum = CounterDatum {
        counter :: !Integer     -- ^ The current counter value.
    }
    deriving Show

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 = CounterDatum
    type instance RedeemerType Counter = ()

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

-- | Maybe gets the datum from the transatcion output.
{-# INLINABLE counterDatum #-}
counterDatum :: TxOut -> (DatumHash -> Maybe Datum) -> Maybe CounterDatum
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 -> CounterDatum -> () -> ScriptContext -> Bool
mkCounterValidator parameters oldDatum _ ctx =
    let oldCounterValue        = counter oldDatum
        isRightNexCounterValue = (newDatumValue == (oldCounterValue + 1))
        isIdentityLocked       = isIdentityNftRelocked parameters valueLockedByScript
    in traceIfFalse "Wrong counter value"           isRightNexCounterValue &&
       traceIfFalse "Wrong balance"                 isIdentityLocked &&
       traceIfFalse "Missing signature"             isTransactionSignedByOwner
    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  -> counter 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 @CounterDatum @()

-- | 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 }

I already locked some funds in the script and I am trying to spent the eUTXO using the CLI and I am having a conceptual issue here, there is no way to specify the new output datum using the CLI, it seems I can only specify the datum hash of the new datum.
cardano-cli transaction build-raw --alonzo-era --fee 500000  --tx-in b2997baf426caa94762e4baeed051ac13bad7994f2f3a43f8c43299d2ba8f050#0 --tx-in b2997baf426caa94762e4baeed051ac13bad7994f2f3a43f8c43299d2ba8f050#1 --tx-in-script-file ./counter/out2.plutus --tx-in-execution-units "(491845099,1197950)" --tx-in-datum-value 0 --tx-in-redeemer-value 0 --tx-in-collateral b2997baf426caa94762e4baeed051ac13bad7994f2f3a43f8c43299d2ba8f050#0 --tx-out "addr_test1wqesjavxsh7g2q8lf92ptyt7rnrhh07ghnyjq65ra50uwwqsssy2q+2000000+1 a1c6cefca22b4527acdf17a1d44674b6d7cf17c3e7e35cbd1a57d8b5.Horrocube09997" --tx-out-datum-hash ee155ace9c40292074cb6aff8c9ccdd273c81648ff1149ef36bcea6ebb8a3e25 --protocol-params-file protocol.json --out-file tx-script2.build

Using the CLI to construct the transaction you need to:

Specify the actual datum value matching the datum hash in the current
eUTXO you want to spend. (--tx-in-datum-value)

Specify the new datum hash for the new eUTXO we are creating
(--tx-out-datum-hash)

However, the script needs both values in the validator as it verifies that the new datum value in the output is equal to the current datum value + 1 but it only has the current datum value and hash AND the new datum hash (not the value).
Using the plutus offchain code I can pass the new datum no problem:
-- | Tries to solve the puzzle at the given index.
solve ::  forall w s. HasBlockchainActions s => SolveParams -> Contract w s Text ()
solve solveParams = do
    let cube = CubeParameter {
        cubeId          = spCubeId solveParams,
        stateMachineNft = spStateMachineNft solveParams
    }
    pkh <- pubKeyHash <$> Contract.ownPubKey
    utxos <- utxoAt $ cubeAddress cube
    addressUtxos <- utxoAt $ pubKeyHashAddress pkh

    let constriants = Constraints.unspentOutputs utxos  <>
                      Constraints.unspentOutputs addressUtxos <>
                      Constraints.otherScript (Scripts.validatorScript (cubeInstance cube))  <>
                      Constraints.scriptInstanceLookups (cubeInstance cube) <>
                      Constraints.ownPubKeyHash pkh

    m <- findCubeOutput cube
    case m of
        Nothing -> logInfo @String "Cube output not found for solve parameters "
        Just (_, _, dat) -> do
            let datum = dat { currentPuzzleIndex = spPuzzleIndex solveParams + 1 }
                redeemmer = CubeRedeemer (spPuzzleIndex solveParams) (spAnswer solveParams)
                totalValue  = Prelude.foldMap (Tx.txOutValue . Tx.txOutTxOut) utxos
                orefs       = fst <$> Map.toList utxos
                payToSelf   = assetClassValue (cubeId cube) 1 -- We must pay to outselves the cube so we can prove ownership of the cube.
                payToScript = (buildValue cube datum (spPuzzleIndex solveParams) totalValue)
                tx = mconcat [Constraints.mustSpendScriptOutput oref (Redeemer (PlutusTx.toData redeemmer)) | oref <- orefs] <>
                              Constraints.mustPayToTheScript datum payToScript <>
                              Constraints.mustPayToPubKey pkh payToSelf
            ledgerTx <- submitTxConstraintsWith @Cube constriants tx
            void $ awaitTxConfirmed $ txId ledgerTx

In fact, using the Plutus code I only pass the new datum value to "submitTxConstraintsWith" which now that I think I also don't understand, where is the Plutus off chain code getting the current datum value from? since the output only store the datum hash? Anyways the Plutus API works. But I am trying to use the CLI to use the contract and I don't see a way to pass the actual datum value (not just the hash) to the script so the validator can run.

I already found the answer and will leave it here in case anyone ran into the same problem.
You need to update the node-cli version to the lastest version (currently)  1.31.0 and then you have the following options available:
 [--tx-out ADDRESS VALUE
              [ --tx-out-datum-hash HASH
              | --tx-out-datum-hash-file FILE
              | --tx-out-datum-hash-value JSON VALUE
              | --tx-out-datum-embed-file FILE
              | --tx-out-datum-embed-value JSON VALUE
              ]]

And now you can specify the value of the new datum instead of the hash:
i.e
transaction build --alonzo-era --testnet-magic 1097911063  --change-address $(cat counter/payment.addr) --tx-in-collateral dc5a8bff48a9db6436559945ceb7a3f311045596407021312c133b1db70d7419#0 --tx-in 7d65ca46aca44532d94da57ec6b7297efdda2e523626f90bbdc780f3767202f2#1 --tx-in-script-file ./counter/out2.plutus --tx-in-datum-value 0 --tx-in-redeemer-value [] --tx-out "addr_test1wpxzyxrdt06f08v5le8h6tgwww9ud7qh4p7w3q8mhndtedg9fdzg2+1000000" --tx-out-datum-embed-value 1 --protocol-params-file protocol.json --out-file tx-script2.build


text:
How to move Daedalus's blockchain data folder out of AppData?
I'm a newbie with Cardano. Anyone can tell me how to move the Daedalus blockchain data folder from AppData to another drive?
I want to keep my C-drive's space by moving DB to another drive.

First solution
After installing the wallet, look for the file called daedalus.bat inside Daedalus installation directory. Open it and change the following line:
-n --db-path ^

for anything like this:
-n "%APPDATA%\Daedalus\DB Wallet" ^

If you've already synced, move the ledger database to the new location.

Second solution
You can find the second solution here.

Sorry, I can't find the daedalus.bat file in my installation directory.

C:\Program Files\Daedalus\daedalus.bat

Yes, there's no file in my dir.

Updated my answer.

I'd use directory junction ( aka. Hard Link).
Stop Daedalus, open and elevated command prompt and type:
mklink /J C:\Users\YOURUSER\AppData\Roaming\Daedalus D:\Daedalus

YOURUSER = Your Windows User running Daedalus
D:\Daedalus = Your path where you will store the Daedalus folder
In this way you don't have to modify any config file in Daedalus.

source: Stack Exchange

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

sort: votes


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"

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


text:
What are some ways a SPO can attack the network and what mechanisms exist to discourage or mitigate such attacks?
What are some ways a SPO can attack the Cardano blockchain? E.g. in Bitcoin, a miner could intentionally exclude certain transactions to the extend that the miner's hash power allows. Is something like this possible in Cardano? What about other forms of attack? What discourages such attacks or mitigates the harm they can cause?

I am still researching if it is possible for a SPO to choose and exclude transactions when they are elected to create the block. I am pretty sure it isn't something you can just do 'out of the box,' I believe you would need to modify the client code of your block producer. With that said, if they could do that, it still wouldn't cause much damage. The reason why is because there is enough entropy built into the slot leader selection that the next block would pick up the excluded transaction. This is because it would be a new slot leader, thus only causing a ~20 second delay. This kind of attack is also discouraged because there is not incentive for just 1 pool operator to cherry pick (choose some, exclude others) transactions because the rewards are pooled and distributed at the end of the epoch. Meaning that if there were a lot of full-blocks, you could very slightly increase the overall rewards. However, after dividing it out to all the SPOs who created blocks, it likely wouldn't be worth your time. Now if multiple SPOs worked together on something like this, and we were constantly creating full blocks there could be incentive to choose the transactions that have larger fees (like ETH).

Decentralization is the mitigation against attacks in almost all of these systems, they all assume that a centralized player has not gained the power to control consensus.
An SPO could theoretically re-write their block producers software to do anything, like award themselves a million ADA.  But it doesnt have any effect because no other SPOs agree that should happen.
Chain forks are probably the next thing an SPO could try to do, if they could create a dummy chain they could double-spend ADA.  Ouroborous can withstand at least 6 blocks in any 22 blocks being created by attackers trying to fork the chain, and with 15 confirmations no users will be duped onto the wrong chain.  It would be very hard for any SPO to co-ordinate more than 6 in 22 blocks becaise of the random nature of slot leader selection, unless they had a very high amount of stake and could wait for the the right time.  Of course the problem there is that having a lot of stake on the system and damaging the system is stupid, because you are damaging your own value.
Forking is also dis-incentivized by the fact that all SPOs earn more if there are more successful blocks on the main chain.  As rewards are held to the epoch end and distributed to SPOs based on the number of blocks they created on the main chain, its an incentive for all SPOs to find and stay on the main chain.

The most feasible (and most well-established) method by which any kind of validator (be it a miner, SPO, etc) can game the system is through Miner Extractable Value (MEV), a.k.a front-running. It is an endemic (though non-catastrophic) problem for any public blockchain network that is maintained in a trust-less fashion.
In a nutshell, when a validator creates a new block, she temporarily gains a non-insignificant glimpse into the future of the blockchain before the rest of the network does. This is because there is a small amount of time elapsed between the validator making the block locally and that block being validated and incorporated into the rest of the network. Let's call this the MEV-window. If during this window the issuing validator is quick enough to act, they can gain an arbitrage opportunity over the rest of the network. This is especially true if the validator in question is responsible for more than just good 'ol block production on the CSL, but is also providing oracle data, babel fee liquidity, DEX scooping, and/or a variety of other distributed services.
For example, if I'm an SPO and an oracle provider, and I see that the block I'm about to publish contains a sudden surge of transactions towards a known exchange address(es), I may conclude that the price is about to go down, so I may then include some of my own buy orders in the same block. I can also adjust my oracle feeds to match where I expect the price to go before anyone else does; I'd be using my position as a block producer (in that moment) to front-run the market. This is just one of many ways MEV can be used to game the system.
As far as I am aware, there is no generalized solution to the problem of MEV, and I believe it is widely accepted as an issue that can only be minimized, but not completely eliminated. The good news is there may be ways to minimize this problem to the point of relative obscurity. Things like minimizing the MEV window, clever use of ZK-technology, or just building applications with a highly meticulous approach to the underlying game theory, just like IOG did with the development of Cardano.


text:
Is there a site (or one being developed) that contains a library of Plutus smart contracts?
Can someone direct me to a site where I can search for specific Plutus smart contracts? It would be useful both for inspiration, and also to reduce the amount of redundant work spent creating smart contracts across different teams. Thanks!

Im not sure anyone has gone out and created that yet, but here is a link to the use-cases repository put together by IOHK. These contracts are a pretty solid spot to take design ideas from.

Thanks for the resource. It's not as extensive as I was hoping, but still helpful.


text:
How to connect wallet with my dapps using yoroi dapp connector.?
I am trying to connect my users to my NFT Trading card game with yoroi. Can you provide me with an metamask equivalent for cardano

Currently the only wallet extension that supports Cardano is Nami, but once the PAB comes out Yoroi will have theirs out very quickly.


text:
Error: Reference to a name which is not a local, a builtin, or an external INLINABLE function
I am writing a minting policy that takes half the bytes of one of the eUTXOs being used during mint and encoded them as a base89 readable string then checks that the Asset being minted has as a postfix said string, I am doing this in an attempt to create true NFTs without having different policy ids for each NFT.
To do this I slice the BuiltinByteString with the hash of the eUTXO in half, and then convert it to an int to pass it to the following function:
{-# INLINABLE encodeBase #-}
encodeBase :: BuiltinByteString -> Integer -> BuiltinByteString
encodeBase charset value = encoded where
  base     = lengthOfByteString charset
  encoded  = expand (value `divMod` base) emptyByteString
  lookup n = indexByteString charset n
  expand (dividend, remainder) xs
    | (dividend >  0) = expand (dividend `divMod` base) result
    | (dividend == 0 && remainder >  0) = result
    | (dividend == 0 && remainder == 0) = xs
    where result = consByteString (lookup remainder) xs

charset is also a BuiltinByteString.
But when compiling I get the following error:
GHC Core to PLC plugin: E043:Error: Reference to a name which is not a local, a builtin, or an external INLINABLE function: Variable GHC.Integer.Type.orInteger

I don't understand, I have been using integers without issue so far in the contracts I have written, what causes this error in this case specifically?
This is the whole script:
{-|
Module      : Horrocubes.MintingScript.
Description : Mint policy for NFTs.
License     : Apache-2.0
Maintainer  : angel.castillob@horrocubes.io
Stability   : experimental

This policy creates an NFT and uses an UTXO to make the NFT truly unique.

This minting policy was taken from https://github.com/input-output-hk/lobster-challenge
and sightly modified to the the token name as an outside parameter.

-}

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

{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
 {-# LANGUAGE OverloadedStrings #-}

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

module Horrocubes.MintingScript
(
  mintScript,
  nftScriptShortBs
) where

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

import           Cardano.Api.Shelley      (PlutusScript (..), PlutusScriptV1)
import           Codec.Serialise
import qualified Data.ByteString.Lazy     as LB
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         hiding (Semigroup (..), unless)
import qualified Data.ByteString.Char8    as C
import           PlutusTx.Builtins
import Data.Bits (shift, (.|.))

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

{- HLINT ignore "Avoid lambda" -}

{-# INLINABLE utxoHash #-}
utxoHash:: TxOutRef -> BuiltinByteString
utxoHash utxo = getTxId $ txOutRefId utxo

{-# INLINABLE readInt #-}
readInt :: BuiltinByteString -> Integer
readInt bs =     (byte 0  `shift` 120)
             .|. (byte 1  `shift` 112)
             .|. (byte 2  `shift` 104)
             .|. (byte 3  `shift` 96)
             .|. (byte 4  `shift` 88)
             .|. (byte 5  `shift` 80)
             .|. (byte 6  `shift` 72)
             .|. (byte 7  `shift` 64)
             .|. (byte 8  `shift` 56)
             .|. (byte 9  `shift` 48)
             .|. (byte 10 `shift` 40)
             .|. (byte 11 `shift` 32)
             .|. (byte 12 `shift` 24)
             .|. (byte 13 `shift` 16)
             .|. (byte 14 `shift` 8)
             .|.  byte 15
        where byte n = indexByteString bs n

{-# INLINABLE encodeBase #-}
encodeBase :: BuiltinByteString -> Integer -> BuiltinByteString
encodeBase charset value = encoded where
  base     = lengthOfByteString charset
  encoded  = expand (value `divMod` base) emptyByteString
  lookup n = indexByteString charset n
  expand (dividend, rem) xs
    | (dividend >  0) = expand (dividend `divMod` base) result
    | (dividend == 0 && rem >  0) = result
    | (dividend == 0 && rem == 0) = xs
    where result = consByteString (lookup rem) xs

-- | Creates the minting script for the NFT.
{-# INLINABLE mkNFTPolicy #-}
mkNFTPolicy :: BuiltinByteString -> PubKeyHash -> BuiltinData -> ScriptContext -> Bool
mkNFTPolicy charset _ _ ctx = traceIfFalse "Invalid Posfix" checkMintedAmount
  where
    info :: TxInfo
    info = scriptContextTxInfo ctx

    expectedPosfix :: BuiltinByteString
    expectedPosfix = encodeBase charset $ readInt $ sliceByteString 16 16 $ utxoHash getUTxO

    actuallPosfix :: TokenName -> BuiltinByteString
    actuallPosfix tn = sliceByteString 10 20 $ unTokenName tn

    getUTxO :: TxOutRef
    getUTxO = txInInfoOutRef $ ((txInfoInputs info) !! 0)

    checkMintedAmount :: Bool
    checkMintedAmount = case flattenValue (txInfoMint info) of
        [(_, tn', amt)] -> (equalsByteString (actuallPosfix tn') expectedPosfix) && amt == 1
        _               -> False

-- | Compiles the policy.
nftPolicy :: BuiltinByteString -> PubKeyHash -> Scripts.MintingPolicy
nftPolicy charset pkh = mkMintingPolicyScript $
    $$(PlutusTx.compile [|| \charset' pkh' -> Scripts.wrapMintingPolicy $ mkNFTPolicy charset' pkh' ||])
    `PlutusTx.applyCode`
     PlutusTx.liftCode charset
    `PlutusTx.applyCode`
     PlutusTx.liftCode pkh

-- | Generates the plutus script.
nftPlutusScript :: BuiltinByteString -> PubKeyHash -> Script
nftPlutusScript charset pkh = unMintingPolicyScript $ nftPolicy charset pkh

-- | Generates the NFT validator.
nftValidator :: BuiltinByteString -> PubKeyHash  -> Validator
nftValidator charset pkh = Validator $  nftPlutusScript charset pkh

-- | Serializes the contract in CBOR format.
nftScriptAsCbor :: BuiltinByteString -> PubKeyHash -> LB.ByteString
nftScriptAsCbor charset pkh = serialise $ nftValidator charset pkh

-- | Serializes the contract in CBOR format.
nftScriptShortBs :: BuiltinByteString -> PubKeyHash -> SBS.ShortByteString
nftScriptShortBs charset pkh = SBS.toShort . LB.toStrict $ nftScriptAsCbor charset pkh

-- | Gets a serizlize plutus script from the given UTXO and token name.
mintScript :: BuiltinByteString -> PubKeyHash -> PlutusScript PlutusScriptV1
mintScript charset pkh = PlutusScriptSerialised . SBS.toShort . LB.toStrict $ nftScriptAsCbor charset pkh

It's because one of the used functions in your INLINABLE functions doesn't belong to Plutus. For example, if you do something like this inside your validator, you'll get a similar error:
numberList :: [Integer]
numberList = [1..5]

It's because .. is not recognized by Plutus.
So, make sure all functions used in your INLINABLE functions are imported from Plutus library.

I would guess that the use of Data.Bits-functions in your on-chain code is the problem.


text:
How to mint multiple NFT assets in the same transaction?
The developer guide doesn't cover this.
Here is an example of what I'm trying to do:
https://cardanoscan.io/transaction/e1c7bc707e56bf37b4325dc4b7fe524eafe8ca746e54746d60b321588ffebb6c?tab=tokenmint
I tried making the metadata look identical in structure but cardanoscan says my transaction only minted 1 coin.
I want my mint transaction to have multiple asset names.

The process is the same but you need to specify in your cardano-cli transaction build command, all your assets to mint. For example:
cardano-cli transaction build-raw \
  --fee 197797 \
  --tx-in 6af4fea10fe3fd7120ab7e3f5361ae15d898f4fa6ebddcf585a80865010722dd#0 \
  --tx-out $(cat key1/payment.addr)+15850022+"1 $(cat policy.id).nft1"+"1 $(cat policy.id).nft2" \
  --mint="1 $(cat policy.id).nft1"+"1 $(cat policy.id).nft2" \
  --minting-script-file policy.json \
  --metadata-json-file metadata.json \
  --invalid-hereafter=41797828 \
  --out-file transaction.raw

And of course, modify your metadata to have all your assets.
UPDATE
Consider that from cardano-cli v 1.31, your asset names should be  base16-encoded, this is only for the build-raw command.
Your metadata.json should look like this:
{
    "721": {
        "1573568cde0f3c340266e50f0d108795f5e4190de939081f15287a24": {
            "nft1": {
                "name": "nft#00001",
                "image": "ipfs://QmfVzQceRW7Awo1t82CrzdLeoLddQqz4SB3kNC2wiWyGAs",
                "mediaType": "image/gif",
                "description": "My TEST NFT 00001",
                "propety1": "Serie 1",
                "propety2": "Red"
            },
            "nft2": {
                "name": "nft#00002",
                "image": "ipfs://QmfVzQceRW7Awo1t82CrzdLeoLddQqz4SB3kNC2wiWyGEs",
                "mediaType": "image/gif",
                "description": "My TEST NFT 00002",
                "propety1": "Serie 1",
                "propety2": "Black"
            }
        }
    }
}

Can you include here an example of what metadata.json might look like for multiple nfts?

Done, check my updated answer.


text:
What Utility Do Third-Party Services Provide with Undisclosed Slot Lottery Information?
Small Sample of Concerns Belonging to Larger Family of Unknown Real or Figurative Concerns
I would like to send my predetermined Slot Leader reports to PoolTool, yet I only use the API key they provide for sending tip heights.
What happens when they know I won the slot lottery? At first I was very paranoid and could only imagine slot leader, even when plural for a single slot, is private information not for public disclosure. But aha, it's not! At least I am unable to find it on PoolTool after a reasonable search.
Worse though, it's not public and not private, so it's valuable information in the hands of a privileged few, or so I thought to myself. My reasoning being if I am an SPO with a relay or two, and the Whales and pre-AML/KYC bullies are around, it would be trivial to assault my nodes, and also interesting:

Can we force a Slot Leader to fail to forge with a given attack that is cheap enough to put me back in the lottery for that slot? DDoS cheap, for example.
Is this easier when colluding with other giants?
Could small SPOs be denied the ability to mint new blocks in the worst case scenario of mass-collusion scenarios where the at least one of the collaborators would have a better chance at being the slot leader than they did if they were to do nothing.

Effect on Operator Behavior
So I never reported, yet I still missed two blocks when I was slot leader anyway. Now that I've probably figured out the network issues causes this, I will report my slot, just because, why not?
But still, what utility is being served by conceding privileged information to a community member, which means many things from competitor to valued contributor, but still a private third-party.
Bounty Will Likely Not Be Rewarded Within Seven Days
I am asking for a canonical answer. @Anton, tried to derive one, but I see holes that I can comment on later.
Therefore, I will delegate to the answers I find interesting, thought-provoking, reasonable-yet-contradicting, and so on; just ones I personally found valuable. I encourage you to do the same.
Upvote and ADA-only Recipients
So far these are those delegators, with the first satisfying all of the listed qualities.

Ticker: SNOWY for Anton's Answer - OP comments,

"having the previous slot would be quite the computational challenge
alone, and it does take days or weeks for those pages to populate, but
they don't show a decision tree for a slot battle–maybe a deceptive
illustration of 3,100 pools POSTing (every second as required) its Tip Height API
endpoint, which does some processing on before responding to the POST. Like
wanting to know which node your running, if it's a release or dev
build, other things it must record before responding. It does not
report a Slot Battle diagram based on what delegators are
reporting to relays and other delegators. I don't even think it
asks if a delegator is saying it is the Slot Leader.
The API has nine endpoints, but Amazon masks their location, claiming
they are all in the US. But they appear to be AWS CloudFront "Web 3.0"
CDNs, and that a show of good faith if CloudFront was chosen for its
equal access to low-latencies ambitions:

> To deliver content to end users with lower latency, Amazon CloudFront
> uses a global network of 275+ Points of Presence (265+ Edge locations
> and 13 regional mid-tier caches) in 90+ cities across 47
> countries. Amazon CloudFront Edge locations are located in:

"Looks nice, but you can't know where they are. You can experiment,
but if you just want gains you don't experiment, you stake in the most
developed of Western Europe, hedging in the coasts of the US, because
it had had an inflation clock downtown from me since before I was
born, and the world likes it that way. AAA debt for sale for almost
all of me and that clock's life, ala CIA and USN, and so on."
"Meanwhile, the orphan graph reminds me of a PoolTool page, or the
other way around..."
[Middle Finger Emoji to almost every stake holder]
"Okay, I'll lay off pooltool, or why it doesn't report past slot
leader, leader arrays, empty slots, or pull from the verbose as the
need for a reconstructed Globe Theater."
What if you just need 51% of topology pathfinders to agree that your
AWS CloudFront WebAPI is gospel? You'd make a topologyUpdater script
that basically reinforced this Western exploit attacking the
single-second slot. Sites like PoolVet claiming if you don't
comply, go let the Best Practices Group promote gain over virtue.

"And on and on," he continued ranting.
"Where's the utility? What's this project really about?"

I didn't realize you could send your slot leader reports. I am doing the tip heights but not slot leader. Can you add a link where you found out how to do that as well as view that? I would think this would be something you wouldn't want public based off what you've stated above.

Yes, there's a talented group that builds tools for the community. Many actually. They range from sites (graph explorers, big data, etc), to various niches like Pool Operator tools. They are well rewarded for the hours on ongoing OSS work. As an example, one tool was communally improved into a pretty polished piece of SPO software, it can tell you your block slots, if any, in the current, previous and next epoch. This isn't magic, IOHK goes out of its way to use English with equations. But forgive me if I failed, I cannot find the discussion about private centralized Slot Leader databases.

I had to do a lot of digging but this is what I have came up with. Please correct me if any of this is incorrect and I'll update the answer.
What happens when they [PoolTool] know I won the slot lottery?
After going through the CNCLI documentation, it looks like the intention is to only ever send the Current and Previous slot leader. Furthermore, when I look at the json result for a LeaderLog, it returns the "slot", the "slotInEpoch" and an "at" which is a date time. Based off knowing this payload as well as the intended use, I am guessing they are using it to fill in the Orphans section of the site before rewards are calculated. Looking at a couple of examples, I am only seeing Orphans 3 to 4 Epochs back (so 297/298). I believe with these logs they could fill in more realtime.
Can we force a Slot Leader to fail to forge with a given attack that is cheap enough to put me back in the lottery for that slot? DDoS cheap, for example.
If you could keep the relays down long enough for another slot leader to propagate, then yes you could. If the pool is protecting against DDOS/DOS attacks, then this is probably unlikely to work.
Is this easier when colluding with other giants?
If you were a pool like Binance, with 42 saturated pools, then you could potentially cause issues for other SPOs by denying them in your topology files. This could potentially cause issues for their propagation. (Still a big if). The other would be a 51% attack if you got enough people to join you. This would be extremely unlikely to happen though.
Could small SPOs be denied the ability to mint new blocks in the worst case scenario of mass-collusion scenarios where the at least one of the collaborators would have a better chance at being the slot leader than they did if they were to do nothing.
Short answer yes but it would likely be a very small effect. The example would be the Binance one above. This also could be worse if the pool has no protection against DDOS type attacks.
What utility is being served by conceding privileged information to a community member, which means many things from competitor to valued contributor, but still a private third-party.
I believe the utility would be keeping a more up-to-date Orphaned block tab for PoolTool. In general, it would be statistical.
I hope this is helpful.

Please correct me if I'm wrong, but I think this is a non-issue if you don't send upcoming slots/the slot leader schedule, but use the Sendslots command instead:
CNCLI does not send the slot number and/or date and time of the blocks you are assigned to mint. Straight from the CNCLI Git:

Sendslots command
The sendslots command securely sends pooltool the number of slots you
have assigned for an epoch and validates the correctness of your past
epochs. You must have a synchronized cncli.db database and have
calculated leader logs for every pool in pooltool.json before calling
this command. It should be called within the first 10 minutes of the
epoch cutover.

Here is an example:

2020-12-01T03:34:33.883Z INFO  cncli::nodeclient::leaderlog > Sending:
{"apiKey":"blah-blah-blah","poolId":"00beef0a9be2f6d897ed24a613cf547bb20cd282a04edfc53d477114","epoch":232,"slotQty":25,"hash":"d15b6c8d4c81fe48cff0650c5b59ab20da9765374c58c933dacd058eb38bb670"}
2020-12-01T03:34:33.969Z INFO  cncli::nodeclient::leaderlog > Pooltool
Response:
{"statusCode":200,"headers":{"Content-Type":"application/json","Access-Control-Allow-Origin":"*"},"body":"{"success":true,"message":"We have updated your assigned slots for epoch 232 to be 25 with a hash of
d15b6c8d4c81fe48cff0650c5b59ab20da9765374c58c933dacd058eb38bb670.  You
must provide an array of slots that matches this hash to have your
performance counted."}"}

So as I understand, pooltool does not know which slots you are assigned to and they can't find out based on the info CNCLI sends to them.

Something that could be done is to ask stake pool operators to report just the number of blocks they have been awarded for the next epoch.  They could report this just prior to the start of the epoch.
If a pool operator chooses to report his number of slots awarded then he would be incentivised to report the correct number.
He must tell the truth because if he lied by reporting just one less than the actual number, he will be found out if/when his pool successfully produces all its blocks.  Maybe occasionally his pool will lose a block to a slot battle etc. but mostly it will produce all the blocks issued and then if he lied by saying less then everyone will know.  He will then lose trust with the community.
I don't think reporting slots issued like this would create a security concern because no one would know the actual timing of the slots issued except for the pool operator himself.  Even knowing the precise number of slots awarded doesn't reveal anything much since this amount can be approximated simply by looking at the total amount staked at his pool.
I did think about sending abridged slot leader reports like this but didn't look into where to send this information.  I certainly formed the opinion that there was no way that I was going to send the full slot leader reports containing the timing because, as you say, that would provide timing information to potential attackers.


text:
What is the best approach to implement Nami Wallet. Can some provide a boiler plate or any kind of documentation.?
What is the best approach to implement Nami Wallet. Can some provide a boiler plate or any kind of documentation.?

Here is an open-source starter project:
https://github.com/cheffNFT/namiwallettemplate

Berry-Pool's github page is the only info in the public domain.

There is a demo in the Plutus GitHub repository since a few days: https://github.com/input-output-hk/plutus-apps/tree/main/plutus-pab/demo/pab-nami
Basically, you have the following parts;

The PAB instance,
the webserver backend,
the webserver frontend.

I think, you should not expose the PAB through a public entry point. Instead have it running on local host. The PAB exposes post-, get-, and put-request that your webserver backend can use.
Your webserver backend should have a basic utility method to query the PAB consisting of 4 steps (all http request to the PAB using its standard http-endpoints):

Activate a contract instance (this returns an instance-id that you need in steps 2 to 4).
Post a request to the instance to execute your Plutus contracts.
Wait 2 seconds and query the status of the instance. This status contains the transaction that you need to pass to the Nami wallet later on in your JavaScript code.
Close the endpoint (or leave it open If you want to cache it).

You can use this utility function to construct your service functions (eg. buyTokens(amount, wallet_address))
In your frontend, you have JavaScript code that interacts with the Nami wallet. This code does the following steps:

Connects to the Nami wallet extension and fetches the wallet address.
Passes the wallet address (and needed arguments) to the service function of the webserver backend.
Receives the partial transaction from the webserver backend and passes it to Nami to balance, sign, and submit it.

The only current complication is that in the last step 3, the balancing of the partial transaction cannot be performed by Nami because it does not yet expose a corresponding function. This will certainly change soon. For the moment a workaround is needed. One is shown in the Plutus PAB demo.


text:
What is the use case of the mustSpendAtLeast constraint?
What I can figure out:
mustSpendAtLeast is basically just a wrapper around MustSpendAtLeast. This gets processed here, by adding a required value to this thing. These values get turned into outputs in addMissingValueSpent.
With all this, I still don't understand how this constraint is supposed to be used.
edit:
The root of my inability to figure this out was that I was looking in the wrong place for the information. Ledger.Constraints.OnChain is the place to go to figure out what all the constraints actually mean. In the case of mustSpendAtLeast, it simply means that all the values of all the inputs to the transaction must add up to at least that amount.

Here is a contrived use case:
Imagine some dApp that includes governance (voting and stuff). Among the requirements for voting on some referendum, you must prove your right to vote with governance tokens. The smart contract doesn't need to be paid the governance tokens, rather just see that they are included in any vote transaction, after which the tokens can be returned to the voter.
To achieve this, you will need to spend the tokens, and just have yourself as the recipient*. You will include the constraint:
Constraints.mustSpendAtLeast govTokenValue

Which under the hood will select enough UTxOs to spend and meet the minimum govTokenValue (or return an error if you don't have enough).
The dApp smart contract can then check its ScriptContext to ensure that at least the minimum number of governance tokens needed were included in the transaction to perform the desired action, e.g. vote.
*not specifying a recipient will default to returning them to the transaction builder (you)


text:
Cardano Node + DB Sync + Graph QL vs. Blockfrost API
I've been contemplating the value of essentially running all your own infrastructure by deploying a Cardano node alongside DB Sync and exposing it through Cardano GraphQL.
I like the idea of building essentially my own payment gateway into Cardano completely ran by myself, without the use of any third-party APIs.
Given the cost of cloud solutions and per the requirements of the node/db-sync and GraphQL the costs would be around:

On DigitalOcean as an example, the cheapest VM that meets the basic requirements for db-sync is $120/mo
Blockfrost 300,000 tier is roughly $70/mo

Is the convenience of not running your own infrastructure and hooking into Blockfrost the best option for low traffic websites/dApps?
1,000,000 requests per day can go pretty quickly when running a decently sized web3 based website, though the managed IPFS storage and pinning does seem tempting.
To be clear, I think Blockfrost has done a lot for the Cardano ecosystem and will probably end up going with them. This was more of a thought experiment to see both sides of the coin and lay out the strongest possible case for each. I do like the idea of running my own Cardano infrastructure but think that until you're getting into a decent size of traffic it may be better to utilize Blockfrost.

I've been on a bit of a journey with this so might be able to add some insight. We originally started by running our own node inside our Kubernetes cluster, alongside a cardano-wallet container that we used to interact with the Wallet REST API. This proved to be reasonably easy at first while we were on testnet. However, when our app hit mainnet, suddenly we needed a far larger Kubernetes node to run the cardano-node binary. Our hosting costs sky-rocketed to $250+ a month, and we had the extra work of ensuring our node version was kept up-to-date, and that the node was up reliably in order for our app to transact consistently. It suddenly made absolutely no sense for us to continue this model, and we are now in the process of migrating all our code to use Blockfrost instead. Even if we have to pay $70 a month, we'd be saving a massive amount of time and money compared to running the node. Personally, I also can sleep better at night knowing that our Cardano node isn't sat on the internet somewhere, i.e. if someone accidentally modified our Kubernetes config and exposed the API to bad actors.
In the future I hope to go to a hybrid approach where we use a combination of both our node and Blockfrost, since it's also worth noting that if everyone used Blockfrost or similar API's it hurts decentralization.

This is where I'm at as well. If and when my DApp becomes successful enough to warrant running my own infrastructure, $250 will be a small price to pay, but for now Blockfrost just makes sense.

I think the best answer is that it depends on your specific use case.
A lot of people start their project using just Blockfrost as they do not want to invest a lot of resources into their infrastructure before exploring their idea.
Most of the large Blockfrost customers are actually running both, mostly for scaling and fail-over.
Also, I would point out, the cost of cloud resources are not as significant as the effort of providing 24/7 maintenance of the infrastructure and keeping up with different bugs and upgrades of the specific components. However, that strongly depends on how much you value your own time and how much new skill you would have to acquire to become your own devops.
Full disclousure, I'm a Blockfrost developer.
EDIT: Now that Blockfrost is fully open source, you can run your own while preserving decentralization.

I was leaning towards using Blockfrost, atleast for the foreseeable future. I will note that I am surprised to find out that many large projects are running both, but I guess that does make sense to not have a single point of failure.


text:
Move a node to another computer
What do I need to do to move a node on one machine to another so the node appears to be the same node. I have a node on one machine but need to discontinue that machine. When I build the new machine out I need it to have the same keys I'm guessing. I'm not exactly sure what files would need to be copied over. Thanks for the help.

Is this for a Stake Pool block producing node?

Based off the "same keys" part of the question, I am going to assume this is for a block producing node.
Block Producing Node:
For the BP, all you need to do to move it is copy the kes.skey, vrf.skey and node.cert. You will also want to copy your configuration files and make sure your UFW configuration is the same. The last step is, if you changed the IP address, to update your relay topology to connect to the new IP address, as well as update the relay UFW if needed.
Minting Tokens:
Although I have not tested this, I believe you need to copy over your policy.vkey, policy.skey, policy.script, and your policy.ID. You also may need your payment address and keys. If I am missing anything please correct me and I'll update this.
Minting Token's Source
Hope this helps!

Thanks for taking the time to respond! It's not a block producing node, but I want to be able to mint tokens and make associated metadata (or alter previous metadata) later which requires the "same" node. (that's what I've been lead to believe anyway)

just to be sure,
you need to define what kind of files you store this moment to your old node.
it depends on your folder structure and for what reason the node is running.
i would recommend you to install the same way the new node and use the same folder structure.
then you store the files on the same folder as it is now.
cold.counter*
cold.skey*
cold.vkey*
hot.skey*
hot.vkey*
pool.id
pool.id-bech32
vrf.skey*
vrf.vkey*
kes.start*
op.cert*
pool.cert*
pool.config*
poolmeta.json*
if you run the node as a BP only, and you store the rest of your files on offline system, then our friend before is right,
you need only this 3 files on the node :
kes.skey,
vrf.skey and
node.cert.


text:
I am completely new to Cardano eco system. To learn it from the absolute basic, where do I start?
This is a broad question but I am sure many might have this in their mind.
I am an upcoming blockchain engineer and my exposure to Cardano eco system is limited to buying the ADA cryptocurrency and watching Charles's vlogs. But I want to professionally start using Cardano as my blockchain of choice, for building applications on top of it. For that, I want to learn how to create smart contracts and dApps using this network. I couldn't find any tutorials on sites like Udemy for this but there were many a plenty for Ethereum.
Can someone suggest a learning path to learn to build dApps? Any tutorials that I can follow?

There are a lot of places/tools to start, so, here are some of them sorted in a learning path:

Developers guide, this has a complete guide of tools to start developing on cardano. You can find them in the Builder Tools section.
Plutus, the smart contracts language (based on Haskell) used in Cardano: Plutus pioneer program

Haskell and Cryptocurrencies by IOHK, recently published on Github.
Haskell, you need to understand the basics: Learn You a Haskell

cardano-node and cardano-cli, last one is a command line tool to interact with Cardano: Installing the Cardano node (just note there are executable nodes)

Learn some basic commands from Cardano Node CLI Reference

Minting NFTs (as native assets without plutus) there is a good tutorial in the developers guide
Alonzo testnet program has a set of exercises to write and submit Plutus scripts on the Alonzo testnets using the node CLI. Also to create DApps.
There are more tools to use on your DApps:

Blockfrost is a gateway to the Cardano ecosystem as an API
Nami Wallet is a browser based wallet extension to interact with the Cardano blockchain
PAB (Plutus Application Backend) provides the components and environment to help developers interact with smart contracts. Beta release to use on testnet.
Cardano Wallet provides an HTTP Application Programming Interface (API) and command-line interface (CLI) for working with your wallet.

I know it's a lot of information, but you can go step by step. Hope it helps!

Thanks @georgeos !

Start learning Plutus Pioneer Program.


text:
How to get all utxos from script with off chain code ordered from the oldest to the newest?
Is it possible to get all utxos from address but with specific order for example from the oldest to the newest ones? I am not sure in which order this function utxosAt returns: https://github.com/input-output-hk/plutus-apps/blob/404af7ac3e27ebcb218c05f79d9a70ca966407c9/plutus-contract/src/Plutus/Contract/Request.hs#L397

I am not familiar with this function, but if you could share a/the result from the function, that might be helpful.

You could use Time Tokens, this solution is proposed by Minswap team:

An effective way to prevent malicious ordering is to make each batch
request hold a time token. A time token can only be created if its
asset name is a timestamp that is after the validation range upper
bound. This prevents anybody from creating a time token in the past.
This BR will only be validated if all BRs in the same transaction are
of the same type and are ordered by this time token. This enforces
that there would only be one way to order BRs in one transaction.

https://medium.com/minswap/introducing-laminar-an-eutxo-scaling-protocol-for-accounting-style-smart-contract-d1ac8847dde8#:~:text=An%20effective%20way,in%20one%20transaction.

Here is one way:
If you print out the result of utxosAt you'll see that each UTxO has a field txValidRange which is the slot range over which the Tx could have been executed. By default that field is set to
txValidRange = Interval {ivFrom = LowerBound NegInf True, ivTo = UpperBound PosInf True}

This isn't helpful in your case, since it means it could have been executed any time.
When constructing a Tx, however, you can constrain the valid range:
Constraints.mustValidateIn (interval (Slot 11) (Slot 11))

Which will change the valid range to:
txValidRange = Interval {ivFrom = LowerBound (Finite (Slot {getSlot = 11})) True, ivTo = UpperBound (Finite (Slot {getSlot = 11})) True}

You can then know that this UTxO was created on slot 11 (if not, the Tx would have failed execution), and use these values to sort the UTxOs.

Notes:
In my experience, the txValidRange is useful in Plutus scripts, since the execution is deterministic, i.e. you can check the valid range of the tx, but you can't check the current slot from within the script. I'm not sure that means the execution slot isn't knowable after the fact though, outside of the script.
I'm going to dig into the codebase a little and see if there is a way to lookup a UTxO after it's added to the chain to see when it was added. For now the above answer is the best I've got.

The UTxO itself doesn't provide information on the time it was created. However, each UTxO is part of a transaction.

Using blockfrost.io you could query all UTxOs of an address:
https://docs.blockfrost.io/#tag/Cardano-Addresses/paths/~1addresses~1{address}~1utxos/get

This will give you a list of UTxO that look like this:
{
"tx_hash": "39a7a284c2a0948189dc45dec670211cd4d72f7b66c5726c08d9b3df11e44d58",
"output_index": 0,
"amount": [],
"block": "7eb8e27d18686c7db9a18f8bbcfe34e3fed6e047afaa2d969904d15e934847e6",
"data_hash": "9e478573ab81ea7a8e31891ce0648b81229f408d596a3483e6f4f9b92d3cf710"
}

Using the tx_hash of each UTxO, you can query the transactions: https://docs.blockfrost.io/#tag/Cardano-Transactions/paths/~1txs~1{hash}/get

Besides other information, you can see the block_time (UNIX timestamp) there:
{
"hash": "1e043f100dce12d107f679685acd2fc0610e10f72a92d412794c9773d11d8477",
"block": "356b7d7dbb696ccd12775c016941057a9dc70898d87a63fc752271bb46856940",
"block_height": 123456,
"block_time": 1635505891,
"slot": 42000000,
...

With this information you can then order your UTxOs. Hope this helps!


text:
Verifiying a digital signature in a Plutus script
Is there a function like signedBy that I can call in a Plutus script to verify a digital signature?

So are you looking for a type like this: verifySig :: Signature -> PubKey -> Bool? (signedBy without the tx)?

Well the problem is that a Plutus script calling signedBy will not compile because signedBy is not inlinable. So I need a function that can be called by a Plutus script. The TxId argument isn't a big deal because I can always get that from the ScriptContext.

You can use this function to verify signature from a validator


text:
Where to find proper info on the cardano graphql
I am new to Cardano and have setup the GraphQL node
All is running, but my problem is I can not find proper info on how to actually get the data.
What I would like to query is asset data and smart contract data.
Lets say there is an Cardano DEX, they work with some smart contract and liquidity pool, i would like to get data on what pools and calculate a price from that.
Btw, I try to build a simple Cardano DEX tool with MERN stack.
Any help, any pointing to the right direction is welcome.
-- UPDATE --
So, lets say I need to calculate a pair price which is done from an liquidity pool of a DEX. How to get that data?
Or I want to get sell/buy orders from a DEX.
I know how this works for eth and bsc, all those have awesome documentation, but Cardano is not really made well for new coming dev's to the Cardano blockchain.

I'm not sure if you have explored their wiki yet, it has guide how to interact with their api:
Interacting with the API
You can also check their API Documentation:
API Documentation
They've got a bunch of samples too:
Example Queries

Hi, thanks for your answer. I know all those pages, but non give me the info I need to get the job done.

how do you like this?
i really liked the source of info here:
https://github.com/input-output-hk/cardano-graphql

That's the node I have running, but the documentation is so bad for beginners.


text:
Future adjustment of minimum ADA to be sent?
I am wondering about the minimum amount of ADA to be sent with a transaction (and/or has to be held by a wallet alongside a CNFT): Right now its 1,379something, but there surely has to be a plan how and when to lower this amount as ADA vs USD reaches higher levels?
Can anyone shed some light on this issue?

Micro-transactions with low fees will become possible when Hydra is implemented.

This doesn't exactly answer your question but could be useful for you and others.
Since cardano-cli 1.31, there is a new command to calculate the minimum required ADA for a transaction output:

cardano-cli transaction calculate-min-required-utxo

Usage: cardano-cli transaction calculate-min-required-utxo
            [ --byron-era
            | --shelley-era
            | --allegra-era
            | --mary-era
            | --alonzo-era
            ]
            (--genesis FILE | --protocol-params-file FILE)
            --tx-out ADDRESS VALUE
            [ --tx-out-datum-hash HASH
            | --tx-out-datum-hash-file FILE
            | --tx-out-datum-hash-value JSON VALUE
            | --tx-out-datum-embed-file FILE
            | --tx-out-datum-embed-value JSON VALUE
            ]

  Calculate the minimum required UTxO for a transaction output.


text:
1.) Do all sidechains require their own token, consensus, node operators, etc?
I just finished IOHK’s whiteboard video about sidechains.
https://www.youtube.com/watch?v=04D2BP33YI8
I felt like I absorbed much of the information like NiPoPow’s and the problems that sidechains can solve. However, I am left with a few burning questions:
1.) Do all sidechains require their own token, consensus, node operators, etc?
2.) How does the receiving chain mint the newly transferred coin? How is this even possible? I thought minting was only allowed based on a monetary policy. Is this a special exemption? I understand chain a will burn the token, and chain b will validate bc of the NiPoPow, but I don’t understand how chain b can mint a new token on request.

Sidechains do require their own tokens, consensus protocols, and operators, but there's no reason why all three of those have to be different than the tokens, protocols, and operators of the main chain.
They can be different, which is why sidechains are so flexible and versatile, it really just depends on the needs/purposes of the specific sidechain.
For example, a sidechain (or Hydra Head) whose sole purpose is to scale ADA or native token transactions can use sidechain-ADA on a 1:1 basis to mainchain-ADA, a modified version of Ouroboros that prioritizes speed over security, and a node operator that has already built a solid track record of distributed systems administration (i.e. established SPO's).
On the other hand, a side chain can have its own monetary policy with a (locally) global accounting style and arbitrary tokenomics, or any combination of services.
Sky's the limit!


text:
What's the difference between sharding & a payment channel, & how does Hydra compare?
The question is all in the title.
My take: sharding is a base level solution which ideally a programmer using a sharded system shouldn't need to interact with (but I think this probably isn't true, which is why sharding is often considered inelegant). Whereas a payment channel is also a method of scaling, but is a temporary thing that is opened for a period of time and then closed, with a settlement to the main chain which happens when the channel is closed.
So, sharding is at infrastructure level (programmers using the system should not be involved in creating shards), whereas to use a channel it's more likely that a programmer is going to open & close one.
Sharding has its own issues; putting transactions on a payment channel means that anything that happens on the channel will not be visible on-chain until the channel is closed, or at least until it issues a settling transaction on-chain, so visibility will be reduced.
Reason I'm asking this question is I'd like to establish whether a (very) fast L1 actually has an advantage of any kind over Hydra (which I'm also seeking to understand here). Apologies the question is very incomplete at present, and this is just a draft note, can update it as we learn more.

First lets imagine a state channel, which is similar to a payment channel, only that in addition to basic transactions, it can contain arbitrary business logic. As you've said, it helps to think of such channels as sort of "black boxes" that can be periodically settled on the main chain, so long as the inputs match the outputs.
Below is an infographic example of such channels (not by me)

In global account ledgers like Ethereum or Solana, smart contract logic exists outside of individual transactions and must be "called" by every transaction wishing to make use of it. This means that when state channels are created, it isn't easy to port over smart contract logic into the channel, without either rewriting the code inside the channel, or by having a complex setup where the channel isn't really a black box but more of a gray box that allows some level of constant exposure to code on the main chain. Either way, not very elegant and perhaps overly complicated.
The full power of state channels is only realized when they are used in a blockchain with a UTXO accounting style, such as Cardano. Since smart contract validator logic exists on the UTXO itself, and the entire UTXO is used as a channel input, contract composability becomes a natural byproduct, rather than a complex workaround, of the state channel.
And so we have Hydra - Isomorphic (native composability) State (arbitrary logic) Channels (Off-chain/L2).


text:
Why is there no mechanism available to restrict creation of UTXOs at a script address?
It has been told that anyone can create UTXOs at any script address without restrictions since the validator does not run for transaction that do not consume UTXOs. The question is, why so?
I think it would have been convenient if there was mechanism to assign (if needed) some validation logic to the creation of UTXOs at a script address. It would have enabled developers to define boundaries on what can possibly sit at their script addresses and that can simplify subsequent operations with those UTXOs.
It's hard to imagine that the absence of such a mechanism was not a conscious decision or that its technically not feasible. I am curious to know the reasoning behind it.
Update: While it is possible to filter out utxos in consuming tx, by looking at the datum associated with them, it also feels like a side effect of not being able to restrict the creation in the first place. That is the motivation for this question.

Because the purpose of a script is to determine the conditions a UTxO can be spent.
If you want to deter people from creating arbitrary UTxOs at your script address, you can write the script in a way that makes those UTxOs unspendable, e.g. require the UTxO to include a specific NFT.
Other than that, you can't stop someone from sending their tokens to an unreachable address. Adding some validation on every UTxO being created at the address would only serve to protect people from accidentally burning their tokens--that's not really your job as the script writer. It would also increase the cost of transactions.

Would it not increase the cost of transactions for having to pick the utxos linked to the specific NFT?

Sure. It would. But only on the relevant transactions. If you put a script that validated all incoming Txs, it would have to be run on every Tx.

It is simply not feasible. The only way would be to require that the transaction includes the script that hashes to the output-address. But in the general case this script is publicly available on the blockchain in a previous transaction where a UTxO with this same script address was consumed. So you could just extract it and include it in your transaction to circumvent this restriction. The only case where this mechanism would prevent UTxOs sitting at arbitrary script addresses is the one of secret one-way scripts, and I don't see this to be meaningful use case.
Edit: Actually requiring to include the script that hashes to the output-address exposes the script. So this mechanism does not work either.


text:
How do I export my .hs contract to .Plutus?
How do I export my .hs contract to .Plutus? Please provide step by step guidance.

You can find a good example in Exercise4-solution of Alonzo-testnet program.
Source code is here: plutus-helloworld, if you have any doubt check the code to understand what it does.
Basically you need to:

Create an executable plutus-helloworld as defined in plutus-helloworld.cabal file
Compile the plutus file using: cabal run plutus-helloworld -- 1 helloworld2.plutus
Build the address: cardano-cli address build --payment-script-file helloworld2.plutus --testnet-magic 8 --out-file helloworld2.addr

Then you can follow the exercise solution.


text:
Calculation of transaction fees
Is there documentation for the calculation of transaction fees with examples and real parameter values somewhere ?  Maybe something similar to the one on the minimum Ada value here: https://docs.cardano.org/native-tokens/minimum-ada-value-requirement

Calculation procedure is here: Cardano fee structure

The formula for calculating minimal fees for a transaction (tx) is a * size(tx) + b, where:

a/b are protocol parameters
size(tx) is the transaction size in bytes

Where protocol parameters are (as of November 11, 2021):

a: txFeePerByte = 44 lovelace
b: txFeeFixed   = 155381 lovelace

You can find those parameters using:

cardano-cli query protocol-parameters --testnet-magic 1097911063 --out-file protocol-params.json
Protocol params

I meant documentation on the calculation itself. How are the fees determined. Is there a fixed part and a variable part ?; How high is the fixed part ?; Does the variable part depend on the byte-size of the transaction ?; How high are the costs per byte ?; How large (in bytes) as a transaction with some plain vanilla UTxOs ?; How large is a UTxO with some native assets ? ... and so on.

Check the updated answer.

Thank you, this is helpful. Can I suggest you add the values of txFeePerByte and txFeeFixed at the time of writing to your response. I think, I can then accept it as the answer.

Done, glad to help!

But.. we can only know the size once that we said  the outputs right? ... so how can I calculate the real fee incluiding the output to wich i am going to be sending the change if i dont know the fee yet? I ask because calculating the fee with cardanoserialization lib TxBuilder.add_change_is needed() is taking too long to run in the browser and i wanted to calculate manually the fees

In fact in the function TxBuilder.add_change_is needed()  there is one warning saying : The minimal fee may not be the real fee! :s

I haven't used cardano-serialization-lib but I guess should be same process as here: https://cardano.stackexchange.com/revisions/4473/2

The byte size of the fees and the output values are probably constant. So you can calculate the fees and than adjust the values accordingly without impacting the size of the transaction.


text:
Can't run test node on windows
When I try to run cardano-node on windows, it starts to run fine (Opened imm db, Replaying ledger from genesis, etc.), so configuration seems fine, but it exits upon trying to create a named pipe:
CreateSystemdSocketForSnocketPath "\\\\\\\\.\\\\pipe\\\\cardano-node-testnet"
DiffusionErrored CreateNamedPipe ('\\\\.\\pipe\\cardano-node-testnet'): does not exist (The specified path is invalid.)
That UNC-style path above is what I pass as the --socket-path param.  In fact, the docs say this is the path is used by the Daedalus Testnet Wallet for Windows, which is running on my machine.  Any proper pipe path should work, but none do.
Suggestions?
Command (powershell)
./cardano-node run --topology "C:\Program Files\CardanoNode\configuration\testnet-topology.json" --database-path "C:\Program Files\CardanoNode\db" --socket-path "\\\\.\\pipe\\cardano-node-testnet" --host-addr 127.0.0.1 --port 3001 --config "C:\Program Files\CardanoNode\configuration\testnet-config.json"

Version
cardano-node 1.29.0 - mingw32-x86_64 - ghc-8.10
git rev 4c59442958072657812c6c0bb8e0b4ab85ce1ba2

Well, comparing the 2 error messages above gave the answer; I needed to reduce the backslashes passed to --socket-path even though the backslashes reported in output as the pipe it tried to create was correct.  So I have to pass --socket-path "\\.\pipe\cardano-node-testnet" (apparently the cardano-run doubles them).


text:
Can you create a DAO on cardano using only native tokens or would it require a sidechain?
I am researching creating a community-driven dapp with tokenomics similar to steem. Can someone point me in the right direction regarding implementation on the cardano ecosystem? I can not find a lot of information regarding DAO's and sidechains on cardano.

Your question seems to be asking for a technical answer to a non-technical question. As far as I understand it, a DAO is simply a way of conceptualizing a distributed/decentralized system for decision making. The specifics by which such a system is implemented can vary greatly depending on the needs of the organization/application. It can be as simple a trusted relationship between n parties with all transactions on mainchain, to as complex as a hydra head with its own monetary policy facilitating arbitrary business logic.
Really just depends what the DAO is intended for.


text:
Smart Contract NFT minting with Rarities
I'm trying to work out how an NFT collection might be sold on Cardano in the future, specifically by making use of smart contracts.
Let's say that I am creating a 10k pfp collection or something of the sort where each NFT has different attributes and therefore there is some sort of rarity distribution. As the creator of the project I can mint all 10k NFTs and transfer them over to a smart contract. For simplicity we'll say there is one NFT per transaction, so I have 10k UTXOs sitting at my smart contract with 1 NFT each.
When someone comes along to purchase an NFT, how can I make it so they are distributed a random NFT. Since they construct the transaction off the blockchain, they can just select the rarest available NFT.
I am able to come up with a mechanism where I might be able to sell placeholder "redeemable" NFTs that people can purchase and send back to the smart contract, but that would require me to then create a transaction on my end where I consume the buyer's placeholder NFT and one of the unpurchased NFT UTXOs to eventually send the buyer their asset. I don't like this solution because the final transaction, the one executed by the creator to send the NFT, can be executed by off-chain code that isn't transparent to the buyers, which would allow for it to rigged or otherwise incorrect in some way, and the buyer's would be unaware.
I apologize if this is the wrong venue for this question, but I'm eager to start writing Plutus code.
Thanks.

I think the problem is that, even if you create some sort of entropy source and force the user to use it to redeem an NFT, they will always be able to see what NFT they will be getting before submitting the transaction, so they could just drop it and wait until they can get the right random value for the one they want. A way could be by committing to the attributes of the NFT via a preimage (hash) on the metadata, and then after all NFTs are sold, reveal the values.

We could use your redeemable approach and make it so the seller cant rig it.
This is the idea, you will need to create 2 different minting policies, one for your NFTs and one for the redeemable NFTs, it is important that both policies do not allow duplication of the asset names (you can do that with something like this https://forum.cardano.org/t/mary-era-nfts-alonzo-era-nfts-which-are-better/82034/24)
Additionally, the policy of the redeemable tokens must allow anyone to burn the token.
So first, you create (but don't mint or reveal yet) the name of your main NFTs, the name of your NFT will have encoded the attributes of the metadata in base 58 for example (or hex even).
And you will have something like:
AwesomeNFT00001mASD34fR342332
The bold part is the encoded metadata.
Then without revealing the asset name of these tokens yet, you create a redeemable token for each, which asset name is the hash of the original token encoded in base58.
AwesomeNFT00001mASD34FR342332 -> FHY45G86DFHY45G86DFHY45G86D
Now you have in policy 1
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFF.AwesomeNFT00001mASD34FR342332
And in policy 2
0000000000000000000000000000000.FHY45G86DFHY45G86DFHY45G86D (Redeemer token)
And you place all these redeemable tokens in your contract. Once all the redeemable tokens are sold. You then mint the real tokens and place them in a contract with the following condition:
The eUTXO can only be spent if an asset with policy id "0000000000000000000000000000000" and an asset name which is equal to the hash encoded in base58 of the asset name of the token inside this eUTXO is brunt.
Of course, you could have more validations on the contracts, etc.
Now because the contracts don't have access to the transaction metadata, we can't really enforce which values will be there, so this is why I encoded the metadata in the token name instead.
All hashes, encoded values, and policy IDs are dummy values just for demonstration.
In essence, the key would be to commit to the attributes without revealing them, so the buyers cant choose, and the minter cant rig it as they already committed to the value.
I think the current trend of having the NFT attributes in the transaction metadata is not very good, as we can't access these attributes from the contracts, we need to find a better way to express and display attributes on the tokens themselves (and not the transactions)


text:
Insufficient funds when trying to use script unspent output
I was following the example from the basic split app and changing it a bit to try to make a simple sell/buy NFT transaction.
For now I'm just trying to transfer the NFT from one wallet to another.
My idea is basically that a user has to call the 'Offer' endpoint to send the NFT to the script and then the other wallet calls the 'Buy' endpoint to get the NFT.
doOffer :: OfferArgs -> Contract () MarketplaceSchema T.Text ()
doOffer offerData@OfferArgs{..} = do
    pkh <- pubKeyHash <$> Plutus.Contract.ownPubKey
    let offerData = OfferData
                { seller         = pkh
                , price          = aPrice
                , nftCurrencySymbol = aCurrencySymbol
                , nftTokenName      = aTokenName
                }
    logInfo @Haskell.String $ printf "creating offer %s" (Haskell.show offerData)
    let tx = Constraints.mustPayToTheScript offerData (Value.singleton aCurrencySymbol aTokenName 1)
    void $ submitTxConstraints offerValidator tx

doBuy :: OfferArgs -> Contract () MarketplaceSchema T.Text ()
doBuy offer@OfferArgs{..} = do
    logInfo @Haskell.String $ printf "buying %s" (Haskell.show offer)
    pkh <- pubKeyHash <$> Plutus.Contract.ownPubKey
    let contractAddress = Scripts.validatorAddress offerValidator
    utxos <- utxosAt contractAddress
    let tx =
            collectFromScript utxos Buy
            <> Constraints.mustPayToPubKey pkh (Value.singleton aCurrencySymbol aTokenName 1) -- Send the NFT to buyer
    void $ submitTxConstraintsSpending offerValidator utxos tx

The offer part seems to work well, and the NFT shows up at the script output. However when I try to send it to the buyer in mustPayToPubKey I get an error:
Contract instance stopped with error: "WalletError (InsufficientFunds \"Total: Value (Map [(,Map [(\\\"\\\",100)])]) expected: Value (Map [(,Map [(\\\"\\\",3242)])])\")" ]

I don't know but it looks like it's trying to pay the token using the Buyer's wallet, but I thought the collectFromScript part was supposed to use script utxo?
Here is how it looks in the simulator when the error occurs:

I believe the rest of the code is not necessary as I'm not doing any kind of complex validation yet, I'm just trying to make a simple transfer but if you need the validator piece let me know :)

expected: Value (Map [(,Map [(\\\"\\\",3242)])])\")"
Try adding a few zeros to the starting balances. It's saying it doesn't have enough to pay the fees.
I'm surprised that the first transaction worked, but without seeing all of your code it's hard to diagnose why.

Yeah that was exactly it, thank you!!

Transaction should be done by someone, in this case by the Buyer. In order to do that, buyer should pay the fees of the transaction.
Actually, this error is explaining that buyer has less lovelace than the required to pay the fees.
"WalletError (InsufficientFunds \"Total: Value (Map [(,Map [(\\\"\\\",100)])]) expected: Value (Map [(,Map [(\\\"\\\",3242)])])\")" ]

Buyer has 100 lovelace and it's required to pay 3242.
Function collectFromScript has nothing to do with it.


text:
Burn token using blockfrost java sdk?
Does anyone have an example how to burn a NFT using the blockfrost.io java SDK or Javascript SDK?
Thanks a lot in advance.

There is a great post on the Cardano form that goes in-depth on different types of burning methods [1]. Note that these tokens send to such addresses still exists but can't be transferred anymore by anyone. But for some of the solutions mentioned one can proof that the address corresponds to a unspendable script.

There is an explanation of burning tokens on Github.
It's using cardano-serialization-lib ^10, the latest version. So it's very useful.

This tutorial assumes that the minting policy allows the action of burning. This may not be the case. In the case that the minting policy allowed you link to burn this works, its just minting with negative value. If the policy is locked or not accessible by you (for example only certain key holders can burn), then you can indefinitely lock your tokes like above mentioned (just like burning).

ok, thank you very much for your clarification!

As far as I know, there is no support for burning tokens out of box yet.
You might want to look at this specific part of the pull request to the transaction builder to get an inspiration on how to do that.


text:
How to convert a cardano address into a public key hash?
After spending some time learning Plutus with emulators, I decided to start learning how to actually deploy and use the scripts in the testnet. In this process, I installed cardano-cli and created multiple key files, such as "payment.addr", "payment.skey", "payment.vkey", etc. But now, the validator script that I created requires as one of it's parameters a Plutus AssocMap associating public key hashes to integers.
My question is, based on the keys I created, how can I find out their PubKeyHash? I believe this is related to "payment.addr", but I'm not sure.

How to get this value when using e.g. Nami Wallet?

Is there a way to get key-hash from payment.address only?

@AdamMachera See my new answer

I think you're looking for this:

cardano-cli address key-hash --payment-verification-key STRING
cardano-cli address key-hash --payment-verification-key-file FILE

You should use your payment.vkey

This is the cborHex value in the .vkey file yes?

If anyone is trying to do this using cardano-serialization-lib and Nami:
const PUBKEY_HASH = async () => {
  const cardano = window.cardano;

  const pkh = Loader.Cardano.BaseAddress.from_address(
    Loader.Cardano.Address.from_bytes(
      Buffer.from(await cardano.getChangeAddress(), "hex")
    )
  )
    .payment_cred()
    .to_keyhash();

  return pkh;
};

Assuming you are using a loader like the one from spacebudz and you are importing Buffer import { Buffer } from "buffer";
UPDATE
Made a more abstract version that takes a string (the bech32 address) and returns another string (the public key hash)
function addrToPubKeyHash(bech32Addr) {
  const pkh = Loader.Cardano.BaseAddress.from_address(
    Loader.Cardano.Address.from_bech32(bech32Addr)
  )
    .payment_cred()
    .to_keyhash();

  return toHex(pkh.to_bytes());
}

Sorry fromHex is defined as const fromHex = (hex) => Buffer.from(hex, "hex")

And toHex const toHex = (bytes) => Buffer.from(bytes).toString("hex")

I am working on this as well... I am not sure but this seems quite promising
https://input-output-hk.github.io/cardano-addresses/demo/
Maybe this is usefull as well
https://cips.cardano.org/cips/cip19/#shelleyaddresses

If you are using the serialization lib, my answer may help

You can use the "cardano-address address inspect" syntax to get the public key hash from an address without requiring the verification key. Requiring the verification key assumes having access to the file while addresses can be shared without having to know the owner.
This link can help: https://github.com/input-output-hk/cardano-addresses

Couldn't you just pass the address to Plutus and then convert it there to a public key hash using the function in Ledger.Address:
{-# INLINABLE toPubKeyHash #-}
-- | The PubKeyHash of the address, if any
toPubKeyHash :: Address -> Maybe PubKeyHash

The address is serializable so you can pass it easily and get a proper instance of Address that you can use at your will in your Plutus code.

Are you sure this Address is a bech32 string? I don't think it is https://staging.plutus.iohkdev.io/doc/haddock/plutus-ledger-api/html/Plutus-V1-Ledger-Address.html#t:Address

I don't know if this deserialisation is this easy, actually. I haven't tried yet. But, there must be a function in Plutus to deserialise the string to the Address class.

This is getting strange. Why is it so difficult to find a function in Plutus that parses the address representation to the address class ?


text:
Convert Redeemer, Datum or Script Parameter to JSON
By following the alonzo-testnet exercises, I'm right now having to build a transaction with cardano-cli. One of the arguments necessary to consume a script is the datum, another is the redeemer, both of which should be in a JSON file (or value).
Is there any reference of how Data should be expressed in JSON? Because I tried converting it with Data.Aeson in Haskell, but received the following error
JSON object does not match the schema.
Expected a single field named "int", "bytes", "string", "list" or "map".
Unexpected object field(s): {"contents":{"getPubKeyHash":"3e7181860513a17dfa44d69232429e5c328e79c748d4a176950c42b6"},"tag":"Collect"}

Also, is there any library to make my life easier, so I can be able to easily convert my redeemers into JSON?

Reading some old messages in discord, someone mentioned that I could use encode (scriptDataToJson ScriptDataJsonDetailedSchema $ fromPlutusData data), taken from here, so I made a redeemerJSON function defined as follows:
redeemerJSON :: DistributionRedeemer -> ByteString
redeemerJSON dr =
  encode (scriptDataToJson ScriptDataJsonDetailedSchema $ fromPlutusData (PlutusTx.toData dr))

Of course some imports are necessary, but I believe you can use this same approach for the datum and other script parameters too.

I would make it even more general to:
plutusDataToJSON :: PlutusTx.ToData a => a ->  Data.ByteString.Lazy.Internal.ByteString
plutusDataToJSON = encode . (scriptDataToJson ScriptDataJsonDetailedSchema) . fromPlutusData . Plutus.toData```

The Cardano-node github is the best resource that I have found
JSON conversion

Script data is similar to JSON but not exactly the same. It has some
deliberate limitations such as no support for floating point numbers
or special forms for null or boolean values. It also has limitations
on the length of strings.
On the other hand, unlike JSON, it
distinguishes between byte strings and text strings. It also supports
any value as map keys rather than just string. It also supports
alternatives / tagged unions, used for  representing constructors for
Plutus data values.
continues ....

Further extensive details in Cardano-node github file ScriptData.hs


text:
Error while decoding the protocol parameters
This is occurring on testnet. Trying to calculate a fee for a transaction that will include metada.
Here's the script:
cardano-cli transaction calculate-min-fee \
    --tx-body-file tx.draft \
    --tx-in-count 1 \
    --tx-out-count 1 \
    --witness-count 1 \
    --byron-witness-count 0 \
    --testnet-magic 1097911063 \
    --protocol-params-file testnet-shelley-genesis.json

The error:
Command failed: transaction calculate-min-fee  Error: Error while decoding the protocol parameters at: "testnet-shelley-genesis.json" Error: "Error in $: key "protocolVersion" not found"
And the first part of the testnet-shelley-genesis.json file
{
  "activeSlotsCoeff": 0.05,
  "protocolParams": {
    "protocolVersion": {
      "minor": 0,
      "major": 2
    },
    "decentralisationParam": 1,
    "eMax": 18,
    "extraEntropy": {
      "tag": "NeutralNonce"
    },
    "maxTxSize": 16384,
    "maxBlockBodySize": 65536,
    "maxBlockHeaderSize": 1100,
    "minFeeA": 44,
    "minFeeB": 155381,
    "minUTxOValue": 1000000,
    "poolDeposit": 500000000,
    "minPoolCost": 340000000,
    "keyDeposit": 2000000,
    "nOpt": 150,
    "rho": 0.003,
    "tau": 0.20,
    "a0": 0.3
  },

Checked byron and alonzo genesis files and they do not contain the protocolVersion element. Haven't made any updates to any of the genesis files.
Is there a different params file I should be using?

You're using the genesis file instead of the protocol-params-file.
Try using the protocol-params. You can get it using this command:
cardano-cli query protocol-parameters --testnet-magic 1097911063 > protocol-params.json

It works:
cardano-cli transaction calculate-min-fee \
--tx-body-file tx.draft \
--protocol-params-file protocol-params.json \
--testnet-magic 1097911063 \
--tx-in-count 1 \
--tx-out-count 1 \
--witness-count 1

Thanks for the help!  The tutorial specifically said protocol-params.json, but since I couldn't find it from the download sites, I thought maybe the tutorial had it wrong, so I assumed one of the genesis files.  That worked.

Download the latest files from https://hydra.iohk.io/build/7654130/download/1/index.html
There was an update did you update your node? You should also get the latest config files


text:
Parse error on input ']' when running cabal build in my Plutus code
I have a code that compiles and runs well in the Plutus playground, but when I try to run cabal build I get an error when calling mkTypedValidator:
offerValidator :: Scripts.TypedValidator Offer
offerValidator = Scripts.mkTypedValidator @Offer
    $$(PlutusTx.compile [|| validateOffer ||])
    $$(PlutusTx.compile [|| wrap ||]) where
        wrap = Scripts.wrapValidator @OfferData @OfferAction

using ghc version ghc-8.10.7
cabal version 3.6.0

Any ideas what might be happening? Not very experienced with cabal/plutus yet.
Also already tried cabal update but looks like everything is up-to-date.

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

Looks like I was missing some imports that are not necessary in the playground, but are still necessary when building with cabal. Will leave this here since it may help someone else :)


text:
Empty txInfoSignatories after building transaction with cardano-cli
In the Plutus Pionner Lectures, Lars instructed us to use txSignedBy in order to ensure that a user signed the transaction. The function tries to find a public key hash in the txInfoSignatories list, if it's able to find, it returns True.
Everything was working in the emulator, but now, when I tried to manually build and sign the transaction with cardano-cli, the transaction doesn't appear to add the public key hash from the user who signed it to txInfoSignatories and the script validation fails. My question is: how do I add the user pubkeyhash to txInfoSignatories with cardano-cli? No information regarding the signature appears when I execute cardano-cli transaction build -- help

------ UPDATE------
Since version 1.31 of cardano-cli, there is the following option to sign the transaction when it is built, so you can avoid that error from the script:
--required-signer FILE   Input filepath of the signing key (zero or more)
                         whose signature is required.

-----------------------
It's related to this bug: Cli to pass required signer (reqSignerHashes) to plutus script for txInfoSignatories
In a near future, there will be a --required-signer option in cardano-cli
As a workaround try to combine toPubKeyHash and txOutAddress function to get the PubKeyHash from any output.
info :: TxInfo
info = scriptContextTxInfo ctx

txOuts :: [TxOut]
txOuts = txInfoOutputs info

outPubKeyHash :: Maybe PubKeyHash
outPubKeyHash = toPubKeyHash $ txOutAddress $ head txOuts

@georgeos answer was correct, but from node version 1.32 there is
--required-signer-hash HASH
                           Hash of the verification key (zero or more) whose
                           signature is required.

(so you don't need to know users signing key, just pass the PubKeyHash)