text:
Claiming two tokens by the locking account - owning tokens address
I'm trying to implement some simple two tocken lockup similary to what has been done in Vesting.hs on week03
{-# 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              #-}

import           Control.Monad        hiding (fmap)
import           Data.Aeson           (ToJSON, FromJSON)
import           Data.List.NonEmpty   (NonEmpty (..))
import           Data.Map             as Map
import           Data.Void            (Void)
import           Data.Text            (pack, Text)
import           GHC.Generics         (Generic)
import           Ledger               hiding (singleton)
import           Ledger.Constraints   (TxConstraints)
import qualified Ledger.Constraints   as Constraints
import qualified Ledger.Typed.Scripts as Scripts
import           Ledger.Value         as Value
import           Ledger.Ada           as Ada
import           Playground.Contract  (IO, ensureKnownCurrencies, printSchemas, stage, printJson)
import           Playground.TH        (mkKnownCurrencies, mkSchemaDefinitions)
import           Playground.Types     (KnownCurrency (..))
import           Plutus.Contract
import qualified PlutusTx
import           PlutusTx.Prelude     hiding (unless)
import qualified Prelude              as P
import           Schema               (ToSchema)
import           Text.Printf          (printf)

minLovelace :: Integer
minLovelace = 2000000

data BreedingDatum = BreedingDatum
    { bOwner :: !PaymentPubKeyHash
    , bNft1  :: !TokenName
    , bNftCurr1 :: !CurrencySymbol
    , bNft2  :: !TokenName
    , bNftCurr2 :: !CurrencySymbol
    , bDeadline  :: !POSIXTime
    } deriving (P.Show, Generic, ToJSON, FromJSON, ToSchema)

instance Eq BreedingDatum where
    {-# INLINABLE (==) #-}
    a == b = (bOwner   a == bOwner   b) &&
             (bNft1 a == bNft1 b) &&
             (bNftCurr1   a == bNftCurr1   b) &&
             (bNft2 a == bNft2 b) &&
             (bNftCurr2    a == bNftCurr2    b) &&
             (bDeadline    a == bDeadline    b) &&
             (bDeadline    a == bDeadline    b)

PlutusTx.unstableMakeIsData ''BreedingDatum
PlutusTx.makeLift ''BreedingDatum

{-# INLINABLE mkValidator #-}
mkValidator :: BreedingDatum -> () -> ScriptContext -> Bool
mkValidator dat () ctx = traceIfFalse "owner signature missing" signedByOwner &&
                         traceIfFalse "breeding not ended" breedingNotEnded
  where
    info :: TxInfo
    info = scriptContextTxInfo ctx

    signedByOwner :: Bool
    signedByOwner = txSignedBy info $ unPaymentPubKeyHash $ bOwner dat

    breedingNotEnded :: Bool
    breedingNotEnded = contains (from $ bDeadline dat) $ txInfoValidRange info

data Breeding
instance Scripts.ValidatorTypes Breeding where
    type instance DatumType Breeding = BreedingDatum
    type instance RedeemerType Breeding = ()

typedValidator :: Scripts.TypedValidator Breeding
typedValidator = Scripts.mkTypedValidator @Breeding
    $$(PlutusTx.compile [|| mkValidator ||])
    $$(PlutusTx.compile [|| wrap ||])
  where
    wrap = Scripts.wrapValidator @BreedingDatum @()

validator :: Validator
validator = Scripts.validatorScript typedValidator

valHash :: Ledger.ValidatorHash
valHash = Scripts.validatorHash typedValidator

scrAddress :: Ledger.Address
scrAddress = scriptAddress validator

data BreedingParams = BreedingParams
    { bpOwner :: !PaymentPubKeyHash
    , bpNft1  :: !TokenName
    , bpNftCurr1 :: !CurrencySymbol
    , bpNft2  :: !TokenName
    , bpNftCurr2 :: !CurrencySymbol
    , bpDeadline  :: !POSIXTime
    , bpPrice :: !Integer
    } deriving (Generic, ToJSON, FromJSON, ToSchema)

type BreedingSchema =
            Endpoint "breed" BreedingParams
        .\/ Endpoint "claim" ()

breed :: AsContractError e => BreedingParams -> Contract w s e ()
breed bp = do
    let dat = BreedingDatum
                {
                    bOwner = bpOwner bp
                    ,bNft1  = bpNft1 bp
                    ,bNftCurr1 = bpNftCurr1 bp
                    ,bNft2  = bpNft2 bp
                    ,bNftCurr2 = bpNftCurr2 bp
                    ,bDeadline = bpDeadline bp
                }
        v = Value.singleton (bpNftCurr1 bp) (bpNft1 bp) 1 <> Value.singleton (bpNftCurr2 bp) (bpNft2 bp) 1 <> Ada.lovelaceValueOf (bpPrice bp)
        tx  = Constraints.mustPayToTheScript dat v
    ledgerTx <- submitTxConstraints typedValidator tx
    void $ awaitTxConfirmed $ getCardanoTxId ledgerTx
    logInfo @P.String $ "locked two tokens"

claim :: forall w s e. AsContractError e => Contract w s e ()
claim = do
    now   <- currentTime
    pkh   <- ownPaymentPubKeyHash
    utxos <- Map.filter (isSuitable pkh now) <$> utxosAt scrAddress
    if Map.null utxos
        then logInfo @P.String $ "no breeding finished yet"
        else do
            logInfo @P.String $ "start claiming tokens"
            let orefs   = fst <$> Map.toList utxos
                lookups = Constraints.unspentOutputs utxos P.<>
                          Constraints.otherScript validator
                tx :: TxConstraints Void Void
                tx      = mconcat [Constraints.mustSpendScriptOutput oref unitRedeemer | oref <- orefs] P.<>
                          Constraints.mustValidateIn (from now)
            logInfo @P.String $ "before submitTxConstraintsWith"
            ledgerTx <- submitTxConstraintsWith @Void lookups tx
            void $ awaitTxConfirmed $ getCardanoTxId ledgerTx
            logInfo @P.String $ "collected tokens"
            logInfo @P.String $ "collected tokens2"

  where
    isSuitable :: PaymentPubKeyHash -> POSIXTime -> ChainIndexTxOut -> Bool
    isSuitable pkh now o = case _ciTxOutDatum o of
        Left _          -> False
        Right (Datum e) -> case PlutusTx.fromBuiltinData e of
            Nothing -> False
            Just d  -> bOwner d == pkh && bDeadline d <= now

endpoints :: Contract () BreedingSchema Text ()
endpoints = awaitPromise (breed' `select` claim') >> endpoints
  where
    breed' = endpoint @"breed" breed
    claim' = endpoint @"claim" $ const claim

mkSchemaDefinitions ''BreedingSchema

myToken1 :: KnownCurrency
myToken1 = KnownCurrency (ValidatorHash "f") "Token" (TokenName "T1" :| [])

myToken2 :: KnownCurrency
myToken2 = KnownCurrency (ValidatorHash "f") "Token" (TokenName "T2" :| [])

mkKnownCurrencies ['myToken1, 'myToken2]

however if my code has this validation enabled
                 traceIfFalse "breeding not ended" breedingNotEnded

in the mkValidator
and if I add this on the claim side from the web part
P.<>
                          Constraints.mustValidateIn (from now)

I cannot claim tokens
I was running it in the plutus-playground-client but I cannot figure out what I'm doing wrong.
To compute deadline I used following command:
slotToEndPOSIXTime def 10
POSIXTime {getPOSIXTime = 1596059101999}

I use only one wallet and I'm gettings it's public key hash using this command:
mockWalletPaymentPubKeyHash $ knownWallet 1

First operation is breed.
Next I wait until slot 11.
Next operation is claim and after it I wait one slot.
Tokens are stay locked in the smart contract.
Logs:
Validating transaction: 0867c69e68ffc5825d6ef4d4fa2a8f2362dd78e22a2b51cadd2a6aaffcc5eea6
Add slot 1
Contract instance for W872cb83: (ReceiveEndpointCall (EndpointDescription { getEndpointDescription: "breed" }) (RawJson "{\"contents\":[{\"getEndpointDescription\":\"breed\"},{\"unEndpointValue\":{\"bpNft2\":{\"unTokenName\":\"T2\"},\"bpNftCurr1\":{\"unCurrencySymbol\":\"66\"},\"bpOwner\":{\"unPaymentPubKeyHash\":{\"getPubKeyHash\":\"a2c20c77887ace1cd986193e4e75babd8993cfd56995cd5cfce609c2\"}},\"bpDeadline\":1596059101999,\"bpPrice\":5000000,\"bpNft1\":{\"unTokenName\":\"T1\"},\"bpNftCurr2\":{\"unCurrencySymbol\":\"66\"}}}],\"tag\":\"ExposeEndpointResp\"}"))
Contract instance for W872cb83: (ContractLog (RawJson "{\"mkTxLogResult\":{\"Right\":{\"unBalancedTxTx\":{\"txData\":[[\"0661ffdf5634559c3239fcd8f84bd2ec83213c79bf94fde4c8ab537918000831\",\"d8799f581ca2c20c77887ace1cd986193e4e75babd8993cfd56995cd5cfce609c2425431416642543241661b000001739c892b2fff\"]],\"txInputs\":[],\"txRedeemers\":[],\"txOutputs\":[{\"txOutValue\":{\"getValue\":[[{\"unCurrencySymbol\":\"66\"},[[{\"unTokenName\":\"T1\"},1],[{\"unTokenName\":\"T2\"},1]]],[{\"unCurrencySymbol\":\"\"},[[{\"unTokenName\":\"\"},5000000]]]]},\"txOutAddress\":{\"addressStakingCredential\":null,\"addressCredential\":{\"contents\":\"6a94edbec4f04aae3b09dec9382f0f742413976728cad1e67715086c\",\"tag\":\"ScriptCredential\"}},\"txOutDatumHash\":\"0661ffdf5634559c3239fcd8f84bd2ec83213c79bf94fde4c8ab537918000831\"}],\"txValidRange\":{\"ivTo\":[{\"tag\":\"PosInf\"},true],\"ivFrom\":[{\"tag\":\"NegInf\"},true]},\"txMint\":{\"getValue\":[]},\"txFee\":{\"getValue\":[]},\"txCollateral\":[],\"txMintScripts\":[],\"txSignatures\":[]},\"unBalancedTxRequiredSignatories\":[],\"unBalancedTxValidityTimeRange\":{\"ivTo\":[{\"tag\":\"PosInf\"},true],\"ivFrom\":[{\"tag\":\"NegInf\"},true]},\"unBalancedTxUtxoIndex\":[]}},\"mkTxLogTxConstraints\":{\"txOwnInputs\":[],\"txOwnOutputs\":[{\"ocValue\":{\"getValue\":[[{\"unCurrencySymbol\":\"66\"},[[{\"unTokenName\":\"T1\"},1],[{\"unTokenName\":\"T2\"},1]]],[{\"unCurrencySymbol\":\"\"},[[{\"unTokenName\":\"\"},5000000]]]]},\"ocDatum\":\"d8799f581ca2c20c77887ace1cd986193e4e75babd8993cfd56995cd5cfce609c2425431416642543241661b000001739c892b2fff\"}],\"txConstraints\":[{\"contents\":\"d8799f581ca2c20c77887ace1cd986193e4e75babd8993cfd56995cd5cfce609c2425431416642543241661b000001739c892b2fff\",\"tag\":\"MustIncludeDatum\"}]},\"mkTxLogLookups\":{\"slOtherScripts\":[],\"slPaymentPubKeyHashes\":[],\"slOwnPaymentPubKeyHash\":null,\"slOwnStakePubKeyHash\":null,\"slOtherData\":[],\"slTypedValidator\":{\"tvForwardingMPSHash\":\"880b3b18ecc486c237105484b3557cd4a7dced9987da9ffb4f44a623\",\"tvForwardingMPS\":{\"getMintingPolicy\":\"mintingPolicyBytesRemovedOnPurpose\"},\"tvValidator\":{\"getValidator\":\"validatorBytesRemovedOnPurpose\"},\"tvValidatorHash\":\"6a94edbec4f04aae3b09dec9382f0f742413976728cad1e67715086c\"},\"slTxOutputs\":[],\"slMPS\":[[\"880b3b18ecc486c237105484b3557cd4a7dced9987da9ffb4f44a623\",{\"getMintingPolicy\":\"mintingPolicyBytesRemovedOnPurpose\"}]]}}"))
Validating transaction: e6095dc750a9d0786ff4b627d99239a3a9a1c8058839aad3a9019f74a352da72
Add slot 2
Contract instance for W872cb83: (ContractLog (RawJson "locked two tokens"))
Add slot 3
Add slot 4
Add slot 5
Add slot 6
Add slot 7
Add slot 8
Add slot 9
Add slot 10
Add slot 11
Contract instance for W872cb83: (ReceiveEndpointCall (EndpointDescription { getEndpointDescription: "claim" }) (RawJson "{\"contents\":[{\"getEndpointDescription\":\"claim\"},{\"unEndpointValue\":[]}],\"tag\":\"ExposeEndpointResp\"}"))
Contract instance for W872cb83: (ContractLog (RawJson "start claiming tokens"))
Contract instance for W872cb83: (ContractLog (RawJson "before submitTxConstraintsWith"))
Contract instance for W872cb83: (ContractLog (RawJson "{\"mkTxLogResult\":{\"Right\":{\"unBalancedTxTx\":{\"txData\":[[\"0661ffdf5634559c3239fcd8f84bd2ec83213c79bf94fde4c8ab537918000831\",\"d8799f581ca2c20c77887ace1cd986193e4e75babd8993cfd56995cd5cfce609c2425431416642543241661b000001739c892b2fff\"]],\"txInputs\":[{\"txInType\":{\"contents\":[{\"getValidator\":\"validatorBytesRemovedOnPurpose\"},\"d87980\",\"d8799f581ca2c20c77887ace1cd986193e4e75babd8993cfd56995cd5cfce609c2425431416642543241661b000001739c892b2fff\"],\"tag\":\"ConsumeScriptAddress\"},\"txInRef\":{\"txOutRefId\":{\"getTxId\":\"e6095dc750a9d0786ff4b627d99239a3a9a1c8058839aad3a9019f74a352da72\"},\"txOutRefIdx\":1}}],\"txRedeemers\":[],\"txOutputs\":[],\"txValidRange\":{\"ivTo\":[{\"tag\":\"PosInf\"},true],\"ivFrom\":[{\"tag\":\"NegInf\"},true]},\"txMint\":{\"getValue\":[]},\"txFee\":{\"getValue\":[]},\"txCollateral\":[],\"txMintScripts\":[],\"txSignatures\":[]},\"unBalancedTxRequiredSignatories\":[],\"unBalancedTxValidityTimeRange\":{\"ivTo\":[{\"tag\":\"PosInf\"},true],\"ivFrom\":[{\"contents\":1596059102999,\"tag\":\"Finite\"},true]},\"unBalancedTxUtxoIndex\":[[{\"txOutRefId\":{\"getTxId\":\"e6095dc750a9d0786ff4b627d99239a3a9a1c8058839aad3a9019f74a352da72\"},\"txOutRefIdx\":1},{\"scriptOutputValue\":{\"getValue\":[[{\"unCurrencySymbol\":\"66\"},[[{\"unTokenName\":\"T1\"},1],[{\"unTokenName\":\"T2\"},1]]],[{\"unCurrencySymbol\":\"\"},[[{\"unTokenName\":\"\"},5000000]]]]},\"scriptOutputValidatorHash\":\"6a94edbec4f04aae3b09dec9382f0f742413976728cad1e67715086c\",\"scriptOutputDatumHash\":\"0661ffdf5634559c3239fcd8f84bd2ec83213c79bf94fde4c8ab537918000831\"}]]}},\"mkTxLogTxConstraints\":{\"txOwnInputs\":[],\"txOwnOutputs\":[],\"txConstraints\":[{\"contents\":[{\"txOutRefId\":{\"getTxId\":\"e6095dc750a9d0786ff4b627d99239a3a9a1c8058839aad3a9019f74a352da72\"},\"txOutRefIdx\":1},\"d87980\"],\"tag\":\"MustSpendScriptOutput\"},{\"contents\":{\"ivTo\":[{\"tag\":\"PosInf\"},true],\"ivFrom\":[{\"contents\":1596059102999,\"tag\":\"Finite\"},true]},\"tag\":\"MustValidateIn\"}]},\"mkTxLogLookups\":{\"slOtherScripts\":[[\"6a94edbec4f04aae3b09dec9382f0f742413976728cad1e67715086c\",{\"getValidator\":\"validatorBytesRemovedOnPurpose\"}]],\"slPaymentPubKeyHashes\":[],\"slOwnPaymentPubKeyHash\":null,\"slOwnStakePubKeyHash\":null,\"slOtherData\":[],\"slTypedValidator\":null,\"slTxOutputs\":[[{\"txOutRefId\":{\"getTxId\":\"e6095dc750a9d0786ff4b627d99239a3a9a1c8058839aad3a9019f74a352da72\"},\"txOutRefIdx\":1},{\"_ciTxOutAddress\":{\"addressStakingCredential\":null,\"addressCredential\":{\"contents\":\"6a94edbec4f04aae3b09dec9382f0f742413976728cad1e67715086c\",\"tag\":\"ScriptCredential\"}},\"_ciTxOutValidator\":{\"Left\":\"6a94edbec4f04aae3b09dec9382f0f742413976728cad1e67715086c\"},\"_ciTxOutDatum\":{\"Right\":\"d8799f581ca2c20c77887ace1cd986193e4e75babd8993cfd56995cd5cfce609c2425431416642543241661b000001739c892b2fff\"},\"_ciTxOutValue\":{\"getValue\":[[{\"unCurrencySymbol\":\"66\"},[[{\"unTokenName\":\"T1\"},1],[{\"unTokenName\":\"T2\"},1]]],[{\"unCurrencySymbol\":\"\"},[[{\"unTokenName\":\"\"},5000000]]]]},\"tag\":\"ScriptChainIndexTxOut\"}]],\"slMPS\":[]}}"))
Add slot 12

This line can be a bit confusing in order to debug:
then logInfo @P.String $ "no breeding finished yet"
Better use:
"no gifts available" as a message.

After reproducing the scenario in my local playground, I've checked that the error comes from the fact that the last action is Wait For 1 slot. If you set Wait For 2 instead, you will able to grab the assets.
Honestly, I don't know why setting Wait For 1 slot doesn't work.

Even if correct, this answer is an opportunity for somebody to write a better one.  It was auto-flagged as likely to be insufficient.  Would be much better if it actually spelt out what you mean.  Looks more like advice than an answer to the question.

@gRebel you are right. It should have been a comment better than a answer.


text:
Updating counter on the extended UTXO
I would like to be able to update state on the token that is locked in the smart contract address.
My assumption was that using below code
    getLockingDatum :: Maybe LockingDatum
    getLockingDatum = let os = [ o | o <- txInfoOutputs info, valueOf (txOutValue o) cs tn == 1 ] in
        case os of
        [o] -> lockingDatum o (`findDatum` info)
        _   -> Nothing

    checkIfCounterWasUpdated :: Bool
    checkIfCounterWasUpdated = case getLockingDatum of
        Nothing -> False
        Just ld -> owner     ld      == owner    dat &&
                   currency ld       == currency dat &&
                   token    ld       == token    dat
            -- &&   (counter  ld) + 1 == (counter  dat)

I should be able to take old datum and compared with the incoming one.
However if I uncomment line
-- &&   (counter  ld) + 1 == (counter  dat)
I'm getting this exception:
EvaluationError [\"counter was updated by more than one\",\"PT5\"]
{-# LANGUAGE DataKinds             #-}
{-# LANGUAGE DeriveAnyClass        #-}
{-# LANGUAGE DeriveGeneric         #-}
{-# LANGUAGE FlexibleContexts      #-}
{-# LANGUAGE NoImplicitPrelude     #-}
{-# LANGUAGE OverloadedStrings     #-}
{-# LANGUAGE ScopedTypeVariables   #-}
{-# LANGUAGE TemplateHaskell       #-}
{-# LANGUAGE TypeApplications      #-}
{-# LANGUAGE TypeFamilies          #-}
{-# LANGUAGE TypeOperators         #-}
{-# LANGUAGE NumericUnderscores    #-}
{-# LANGUAGE MultiParamTypeClasses #-}

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

module Week04.Homework where

import           Control.Monad.Freer.Extras as Extras
import           Control.Monad        hiding (fmap)
import           Data.Aeson           (ToJSON, FromJSON)
import           Data.Map             as Map
import           Data.Text            (Text)
import           Data.Default
import           Data.Void            (Void)
import           GHC.Generics         (Generic)
import           Plutus.Contract            as Contract
import           PlutusTx             (Data (..))
import qualified PlutusTx
import           PlutusTx.Prelude     hiding (Semigroup(..), unless)
import           Ledger               hiding (singleton)
import           Ledger.Constraints   (TxConstraints)
import           Ledger.TimeSlot
import qualified Ledger.Constraints   as Constraints
import qualified Ledger.Typed.Scripts as Scripts
import           Ledger.Ada           as Ada
import           Ledger.Value         as Value
import           Playground.Contract  (printJson, printSchemas, ensureKnownCurrencies, stage, ToSchema)
import           Playground.Contract
import           Playground.TH        (mkKnownCurrencies, mkSchemaDefinitions)
import           Playground.Types     (KnownCurrency (..))
import           Prelude              (IO, Semigroup (..), Show (..), String)
import           Text.Printf          (printf)
import           Plutus.Trace.Emulator as Emulator
import           Wallet.Emulator.Wallet
import           Wallet.Emulator.Wallet (Wallet(..))
import           Plutus.V1.Ledger.Value
import           Plutus.Trace.Emulator (EmulatorTrace, EmulatorConfig(..), runEmulatorTraceIO',
                              activateContractWallet)
-- import           Plutus.ChainIndex.Tx ( ChainIndexTx(_citxData) )
import Plutus.ChainIndex.Tx
data BreedAction = Grab | Update
    deriving (Generic, ToJSON, FromJSON)
PlutusTx.makeIsDataIndexed ''BreedAction [ ('Grab,      0)
                                         , ('Update,    1)
                                        ]
PlutusTx.makeLift ''BreedAction

data LockingDatum = LockingDatum
    { owner       :: PaymentPubKeyHash
    , deadline    :: POSIXTime
    , currency    :: CurrencySymbol
    , token       :: TokenName
    , counter     :: Integer
    } deriving Show

PlutusTx.unstableMakeIsData ''LockingDatum

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

{-# INLINABLE mkValidator #-}
mkValidator :: LockingDatum -> BreedAction -> ScriptContext -> Bool
mkValidator dat ba ctx = case ba of
        Grab ->
            traceIfFalse "owner's signature missing" signedByowner &&
            traceIfFalse "deadline not reached" deadlineReached
        Update ->
            traceIfFalse "owner's signature missing" signedByowner &&
            traceIfFalse "counter was updated by more than one" checkIfCounterWasUpdated &&
            traceIfFalse "NFT left the script" checkContinuingNFT
  where
    info :: TxInfo
    info = scriptContextTxInfo ctx

    signedByowner :: Bool
    signedByowner = txSignedBy info $ unPaymentPubKeyHash $ owner dat

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

    tn :: TokenName
    tn = token dat

    cs :: CurrencySymbol
    cs = currency dat

    getLockingDatum :: Maybe LockingDatum
    getLockingDatum = let os = [ o | o <- txInfoOutputs info, valueOf (txOutValue o) cs tn == 1 ] in
        case os of
        [o] -> lockingDatum o (`findDatum` info)
        _   -> Nothing

    checkIfCounterWasUpdated :: Bool
    checkIfCounterWasUpdated = case getLockingDatum of
        Nothing -> False
        Just ld -> owner     ld      == owner    dat &&
                   currency ld       == currency dat &&
                   token    ld       == token    dat
            -- &&   (counter  ld) + 1 == (counter  dat)

    checkContinuingNFT :: Bool
    checkContinuingNFT = let cos = [ co | co <- getContinuingOutputs ctx, valueOf (txOutValue co) cs tn == 1 ] in
        case cos of
            [_] -> True
            _   -> False

data Locking
instance Scripts.ValidatorTypes Locking where
    type instance DatumType Locking = LockingDatum
    type instance RedeemerType Locking = BreedAction

typedValidator :: Scripts.TypedValidator Locking
typedValidator = Scripts.mkTypedValidator @Locking
    $$(PlutusTx.compile [|| mkValidator ||])
    $$(PlutusTx.compile [|| wrap ||])
  where
    wrap = Scripts.wrapValidator @LockingDatum @BreedAction

validator :: Validator
validator = Scripts.validatorScript typedValidator

valHash :: Ledger.ValidatorHash
valHash = Scripts.validatorHash typedValidator

scrAddress :: Ledger.Address
scrAddress = scriptAddress validator

data LockParams = LockParams
    { lpOwner :: !PaymentPubKeyHash
    , lpDeadline    :: !POSIXTime
    , lpAmount      :: !Integer
    , lpCurrency    :: !CurrencySymbol
    , lpToken       :: !TokenName
    , lpCounter     :: !Integer
    } deriving (Generic, ToJSON, FromJSON, ToSchema)

type LockingSchema =
            Endpoint "lock" LockParams
            .\/ Endpoint "grab" ()
            .\/ Endpoint "updcntr" LockParams

lock :: AsContractError e => LockParams -> Contract w s e ()
lock lp = do
    Contract.logInfo @String $ printf "starting"
    let dat = LockingDatum
                { owner       = lpOwner lp
                , deadline    = lpDeadline lp
                , currency    = lpCurrency lp
                , token       = lpToken lp
                , counter     = lpCounter lp
                }
        val = Ada.lovelaceValueOf (lpAmount lp) <> Value.singleton (lpCurrency lp) (lpToken lp) 1
        tx  = Constraints.mustPayToTheScript dat val
    ledgerTx <- submitTxConstraints typedValidator tx
    void $ awaitTxConfirmed $ getCardanoTxId ledgerTx
    Contract.logInfo @String $ printf "locked %d lovelace by %s with deadline %s"
        (lpAmount lp)
        (show $ lpOwner lp)
        (show $ lpDeadline lp)

grab :: forall w s e. AsContractError e => Contract w s e ()
grab = do
    now   <- currentTime
    pkh   <- ownPaymentPubKeyHash
    utxos <- Map.filter (isSuitable pkh now) <$> utxosAt scrAddress
    if Map.null utxos
        then Contract.logInfo @String $ "nothing is locked " ++ show scrAddress
        else do
            let orefs   = fst <$> Map.toList utxos
                lookups = Constraints.unspentOutputs utxos  <>
                          Constraints.otherScript validator
                tx :: TxConstraints Void Void
                tx      = mconcat [Constraints.mustSpendScriptOutput oref $ Redeemer $ PlutusTx.toBuiltinData Grab | oref <- orefs] <>
                          Constraints.mustValidateIn (from now)
            ledgerTx <- submitTxConstraintsWith @Void lookups tx
            Contract.logInfo @String $ "[Grab redeemer] collected locked tokens: " ++ show scrAddress
            void $ awaitTxConfirmed $ getCardanoTxId ledgerTx
  where
    isSuitable :: PaymentPubKeyHash -> POSIXTime -> ChainIndexTxOut -> Bool
    isSuitable pkh now o = case _ciTxOutDatum o of
        Left _          -> False
        Right (Datum e) -> case PlutusTx.fromBuiltinData e of
            Nothing -> False
            Just d  -> owner d == pkh && deadline d <= now

updcntr :: forall w s e. AsContractError e => LockParams -> Contract w s e ()
updcntr lp = do
    tkn   <- findLocked (lpCurrency lp, lpToken lp)
    case tkn of
        Nothing -> Contract.logError @String "No token was locked"
        Just (oref, o, lockedDat) -> do
            let r       = Redeemer $ PlutusTx.toBuiltinData Update
                val     = Value.singleton (currency lockedDat) (token lockedDat) 1 <> Ada.lovelaceValueOf (lpAmount lp)
                newCounter  = (counter lockedDat) + 1
                lockedDat'   = lockedDat { counter = newCounter }
                lookups = Constraints.typedValidatorLookups typedValidator <>
                          Constraints.otherScript validator                    <>
                          Constraints.unspentOutputs (Map.singleton oref o)
                tx      = Constraints.mustSpendScriptOutput oref r <>
                          Constraints.mustPayToTheScript lockedDat' val
            Contract.logInfo $ "Updating counter old datum: " ++ show lockedDat ++ " new datum: " ++ show lockedDat'
            ledgerTx <- submitTxConstraintsWith lookups tx
            void $ awaitTxConfirmed $ getCardanoTxId ledgerTx
            Contract.logInfo @String "Counter was updated"

findLocked :: forall w s e. AsContractError e => (CurrencySymbol, TokenName) -> Contract w s e (Maybe (TxOutRef, ChainIndexTxOut, LockingDatum))
findLocked (cs, tn) = do
    utxos <- Map.filter f <$> utxosTxOutTxAt scrAddress
    return $ case Map.toList utxos of
        [(oref, (o, citx))] -> do
            bd <- lockingDatum (toTxOut o) $ \dh -> Map.lookup dh $ _citxData citx
            Just (oref, o, bd)
        _           -> Nothing

  where
    f :: (ChainIndexTxOut, Plutus.ChainIndex.Tx.ChainIndexTx) -> Bool
    f (o, _) = valueOf (txOutValue $ toTxOut o) cs tn == 1

endpoints :: Contract () LockingSchema Text ()
endpoints = awaitPromise (lock' `select` grab' `select` updcntr') >> endpoints
  where
    lock' = endpoint @"lock" lock
    grab' = endpoint @"grab" $ const grab
    updcntr' = endpoint @"updcntr" updcntr

mkSchemaDefinitions ''LockingSchema

myToken :: KnownCurrency
myToken = KnownCurrency (ValidatorHash "f") "Token" (TokenName "T" :| [])

mkKnownCurrencies ['myToken]

testTrace :: Integer -> EmulatorTrace ()
testTrace lov = do
    end <- activateContractWallet (knownWallet 1) endpoints
    let ownWallet = knownWallet 1
        ownPkh       = mockWalletPaymentPubKeyHash ownWallet
        d           = slotToEndPOSIXTime def 10
        pp  = LockParams {
                      lpOwner = ownPkh
                    , lpDeadline = d
                    , lpAmount = lov
                    , lpCurrency = CurrencySymbol { unCurrencySymbol = "f"}
                    , lpToken    = TokenName { unTokenName = "T" }
                    , lpCounter  = 0
                    }

        pp1  = LockParams {
                      lpOwner = ownPkh
                    , lpDeadline = d
                    , lpAmount = lov
                    , lpCurrency = CurrencySymbol { unCurrencySymbol = "f"}
                    , lpToken    = TokenName { unTokenName = "T" }
                    , lpCounter  = 1
                    }

    Extras.logInfo $ "ownerPkh: " ++ show ownPkh ++ " wallet: " ++ show ownWallet ++ " params: "

    callEndpoint @"lock" end pp
    void $ Emulator.waitNSlots 12

    Extras.logInfo @String "calling updcntr for first time"
    callEndpoint @"updcntr" end pp1
    void $ Emulator.waitNSlots 1
    Extras.logInfo @String "called updcntr for first time"

    -- Extras.logInfo @String "calling updcntr for second time"
    -- callEndpoint @"updcntr" end pp2
    -- void $ Emulator.waitNSlots 1
    -- Extras.logInfo @String "calling updcntr for second time"

testLock :: IO ()
testLock = do
    let curr = CurrencySymbol { unCurrencySymbol = "f"}
        tok  = TokenName { unTokenName = "T"}
        dist = Map.fromList [ (knownWallet 1, Ada.lovelaceValueOf 100_000_000 <> Value.singleton curr tok 1)
                             , (knownWallet 2, Ada.lovelaceValueOf 25_000_000)]
        emCfg = EmulatorConfig (Left dist) def def
    runEmulatorTraceIO' def emCfg (testTrace 15_000_000)

any idea what I'm doing wrong?

From what I see in your code I understand that you want to check that the new datum increases the counter of the old datum in 1. If this statement is correct, the fix is easy.
checkIfCounterWasUpdated :: Bool
checkIfCounterWasUpdated = case getLockingDatum of
    Nothing -> False
    Just ld -> owner ld   == owner    dat &&
        currency ld       == currency dat &&
        token    ld       == token    dat &&
     -- (counter  ld) + 1 == (counter  dat)
     -- (counter  ld)     == (counter  dat) + 1  -- This works
        counter  ld       == succ (counter dat)  -- This works and it's more idiomatic

I've tested it and it works.
As a side note, I'd say that your use case fits great with the Plutus.Contract.StateMachine library.

source: Stack Exchange

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

sort: votes


text:
Can't start Cardano Node
I have a node that I had run a few months ago and then stopped using for a long time, a few days ago I decided to start the node again, the node started syncing with no issues but midway trough it all the Terminal app (I'm using a Mac) stopped responding, so after seeing it for a while like that (and after all the other apps stopped responding too) I decided to turn off the computer thinking I could start the process again, but then today I got this:
[yeshco:cardano.node.ChainDB:Info:5] [2022-02-01 00:39:49.68 UTC] Opened imm db with immutable tip at 9ff948e88999a5de60fa92694c55e764ef4b3985dbcf1c88d7442fdcca576ed4 at slot 40555639 and chunk 1877

Shutting down..
FsError {fsErrorType = FsResourceDoesNotExist, fsErrorPath = /Volumes/2T WD NEGRO/Crypto/Cardano/db/volatile/blocks-6266.dat, fsErrorString = "No such file or directory", fsErrorNo = Just (Errno 2), fsErrorStack = CallStack (from HasCallStack):
  prettyCallStack, called at src/Ouroboros/Consensus/Storage/FS/API/Types.hs:297:23 in rbrs-cnsnss-0.1.0.0-0b62aa4c:Ouroboros.Consensus.Storage.FS.API.Types
  ioToFsError, called at src/Ouroboros/Consensus/Storage/FS/IO.hs:88:41 in rbrs-cnsnss-0.1.0.0-0b62aa4c:Ouroboros.Consensus.Storage.FS.IO
  handleError, called at src/Ouroboros/Consensus/Storage/FS/IO.hs:84:23 in rbrs-cnsnss-0.1.0.0-0b62aa4c:Ouroboros.Consensus.Storage.FS.IO
  rethrowFsError, called at src/Ouroboros/Consensus/Storage/FS/IO.hs:37:21 in rbrs-cnsnss-0.1.0.0-0b62aa4c:Ouroboros.Consensus.Storage.FS.IO
  hOpen, called at src/Ouroboros/Consensus/Storage/FS/API.hs:152:43 in rbrs-cnsnss-0.1.0.0-0b62aa4c:Ouroboros.Consensus.Storage.FS.API
  withFile, called at src/Ouroboros/Consensus/Util/CBOR.hs:227:7 in rbrs-cnsnss-0.1.0.0-0b62aa4c:Ouroboros.Consensus.Util.CBOR
  withStreamIncrementalOffsets, called at src/Ouroboros/Consensus/Storage/VolatileDB/Impl/Parser.hs:67:5 in rbrs-cnsnss-0.1.0.0-0b62aa4c:Ouroboros.Consensus.Storage.VolatileDB.Impl.Parser, fsLimitation = False}

cardano-node: FsResourceDoesNotExist for /Volumes/2T WD NEGRO/Crypto/Cardano/db/volatile/blocks-6266.dat: No such file or directory at CallStack (from HasCallStack):
  prettyCallStack, called at src/Ouroboros/Consensus/Storage/FS/API/Types.hs:297:23 in rbrs-cnsnss-0.1.0.0-0b62aa4c:Ouroboros.Consensus.Storage.FS.API.Types
  ioToFsError, called at src/Ouroboros/Consensus/Storage/FS/IO.hs:88:41 in rbrs-cnsnss-0.1.0.0-0b62aa4c:Ouroboros.Consensus.Storage.FS.IO
  handleError, called at src/Ouroboros/Consensus/Storage/FS/IO.hs:84:23 in rbrs-cnsnss-0.1.0.0-0b62aa4c:Ouroboros.Consensus.Storage.FS.IO
  rethrowFsError, called at src/Ouroboros/Consensus/Storage/FS/IO.hs:37:21 in rbrs-cnsnss-0.1.0.0-0b62aa4c:Ouroboros.Consensus.Storage.FS.IO
  hOpen, called at src/Ouroboros/Consensus/Storage/FS/API.hs:152:43 in rbrs-cnsnss-0.1.0.0-0b62aa4c:Ouroboros.Consensus.Storage.FS.API
  withFile, called at src/Ouroboros/Consensus/Util/CBOR.hs:227:7 in rbrs-cnsnss-0.1.0.0-0b62aa4c:Ouroboros.Consensus.Util.CBOR
  withStreamIncrementalOffsets, called at src/Ouroboros/Consensus/Storage/VolatileDB/Impl/Parser.hs:67:5 in rbrs-cnsnss-0.1.0.0-0b62aa4c:Ouroboros.Consensus.Storage.VolatileDB.Impl.Parser

And I can't sync it.
I would be very thankful if somebody can help!

The first thing I'd check is if your disk is full. A lot of unix programs will error failing to create a file because there's no disk space and report it as no such file or directory...
The next thing would be that the user running node has permission to write to the state directories. If you ran it as a service user in the past and now are running it as your normal user (or if you did something bad like running node with sudo), fixing permissions with chown might do the trick.
Next thing I'd do is update the node to latest and remove only the ledger and volatile directories. This will force a ledger rebuild that could take a while, so just be patient. While it's doing the rebuild if it detects any corruption in immutable the node should truncate to that point and start syncing. Leaving immutable will significantly reduce sync time if there's no corruption early in the chain data.

Thanks!, I was going to ask this before but how do you update the node, I tried to clone the repository again on a copy I made but my node is still 1.29.0?

It looks like the on disk storage is corrupted. If you also have not run it in a couple of months you probably need to upgrade your node version.
Upgrading the software may help with the other problem, otherwise delete all the storage and resync the node.

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


text:
Failed to automate entering spending passphrase through 'cardano-cli'
I have been experimenting with cardano-cli in the past week. My goal is to find a way to automate sending transactions from multiple wallets in my Daedalus Mainnet.app.
After doing some research, I found: Bash script to send the transaction through cardano-cli. So I followed the instructions on GitHub, and everything was successful.
From here on out, sending transactions from multiple wallets is easy, as I only need to run the function daedalus-cli-send-tx numerous times with different arguments each time. Here's what I've got so far:
$ cat test.sh

#!/bin/bash
echo Please enter sender address:
read sender
echo $sender

daedalus-cli-send-tx wallet1 1000000 $sender #sending from wallet1 with 1ADA to sender
daedalus-cli-send-tx wallet2 1000000 $sender #sending from wallet2 with 1ADA to sender

And I also made a text file to redirect my input from test.sh to this input file:
$ cat input
addr1q8sypyrh63y6pgjq0ys0j7rkj2qjun6wnq4haj9d945d9cqu7krtq8wjazqvqxmtmmmyx20kuftmg0578npzdpy3vkasyjn3p3 #sender address
8736867242 #wallet1 passphrase
1932862497 #wallet2 passphrase

But when I redirect my input, here's what I get:
$ source ~/test.sh < input

Please enter sender address:
addr1q8sypyrh63y6pgjq0ys0j7rkj2qjun6wnq4haj9d945d9cqu7krtq8wjazqvqxmtmmmyx20kuftmg0578npzdpy3vkasyjn3p3
Please enter your passphrase: **********
The given encryption passphrase doesn't match the one I use to encrypt the root private key of the given wallet: 890483bc9ec5c5bfc7d612d9cad885df199c3533
Please enter your passphrase: cardano-wallet: <stdin>: hGetChar: end of file

Note that I purposely used a wrong passphrase for both transactions, but the first one actually read the input from the text file, so that isn't the problem. The problem lies in that the second transaction asked for a passphrase, yet it returned this line:
Please enter your passphrase: cardano-wallet: <stdin>: hGetChar: end of file

Even though the input textfile supplies both passphrases.
I have very little knowledge of shell script, so I am asking for help here. What is this error cardano-wallet: <stdin>: hGetChar: end of file (AFAIK it is because the input was not captured), and how do I actually automate entering my passphrase when prompt?

In shell scripting, for something like this you want to use expect and send. Here's an example of how we use it for cardano-faucet: https://github.com/input-output-hk/cardano-faucet/blob/master/nix/nixos/create-faucet-wallet/create-faucet-wallet.sh#L69-L70

Hi this is a fairly common problem in bash. It has nothing to do with Cardano-cli and can be thought of as the general problem of automating password-based authentication for applications via bash scripts.
I did something similar to this using https://stackoverflow.com/questions/67570700/how-do-i-automate-a-remote-login-with-a-bash-script
if you have any problems feel free to reach out I will happily take a look at your code and fix the bug.


text:
Decrypt data with wallet private key
If data is encrypted using the public key from a wallet is there a way to decrypt that data using the private key of the wallet? I am essentially looking for the inverse of signData from CIP-0030. I'd like to encrypt a payload using the public key and then allow the user to decrypt it with their private key.

Please have a look at https://crypto.stackexchange.com/questions/83266/why-are-ed25519-keys-not-recommended-for-encryption

@Fermat thank you for the link as it was very helpful. What I had in mind was https://en.wikipedia.org/wiki/ElGamal_encryption where the key generation had already occurred when the wallet was created. From the answer in the link you posted, it looks like that should work fine or am I misreading that?

I am familiar with El-Gamal (look at https://github.com/fermatspace/el-gamal-onchain for a small experiment onchain). The problem with key generation in the wallet is that it uses Ed25519 keys (El-gamal uses big integers). Now of course you could convert the Ed25519 binary representation of a key to an integer to fix this, but you will have to build the tools.

@Fermat thank you again. It is very cool that you already put together a little proof-of-concept for El-Gamal encryption on chain. Converting the binary representation of the Ed25519 key to an integer makes sense and I have no problem building the tools to do all this. Thank you for your help!

No problem! Looking forward to your implementation :) Hope you open source it!

There is a difference in encryption and signing.

Signing is the act of providing a piece of evidence alongside data that prove that the information is processed with a particular signing key. Given a public corresponding to the singing private key you can check if the data is aproved by that public key.

Encryption is the act of obscuring data to make it not readable. Depending on what type of encryption you use, symmetric vs asymmetric, one can encrypt the data with a private key or public key. Decrypting can only be done with the private key.

Cardano's wallets use an elliptic curve signature scheme (1). Note that this can not encrypt data! It can only create signatures, you can verify signatures onchain with, for example (2). If you want to encrypt some data, you have to use another scheme (like the mentioned El-Gamal encryption scheme).


text:
What are the current options for spending a UTxO at a script address?
If the following script is protecting a UTxO
{
    "type": "all",
    "scripts": [
        {
            "type": "after",
            "slot": 1000
        },
        {
            "type": "sig",
            "keyHash": "..."
        }
    ]
}

and the slot has passed and I have the private key specified by the keyHash property, what are my options for spending a UTxO sitting at the script address?
I know that I can use cardano-cli to manually build a transaction that sends the UTxO to a wallet address I own, provide my key as a witness for the transaction and then submit it.
I am fine with doing this but are there any other "user friendly" options for spending this UTxO for users not wanting to use the cli?
I was hoping to find something that might allow me to tell my wallet about this script address and then have the wallet either track this address or build the transaction to "spend" the UTxO into a wallet address. I understand there could be difficulties around this for scripts requiring multiple signatures, etc. but am just looking for other currently available options.

To be user friendly, such features would have to be implemented in wallet software like Daedalus, Nami, Eternl, etc. In principle, there is no reason why this can't be done, in fact I'd imagine someone out there has already written some simple wrapper scripts that simplify the CLI workflow. However, for real user friendliness, we'd have to wait for someone with the right shovel to come along.

Thank you. That's what I figured but wanted to see if maybe I had missed something in my research. You have been very helpful in my Cardano journey and I really appreciate it.


text:
Multi-signature time-locking script
I am trying to create a multi-signature time locking script similar to this example. I want to lock assets into a script to be released at a later date.
{
    "type": "all",
    "scripts": [
        {
            "type": "after",
            "slot": 55596400
        },
        {
            "type": "sig",
            "keyHash": "..."
        }
    ]
}

According to the docs linked above, I have to add the --invalid-before [slot] argument, where slot is greater than or equal to the value specified in my script (55596400 in my example). By doing that, I cannot submit the transaction until that slot number.
I was hoping to be able to lock the assets into a script address that could then be redeemed by the holder of the key specified in the script after the given slot. So my questions are:

Is that not possible with a multisig script?
If not, what is the purpose of a time-locked multisig script? I guess I could give the assembled transaction with the needed witness off-chain, but then nothing prevents me from spending the assets before the given slot.
Is there a way to do what I'm wanting to do?

It is possible
The script used in the above example is used to construct an address from which funds UTXOs can only be used if they follow the logic specified by the script.
Looks like you've already done it! Just continue following the instructions in your linked example for creating and funding the script address. Be sure to test with a round trip before committing any large funds!

Thank you! I was running into an error that looked exactly like this https://forum.cardano.org/t/transaction-submit-error-on-testnet-for-time-locked-policy-script/57449 and got off the path. I was just witnessing with the wrong key. :( I appreciate you confirming that what I was wanting to do is possible and for pointing me in the right direction.


text:
Why does my testnet wallet "disappear"?
I have an instance of Cardano Wallet running and pointing at testnet. I create/restore a wallet like this:
curl -v -H "Content-Type: application/json" -d '{"name":"My Wallet","mnemonic_sentence":["..."],"passphrase":"..."}' https://myserver.dev/cardano-wallet/v2/wallets

and get a successful response back, which includes a valid walletId.
For a few minutes, I can successfully query the API using this walletId. If I hit the /wallets/{walletId}/addresses endpoint, I get back a list of 20 unused addresses, as expected. However, after a short time (I haven't found the exact time but it seems to be around 5 minutes) I start to get a 404 with a response body similar to:
{"code":"no_such_wallet","message":"I couldn't find a wallet with the given id: ..."}

Is this expected behavior? Is there something else I need to do to ensure the wallet can be found when I need to "create" addresses for it? I know I could always just "restore" it before executing an operation against the wallet, but this seems like it would add a lot of extra potentially unnecessary requests.

After writing the question, I realized that maybe it was my instance of Cardano Wallet that was the problem. I checked the logs and it looks like the problem is two-fold: 1) I only allocated 1G of memory for the Cardano Wallet Docker container and it was being killed by the OOM killer. 2) I didn't have the wallet db mapped to a persistent volume, so whenever the container was restarted, I would lose my wallet.
So it doesn't appear that this is expected behavior. Host the Cardano Wallet API correctly and you shouldn't have this issue.


text:
"You may need to update to a newer hackage.nix" when trying to enter a nix-shell
I am trying to update the packages in my plutus app to the newest version of the PAB. I am by no means an expert with nix or cabal, or any haskell package managers for that matter. I can't seem to figure out how to update hackage.nix, like the error says to do.
>>>  nix-shell
trace: haskell-nix.haskellLib.cleanGit: /Users/{...} does not seem to be a git repository,
assuming it is a clean checkout.
error: Unknown index-state 2022-01-22T00:00:00Z, the latest index-state I know about is 2021-08-15T00:00:00Z.
You may need to update to a newer hackage.nix.
(use '--show-trace' to show detailed location information)

>>>  nix-shell --show-trace
trace: haskell-nix.haskellLib.cleanGit: /Users/{...} does not seem to be a git repository,
assuming it is a clean checkout.
error: Unknown index-state 2022-01-22T00:00:00Z, the latest index-state I know about is 2021-08-15T00:00:00Z. You may need to update to a newer hackage.nix.

       … while evaluating anonymous lambda

       at /nix/store/8n76c1c3nz2wl6dzxmxdz2y5xrx70flw-source/lib/call-cabal-project-to-nix.nix:9:1:

            8| in
            9| { name          ? src.name or null # optional name for better error messages
             | ^
           10| , src

       … from call site

       at /nix/store/8n76c1c3nz2wl6dzxmxdz2y5xrx70flw-source/overlays/haskell.nix:487:36:

          486|               args = { caller = "cabalProject'"; } // args';
          487|               callProjectResults = callCabalProjectToNix args;
             |                                    ^
          488|               plan-pkgs = importAndFilterProject {

       … while evaluating anonymous lambda

       at /nix/store/8n76c1c3nz2wl6dzxmxdz2y5xrx70flw-source/lib/import-and-filter-project.nix:5:1:

            4| { pkgs, haskellLib }:
            5| { projectNix, sourceRepos, src }:
             | ^
            6| let

       … from call site

       at /nix/store/8n76c1c3nz2wl6dzxmxdz2y5xrx70flw-source/overlays/haskell.nix:488:27:

          487|               callProjectResults = callCabalProjectToNix args;
          488|               plan-pkgs = importAndFilterProject {
             |                           ^
          489|                 inherit (callProjectResults) projectNix sourceRepos src;

       … while evaluating the attribute 'hsPkgs'

       at /nix/store/8n76c1c3nz2wl6dzxmxdz2y5xrx70flw-source/overlays/haskell.nix:510:43:

          509|               project = addProjectAndPackageAttrs rec {
          510|                   inherit (pkg-set.config) hsPkgs;
             |                                           ^
          511|                   inherit pkg-set;

       … while evaluating the attribute 'hsPkgs'

       at /nix/store/8n76c1c3nz2wl6dzxmxdz2y5xrx70flw-source/overlays/haskell.nix:533:15:

          532|               # Haskell packages
          533|               hsPkgs = final.lib.mapAttrs (packageName: package':
             |               ^
          534|                 if package' == null

       … while evaluating 'project'

       at /nix/store/8n76c1c3nz2wl6dzxmxdz2y5xrx70flw-source/overlays/haskell.nix:836:19:

          835|         # for `cabalPackage` and `stackPackage`.
          836|         project = args: let p = project' args;
             |                   ^
          837|           in p.hsPkgs // p;

       … from call site

       at /Users/{...}/nix/pkgs/haskell/haskell.nix:12:13:

           11| let
           12|   project = haskell-nix.project {
             |             ^
           13|     # 'cleanGit' cleans a source directory based on the files known by git

       … while evaluating anonymous lambda

       at /Users/{...}/nix/pkgs/haskell/haskell.nix:4:1:

            3| ############################################################################
            4| { haskell-nix
             | ^
            5| , gitignore-nix

       … from call site

       at /Users/{...}/nix/pkgs/haskell/default.nix:24:13:

           23|   # The haskell project created by haskell-nix.cabalProject'
           24|   project = import ./haskell.nix {
             |             ^
           25|     inherit lib haskell-nix compiler-nix-name gitignore-nix libsodium-vrf;

       … while evaluating the attribute 'project.shellFor'

       at /Users/{...}/nix/pkgs/haskell/default.nix:35:10:

           34| rec {
           35|   inherit project projectPackages packages;
             |          ^
           36| }

I found the hackage.nix repository located at https://github.com/input-output-hk/hackage.nix. It seems that somehow this needs to be used to update it using nix-tools, located at https://github.com/input-output-hk/nix-tools.
I have very limited experience using nix or other haskell package managers so upgrading hackage.nix has been a blocker for me.
If someone can provide any guidance, or even better, a step by step of how to update hackage.nix, that would be greatly appreciated.
Thanks

Did you resolve this error? I met this error.

Try installing niv and running niv update hackage-nix from the root of the repository.


text:
zsh: exec format error: cardano-node on MacOS BigSur

I'm getting this zsh: exec format error: cardano-node
I ran file $(command -v cardano-node)
This returned the following
/usr/local/bin/cardano-node: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, stripped
this looks to be correct. So why am I getting "exec format error"
Any help de-bugging would be greatly appreciated.

Did you install an already build binary or did you build the binary from source? The M1 processors also tend to have slight differences.
For mac I would recommend building your own binaries. This is probably the safest besides also checking a checksum or hash of the already built binaries.
Here's an instructional link on how to build cardano-node and cardano-cli from source:
Building from source on MacOS

Thank you for the response as it turned out my server instance did not have enough RAM, after upgrading to 16 GB my issues where resolved.

Did you compile it on that architecture and version of MacOS?
Can only check for you against version 1.33 compiled on Ubuntu which reports a few of differences which might point to the way you compiled?
ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 3.2.0, BuildID[sha1]=b832d0d517ddc9b6e4d692d4cb2fb6663136e8ae, with debug_info, not stripped

Thank you for the reply, I'm running this on MacOs BigSur I have an intel i7 processor on the mac. So it is 64 bit is there something else I need to check?  I did the Brew install  with cardano-node version 1.33.0


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

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

As the error says:

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

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

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

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

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

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

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

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

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

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

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

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


text:
How long will it takes a cardano node to fully sync?
I have startted my cardano node with this command.
cardano-node run \
--config $HOME/cardano/testnet-config.json \
--database-path $HOME/cardano/db/ \
--socket-path $HOME/cardano/db/node.socket \
--host-addr 127.0.0.1 \
--port 1337 \
--topology $HOME/cardano/testnet-topology.json

Now what i can see in my terminal is this.
dk-Latit:cardano.node.ChainDB:Notice:142] [2022-02-15 08:42:59.71 UTC] Chain extended, new tip: 4ec48842a96990c32bcc0bb3fa99037d12c70228df6a57bec7e273c9fb5789f8 at slot 45502922
[dk-Latit:cardano.node.ChainDB:Notice:142] [2022-02-15 08:43:01.05 UTC] Chain extended, new tip: 001df73cc6c3f531d4bb304ec579ccf4323811aa9f2404865684fa65554c3bfd at slot 45503205
[dk-Latit:cardano.node.ChainDB:Notice:142] [2022-02-15 08:43:03.18 UTC] Chain extended, new tip: 601a92bdbbc85fd99b8108780419b9716ce74379ad39dffed21d8753cc3d067f at slot 45503277
[dk-Latit:cardano.node.ChainDB:Notice:142] [2022-02-15 08:43:04.53 UTC] Chain extended, new tip: ffe4eeeb00529dbf0b031f6822c33dc3c93c68c02c22b01f709c2f3cf6cd7e44 at slot 45503504
[dk-Latit:cardano.node.ChainDB:Notice:1

How long am i supposed to see this? Is there any way to check whether the node is fully synced or not or what percentage its got synced?

When you accept an answer, you should also up-vote it.  ;-)  Let's build this community.

Testnet should sync within a couple of hours. Mainnet will be longer (I have not done this recently so I do not know).
There is a cardano-cli query tip command. eg:
CARDANO_NODE_SOCKET_PATH=state-node-mainnet/node.socket ./cardano-cli query tip --cardano-mode --mainnet
{
    "epoch": 321,
    "hash": "561310c715bff5d8a8f310e55e3ceb5b9116a058aaf716e3ab930bc120c6e47e",
    "slot": 53350023,
    "block": 6884753,
    "era": "Alonzo",
    "syncProgress": "100.00"
}

As of early 2022, I would expect about two days.

is that same for testnet as well?

for testnet, it typically takes 4-6 hours depending upon your internet connection.

It took about half a day to a day, from my personal experience in early 2022. But I think it varies depending on internet connection and the computer.
Make sure your machine is not resource-starved. I.e. check that you have enough RAM as you sync. While cardano-node does not require a super powerful computer, any computer process would struggle to get any work done if there are not enough resources ;)


text:
My wallet showing nothing in it
Explorer showing me this.
https://explorer.cardano-testnet.iohkdev.io/en/address.html?address=addr_test1vp465rg9nm7x3th67nfsccuav25ffvjk3wr5upk57k3ec9gadwcjp
But if i check my wallet balance directly from the shell it is showing me nothing in it.
cardano-cli query utxo --address addr_test1vp465rg9nm7x3th67nfsccuav25ffvjk3wr5upk57k3ec9gadwcjp --testnet-magic 1097911063 --cardano-mode
                           TxHash                                 TxIx        Amount

Is the node fully synced? The CLI will show zero balance if the transaction that created the paid to that added has not been downloaded yet.

How do i know if the node is fully synced or not? I can see that this is going on eb4cde7e343e83820321069f5df4b3dbf705feef741f19270a2b56404f43aa3a at slot 44463043 [dk-Latit:cardano.node.ChainDB:Notice:142] [2022-02-15 08:02:03.05 UTC] Chain extended, new tip: b1c0fe52e6fac43668ac485dd922b57d160ee999a0d4e327a105d6a4422098df at slot 44463323 [dk-Latit:cardano.node.ChainDB:Notice:142] [2022-02-15 08:02:04.34 UTC] Chain extended, new tip: 4ff762c7491523fadf6406ca66325f8ac43f000f444ed07f8656156149e4da78 at slot 44463606 [dk-Latit:cardano.node.ChainDB:Notic

Use the cardano-cli query tip command to check if the node is synced, a syncProgress with the percentage value will appear there.
You will need your node to be synced to at least 4 days ago (Epoch 186, Block 3312024), when your transaction in the testnet took place. Otherwise it could be that what you are seeing is the status of your wallet in an older point in time.

This is what i am getting cardano-cli query tip syncProgress Invalid argument syncProgress'
Usage: cardano-cli query tip
[ --shelley-mode
| --byron-mode [--epoch-slots NATURAL]
| --cardano-mode [--epoch-slots NATURAL]
]
(--mainnet | --testnet-magic NATURAL)
[--out-file FILE]
Get the node's current tip (slot no, hash, block no)`

You don't have to run cardano-cli query tip syncProgress, only cardano-cli query tip. The syncProgresswill be part of the output in your terminal.

cardano-cli query tip --cardano-mode --testnet-magic 1097911063  This is what worked


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

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

It is impossible to make outputs containing only custom tokens

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

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

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

It is not in ada it is in lovelace.

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

Okey. The transaction was successfull.


text:
Command failed: query utxo Error: This query cannot be used for the Byron era
When I am trying below command.
cardano-cli query utxo --address $(cat payment.addr) --testnet-magic 1097911063

I am getting this error.
Command failed: query utxo  Error: This query cannot be used for the Byron era

What I have to do now?

What are the contents of the payment.addr? Does it contain a Byron or a Shelley address?

$(cat payment.addr) zsh: command not found: addr_test1vp465rg9nm7x3th67nfsccuav25ffvjk3wr5upk57k3ec9gadwcjp  This is what i am getting

How do i know whether it is a shelly or byron?

Ok, that is a Shelley era address. You might try adding --shelley-mode or --cardano-mode to the command line.

cardano-cli: encodeFailure: local state query: using acquire without a Point must be conditional on negotiating v8 of the node-to-client protocol CallStack (from HasCallStack):   error, called at src/Ouroboros/Network/Protocol/LocalStateQuery/Codec.hs:80:7 in ouroboros-network-0.1.0.0-a6337e1ec691134555c3c4cba8800a5d3d08f8812cda7fdf6590dc6bf33ac964:Ouroboros.Network.Protocol.LocalStateQuery.Codec%   I am getting this now after adding shelly-mode

Try --cardano-mode instead.

I am getting this error now Command failed: query utxo  Error: This query cannot be used for the Byron era for --cardano-mode

I got it working using cardano-mode but the wallet is showing me zer balance . cardano-cli query utxo --address $(cat payment.addr) --testnet-magic 1097911063 --cardano-mode
                           TxHash                                 TxIx        Amount --------------------------------------------------------------------------------------

I had the same problem, but i found these posts (https://forum.cardano.org/t/testnet-tutorial-querry-utxo-error/45249 + https://forum.cardano.org/t/command-failed-query-utxo-error-this-query-cannot-be-used-for-the-byron-era/55606) with basically the same instruction: Just wait till the node is fully synced !. I did that, and 1 hour later the query command passed.
Hope it helps.

It can take 6hr to 2days for node to sync. So don't panic wait for an hour
You can monitor the progress of sync using this command
cardano-cli query tip --mainnet
Check the syncProgress param in the generated json


text:
symbol lookup error: cardano-node: undefined symbol: crypto_vrf_publickeybytes
I am trying to run a cardano node in my local and the command which i am running goes like this.
cardano-node run \
   --topology mainnet-topology.json \
   --database-path db \
   --socket-path db/node.socket \
   --host-addr 127.0.0.1 \
   --port 3001 \
   --config mainnet-config.json

But it is showing me this error.
cardano-node: symbol lookup error: cardano-node: undefined symbol: crypto_vrf_publickeybytes

In at this post it is getting solved but the links on that post is broken.
Does anyone knows how to resolve the same.
https://forum.cardano.org/t/cardano-node-symbol-lookup-error-cardano-node-undefined-symbol-crypto-vrf-publickeybytes/36359
The cardano installation progress is here.
{
    "era": "Byron",
    "syncProgress": "61.71",
    "hash": "21e4ea98fafcb565733debefca7fecf2d2ab901b7ce6587f1ad4f5ca327e93d1",
    "epoch": 207,
    "slot": 4490076,
    "block": 4487787 }

Once solution is to add the following to cabal.project.local:
package cardano-crypto-praos
  flags: -external-libsodium-vrf

and then rebuild the node executable.
If the file does not already exist, just add at the top level directory of the git checkout, with just the two lines above.

How do i do this? do i need to execute this command in terminal?

where is this cabal.project.local i am fairly new to haskel

The cabal.project.local file should be in the top level directory of the Gut checkout. There should already be a cabal.project file in the same location.


text:
How to define decimel points while minting tokens?
I am minting some tokens on the testnet by following the instructions in at this document. https://docs.google.com/document/d/1gyIOEjxhGhlXsgPtM35DsY3QX02jxLwZSpek7zO4q7M/edit
Everything is working fine and i am able to do the transaction to my daedalus wallet which is running in my local system.
I have minted a token count of 1000 I am able to sent the token of

1.12(Two decimeal places)

What i want to do is this I want to sent a token count of

1.123456 (Six decimal places after the dot)

I am not sure how can i achive this. Any idea?

Not quite finalised, but CIP 38 is probably what you're looking for. You define the "decimals" value on-chain in your minting tx metadata.
See: https://github.com/cardano-foundation/CIPs/pull/137
The way its achieve before this is off-chain by registering your token with that information here in the token registry:
https://github.com/cardano-foundation/cardano-token-registry
In general there is technically no difference between tokens with and without decimals (except for the amount in existance), it's only a matter of interpretation - so its really just about educating the consumer of the tokens about how many digits to interpret as decimals.

I need to test this before working on mainnet do the above mentioned stuffs will work for test net as well?

Yes, here's the off-chain registry for testnet: https://github.com/input-output-hk/metadata-registry-testnet

if i specify decimal places here will i be able to sent 1.123456(Six decimal) Tokens from wallet?

Yes. Technically you'd be sending 1123456 tokens - just like 1 Ada is sent as "1000000 Lovelace". It's up to the wallet to implement your token decimals in the user interface, but most wallets will respect this no problem. Nami for example will.


text:
Creating wallets using apis
I am wondering whether the cardano block chain has the apis which i can integrate with a third arty cms. For example if i call an api the wallet has to be created and i can sent funds using the same wallet thinks like that?

REST Api there is https://blockfrost.io/
Otherwise it´s the cardano-cli

You create a wallet (keys and addresses) with just a few lines of code, eg like this: https://github.com/Emurgo/cardano-serialization-lib/blob/master/doc/getting-started/generating-keys.md. No need for remote services or interfacing w. the blockchain for this. Once you generate an address it's ready for you to use. Just create transactions using that address and submit those to the network (eg using blockfrost). Whatever you send to an address will just be sitting there until the key-holder decides to spend it.

I need a remote service becose i am using a cms in which i have to give a wallet whenever a user is signing up.

ah okay sorry can't recommend any such service unfortunately. Must be one that you'd potentially trust access to all your funds to, though, if I understand correctly.


text:
How to setup carndano node-socket?
I am executing the following query and then I am getting the following error.
The query I am executing.
cardano-cli query utxo --address $(cat payment.addr) --testnet-magic 1097911063

And the error I am getting.
Command failed: query utxo  Error: Error while looking up environment variable: CARDANO_NODE_SOCKET_PATH  Error: "CARDANO_NODE_SOCKET_PATH"

How do i debug this?

Ensure that cardano-node is running.
open a new terminal window, and enter nano ~/.bashrc
Scroll to the bottom of the file and add the following line:

EXPORT CARDANO_NODE_SOCKET_PATH=/home/user/cardnao/db/socket (or whatever the path is to the socket in your db folder)

Save the file and exit, then in the same terminal window, type: source ~/.bashrc and hit enter.
Now things should work. To check if the socket path is recognized, run:

cardano-cli query tip --testnet-magic 1097911063, and you should receive a sync status update. Comment if you're still getting an error.

How do i know the path of socket?

when you run cardano-node, one of the mandatory flags is to specify a db folder. When you do that, a socket file is automatically created in that folder. CARDANO_NODE_SOCKET_PATH in your ~/.bashrc folder must then be pointed to that socket (following the instructions above)

EXPORT CARDANO_NODE_SOCKET_PATH=/home/user/cardnao/db/socket How do i know /home/user/cardnao/db/socket With what I have to replace this with?


text:
How to mint a token on testnet?
Now I am experimenting to mint a token on cardano testnet I have installed the followings like deadalus wallet for testnet and cli tools as well.Then I recived ada from the testnet to the testnet deadalus wallet  Then I have followed thease Instructions over here.
cardano-cli address key-gen \
--verification-key-file payment.vkey \
--signing-key-file payment.skey

cardano-cli address build \
--payment-verification-key-file payment.vkey \
--out-file payment.addr \
--mainnet

cat payment.addr

From the last command which i have executed given me an ada address when I am pasting that address on deadalus wallet it is showing me the address is invalid. I couldnt find much about this from official documentation as well. What should i do now? Where am i going wrong?

Anytime you do things on testnet, you need to replace the --mainnet flag in your CLI commands with the --testnet-magic 1097911063 flag. The address you built above is a mainnet address, which is incompatible with testnet.

Can You give an example script I am seeing this error on my terminal Invalid option --testnet'`

sorry, forgot to include the "magic" option. Edit was applied above ^


text:
How do I properly parse the CIP-30 output from NAMI to send a users wallet tokens?
If you can help me with this I will really appreciate it. I have worked through the token construction tutorial on Cardano docs https://docs.cardano.org/core-concepts/cardano-addresses. Using the command line I can successfully create transactions
cardano-cli transaction-build-raw /
--fee 0 /
--tx-in ${TxHash}#$T{xIX} /
--tx-out ${receiveAddress}+${amountToSend} /
--out-file mat.raw
when running this command I can successfully send ada to my Nami wallet if I set the variable:
receiveAddress="addr_test1qq5vc9wurul0cd3f2n8fu5uahdaefp6r4rn6nq9tmnvdwzdgchadmnjxnqgaf4k3ju8t74jaj80uwdrcvnxfjmawzats23jjcl"
This address can be obtained by clicking the nami wallet "receive button" and copying the address.
This part works fine.
I am trying to tie this transaction building command to a button in javascript.  To do this I am looking at CIP-30. https://cips.cardano.org/cips/cip30/.  But when I use the injected javascript from Namie wallet
'''
let address = await cardano.getChangeAddress()
'''
the variable address is a string not in the proper format.
"0028cc15dc1f3efc362954ce9e539dbb7b948743a8e7a980abdcd8d709a8c5faddce469811d4d6d1970ebf565d91dfc7347864cc996fae1757".
What is this format? How do I convert it to the Addr_test- string?
Thank you in advance!

It is hex encoded byteString. You can use the Cardano serialization lib browser
https://www.npmjs.com/package/@emurgo/cardano-serialization-lib-browser
And the following code in javascript
const addressBech32 = async () => {
  await Loader.load();
  const address = (await window.cardano.getUsedAddresses())[0];
  return Loader.Cardano.Address.from_bytes(
    Buffer.from(address, "hex")
  ).to_bech32();
};

Where Loader is my loader to the above Library :) the Address class has a method for converting Hex encoded bytes to Address Bech 32 :
class Loader {
  async load() {
    if (this._wasm) {
      return;
    }
    /**
     * @private
     */
    this._wasm = await import(
      "./@emurgo/cardano-serialization-lib-browser/cardano_serialization_lib_bg"
    );
  }

  get Cardano() {
    return this._wasm;
  }
}

export default new Loader();

Could you elaborate on "loader to the above library".  I installed the link you posted using npm, copied this code to a file called "index.js" and then tried running the code with "node index.js".  I get an error saying "Loader is not defined".  I apologize if there is something obvious I'm missing here, I have a programming background but am brand new to javascript.

Done, nothing obvious at all if you are new to JS. If you run it in node.js you do not need this...  it is only needed if it is going to run in the browser... put the above code in another file that you import in the file where you are going to use the script that gets the address.

I have tried copying the exact code into a file and importing that file and get an error saying only modules can import. If the only way to do this is to learn webpack and node so be it but I feel there has to be a simple way of doing this. that doesn't require learning all these new javascript tools  I'm not concerned about being in browser,  python or command line are fine too.  I just need a working script that I can run that will convert this string into a usable address.  I can figure out how to port it to my application if I can just figure that part out.

in python this would be two lines of code:
import
.decode(encodedString)

I found out there was a binary Bech32 that does the job.  Thank you for the help!

For imporrting in ES6 notation you might change to .mjs file extention ... all your code should be handled in that way. If you do not want to do it that way you can use require() notation in normal .js files. I underestand your fustration, i am a native Python developer more thatn Js Developer. You can read about it here https://www.digitalocean.com/community/tutorials/js-modules-es6 .. but what you need to do is change your file to .mjs ... and keep it like that all over your project, or import using 'require' and export using module.exports=

According to the docs, this is a BaseAddress type, which is a hex representation in byte strings
https://github.com/Berry-Pool/nami-wallet/blob/main/README.md#cardanogetusedaddresses

ok. so how do i convert that to address format?

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


text:
Where are the bech32 binaries?
Hi I am trying to convert from hex to bech32.
This repo says that there is a tool which can do this and that the binaries can be found at cardano-wallet releases, however I cannot find them there.  The readme also gives no instructions on how to build the binaries from source. https://github.com/input-output-hk/bech32#usage  Where can I find these binaries?

Hi guys. For anyone who is a dingus like me (unlikely).  they are in the .tar.gz file.  I was confused because they are not present in the zip file

bech32 binaries/cli commands come preinstalled with cardano-wallet software. If you follow the instructions to install cardano-wallet, you'll be able to use bech32 commands from the same executable path (the same is true for cardano-addresses).
Alternatively, if you really don't want to install cardano-wallet, you can download the bech32 binaries here.

so I found the binaries, but jsuk  I have cardano-wallet installed.  v2022-01-18 (git revision: a5085acbd2670c24251cf8d76a4e83c77a2679ba).
i can call cardano-wallet, but the binaries were not automatically added


text:
Can someone show me how to get the transaction in the proper format for cip-30?
I have generate a transaction using cardano-cli and I am trying to get Nami wallet to sign the transaction.
The command to build the transaction

cardano-cli transaction build-raw
--fee 0
--tx-in $browserTxHash#$browserTxIx
--tx-out ${desktopAddress}+5000000
--tx-out ${browserAddress}+10000000
--out-file transaction.raw

Which writes the following to the file "transaction.raw"

{
"type": "TxBodyAlonzo",
"description": "",
"cborHex": "86a50081825820e34a60ee397dee115b75379af692962dabc085bed002fc0371e578ebd27acd62000d80018282581d60bf1466152d256eb5e8b490c5febc029593f0e9a5b9ee270d75ba35491a004c4b4082583900d9cdd3ead63bd0db91bd83cfa9f3d588bb05a3fb487d5eb62946672cbfcbf21db7267631bbd23f1b8744b9491088eda66ba2ec0e7d2d98841a0098968002000e809fff8080f5f6"
}

I then tried using the CIP-30 based javascript command with nami in the chrome console to request a transaction signature with the command

namiAPI.signTx("86a50081825820e34a60ee397dee115b75379af692962dabc085bed002fc0371e578ebd27acd62000d80018282581d60bf1466152d256eb5e8b490c5febc029593f0e9a5b9ee270d75ba35491a004c4b4082583900d9cdd3ead63bd0db91bd83cfa9f3d588bb05a3fb487d5eb62946672cbfcbf21db7267631bbd23f1b8744b9491088eda66ba2ec0e7d2d98841a0098968002000e809fff8080f5f6",
partialSign=true)

However, I get an error:
"Inputs do not conform to this spec or are otherwise invalid."
The CIP-30 spec from https://github.com/cardano-foundation/CIPs/tree/master/CIP-0030 is as follows:

api.signTx(tx: cbor, partialSign: bool = false):
Promise<cbor<transaction_witness_set>>

I am passing a cbor encoded string (I think), so why is this not working/what should that input look like?

Typhon Wallet Dapp connector is an alternative to CIP-0030 standard where You don't need to build transactions in the backend with Cardano CLI or build transactions in front-end application after fetching UTXOs. https://cardano.stackexchange.com/a/7658/117

i am at the same point, did you figure out what is wrong?

You were on the right track, the key is to add --cddl-format to the build command


text:
Is there a precedent or example for using a cardano NFT for permission verification?
I would like to use ownership of a Cardano NFT as a requirement for editing an online document. i.e. if you own the nft then you will be capable of writing to the document,but if you do not own the required NFT then you will only be able to read.  Are there any examples of NFT ownership being used as a password of sorts like this?  any recommendations of where to start looking for a way to do this?

What you say is possible.
In this repo you can find an example on how to mint an NFT and then use it to login to a web app.
I reckon you can use a similar approach for your use case.

Are you sure that you posted the link you intended?  I searched the repo and do not even see the word NFT appear

Yes, I'm sure. Here you can find how to mint the NFTs: https://github.com/CardanoSevilla/cardano-summit-2021/tree/main/src/NFTs. The project uses GameChanger wallet to mint (https://gamechanger.finance). You can import those JSON in the Playground and mint your NFTs from there.

Here is another example: SpaceBudz Contract
He created individual SpaceBudBid NFTs that basically mark the highest bid on-chain for a specific SpaceBud. That way he doesn't need to scan a lot of UTxOs and instead always keeps track of the highest bidder.
You can do the same thing by generating an NFT series for each document. The policy could be unlocked so that the owner of the document can grant an arbitrary number of people different rights (reading, writing, commenting etc.) which correlates to some action that mints a respective NFT for that user.


text:
What do unusual symbols "@" and ".\/" in off-chain code mean?
I was wondering about syntax I am not used to in the off-chain code.
What does @ mean in the following context?
logInfo @String $ printf "made a gift"
What does .\/ mean in the following context?
type GiftSchema = Endpoint "give" Integer .\/ Endpoint "grab" ()
I guess that it has to do to the multiple GHC extensions invoked in Plutus code but I do not have the time to understand each and everyone of them.

@String is from TypeApplications. logInfo has type logInfo :: forall a effs. Member (LogMsg a) effs => a -> Eff effs (), so logInfo @String fixes a to be String. (That this is needed here is because of another extension OverloadedStrings, so "made a gift" is not necessarily of type String)
.\/ is not from an extension, but an operator defined by the row-types library.


text:
Is there a way for a contract to look at the duration of the timeslot?
Are there oracles for knowing in real time the duration of the Cardano time slot in real time ? One learns in the Plutus Pioneer Program that the duration of this time slot can change, is there a way to give Ada to my children in 3 years (and not 6 or 1.5 years ^^) ?

Simple timelocking scripts have been around since before smart contracts were launched, though they do rely on slot length as their notion of time. You can read more about them at IOHK's simple scripts repo.
While slot length can indeed be changed, that doesn't mean that it will be changed without a significant heads up. Currently, slotLength is a non-updateable protocol parameter, meaning it would require at least an HFC to change, which we would be aware of ahead of time.
For this reason I would argue the slotLength parameter is currently, by far, a more reliable source of time than any oracle. The former has roughly the same security/reliability guarantees as something like Max-ADA-supply, whereas the latter is only as trustworthy as the underlying data aggregator.
If I were time-locking UTXO's for years ahead, I would use the slot-based time locking scripts mentioned above, in combination with an emergency fallover key that is non-timelocked and buried/kept somewhere safe, just in case of whatever.

What does it mean  HFC to change ?


text:
What is the transaction fees for the native tokens in ADA? can i design a wallet exclusively for my own token which is in cardano block chain?
I am looking forward to build tokens in ADA block chain. I have some questions about the transaction fee in at this network such as do I need to sent ADA along with the tokens in order to make the transactions and how the transaction fees will be calculated in the network? Is that going to change in future? and is that possible to sent tokens for a non ada holder? Is that possible to sent ada tokens to some other wallets. for example if i want to use a custom made wallet for ada transaction is that possible to use something like that?

What are the costs related to minting and trading native tokens?
Costs related to multi assets can be divided into two categories:
Fees: Sending and minting tokens affects the fees that the author of the transaction must pay. As with an ada-only ledger, the fees are calculated based on the total size of the transaction. There might also be fees for checking minting policies, but initially only multisig policies are supported, which do not incur additional fees on top of the transaction size-based ones.
Min-Ada-Value: Every output created by a transaction must include a minimum amount of ada, which is calculated based on the size of the output (that is, the number of different token types in it, and the lengths of their names).
resource 1. : https://cardano-ledger.readthedocs.io/en/latest/explanations/faq.html
resource 2. : https://docs.cardano.org/native-tokens/minimum-ada-value-requirement

Is there a way which helps me to calculate the same? i mean the transaction fee? for example I have designed a new token and i want to sent 1000 of them to some one what would be the fee which i have to pay to sent this token?

check next answer,
in your case you need the first 2 steps.

build a raw
calculate min fee

here is what i do in my script,

build a raw
calculate min fee
transaction build
transaction sign
transaction submit

cardano-cli transaction build-raw
--fee 0
--tx-in ${tx_in}
--tx-out ${in_addr}+${amountToSendUser}+"1 ${myToken}"
--tx-out ${paymentAddr}+${myInitADA}+"${tokenAmountFinal} ${myToken}"
--invalid-hereafter $FINALTIP
--out-file tx.draft
fee=$(cardano-cli transaction calculate-min-fee
--tx-body-file tx.draft
--tx-in-count 1
--tx-out-count 2
--witness-count 1
--mainnet
--protocol-params-file protocol.json \
to run this commands, if you are new here, you need a cardano-cli (a cardano node to run).
if you need more details, dont hesitate to ask.
happy to assist,
thomas
TTS17
theTokenSquare17

is threre a testnet calculatin? Where i can experiment with token creatin

exactly, you are right.
there is a testnet, where you can install a node and do test. you can use the link below  to request test_ADA https://testnets.cardano.org/en/testnets/cardano/tools/faucet/


text:
What specifications should be used when creating a native token logo?
What specifications should be used when creating a native token logo (e.g. dpi, pixel dimensions, size, etc.)

There is no standard or specification you need to follow for creating a native token logo. You should use the same width and height if you want your token logo to be correctly displayed in wallets, though.
You can find an example of dimensions that will work properly here: https://cardano.org/brand-assets


text:
Certification for Plutus Smart Contracts
What does the process look like for certification and auditing of Plutus Smart Contracts?  What are required steps to prepare your dApp for certification?

Too soon to say. The only public announcement so far is https://iohk.io/en/blog/posts/2021/09/22/bringing-certified-dapps-to-cardano


text:
Cardano-Node 1.35.0 Build Error on M1 Mac
I'm trying to install cardano-node version 1.35.0 on my M1 Mac.  It worked (somewhat) previously with version 1.34.2 using LLVM.  Currently I am running into this error when it tries to build threepenny-gui:
dlopen(/Users/stefan/.cabal/store/ghc-8.10.7/lib/libHSHsOpnSSL-0.11.7.2-e201b3b3-ghc8.10.7.dylib, 0x0005): symbol not found in flat namespace (_DSA_free)

It looks like the issue is with the openSSL library with cabal is missing a required symbol.  Does anyone have any suggestions on how to make this available?

This might be answered in https://cardano.stackexchange.com/questions/8803/cardano-node-and-cli-install-llvm-error .

@ErikdeCastroLopo, that didn't address my issues.

The issue had to do with the openSSL library I was using and was resolved in the instructions provided here: https://github.com/mallapurbharat/cardano-tx-sample/blob/main/0_installation/Old/macos_m1_process.md
This included including the homebrew openssl library.  Specifically here and here.


text:
Error while syncing with Testnet, Invalid block

I have tried node version 1.30.01, 1.29. 1.29rc-2 .1.33 - latest
They all encounter this invalid block here.
I'm using config file for the testnet here https://hydra.iohk.io/build/7654130/download/1/index.html

Try using the latest node and the latest configuration files.
The latest release can be found here: https://github.com/input-output-hk/cardano-node/releases
The config files for this release are here: https://book.world.dev.cardano.org/environments.html


text:
How can I grant an NFT holder a one time action in a web app?
I would like users to be able to perform a one time action on a web app, i.e. claiming one physical item per NFT owned, what would be the best way to keep track of tokens that have already claimed ownership? I have thought of constructing a list of addresses in the web app code but think this may have security issues. Is it possible to do it in a public way so that users can verify themselves?
Thank you!

Integrate with a browser wallet (Nami, ccvault, ...) so users can log in with their wallet on your web-app.
Let the users sign a message to prove they really own the wallet. Check on server side if the signature is correct.
Get all NFTs owned by the wallet from the blockchain. Don't trust the user input here as it could be manipulated. You can run your own node, use https://blockfrost.io or something similar.
Keep track of which NFTs have already been used to claim your physical goods. The address of the owner is not relevant, since the NFT can be sold after redeeming. You can do this in a simple database if you want. Or you could do it on-chain, e.g. by minting a "redeemed" token for each NFT or even updating the NFT metadata (if the policy is not locked yet).

The only two ways would be to keep a database of tokens and their redemption status, or an easier way to do it would be to update a data attribute inside of the NFTs metadata directly. That way everyone can know (even on the secondary market) whether the redemption has been spent or not. This, however, would require an open policy ID.

interesting, i had not considered modifying the nft its self, i will definitely be taking a look at this !


text:
Is there an open source plutus voting dapp?
I am interested in holding decentralized votes for a DAO like system. I am wondering if an audited standard has been put in place that enables users to place votes on the blockchain or if anyone could share some resources with me regarding the topic.
I feel like this is quite an important topic and building a secure, straight forward to use infrastructure for DAO's to implement votes would definitely encourage more building on Cardano!
Many thanks!

At the current time I have found no implementation of a voting dapp for DAO's. But of course you could make one yourself. As Waalge suggested you could use some multisig functionality to to vote with a group of people.
Another and perhaps better option is to implement a Mixing net, here's  a paper about it. In this protocol a per-selected group of parties form a group of mixing nodes. The voting participants can post their vote via encryption anonymously on the blockchain. These mixing nodes than shuffle the votes and decrypt them together. The result is a verifiable anonymous immutable voting system.
The security of the protocol is fully determined by the chosen mixing nodes. Each of the nodes has a piece of the shuffle and if they share/combine that knowledge the anonymity could be broken. Now if every voter is also a mixer node the protocol is completely secure since only if all parties agree to publish their shuffle the anonymity is broken. But note that in this case if a 1000 people vote and all parties need to mix its quite expensive and cumbersome to perform.
That said, both the mixing net and the multisig voting systems are implementations where all voters have exactly the same voting power. One could extend this by allowing some voters to vote multiple times with other signatures.
Hope this helps!

IOG provide examples of various common things.
https://github.com/input-output-hk/plutus-apps/tree/main/plutus-use-cases
This includes multisig type functionality which can be used akin to voting depending on the use case.
Also there is a module entitled governance.
They should provide a starting point


text:
Question - is there a simple example end-to-end dApp on Cardano
as the title says... is there any example of a simple application built on cardano? I tried to find one but apparently there is none. I want to start learning by interacting directly through code and learn on the way.
If someone already wrote a "hello world" application with a front and back end interacting with cardano's blockchain, please share your github repo.
Thanks for your help!!

Check out the Plutus Pioneer's lecture notes. It is a whole series of lectures and exercises to help beginners get started with Cardano smart contracts. There is even one exercise titled "HelloWorld Script". In addition to this there are video supplements by Lars Brunjes, IOHK's director of education.


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

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

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

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

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

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

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


text:
How to set a specific amount for native token when calling CIP30 api.getUtxos() method in Nami, CCvault, Flint and other CIP30-compliant wallets?
In the CIP30 spec, we are supposed to be able to get a subset of the user's UTXOs if we specify an "amount" when calling the method getUtxos():
api.getUtxos(amount: cbor\ = undefined, paginate: Paginate = undefined): Promise\

And this "amount" parameter, is supposed to allow a Value type which further contains MultiAsset types.
But calling this method like so:
let ScriptHash = csl.ScriptHash.from_bytes( Buffer.from(policyId, "hex") );

let Assets = csl.Assets.new();
Assets.insert(
    csl.AssetName.new( Buffer.from(assetName, "hex") ),
    csl.BigNum.from_str(amount)
);

let MultiAsset = csl.MultiAsset.new();
MultiAsset.insert(ScriptHash, Assets);

let reqdValue = csl.Value.new_from_assets(MultiAsset);
let inputUtxos = await wallet.activeApi.getUtxos(reqdValue); // CIP30 method call

... always gives me the following errors.
In CCVault/Eternl:
Error: invalid input: amount: TypeError: byteaString.startsWith is not a function

In Nami:
Inputs do not conform to this spec or are otherwise invalid.

In Flint:
An error occurred during execution of this API call.

What am I doing wrong here? What is the correct way of passing a Value parameter to getUtxos()?


text:
Missing datums in db-sync
From time to time I encounter transactions which contain UTXOs associated to script addresses with datum hashes for which no corresponding entries are available in the datum table of a fully-synched cardano-db-sync postgres.
Here is a randomly selected example:
select data_hash from tx_out where tx_id = (select id from tx where hash = '\xfc6536534b03f818494f21698994d387c879a121b263153a06975d056d9cf13e');

This will output \x4a664c584e552af70dcc255921811b5f62637fd781a43e5c289d9e571a227117. Then:
select * from datum where hash = '\x4a664c584e552af70dcc255921811b5f62637fd781a43e5c289d9e571a227117';

finds 0 rows.
As datums values are included in the witness set of the corresponding transactions I would expect all hashes to have a matching entry in the datum table.

Is this a bug on cardano-db-sync?
Is there any other way to retrieve those datum values directly, maybe by using cardano-cli to query the blockchain directly?

As datums values are included in the witness set of the corresponding
transactions

This is not true all of the time. When you create a new script UTxO by sending some amount of tokens to it, you don't necessarily need to provide the datum, since there is no validation being made yet. You can if you want, though, by using (in cardano-cli) the tx-out-embeded-datum argument.
When you consume it, however, you'll need the actual datum, since the script validation depends on it. In your case, I assume you are inspecting an UTxO that didn't have any datum attached to it.