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:
Deploy smart contract to testnet using cardano-cli
I am trying to run a few examples of deploying a smart contract to testnet using the cardano-cli. I am running version 1.33.0 for both the cardano-cli and cardano-node. The example I am using is from https://github.com/input-output-hk/cardano-node/tree/master/plutus-example (plutus-example).
I can successfully transfer tADA to the script addresses. However, I cannot unlock the funds that are locked at the script addresses. The error message is below - from the little that I find on internet, it looks like an issue with the redeemer, but I can't figure out how to correct. Can anybody help? My understanding is that both datum and redeemer must both equal a specific value for validation to work (I changed 42 to 1970).
Error message (for cardano-node/plutus-example) ->
Command failed: transaction build  Error: The following scripts have execution failures: the script for transaction input 0 (in the order of the TxIds) failed with:  The Plutus script evaluation failed: An error has occurred:  User error: The provided Plutus code called 'error'. Caused by: [ (builtin unConstrData) (con data #1907b2) ] Script debugging logs:
Code for plutus-example.hs and CustomDatumRedeemerGuess.hs are only slightly modified compared to the repo (no change in logic, only in some file naming).
The cardano-cli commands I use are as follows ->
cardano-cli address build
--payment-script-file custom.plutus
--$testnet
--out-file custom-script.addr
cardano-cli transaction hash-script-data --script-data-value 1970
export scriptdatumhash=7619130e301e1b52e1c333c96d8489fba07ea98eeec3327f719a03d2c713302f
cardano-cli query protocol-parameters --$testnet --out-file protocol.json
cardano-cli transaction build
--alonzo-era
--$testnet
--change-address $address1
--tx-in 4c7c3e12d3ed18241520a8c95a7f68855a1e17af933e207918f65a66bd02c49e#0
--tx-out $(cat custom-script.addr)+10000000
--tx-out-datum-hash $scriptdatumhash
--protocol-params-file protocol.json
--out-file tx-script.build
cardano-cli transaction sign
--tx-body-file tx-script.build
--signing-key-file ../nft/payment.skey
--$testnet
--out-file tx-script.signed
cardano-cli transaction submit --$testnet --tx-file tx-script.signed
Up until here, everything works great and I can transfer funds to the script address.
However, running the following transaction build command fails with the error message above ->
cardano-cli transaction build
--alonzo-era
--$testnet
--tx-in 29f0adfb6ff1ba9b4cb9117b3678cf84532314a1b82a29a6991dfcc38e37d4c6#1
--tx-in-script-file custom.plutus
--tx-in-datum-value 1970
--tx-in-redeemer-value 1970
--tx-in-collateral 29f0adfb6ff1ba9b4cb9117b3678cf84532314a1b82a29a6991dfcc38e37d4c6#0
--change-address $address3
--protocol-params-file protocol.json
--out-file test-alonzo.tx
Can anyone help me? Thanks in advance, Simon

The error output points to error in the actual script. It seems the BuiltIn data is unreadable:
The Plutus script evaluation failed: An error has occurred:  User error:
The provided Plutus code called 'error'. Caused by: [ (builtin
unConstrData) (con data #1907b2)

Thanks, I'll try and investigate that

source: Stack Exchange

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

sort: votes


text:
How many slots did Byron era (testnet) have?
I was wondering the number of slots the Byron era (testnet) had or the slot number when Byron finished.
The only info I've been able to find is systemStart": "2019-07-24T20:20:16Z" coming from testnet-shelley-genesis.json.
( Calculate timestamp from slot discusses about the same thing but with mainnet Byron. )
Any help would be great. Thanks in advance!

Should you have accepted the answer?

@gRebel right, done   ✅

As far as I know, Shelley started at epoch 1, i.e. after a single Byron epoch 0 on Cardano Testnet.
Byron started on Testnet:
epoch 0 ... slot 1031 ... block 1 ... date 2019/07/25 ... time 02:03:56

Shelley started on Testnet:
epoch 1 ... slot 21600 ... block 20570 ... date 2019/07/29 ... time 20:20:16

P.S.
There's also one simple way to check this out. Start downloading a Cardano Testnet DB onto your computer, and, at the very beginning of the process, apply cardano-cli command:
cardano-cli query tip --testnet

But the best solution is to send a request to the IOHK helpdesk.

So systemStart": "2019-07-24T20:20:16Z" coming from testnet-shelley-genesis.json, what does it mean?

I don't know what it means. Testnet explorer shows another date.

How can I know from the info shown in Testnet explorer that Shelley started in slot 21600?

No way. I saw a hint among 3.5K messages on cardanoupdates.com. Just google this phrase – "Shelley started at epoch 1, i.e. after a single Byron epoch testnet".

One more question if you're so kind. When was the slot duration set to 1 sec on Cardano Testnet? At the beginning of Shelley?

Sorry @kindofdev, I don't know...

No problem, thank you for your help.

Travis found out when 1slot-1sec started, https://cardano.stackexchange.com/questions/6955/when-was-the-slot-duration-set-to-1-sec-on-cardano-testnet
@AndyJazz

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


text:
cardano-cli not showing utxo but Testnet Blockchain Explorer does
I have requested funds via Faucet, twice in fact because the first one I thought the request didn't go through but when I run:
cardano-cli query utxo --address $(cat 01.addr) --testnet-magic 1097911063

I don't get the utxo output but only get a blank line for the hash and transactions. However when I look up the address in the Cardano Blockchain Explorer Testnet I can in fact verify I have 2000 ADA's in that address.
I wonder why this is or what I might have missed doing. Any help will be highly appreciated.

Is your local cardano-node fully updated?

Not sure. I've been running it but how do I know when the node is fully updated?

With : cardano-cli query tip --testnet-magic 1097911063 .
As result you should get: "syncProgress": "100.00"

I can confirm allowing the node to fully sync with the blockchain which incidentally took quite a bit of time fixed the issue. Once the sync was fully established the cardano-cli did output the relevant utxo info.


text:
How to create Datum with ownPaymentPubKeyHash?
I have defined two endpoints.
One for creating a UTxO at the script address with a Datum that contains the wallet's own PaymentPubKeyHash.
And a second endpoint that spends such UTxOs from the script address.
The validator only checks for equality between the two PaymentPubKeyHashes.
First endpoint:
one :: AsContractError e => Params -> Contract w s e ()
one Params{..} = do
    pkh <- ownPaymentPubKeyHash
    let dat = Stake PPDatum { owner = pkh }
        tx  = Constraints.mustPayToTheScript dat $ Ada.lovelaceValueOf amount
    ledgerTx <- submitTxConstraints validatorInstance tx
    void $ awaitTxConfirmed $ getCardanoTxId ledgerTx

Second endpoint:
second :: forall w s e. AsContractError e => Contract w s e ()
second = do
    pkh   <- ownPaymentPubKeyHash
    utxos <- Map.filter (isSuitable pkh) <$> utxosAt validatorAddress
    ...
    where
        isSuitable :: PaymentPubKeyHash -> ChainIndexTxOut -> Bool
        isSuitable pkh o = case _ciTxOutDatum o of
            Left _          -> False
            Right (Datum e) -> case PlutusTx.fromBuiltinData e of
                Nothing -> False
                Just d  -> owner d == pkh

But the equality fails between the PaymentPubKeyHashes.
After testing around I recognized that the type of ownPaymentPubKeyHash does not just return a PaymentPubKeyHash but a Contract w s e PaymentPubKeyHash.
So how can I create the datum so that the PaymentPubKeyHashes match?
UPDATE
I was able to resolve my issue. It has nothing to do with the usage of ownPaymentPubKeyHash. As already correctly stated by others in this thread binding with the help of <- ownPaymentPubKeyHash returns the type PaymentPubKeyHash.
The problem originated from unwrapping the datum incorrectly. And this was caused due to allowing two different types of datum at the script address using the pipe operator. Therefore, I needed to unwrap the datum twice.
My solution looks something like this now:
data ParentDatum = One ADatum | Two BDatum

-- Helper function
getParentDatum :: ChainIndexTxOut -> ParentDatum
getLotteryDatum o = case _ciTxOutDatum o of
    Left _ -> traceError "unexpected datum"
    Right (Datum d) -> do
        let parsedDatum = PlutusTx.fromBuiltinData d :: Maybe ParentDatum
        case parsedDatum of
            Just s -> s
            _ -> traceError "Unknown datum type"

-- inside the off-chain endpoint code
-- {...}
    where
        isSuitable :: PaymentPubKeyHash -> ChainIndexTxOut -> Bool
        isSuitable pkh o = case getParentDatum o of
            One ADatum{..} -> owner == pkh
            Two BDatum{..} -> owner == pkh
            _              -> traceError "Unhandled datum type"

You are using the operator <- to bind the result to pkh. That means that pkh is of type PaymentPubKeyHash. If the equality fails then because of another reason. If pkh wasn’t of the right type you would get a compilation error.
Maybe the way you are retrieving the datum is not correct. I would have written the following function assuming that your datum is of type Stake:
 stake :: ChainIndexTxOut -> Maybe Stake
 stake (ScriptChainIndexTxOut _ _ (Right dd) _) = do
     Datum d <- Just dd
     PlutusTx.fromBuiltinData d
 stake _ = Nothing

Thanks, that makes sense, but what else makes it fail to retrieve the funds?
I've have tested multiple things, like just returning True for the isSuitable function, which works as expected for retrieving any funds from the contract address.
So the validator works and it must be part of the isSuitable function

Maybe it is the way you retrieve the datum. I have edited my answer to show how I would have done it.

Thanks @Jey I resolved the issue - you were right, the problem did originate from unwrapping the datum incorrectly.

Cool, I'm happy that my answer was useful.

If my answer is correct you can accept it as the solution ; )


text:
How to enable cardano CLI REST API on DigitalOcean?
I've set up a Cardano node using DigitalOcean's droplet, and I've gotten to the point where I can run:
cardano-wallet serve
 --port 1337
 --mainnet
 --database ~/cardano/db
 --node-socket ~/cardano/db/node.socket

However, I'm not able to access it publicly either via a web browser or using CURL.
curl --url http://<public ip address>:1337/v2/network/information | jq

I've made sure the firewall rules allow inbound connections via TCP to port 1337 (all ipv4 and ipv6). Outbound supports all TCP and all UDP for all ports.
Any ideas?

First off, the wallet API is not secure. It should never ever be open to the public without TLS client based authentication.
Second, by default it only listen on 127.0.0.1 (localhost loopback) to prevent people from accidentally running it on a public server open to the world. If you're absolutely sure you want to do this (which I would only do if you run in TLS mode with a CA authorizing a client certificate like Daedalus does by default), you would use this parameter:
  --listen-address HOST    Specification of which host to the bind API server
                           to. Can be an IPv[46] address, hostname, or '*'.
                           (default: 127.0.0.1)

Yes, that's the next thing I need to figure out. I didn't want to install Apache, thinking it might conflict with the service. But SSL requires Apache on Ubuntu? Still researching, any pointers would be appreciated.

I personally would secure it with nginx doing ssl termination and a reverse proxy. Then you can also institute things like allow/deny lists, rate limiting, etc... at the service level before it hits the wallet webserver.

THANK YOU. That's actually in line with the advice I got from a dev ops friend this afternoon (he didn't know the details about Cardano, but he knows servers and security)


text:
Why does the grab function in the vesting contract need two slots to complete?
This is about Week3/Homework1 of the third Plutus-Pioneer-Program.
Why does the grab endpoint need two slots to resolve and release the funds back to the wallet1?

This will not create a transaction

This will create the transaction

Code to the contract

A hunch: maybe because of Constraints.mustValidateIn? Try changing/removing that and see what happens.

This happens because 1 slot is not enough to meet the interval when using Constraints.mustValidateIn.
Check this post for more information on why that happens: Constraints.mustValidateIn in a StateMachine


text:
printSchemas error compiling in Plutus Playground
I am getting this error when I try to compile the homework for Week03 of the plutus pioneer program:
You need to import `printSchemas` in order to compile successfully, you can do this
with either
     `import Playground.Contract`
or
     `import Playground.Contract (printSchemas)`

But the import already exist as per the homework draft is. Any way to debug this?

I'm having the same issue for Week04.Homework.hs. Did you find a resolution to this?

@Kyle Yes. The solution is once you've copied the script in playground, you have to make sure that the lines that have the imports occupy only one line. Because of Haskell beautifying the code, you'll notice that the line which imports printSchema occupies 2 lines. Just adjust that import in Playground to occupy only one line by bringing the second line up with the first. This really just concerns the Playground.

I ran into this error as well for the previous homework when copy/pasting output from cat on terminal. I never quite figured out why but for some reason when copy/pasting multiline import statements formatted by stylish-haskell break the interpreter. A quick fix is to move it back up to the previous line.

I don't really know what you mean by 'moving it back up' as it starts on the first line

Yes I see what you mean now. the importr statement in the Playground must be in one line. It works now.


text:
cabal repl outputs a lot of changing git HEADs on plutus-pioneer-program
This is a question regarding the plutus-pioneer-program. I want to load the modules of a given week into the ghci shell. The first time I run cabal repl it takes quite a long time to download things and by the looks, it clones git repos of some sort. I didn't copy the exact output. Then each time I run cabal repl the output tells me something about the git HEAD moving all over the place. I don't know what to make of it, since in the videos that accompany the program I do not see similar output, which makes me wonder whether I have set it up correctly. Here is the context and the output I get.
First I have checked out the commit with SHA1 hash 41149926c108c71831cfe8d244c83b0ee4bf5c8a in the plutus-apps repo. Then I ran nix-shell and then changed directory to the plutus-pioneer-program/code/week02. I ran cabal repl and get the following output:
[nix-shell:~/plutus-pioneer-program/code/week02]$ cabal repl
HEAD is now at ee59880 Don't use the unsafe decodeUtf8
HEAD is now at 3825d3a Merge pull request #9 from input-output-hk/coot/createNamedPipe-error
HEAD is now at d2f86caa Merge pull request #149 from input-output-hk/rvl/adp-1114/fix-npm-publish
HEAD is now at 654f5b7 Merge pull request #240 from input-output-hk/nc/rewrite
HEAD is now at f730793 Merge pull request #69 from newhoggy/add-ghc-8.6.5-and-8.10.2-to-ci
HEAD is now at bf008ce02 Merge pull request #2526 from input-output-hk/jc/fix-alonzo-txwits-again
HEAD is now at 4f65fb9a2 Bump to version 1.32.1
HEAD is now at bb4ed71 Merge pull request #158 from input-output-hk/nc/drop-strict
HEAD is now at 760140e23 Merge #3063
HEAD is now at cde90a2 Re-enable support for GHC 8.6.5
HEAD is now at 46f994e Merge pull request #623 from input-output-hk/cda_490_kafka_backend
HEAD is now at d613de3d8 Merge #3479
HEAD is now at 2721c59fd [Builtins] Drop 'SomeConstantOf' and remove obsolete golden files (#4218)
HEAD is now at 6aff97d59 Update client deps to fix playground (#247)
HEAD is now at 366fc70 Add support for set and map json
HEAD is now at ebea59c Fix encoding
Build profile: -w ghc-8.10.4.20210212 -O1
In order, the following will be built (use -v for more details):
 - plutus-pioneer-program-week02-0.1.0.0 (lib) (first run)
Preprocessing library for plutus-pioneer-program-week02-0.1.0.0..
GHCi, version 8.10.4.20210212: https://www.haskell.org/ghc/  :? for help
Ok, 9 modules loaded.
Prelude Week02.Burn>

What's all those changing git HEADs about?


text:
When was the slot duration set to 1 sec on Cardano Testnet?
I'd like to know the exact date when the slot duration was set to 1 sec on Cardano Testnet.
Thanks in advance!

I did a little bit of digging. Block 1597133, created on 2020/07/28 20:20:16 was the first block to use 1 second per slot.

Epoch
Slot
Block
Created
Delta Next Slot
Delta Next Created
Time Per Slot

73
1598398
1597131
2020/07/28 20:19:36
1
00:00:20
00:00:20

73
1598399
1597132
2020/07/28 20:19:56
1
00:00:20
00:00:20

74
1598400
1597133
2020/07/28 20:20:16
20
00:00:20
00:00:01

74
1598420
1597134
2020/07/28 20:20:36
20
00:00:20
00:00:01

74
1598440
1597135
2020/07/28 20:20:56

Delta Previous Slot is the difference between the block's slot and the one before it
Delta Previous Created is the difference between the blocks creation date and the one before it
Time Per Slot is Delta Previous Created divided by Delta Previous Slot

Page on Cardano Testnet Blockchain Explorer with these blocks

great! Thanks a lot!

From the info in the table I'd say that the first block with 1 sec would be 1597133 because the difference in slots with the next one (1597134) is 20 slots.

You're right. I've updated my answer


text:
How long Cardano node takes to be installed?
I'm running this script but it takes hours !
curl https://hydra.iohk.io/build/9941098/reproduce | bash
Any help?
Thanks

You're missing the binary cache setup referenced here most likely:
https://github.com/input-output-hk/cardano-node/blob/master/doc/getting-started/building-the-node-using-nix.md#iohk-binary-cache

if you want to install Cardano Node,
building the node :
this commands will actually build/compile the node and will take around 40-45 minutes.
cd ~/git
git clone https://github.com/input-output-hk/cardano-node
cd cardano-node
git fetch --tags --all
git checkout 1.33.0
echo -e "package cardano-crypto-praos\n  flags: -external-libsodium-vrf" > cabal.project.local
$CNODE_HOME/scripts/cabal-build-all.sh -o
At the end, check the cardano-cli and cardano-node version
cardano-cli --version
cardano-node --version

The time varies depending on a lot of factors. These can range from the capabilities of your computer to the current length of the chain. For this reason, it's hard to give a blanket answer as it always varies.
But there is a silver lining, you can drastically reduce the build time by using the binary cache setup by iohk:  https://github.com/input-output-hk/cardano-node/blob/master/doc/getting-started/building-the-node-using-nix.md#iohk-binary-cache
Hope this was helpful.
But you can figure it out.
Step 1) using CardanoScan to figure out the current epoch and the current slot it will also display the number of slots in an epoch.
Step 2) let the build process continue for a while a time how long it takes to reach X slot. The larger the X you chose the better the approximation. The amount of time is called t.
Step 3) ((current epoch x  slots in an epoch ) + Current Slot) * t/X approx How long it will take.

You could just install the Deadules Wallet. Due to it being a full node, it must install the Cardano node in the background. The reason I suggest this is that it's easier to find documentation and youtube videos for Deadules than it is for building the node from the repo.
You can do all the same stuff with the Deadules node as the one from the repo because they are basically the same thing. This includes running a local server that acts as a query API to the blockchain.


text:
ValidationError ValueContainsLessThanMinAda in Week02 Homework1.hs (cohort #3)
currently in the 3rd cohort and doing week 2 HW, specifically Homework1.hs. My code compiles, but when I run in the local playground and try the 'give' endpoint, I just keep getting 'Contract instance stopped with error: "WalletError (ValidationError (ValueContainsLessThanMinAda...' which from what I can find means I need to send a certain ADA value as a transaction fee along with the lovelace amount specified in 'give'.
This seems like an error in the playground or in the rest of the provided code for this homework as there is no option to do so. Can anyone confirm? Below is the scenario I'm running.

Here also is the error I'm getting:
Contract instance stopped with error: "WalletError (ValidationError (ValueContainsLessThanMinAda (Tx {txInputs = fromList [TxIn {txInRef = TxOutRef {txOutRefId = 6945becead343ee16a04848adee6d24bcf05129b355021411a0b65eca6e6624e, txOutRefIdx = 1}, txInType = Just ConsumePublicKeyAddress}], txCollateral = fromList [], txOutputs = [TxOut {txOutAddress = Address {addressCredential = PubKeyCredential a2c20c77887ace1cd986193e4e75babd8993cfd56995cd5cfce609c2, addressStakingCredential = Nothing}, txOutValue = Value (Map [(,Map [(\"\",99900000)])]), txOutDatumHash = Nothing},TxOut {txOutAddress = Address {addressCredential = ScriptCredential 847f43379bc66c74dcbe4b92912dd88a44eaa66cde36c55b9d082365, addressStakingCredential = Nothing}, txOutValue = Value (Map [(,Map [(\"\",100000)])]), txOutDatumHash = Just 923918e403bf43c34b4ef6b48eb2ee04babed17320d8d1b9ff9ad086e86f44ec}], txMint = Value (Map []), txFee = Value (Map []), txValidRange = Interval {ivFrom = LowerBound NegInf True, ivTo = UpperBound PosInf True}, txMintScripts = fromList [], txSignatures = fromList [(8d9de88fbf445b7f6c3875a14daba94caee2ffcbc9ac211c95aba0a2f5711853,5a77c67d8fa23cd9a1f2a3e496a323ce8ffd0468d99491e4b651ea6b385a34dc6dc9085d812cbb00ccb95bdc9946ad9c1d8cffae640ecb82c2bfdc1794c0d907)], txRedeemers = fromList [], txData = fromList [(923918e403bf43c34b4ef6b48eb2ee04babed17320d8d1b9ff9ad086e86f44ec,Datum {getDatum = Constr 0 []})]}) (TxOut {txOutAddress = Address {addressCredential = ScriptCredential 847f43379bc66c74dcbe4b92912dd88a44eaa66cde36c55b9d082365, addressStakingCredential = Nothing}, txOutValue = Value (Map [(,Map [(\"\",100000)])]), txOutDatumHash = Just 923918e403bf43c34b4ef6b48eb2ee04babed17320d8d1b9ff9ad086e86f44ec})))" ]

Edit to add: here's my code as well, the parts that I edited at least

There's a constraint that an UTXO must have at least 2 ADA (2.000.000 lovelaces).
I guess that because you are giving less than this value (100.000 lovelaces) you get that error.

Retried with 2 ADA, and it worked. One other thing I did though was do a 'cabal update' and 'cabal build' before starting the playground. I might have missed doing that when switching to week 2


text:
bootstrap chain-index.db
The process to sync the plutus-pab chain-index for the testnet takes over 3+ days now and will take longer as time goes on.   Is it possible to bootstrap the chain-index sync process to reduce the manual sync process?  I've tried copying over the chain-index.db (and referencing that file in the chain-index-config.json  file) that was already sync'd from another machine, but it appears to be starting over again. Thank you.

Copying over chain-index.db should work. What exacly are you running on the command line?

Thanks for confirming.   The command I am running is from the plutus-pab/test-node readme.   cabal exec -- plutus-chain-index --config testnet/chain-index-config.json start-index.

Chain-index tries to use the existing db file, but if anything goes wrong it just starts over, so it's hard to diagnose. It could be a version difference. Or it could be a silly mistake, but without error it's hard to say.
You could try simple things like running it for a bit on the new machine and copying the file over to the old machine and see if it picks that up.

Thanks for the answer and yes, it is a differen't version of chain-index that I am trying to bootstrap, so most likely that is what the issue is.

It seems, that syncing chain-index.db is faster on a Linux in a Windows Subsystem for Linux (WSL2) than in a standalone Linux. This might be caused of a better virtual memory manager on Windows or some special compiled-in kernel features.
On my Windows 11 Home / WSL2 Ubuntu-20.04 system with 16 GB RAM and AMD Ryzen 5 3500U 2.10 GHz processor and SSD, syncing on 2022-04-20 took about 14 hours.
Kernel version of my WSL2 (uname -r): 5.4.72-microsoft-standard-WSL2 of 2021-06-07, see Kernel Updates.


text:
How can I set up my dev environment faster after pulling the pioneer code repos for each week
Each week so far it takes me over 1.5 hours to bring my dev environment up to date after updating the plutus-pioneer-program and plutus-app repos. This is really painful.
I'm wondering if someone can show me how to improve this startup time - possibly avoid unneeded steps, suggest some optimization settings (if any exist)...
I've listed my environment update process below. Any advice on how to streamline this and reduce my startup time would be much appreciated. Note I'm running on Intel Mac (BigSur), I'm in Cohort 3, I'm new to nix and cabal and for the first two weeks I had trouble getting the playground up reliably so after much experimenting I'm down to the following process that seems to work, but it takes a long time!
Summary of steps I need to do each week:

open a terminal and run from my PPP code directory:

cd plutus-pioneers-program
git pull origin plutus-pioneers-program // gets main branch

look inside code/weekxx/cabal.project and find latest plutus-app commit branch -> say ABCDEF
cd to plutus-app directory and do the following

 a) git pull origin plutus-apps // gets main branch
 b) git checkout ABCDEF   // to align plutus-apps code with this week's ppp commit
 c) nix-build -A plutus-playground.client
 d) nix-build -A plutus-playground.server
 e) nix-build -A plutus-playground.generate-purescript
 f) nix-build -A plutus-playground.start-backend

Generally these first steps are reasonably fast although sometimes the nix-builds can take up to 5 min each.

Then I run

nix-shell -v   // -v gives verbose output... nice to watch that it is doing something

this can take a long time each week: 30-60 min

within the shell I run

cd ../plutus-playground-client
plutus-playground-generate-purs    // this can take a while
GC_DONT_GC=1 plutus-playground-server   // start server

open a new terminal/tab at plutus-app root and run

nix-shell -v // again

generally the second nix shell is faster - completing in 5-10 minutes.

within this shell

cd ../plutus-playground-client
GC_DONT_GC=1 npm start   // to start the playground ui

open a 3rd terminal/tab at plutus-app root and run

nix-shell -v // again for cabal repl

similar startup time to 2nd shell

within this 3rd shell access cabal repl with

cd ppproot/plutus-pioneers-program/code/weekxx   // where xx is week # like 03
cabal repl

this takes another 30 minutes to load/build all the dependencies.  Do I really need them all?
At this point I finally have a stable playground to use !!

sometimes I also open another nix-shell and boot up the doc server if I need that.

I don't see anything here that can't be automated with a bit of shell scripting. Checking for the newest branch could probably be done with something like 'git branch | tail -1'. Why not write a cron job that starts all of this at 4 am, so it's ready when you get up?

yeah I can do the scripting, just wondering if I'm including stuff that doesn't need to be done.  For example do I really need all the nix-shells or is there some way I launch some of these processes as background processes from one nix-shell -  I've tried but things don't seem to work

My weekly setup steps are similar to yours. But there's a few steps you do that I skip and, so far, haven't had any issues.
I've never ran any of these:
nix-build -A plutus-playground.client
nix-build -A plutus-playground.server
nix-build -A plutus-playground.generate-purescript
nix-build -A plutus-playground.start-backend

or
plutus-playground-generate-purs

Everything else I do in basically the same order you do.

thanks, I'll try removing these.  They were required in the initial install (at least in the instructions I used). Anybody know why or when these would need to be rerun?  Under what conditions, if ever?

You can create command aliases or write bash scripts to automate certain commands. An example of aliases I've written for myself (in Linux):
alias plutus-nix='cd /home/datapool/plutus-apps; GC_DONT_GC=1 nix-shell'
alias plutus-server='cd plutus-playground-client;  GC_DONT_GC=1 plutus-
         playground-server'
alias plutus-client='cd plutus-playground-client;  GC_DONT_GC=1 npm
         start'

So basically I just run commands like plutus-nix -> plutus-server when I want the server, and plutus-nix -> plutus-client when I want the client.
Bear in mind I can do this easily in Linux but I would think it should be OK to write aliases as well in MacOS.

yes I could definitely use aliases to help with this.  Any thoughts on what I could do to speed these steps up?

Which shell do you use? You can put the aliases on the configuration file for your shell environment. For instance I use bash so I put my aliases in my .bashrc in my home folder.


text:
Can ADA locked on a script be staked?
I am curious to know what happens to ADA when it gets locked to a script as far as staking goes. In other words, can ADA locked at a script address by staked?

This is a brand new resource that's related to this topic which I thought might be interesting for devs to read!
https://github.com/Plutonomicon/plutonomicon/blob/main/stake-scripts.md

When you create an output with a script address, you can put whatever staking key you like on it. That staking key behaves exactly like staking keys do in all other outputs.
Scripts can see staking keys associated with outputs, so if you want to make an assertion about what staking key is used on an output, you can do that.
So yes, if you have an ongoing state machine you can assert that the funds are always staked with a particular key.
In addition, you can also have a script control the delegation rights itself. Each address has a payment credential (key or script hash), and can also have a stake credential (key or script hash — or a reference to a stake address registration certificate, which will yield you a key or script hash, but is more compact in the UTxO).

An Ada address is made up of 2 separate credentials, one for payment and one for staking. These are both treated independently and one, the other or both can be script hashes instead of plain key based addresses. This means the user putting funds in a smart contract can keep those funds associated with their stake address until the script is spent (at which time the person redeeming the script gets to choose what stake credential is used).

Is there an example of this? You mentioned the possibility of the UTxO "creator" to specify the delegation of that UTxO, is this regardless of the the location it ends up at? I thought that once send the funds are delegated to that which the address it sits at specify (not the transaction it originated from).

I would really like for this to be possible, but I don't see how.  Is there a way that I, a normal cardano defi degen can construct a transaction to provide liquidity to Sundae Swap, lock my ada/ pair up in one of their LP scripts and keep my ada staked but still get the LP tokens in return?  If this is doable, it needs to be more publicized than it is.

Yes. There are a few projects doing this, one of them is StakingDAO, which is in Catalyst Fund 7. I cannot give you details about how this is done, but I heard a few other people saying this is possible.


text:
Why would ">:i " work in the repl but not "> :t "?
Doing week 04, watching "PPP 030403 - The EmulatorTrace Monad"
In the repl, having already imported as follows

>import Data.Char
>import Text.Read
>import Plutus.Trace.Emulator
>import Data.Default

If I enter ":t TraceConfig" I see

Prelude Data.Char Text.Read Plutus.Trace.Emulator Data.Default> :t TraceConfig
TraceConfig
  :: (Wallet.Emulator.MultiAgent.EmulatorEvent' -> Maybe String)
     -> GHC.IO.Handle.Types.Handle -> TraceConfig
Prelude Data.Char Text.Read Plutus.Trace.Emulator Data.Default>

Attempting to explore that, I enter (and get error) as follows:

Prelude Data.Char Text.Read Plutus.Trace.Emulator Data.Default> :t Wallet.Emulator.MultiAgent.EmulatorEvent'

:1:1: error:
    Not in scope:
      data constructor ‘Wallet.Emulator.MultiAgent.EmulatorEvent'’
    No module named ‘Wallet.Emulator.MultiAgent’ is imported.

Prelude Data.Char Text.Read Plutus.Trace.Emulator Data.Default> :i Wallet.Emulator.MultiAgent.EmulatorEvent'
type Wallet.Emulator.MultiAgent.EmulatorEvent' :: *
data Wallet.Emulator.MultiAgent.EmulatorEvent'
  = Wallet.Emulator.MultiAgent.ChainEvent Wallet.Emulator.Chain.ChainEvent
  | Wallet.Emulator.MultiAgent.ClientEvent Wallet.Emulator.Wallet.Wallet
                                          Wallet.Emulator.NodeClient.NodeClientEvent
  | Wallet.Emulator.MultiAgent.WalletEvent Wallet.Emulator.Wallet.Wallet
                                         Wallet.Emulator.Wallet.WalletEvent
  | Wallet.Emulator.MultiAgent.ChainIndexEvent Wallet.Emulator.Wallet.Wallet
                                          plutus-chain-index-core-0.1.0.0:Plutus.ChainIndex.ChainIndexLog.ChainIndexLog
  | Wallet.Emulator.MultiAgent.SchedulerEvent Plutus.Trace.Scheduler.SchedulerLog
  | Wallet.Emulator.MultiAgent.InstanceEvent Plutus.Trace.Emulator.Types.ContractInstanceLog
  | Wallet.Emulator.MultiAgent.UserThreadEvent Plutus.Trace.Emulator.Types.UserThreadMsg
      -- Defined in ‘Wallet.Emulator.MultiAgent’
instance Eq Wallet.Emulator.MultiAgent.EmulatorEvent'
  -- Defined in ‘Wallet.Emulator.MultiAgent’
instance Show Wallet.Emulator.MultiAgent.EmulatorEvent'
  -- Defined in ‘Wallet.Emulator.MultiAgent’
Prelude Data.Char Text.Read Plutus.Trace.Emulator Data.Default>

My question is, why does ":i" (requesting info about) work, but ":t" (requesting merely the type, which is actually included in the info) does not?

Tracking these multiple nestings of data structures is straining my brain.

Take into account that :t is for getting the type of a function, and EmulatorEvent' is not a function but a type. So, because it's a type you can use :i EmulatorEvent' but not :t EmulatorEvent'.
You can use :t with the constructors (they are functions) of EmulatorEvent', say :t ChainEvent.

Part of me thinks this should "fail" gracefully, since the focus of the monad video was elegant failure.

What do you mean with fail gracefully? Can you elaborate?

@XiTouch, Do you consider that my answer is correct? I so, you might accept it and help others wiith the same question. Thanks!

your answer is helpful, correct, useful, the best offered, and the best ever likely to be offered so yes, it's "answered" and thank you. By "fail gracefully" I mean cabal should produce a message that is helpful and accurately informative, rather than basically "you screwed up, I won't help you, you should know better." For example, a message like "foo is not a type. Use {>:i foo} for info about foo".

@XiTouch, I agree that the message is not very helpful (in general Haskell error messages are not good), but this message doesn't come from cabal or Plutus. :t and :i is a ghci thing.


text:
Difference between "import" and load (as "> :l ")
Update: I am more confused.
If you follow the sequence below, you see that I

attempt to load Either.hs, and get a missing module error
attempt to load Monad.hs, and get a "one module loaded" happy message
attempt again to load Either.hs, and again get a missing module error
attempt to import Week04.Monad, and get no error or happy message, but "Week04.Monad" joins other modules before my Prelude prompt. So it sure looks like Week04.Monad is fully available.
attempt to load Either.hs and continue to get a missing module message, even though that module has been imported and is in my prompt.

So, still totally confused. If the repl cannot locate a module that has been loaded and imported, how can this error message be made to go away? Or does it mean nothing?
Prelude Data.Char Text.Read Plutus.Trace.Emulator Data.Default> :l src/Week04/Either.hs

<no location info>: warning: [-Wmissing-home-modules]
    These modules are needed for compilation but not listed in your .cabal file's other-modules:
        Week04.Monad
Ok, two modules loaded.
Prelude Data.Char Text.Read Plutus.Trace.Emulator Data.Default Week04.Either> :l src/Week04/Monad.hs
Ok, one module loaded.
Prelude Data.Char Text.Read Plutus.Trace.Emulator Data.Default Week04.Monad> :l src/Week04/Either.hs

<no location info>: warning: [-Wmissing-home-modules]
    These modules are needed for compilation but not listed in your .cabal file's other-modules:
        Week04.Monad
Ok, two modules loaded.
Prelude Data.Char Text.Read Plutus.Trace.Emulator Data.Default Week04.Either> import Week04.Monad
Prelude Data.Char Text.Read Plutus.Trace.Emulator Data.Default Week04.Monad Week04.Either> :l src/Week04/Either.hs

<no location info>: warning: [-Wmissing-home-modules]
    These modules are needed for compilation but not listed in your .cabal file's other-modules:
        Week04.Monad
Ok, two modules loaded.
Prelude Data.Char Text.Read Plutus.Trace.Emulator Data.Default Week04.Monad Week04.Either>
Prelude Data.Char Text.Read Plutus.Trace.Emulator Data.Default Week04.Monad Week04.Either>

======== Original Question ========
I'm pulling this from a comment thread on another question as it is getting long and merits a separate answer.
In the repl, typically if I enter (as an example)

:l src/Week04/Either.hs

I was getting an error (that is fixed and is not the question here). Another helpful Pioneer suggested doing

import Week04.Either

However, I get the following error with that

Prelude Data.Char Text.Read Plutus.Trace.Emulator Data.Default> import Week04.Either
<no location info>: error:
    Could not load module ‘Week04.Either’
    It is a member of the hidden package ‘plutus-pioneer-program-week04-0.1.0.0’.
    Perhaps you need to add ‘plutus-pioneer-program-week04’ to the build-depends in your .cabal file.
Prelude Data.Char Text.Read Plutus.Trace.Emulator Data.Default>

I suspect this is either a directory level problem or (more likely) a "compiled vs interpreted" issue but still new enough to be confused. Can anyone clarify exactly how such things should work?

Are you still "more confused" after my answer?

There is at least two things contributing to the confusion here.

attempt to load Either.hs, and get a missing module error

You don't actually get a missing module error. You get a warning that Week04.Monad is "not listed in your .cabal file's other-modules". So it warns that you may have problems in the cabal-file but the repl compiles and loads the modules Week04.Monad and Week04.Either just fine. So you get Ok, two modules loaded.

attempt to load Monad.hs, and get a "one module loaded" happy message

Week04.Monad has no dependencies so it loads without warning.

attempt again to load Either.hs, and again get a missing module error

Nothing has changed here so this step is exactly the same as step 1 and you get exactly the same result. Why steps 1 and 3 are the same is explained in the description of the :load-command:

"All previously loaded modules, except package modules, are forgotten.
The new set of modules is known as the target set. Note that :load can
be used without any arguments to unload all the currently loaded
modules and bindings.".

The documentation can be found from GHCi commands
The main difference between :load and import is that :load sets the current context in the repl so that you can access the internals of the module that has been loaded as current context. With import you only get access to things that have been exported from the respective module.

Thanks, that's helpful. I think what it boils down to is that GHCi is broken issuing an error message that is either unhelpful or unfixable. I have noticed that in other places, eg. "*** WARNING: /Users/jwb/.ghci is writable by someone else, IGNORING!
Suggested fix: execute 'chmod go-w /Users/jwb/.ghci'". Combined with plutus being new and not-yet-finished, me being new to Haskell, Haskell being difficult, and the entire linkage/reference/nesting structure feeling very opaque, I am feeling perpetually lost in a way I have never felt with any other language.

Does this help? I usually import packages (e.g. Control.Monad) and load local files (src/Week04/Either.hs).
https://www.titanwolf.org/Network/q/c87eb1e3-190b-4f64-ac1f-22ee5b998f0d/y

Unfortunately, no. See my update in the OP. I don't know how the repl can obviously "see" the module but also simultaneously can't see the module.

I couldn't find an explanation of what is going on. The warning message is misleading, adding the file to 'other-modules' results in a duplication error. Moreover :show modules shows that both modules have been successfully loaded. I get no warning if I do  :l src/Week04/Either.hs src/Week04/Monad.hs.


text:
How to start building native tokens on ADA block chain
I saw this blog post from IOHK about building native tokens on ada network. In this particular post apart from command lines a web interface is being discussed but I can find a valid link on that particular post is there some one can give me a good direction in this?
The link which i have saw is below.
https://iohk.io/en/blog/posts/2021/02/18/building-native-tokens-on-cardano-for-pleasure-and-profit/
I have also saw this post as well. https://forum.cardano.org/t/cardano-gui-token-builder/80971/5 .
Atleast If a command line utility is available please share me some step by step instructions for the same.
Eagerly waiting to build token on ADA

Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.

Here are a few resources I found:
https://developers.cardano.org/docs/native-tokens/minting/
https://docs.cardano.org/native-tokens/getting-started
https://forum.cardano.org/t/an-introduction-to-minting-native-tokens-on-cardano/49734

I saw thease guides but i am looking for some web based UI i saw the mention for the same on IOHK blog but i was not able to detect any link that directs me to the mentioned UI. I am wondering is there something like that is available or not.

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


text:
Block diffusion pipelining and spam attacks
In a recent blog post we got more information about block diffusion pipelining: https://iohk.io/en/blog/posts/2022/02/01/introducing-pipelining-cardanos-consensus-layer-scaling-solution/
Technically blocks are propagated before being validated, which in theory opens the network to the risk of spam attacks.  Anyone could create malicious blocks and squirt them into the network, as they are forwarded without validation, then the network resources are squandered.
However we see in the article that block headers are validated independently of block bodies, and based on the graphic, what diffusion piplining is really doing is splitting propagation of blocks into validated headers and validated bodies.  The dark grey areas in the figures appear to be validation, and the light grey areas appear to be transmission.
Q1/ Have I understood the above accurately?
Q2/ What is being validated in the header?  This seems to be critical, it would seem merely validating the header came from a block producer that was verifiable as being able to produce a block in that slot, would be enough.  Although the block producer could then follow an invalid block body if they wanted to, this would make the block producer lose rewards.
Edit Q3/ If a valid block producer chose to transmit 1000s of valid block headers at multiple relay nodes, how would that impact diffusion and consensus on the network?

There is a document being worked on that will better explain this. As soon as that document is posted publicly I will post a link.

From a member of the IOG networking team.

Q1/ Have I understood the above accurately?

Generally, yes. Except wording suggests that you don't realize diffusion is already split into headers and block: that's not new as of pipelining, though it is very relevant to this pipelining strategy.

Q2/ What is being validated in the header? This seems to be critical, it would seem merely validating the header came from a block producer that was verifiable as being able to produce a block in that slot, would be enough. Although the block producer could then follow an invalid block body if they wanted to, this would make the block producer lose rewards.

The crucial info in the header is indeed the proof of the right to mint a block.As you note, a block producer should not mint a block that extends a chain until they have validated that chain.

Edit Q3/ If a valid block producer chose to transmit 1000s of valid block headers at multiple relay nodes, how would that impact diffusion and consensus on the network?

We have also anticipated this and have designed a mitigation strategy discussed in the document.

Thanks, I suppose from the graphic it was clear headers are already propagating discreetly from block bodies, but i had perhaps not explicitly absorbed that. Q3 is important as headers are small and could be constructed easily with a Sybil style attack.  Not surprised this has been addressed, but look forward to the document.  Thanks.


text:
How to do a plutus smart contract vending machine?
I am building a vending machine where the users have to first send ADA to some address then my backend selects NFTs and sends back to the user who payed. I have been wondering if is there a way to do it using smart contracts?
The NFTs are all locked in a contract and we make the tx to the contract from the front end to unlock them. But my problem is: How could I make that the NFTs are randomly seleceted?
The front end might randomly select some. But when the Browser Wallet ask for sign the transaction it will show which NFTs are selected and then the user might decline or accept the transaction depending of the NFTs.
The main problem is that NFT must be randomly selected. How can I solve this problem?

In Cardano, all transactions are deterministic, which means you can not have unpredictable randomness, even if you inject an entropy source from, lets say and Oracle, the user who constructs the transaction will always know in advance the outcome, all variables are known at TX construction time. He then can choose to not sign/send the transaction if the outcome is undesirable.
One way to solve this problem, is to obfuscate from the user the meaning of the outcome, he will know which NFT he is getting (Asset Name), but maybe the NFT metadata is not revealed until after the NFT has been bought. Although this would require some off-chain business logic (when NFT A is bought, publish NFT A metadata). This would work better by committing to the metadata by pre-publishing a Hash of it, so the buyer knows the metadata that is being published was not changed after the fact. Sadly CIP-0025 doesn't allow to do this via smart contract because it relies on transaction metadata which cannot be read from smart contracts, so it would have to be done via an honor system.
Another approach would be to use a model similar to the current liquidity pools (I.E Minswap), The users initiate a buy order by sending ADA to a contract address, then a batcher would continuously select these orders from contract A, and execute the buy by taking the NFTs from contract B and sending it to the users. At this point, the batcher could use an Oracle as the entropy source, or the UTXO ID hashed with some secret value to pick the NFT to send to the user. This would still require some off-chain code (the batcher), but at least you could program some fairness into contracts A and B, for example, by preventing anyone to claim the money the user deposited in the buy order without sending the NFT back. (claiming the ADA in buy Order would require an NFT of a specific policy to be returned to the sender). Extra logic could be put in place to for example, allow the original sender to claim back its ADA if the order has not been executed in X amount of time.

In addition to this great answer, one could also use a VRF to provide provable randomness. This is more involved, though.

I also think the hash scheme can work. Pre mint your NFT's and create tokens that are named the hash of the NFT's with a nonce. Sell tokens that represent these hashes. Later reveal the nonce that give access to the unique name the NFT's has (this is visible for plutus in a transaction). Users can now claim their NFT.

This is a great idea @Fermat :)

You should post this as a separate answer, I think this approach would work great!

First option is not feasible.. metadata URL is not a function like in Solidity contracts. metadata is the hash of the mint. I was thinking on using a hash of the blocktimestamp togueter with the address to generate pseudoradomless.. For Real Randomless..  The use of an oracle is inevitable with out any doubt.

@AliciaBasilio, the Cardano blockchain is passive and fully deterministic, validators only check that transactions are valid. In practice, this means that validators do not fetch additional data that is not already in the signed transaction. The block timestamp is thus something you cannot access. What you do have in a transaction is the validity interval, which is the time for which a transaction is valid.

You are right! me bad about that

Really like the idea with the transforming metadata! You could 1) sell (via smart contract) a lootbox-style NFT with a hash of the future metadata in its metadata, and after a purchase 2) re-create and burn a clone of the sold NFT using the actual metadata in its mint tx - this way you would transform the lootbox nft right after the sale into the real nft without further transactions on the buyer side. Only requirement is that the policy still allows re-minting for long enough. And step 2 is triggered off-chain by your server. Or am I missing anything here?

Lars already gave a pretty good answer to the randomness problem here. Basically, an oracle is probably the easiest and best way to achieve randomness with entropy.
If you want to avoid an oracle, you might be able to seed your randomness with the transaction ID. There could be some concerns with reverse engineering there, but depending on the scale of your project those concerns might be unrealistic.

Supouse the oracle gives the random number (in some sense not specified), then? what should i do ? what transactions should i do and how?

There’s a chance I misunderstood you, but my assumption here is that your third paragraph constitutes an issue you want to avoid, not a feature you want to include. If that’s the case, I think you only need 2 transactions.
The first would be a List transaction which allows you to place an NFT you want to sell in a UTXO at the vending machine's script address.
The second would be a Buy transaction, which allows anyone to pay an amount to get NFTs from the machine. Here you use your oracle to decide which NFT UTXOs to consume, sending the NFTs they contain back to the buyer.

Yes I think  two transactions are needed


text:
Discovering the script source based on address
How to find out what scripts / smart contracts are holding my assets and how could I recover these assets if the script allows?
I have in my transactions log a transfer of 500 ADA to this script address:
DdzFFzCqrht3C53JYNZ3uRUGw7KBESCkV9854fK736678CPVPuKD1uVKLeemubBpDe1EWJNjCofKLATPCfKawQ4Pu2M7BZgFSvDVMbiK
(logged here)
But I don't know what script is this and how to recover my balance. Is there a way to know, based on the script address, which contract is this and how could I recover my balance?

I think it is not posible, because a script address is a hash of the script, and we can not go back from hash to what generated the hash.

You can't get the Smart contract code starting from its address.
As @zhekson already mentioned, smart contract addresses are hashes of the code (the serialization of the untyped Plutus core to be clear).
Hash functions, that we can call h(x), are studied so that there can't be an h-1(x), so given a hash we can't know from which input it was generated via an inverse computation (if that was possible then the whole cryptography thing wouldn't stand).
We can get an input from a hash only if, when creating the hash of the input you store it somewhere and assign to it the generated hash, then we just got a hash-map.
It is possible however to get the Untyped Plutus, program starting from the flat serialized one.

That's a Byron address, not a plutus script address. Likely being sent to an exchange.

This may be factually correct, but doesn't answer the poster's question.

Firstly, the address you referenced in your question is a Byron address, as pointed out by Samuel. Byron addresses are payment only, and are not associated with scripts (smart contracts) or staking.
Second, even if it was a Shelley-era and/or script address, it is not possible to derive the actual smart contract code from a script address because, as Alicia pointed out, script addresses are hash-derivatives of the underlying code. Hashes are one-way by nature; they cannot be reverted back to their original data.


text:
How to estimate execution steps and memory units for a Plutus script?
Question
Is there a tool/API that can calculate the number of steps and max consumed memory units for a Plutus script, given all necessary inputs, e.g. datum, redeemer, and script context?
I could be wrong, but it seems like plutus-core provides an evaluation tool that can probably output something useful. However, I don't know how to use the tool. Any instructions of its usage will be extremely helpful.
Background
I am looking for such tool/API to calculate the min fee required for transactions that consume UTxOs locked in Plutus scripts while not depending on Plutus Application Backend (PAB), because I am building a standalone Python library through which users can write entire off-chain codes in Python. It is fine to have plutus-core in the runtime environment, but it is not ideal if I need to write Haskell code or use PAB to solve this problem.
Related questions
How to calculate fees for Plutus Smart Contract?  The answer linked to a fee calculator, but this is not what I am looking for, because the calculator still requires users to provide the number of execution steps and memory units.
How to calculate fees in Plutus It is basically asking the same question, except that usage of PAB is allowed.

Looks like Ogmios just released a new feature that solves this exact problem. Basically, users can now evaluate a transaction through Ogmios's API EvaluateTx and get accurate execution steps and memory from the response.

You can also use the build command in cardano-cli. Specify the --calculate-plutus-script-cost flag and you will get a JSON object formatted as follows:
{
"executionUnits": {
"memory": 1700,
"steps": 476468
},
"lovelaceCost": 133,
"scriptHash": "67f33146617a5e61936081db3b2117cbf59bd2123748f58ac9678656"
}


text:
How to figure out what address to query for utxos when minting
Following the iohk guide to minting assets we identify the input utxo using the following command:
cardano-cli query utxo --address $address --testnet-magic 1097911063

This is all well and good if you know the address which you wish to query. However, if you are using wallet software (including cardano-wallet) you will find that the change behavior of wallets will move assets across addresses (but within the same wallet). As such, just because you sent ada to an address at one time does not mean you will find it there in the future if you have performed any transactions since sending it.
We'd like to know if anyone is aware of a better approach to identifying a source utxo for buildling an asset minting transaction when starting with a wallet rather than with an address and using the core standard toolset cardano-wallet, cardano-cli, cardano-address, etc

If you run this bash script, you will create a wallet, load it in cardano-wallet and get all the info you need, including the address you are needing. The script if going to create some files for the wallet in the same folder where you are running it.
I can show you also how to do it using only Cardano Cli if you want.
Firts, set this ENV variables for everything to work:
CARDANO_WALLET=rute to your cardano wallet folder
CARDANO_WALLET_PORT=port used in the cardano wallet server (eg. 9091)
CARDANO_NODE=rute to your cardano node folder
NETWORK_WITH_MAGIC=testnet-magic 1097911063

#!/bin/bash

if [ -z "$1" ]; then
    echo "File name:"
    read file
else
  file=$1
fi

if [ -z "$2" ]; then
    echo "Name:"
    read name
else
  name=$2
fi

if [ -z "$3" ]; then
    echo "Passphrase (10 or more characters):"
    read passphrase
else
  passphrase=$3
fi

echo "Creating Wallet with name $name passphrase $passphrase in $file.json"

phrase=$($CARDANO_WALLET/cardano-wallet recovery-phrase generate)

x=''
sep=''
for word in $phrase
do
    x=$x$sep'"'$word'"'
    sep=', '
done

cat > $file.json <<- EOM
{ "name": "$name"
, "mnemonic_sentence": [$x]
, "passphrase": "$passphrase"
}
EOM

echo "Saved restoration file to $file.json"

echo $phrase | $CARDANO_WALLET/cardano-wallet key from-recovery-phrase Shelley > $file.root.prv

cat $file.root.prv | $CARDANO_WALLET/cardano-wallet key walletid > $file.id

wallet_Id=$(cat $file.id)

echo "Wallet ID:" $wallet_Id

curl -H "content-type: application/json" -XPOST \
  -d @$file.json \
  localhost:$CARDANO_WALLET_PORT/v2/wallets

echo ""

addresses=$(curl -H "content-type: application/json" \
      -XGET localhost:$CARDANO_WALLET_PORT/v2/wallets/$wallet_Id/addresses | jq -r '.[]' )

echo $addresses| jq -r '.id' >$file.addrs

echo "Wallet Addresses:"

echo $addresses| jq -r '.id' | nl

address=$(echo $addresses| jq -r '.id'| sed -n 1p)

echo ""

echo "Firts Address:" $address

echo $address> $file.addr

echo "UTxOs At Address:"

$CARDANO_NODE/cardano-cli query utxo --address $address --$NETWORK_WITH_MAGIC

I hope it helps!

for the first point / question, about finding the source address
i would do the follow,
create a "project in blockfrost :
blockfrost.io/
and then execute the commands below:
curl -H 'project_id: type_blockfrost_Project_ID'
https://cardano-mainnet.blockfrost.io/api/v0/txs/${tx_hash}/utxos
| jq '.inputs' | jq '.[0]' | jq '.address' | sed 's/^.//;s/.$//'

I appreciate your feedback, but using a third party service is not an option. We are interested in the low level details of how to do this using Cardano directly.
Further, I think you've misunderstood our goals. We are not trying to determine the utxos related to a tx. We are trying to find a utxo to use as input to a minting tx.

ok the "source" confused me.
sorry for the misunderstanding.
the only option i find for the "cardano-cli query utxo " is only --address.-
then, sorry mate still dont have answer

here is a list of subcommands of the cardano-wallet.
i didnt know you can do it from "wallet",
but looks like you have this options.
transaction
create


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:
Javascript assetName Decoding
I'm trying to figure out a reliable way to decode an assetName using JavaScript.
My current implementation is this:
function hexToBytes (hex) {
    if(!hex){
        return hex;
    } else {
        const bytes = new Uint8Array(hex.length / 2);
        for (let i = 0; i !== bytes.length; i++) {
            bytes[i] = parseInt(hex.substr(i * 2, 2), 16);
        }
        return bytes;
    }
}

return new TextDecoder("UTF-8").decode(hexToBytes(encodedAssetName))

The above seems to be work most of the time but on occasion seems to stumble on some assetNames.
As an alternative, I've been trying to see if the cardano-serialization-lib has anything built in that can help.
The most I can find is this:
let assetName = Loader.Cardano.AssetName.new(Buffer.from(hex, 'hex'))

assetName then seems to only have 3 functions and the name function returns a Uint8Array, which when passed using new TextDecoder().decode(assetName.name()) returns the same result as my current implementation.
Is the cardano-serialization-lib method the best way to decode assetNames or is there a better way?
Any help would be greatly appreciated!

At this stage it looks like both methods work well, but the JS version is obviously lighter.

The asset names are not guaranteed to be UTF-8 encoded. They are just a string of 8-bit bytes.

cardano-serialization-lib does pretty much everything for building and reading transactions and interacting with the webwallets.
Here is how you can extract all the asset names from the a user's wallet and process them to get the policyid, the assename hex value and the asset name string from each of the assets
This part this.API.getUtxos() reads all UTXOs from the user's wallet and TransactionUnspentOutput is a function from cardano-serialization-lib
    /**
     * Gets the UTXOs from the user's wallet and then
     * stores in an object in the state
     * @returns {Promise<void>}
     */

    getUtxos = async () => {

        let Utxos = [];

        try {
            const rawUtxos = await this.API.getUtxos();

            for (const rawUtxo of rawUtxos) {
                const utxo = TransactionUnspentOutput.from_bytes(Buffer.from(rawUtxo, "hex"));
                const input = utxo.input();
                const txid = Buffer.from(input.transaction_id().to_bytes(), "utf8").toString("hex");
                const txindx = input.index();
                const output = utxo.output();
                const amount = output.amount().coin().to_str(); // ADA amount in lovelace
                const multiasset = output.amount().multiasset();
                let multiAssetStr = "";

                if (multiasset) {
                    const keys = multiasset.keys() // policy Ids of thee multiasset
                    const N = keys.len();
                    // console.log(`${N} Multiassets in the UTXO`)

                    for (let i = 0; i < N; i++){
                        const policyId = keys.get(i);
                        const policyIdHex = Buffer.from(policyId.to_bytes(), "utf8").toString("hex");
                        // console.log(`policyId: ${policyIdHex}`)
                        const assets = multiasset.get(policyId)
                        const assetNames = assets.keys();
                        const K = assetNames.len()
                        // console.log(`${K} Assets in the Multiasset`)

                        for (let j = 0; j < K; j++) {
                            const assetName = assetNames.get(j);
                            const assetNameString = Buffer.from(assetName.name(),"utf8").toString();
                            const assetNameHex = Buffer.from(assetName.name(),"utf8").toString("hex")
                            const multiassetAmt = multiasset.get_asset(policyId, assetName)
                            multiAssetStr += `+ ${multiassetAmt.to_str()} + ${policyIdHex}.${assetNameHex} (${assetNameString})`
                            // console.log(assetNameString)
                            // console.log(`Asset Name: ${assetNameHex}`)
                        }
                    }
                }

                const obj = {
                    txid: txid,
                    txindx: txindx,
                    amount: amount,
                    str: `${txid} #${txindx} = ${amount}`,
                    multiAssetStr: multiAssetStr,
                    TransactionUnspentOutput: utxo
                }
                Utxos.push(obj);
                // console.log(`utxo: ${str}`)
            }
            this.setState({Utxos})
        } catch (err) {
            console.log(err)
        }
    }

Or you can take a look at my git repo with this code and other examples of cardano-serialization-lib: https://github.com/dynamicstrategies/cardano-wallet-connector

I did use  console.log(output.amount().multiasset().get(aadaTokenPolicy).get(aadaTokenName).to_str()) to transform output->Value->MultiAsset->Asset->AssetName->string.
For your case .to_str() might do the work.


text:
TransctionBuilder.new() in cardano-serialization-lib 10.0.0
With the new version of library TranasctionBuilder.new() arguments have changed.
When running:
    const txBuilder = this.S.TransactionBuilder.new(
      this.S.LinearFee.new(
        this.S.BigNum.from_str(protocolParameters.linearFee.minFeeA),
        this.S.BigNum.from_str(protocolParameters.linearFee.minFeeB)
      ),
      this.S.BigNum.from_str(protocolParameters.minUtxo),
      this.S.BigNum.from_str(protocolParameters.poolDeposit),
      this.S.BigNum.from_str(protocolParameters.keyDeposit),
      this.S.BigNum.from_str(protocolParameters.coinsPerUtxoWord),
      protocolParameters.maxValSize,
      protocolParameters.maxTxSize,
      protocolParameters.priceMem,
      protocolParameters.priceStep,
      this.S.LanguageViews.new(Buffer.from(languageViews, "hex"))
    );

It throws an error
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'new')

What do I do wrong here?

You should probably now use the ConfigBuilder to create a config for creating the TransactionBuilder.
This should do the trick:
const cfg = TransactionBuilderConfigBuilder.new()
      .fee_algo(this.S.LinearFee.new(
        this.S.BigNum.from_str(protocolParameters.linearFee.minFeeA),
        this.S.BigNum.from_str(protocolParameters.linearFee.minFeeB)
      ))
      .pool_deposit(this.S.BigNum.from_str(protocolParameters.poolDeposit))
      .key_deposit(this.S.BigNum.from_str(protocolParameters.keyDeposit))
      .max_tx_size(protocolParameters.maxTxSize)
      .max_value_size(protocolParameters.maxValSize)
      .coins_per_utxo_word(this.S.BigNum.from_str(protocolParameters.coinsPerUtxoWord))
      .build()

const txBuilder = this.S.TransactionBuilder.new(cfg);

It worked out. Thank you.

the TransactionBuilderConfigBuilder is not part of @cardano/serialization-lib-asmjs .. does anyone know why ?

Just checked and it should be there. Maybe double check the version you have installed. It must be one above 10.0.0 - try installing the latest (which is currently 10.2.0) via: npm i @emurgo/cardano-serialization-lib-asmjs@latest


text:
Transaction with Cardano-CLI Sumbmits But Nothing Happens
I am trying to delegate a wallet through cardano-cli for most it was going okay, but more recently even though I get the message Transaction successfully submitted. after submitting the transaction, no money gets transferred. The same happens when I try to delegate the wallet.
I noticed that on the cardano-node logs I get something that makes me think some sort of ofrk is happening?  Ignoring block already in DB
[x-XP:cardano.node.ChainDB:Info:47551] [2022-02-07 13:30:47.64 UTC] before next, messages elided = 94461957158106
[x-XP:cardano.node.ChainDB:Info:47551] [2022-02-07 13:30:47.64 UTC] Ignoring block already in DB: ce7b38a4b05435f4ebe07e1ba52154b6db7131bd062c7809bc5d4ef29b27f3f3 at slot 52674352
[x-XP:cardano.node.Mempool:Info:47597] [2022-02-07 13:30:49.49 UTC] fromList [("tx",Object (fromList [("txid",String "36f15e82")])),("kind",String "TraceMempoolAddedTx"),("mempoolSize",Object (fromList [("bytes",Number 399.0),("numTxs",Number 1.0)]))]

[x-XP:cardano.node.ChainDB:Info:35] [2022-02-07 13:37:17.56 UTC] Block fits onto some fork: ebf7869a4b082c3d4b2ec60d14f2e8d8f803b9e5a3ab9cd7536927dc9a2b8227 at slot 52674744
[x-XP:cardano.node.ChainDB:Notice:35] [2022-02-07 13:37:17.66 UTC] Switched to a fork, new tip: ebf7869a4b082c3d4b2ec60d14f2e8d8f803b9e5a3ab9cd7536927dc9a2b8227 at slot 52674744

I tried to delete the entire db and resync the entire cardano-node but as soon as I tried to make a transaction the same as above happenend.
How can I fix this so to have successful transactions again? what coudl I be doing wrong?

actually it seem the transactions went through now, so I guess it was indeed a bad database, not sure why it still says Ignore block though. Possible that the problem I had earlier was because I was sending transactions in parallel rather than sequentially and made me fork?

Likely this was congestion in getting the transaction adopted rather than the db state being an issue. As for Ignore block, this is normal consensus layer stuff. Another node on network said I have this block, and the node looked at it's current state and decided it's fork was better than the one that block fit on so it never asked for the block.

oh yes, seeing all the discussion developing right now on certain type of transaction having a preferential way with SPOs makes it more clear my problems where transactions go through only every so often. I just told that once submitted, the Tx was taken, even if it was going to take more time.. increasing TTL could help?

SPOs cannot influence the order of the transactions. Most probably what happened is that your TTL wasn't long enough and the deadline slot no had already been surpassed once your transaction was being processed. "Transaction successfully submitted" just means that the transaction passed the initial checks (balanced values, appropriate signatures, sufficient fee, etc) and has been added to the mempool. However, once the transaction actually starts being processed there are other on-chain checks that are performed, such as valid-before, valid-after and any plutus validators.


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:
How to get Utxos from emulation wallet
I'm doing integration tests with Emulation
As far as I understand under emulation wallets have initial funds.
Example:
test :: IO ()
test = runEmulatorTraceIO $ do
    let
        w1 = knownWallet 1
        walletAddress = mockWalletAddress w1
        # how to get utxos for walletAddress under emulator ????

This helper function can help you. It returns the list of TxOutRef and TxOut owned by an address.
import Control.Lens
import qualified Data.Map as Map
import Ledger
import Ledger.Index
import Plutus.Trace.Emulator qualified as Trace

getUtxos :: Address -> Trace.EmulatorTrace [(TxOutRef, TxOut)]
getUtxos addr = do
    state <- Trace.chainState
    let utxoIndex = getIndex $ state ^. Trace.index
        utxos     =  [(oref, o) | (oref, o) <- Map.toList utxoIndex, txOutAddress o == addr]
    pure utxos

Oh. Really many thanks ! I'll check

@ViktorYasterbov, does it work?

Yeah. Great. Everything is fine. Thank you for help. you gave me good hint eventually how to process things under Emulator. I did the same for getting values etc


text:
Protocol parameters file to calculate min fee
I'm wondering, do I need to always generate a new protocols parameters JSON file when generating the min transaction fee?
I have a few transactions to make and I really don't like to be creating a new protocol parameters file before calculating the min fee. Is there a better approach for that?

Generating a new protocol parameters file just dumps the node's current parameters into a JSON format. Since the parameters are not constantly changing, generating a new params file each time is not strictly necessary - you can reuse it. However, if the parameters do change (as the did just now at the E319 boundary), then your fee calculation might be impacted if you use an outdated file.
Personally, I like to generate a new params file every epoch - this can be easily automated with cron.

Thank you for that, that sounds like a good approach. Every 5 days you regenerate the protocol parameters, right?

Yessir, only if I need to submit a transaction though.


text:
What's the difference between Ledger.CurrencySymbol and Plutus.V1.Ledger.Value.CurrencySymbol?
I'm a bit confused about CurrencySymbol type. In the documentation it appears twice in 2 modules: Plutus.V1.Ledger.Value (first image) and Ledger. (second image)
Are they the same type? When import each?
Thanks in advance!

If you look at the source of Ledger, you will see that it reexports CurrencySymbol from the Value module, so yes, they are the same:
module Ledger (
    module Export,
    AssetClass,
    CurrencySymbol,
    TokenName,
    Value,
    Ada
    ) where

import Ledger.Blockchain as Export
import Ledger.Index as Export
import Ledger.Orphans ()
-- We manually re-export 'Plutus.V1.Ledger.Scripts' so we can include some
-- extra instances
import Ledger.Address as Export
import Ledger.Contexts as Export
import Ledger.Crypto as Export
import Ledger.Scripts as Export
import Ledger.Tx as Export
import Ledger.Value as Export (noAdaValue)
import Plutus.V1.Ledger.Ada (Ada)
import Plutus.V1.Ledger.Interval as Export
import Plutus.V1.Ledger.Orphans ()
import Plutus.V1.Ledger.Slot as Export
import Plutus.V1.Ledger.Time as Export
import Plutus.V1.Ledger.TxId as Export
import Plutus.V1.Ledger.Value (AssetClass, CurrencySymbol, TokenName, Value)


text:
About Homework 4 - Getting PayParams through binding
This question is in the context of the homework for Lecture 4.
What is wrong with the following reasoning?
We know that payContract is type m (), where m stands for the monad Contract () PaySchema Text.  Therefore
payContract = do
    pp <- awaitPromise $ endpoint @"pay" return

must bind () to the variable pp.  Hence pp does not contain information about PayParams.
Obviously my argument is wrong, because ppLovelace pp does give you the payment amount.  But where exactly is the error in my logic?

Could you resolve your question with any of the answers here?

Obviously my argument is wrong, because ppLovelace pp does give you the payment amount.

Yes the argument is wrong because first of all the endpoint @"pay" return means it returns the value of @"pay" immediately so the side-effect which would be () is not reached. Also the function has a final call awaitPromise which returns a new monad with a different return value. Again the () is not seen by awaitPromise.
I hope I explained myself ok.

Here, the full payContract in Homework.hs.
payContract :: Contract () PaySchema Text ()
payContract = do
    pp <- awaitPromise $ endpoint @"pay" return
    let tx = mustPayToPubKey (ppRecipient pp) $ lovelaceValueOf $ ppLovelace pp
    void $ submitTx tx
    payContract

where  pp <- awaitPromise $ endpoint @"pay" return  is an intermediate computation which doesn't determine the type result of the function payContract. The type result of the function is given by the last expression in the function: payContract.
The type of awaitPromise $ endpoint @"pay" return is Contract () PaySchema PayParams. Therefore, pp is PayParams. But again, it's an intermediate computation.