text:
Sending ADA to multiple wallets in a single transaction
We are looking options that current exist for sending 20-40ADA to multiple wallets (20+) simultaneously in a single transaction. Initially the need might only be 10 receiving wallets but might scale rather quickly.
What are some current solutions known by the community for performing this action?
I am aware of this tool by CardaHubs; admittedly I haven't actually used it yet. I would like to hear others perspectives on its limitations. https://cardahub.io/tools
Are there any other tools available besides writing a custom script for these transactions each time?  The addresses will be the same or at least similar sometimes but also new ones fairly regularly.
Thank you all in advance for sharing what you know and any insights, ideas or suggestions.

In Cardano (and I am pretty sure most other cryptos) there are limits to how big a transaction can be (the limit is set in bytes).  As long as the total transaction is within that limit, there is no restriction on how many outputs a single transaction can have. I am pretty sure you can build such a multi-output transaction with cardano-cli.

You can use the Eternl wallet Transaction Builder if you don't want to do it using scripts.

If you are running a node (which it sounds like with a name like 'CarPool') then to send ADA and/or native tokens in one trx you can use multiple --tx-out options within the cardano-cli transaction build-raw command.
Each --tx-out will contain the recipient address, assest(s) and amount of each to send.
Depending on the frequency that you will be sending out ADA, you could use some Linux scripting to make this process reasonably dynamic each time you want to send out. For example import data from a pre-built list of addresses, assets and the amount to send, calculate the fee, build the full trx, and submit.


text:
How to find a cardano wallet's 'account public key'?
cardano-wallet has a method to create a new wallet:
cardano-wallet wallet create from-public-key WALLET_NAME ACCOUNT_PUBLIC_KEY
If I use the public key I get:
Invalid account public key: expecting a hex-encoded value that is 64 bytes in length.
How can I find/derive this hex encoded 64 byte 'account public key'?
The only documentation I can find that mentions how to get the 'account public key' is this:
https://bump.sh/doc/cardano-wallet-diff#operation-getaccountkey
But this is using an API.
Surely I can find it using the cli ?

I found the answer here: https://cardano.stackexchange.com/questions/4008/how-can-i-derive-an-address-from-a-private-key

source: Stack Exchange

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

sort: votes


text:
Plutus V2 Tx Building causing NonOutputSupplimentaryDatums error
I am stuck with this error, what's a NonOutputSupplimentaryDatums?:
""transaction submit error ShelleyTxValidationError ShelleyBasedEraBabbage (ApplyTxError [UtxowFailure (FromAlonzoUtxowFail (NonOutputSupplimentaryDatums (fromList [SafeHash \"13866df5e21887cb0d2c27b8d8ccf03d1cb7f93e929dffa9a91c8a4b83c98c60\"]) (fromList [])))])""

For the reference:

I am spending a script input with inline datum
I am using add_plutus_script_input on TransactionBuilder to add the input
I am using txBuilder.calc_script_data_hash(TxBuilderConstants.plutus_vasil_cost_models()); to get the script witnesses and script hash set up

Thanks for any help!

I don't use cardano-serialization-lib but I can tell you that NonOutputSupplimentaryDatums is the ledger error thrown when datum is unneceserilly included in the tx when using inline datum. When inline datum is being used you can't have the same datum also in the tx body's witness set.

Thanks for the error explanation! The only datum I am attaching is via TxBuilder#add_plutus_script_input which requires a PlutusWitness that is made up of the script, the datum and redeemer.

This actually helped me solving "unspendableDatums" error from Ogmios. I could not find any docs for it, only the mapping from NonOutputSupplimentaryDatums here: https://github.com/CardanoSolutions/ogmios/blob/756b31cfce0a801526745b39e07c69bc0edaae4a/server/src/Ogmios/Data/Json/Alonzo.hs#LL109C18-L109C46

So I was able to resolve the issue. The problem was caused by the way I attached the datum as PlutusWitness. So instead of creating directly instantiating a PlutusWitness I created one with the help of the newly made available constructor PlutusWitness.new_with_ref in CSL version 11.1.0:
const txIn = TransactionInput.new(TransactionHash.from_bytes(Buffer.from(o.txId, 'hex')), o.idx);
...
// Caused error:
const errorCausingPlutusWitness = PlutusWitness.new(myContract, myDatum, myRedeemer);

// Valid way:
const plutusWitness = PlutusWitness.new_with_ref(PlutusScriptSource.new(myContract), DatumSource.new_ref_input(txIn), myRedeemer);

const amt = Value.new(BigNum.from_str(`${o.value.coins}`));

// The script input to be spent
txBuilder.add_plutus_script_input(plutusWitness, txIn, amt);

This essentially allowed me to spend an inline-datum script output.

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


text:
"plutusV2MintingPolicy" lookup not found by "balanceTx"
I am trying to mint some example tokens in offchain plutus code on tag v1.0.0-alpha1.
This is the OffChain code I am currently using:
mintFactoryToken :: Contract () MintFactorySchema Text ()
mintFactoryToken = do
  outRef <- getUnspentOutput
  pkh    <- ownFirstPaymentPubKeyHash
  o      <- fromJust <$> unspentTxOutFromRef outRef
  let
    !policy     = mintValidator outRef
    symbol     = scriptCurrencySymbol policy
    mintValue  = Value.singleton symbol contractDataTokenName 1 <> Value.singleton symbol chunkCreationTokenName 1
  Contract.logDebug outRef
  Contract.logDebug policy
  Contract.logDebug symbol
  Contract.logDebug mintValue
  let
    l          = Constraints.plutusV2MintingPolicy policy <>
                 Constraints.unspentOutputs (Map.singleton outRef o)
    constr     = Constraints.mustMintValue mintValue
  unbalanced <- Contract.mkTxConstraints @Any l constr
  Contract.logDebug @Text "Unbalanced"
  adjusted  <- Contract.adjustUnbalancedTx unbalanced
  Contract.logDebug @Text "adjusted"
  unsigned  <- Contract.balanceTx adjusted
  Contract.logDebug @Text "unsigned"
  signed    <- Contract.submitBalancedTx unsigned
  Contract.logDebug @Text "signed"
  --ledgerTx <- Contract.submitTxConstraintsWith @Void l constr
  Contract.awaitTxConfirmed $ getCardanoTxId signed
  Contract.logDebug @Text "signed"

But as soon as it reaches Contract.balanceTx adjusted I encounter the following error:
Slot 00001: *** CONTRACT STOPPED WITH ERROR: "\"WalletContractError (ValidationError (CardanoLedgerValidationError \\\"MissingScript (RdmrPtr Mint 0) (fromList [(RdmrPtr Mint 0,(Minting (PolicyID {policyID = ScriptHash \\\\\\\"2fcc3c79d2cb27a9784a7d3e69de5f1909406fcbc33567e6dd24288b\\\\\\\"}),Nothing,ScriptHash \\\\\\\"2fcc3c79d2cb27a9784a7d3e69de5f1909406fcbc33567e6dd24288b\\\\\\\"))])\\\"))\""

Do I have to do something special in order to get this to work or is this just not supported at the moment?
I've seen in the Relese Notes that some custom validation rules are used at the moment:

...

plutus-contract emulator has been updated to work with Babbage era types. However, the UTxO index in the emulator does not support transaction outputs with reference scripts and inline datums.
plutus-contract emulator uses the Babbage era validation rules from cardano-ledger. However, we continue to use our old custom validation rules which we plan to remove in the next alpha release in order to fully commit with cardano-ledger 's validation rules.

...

But I am not sure if this causes my problem or not.
Signatures of the OnChain code:
{-# INLINABLE validateMinting #-}
validateMinting :: TxOutRef -> BuiltinData -> BuiltinData -> ()
...

mintValidator :: TxOutRef -> MintingPolicy
mintValidator oRef = mkMintingPolicyScript
   ($$(Tx.compile [|| validateMinting ||]) `Tx.applyCode` Tx.liftCode oRef)

mintCurrencySymbol :: TxOutRef -> CurrencySymbol
mintCurrencySymbol = scriptCurrencySymbol . mintValidator

Can't see anything wrong with what you're doing. A lot has changed since v1.0.0-alpha1 so could you try with latest from next-node branch and see if it helps.

As james noted in a comment a simple update to the head of next-node resolved the issue. now tokens are minted correctly


text:
Error cabal build: "Failed to build lzma-0.0.0.3" even in nix-shell and also tried "sudo-apt install liblzma-dev"
I'm trying to run the command "cabal build" the Week02 code of plutus-pioneer-program but it has this error and I have tried everything but the same error keeps appear:
Failed to build lzma-0.0.0.3.
Build log (
/root/.cabal/logs/ghc-8.10.4.20210212/lzma-0.0.0.3-0c9bb4b908cda90da75c6385d28bd3027ce216c08ab1b83c43f13ae414b04d3b.log
):
Configuring library for lzma-0.0.0.3..
Preprocessing library for lzma-0.0.0.3..
compiling dist/build/LibLzma_hsc_make.c failed (exit code 1)
rsp file was: "dist/build/hsc2hscall1082370-0.rsp"
command was: /nix/store/d2fqghv083a8q7j8sjb2m5q6i840h691-gcc-wrapper-10.2.0/bin/cc -c dist/build/LibLzma_hsc_make.c -o dist/build/LibLzma_hsc_make.o -D__GLASGOW_HASKELL__=810 -Dlinux_BUILD_OS=1 -Dx86_64_BUILD_ARCH=1 -Dlinux_HOST_OS=1 -Dx86_64_HOST_ARCH=1 -Idist/build/autogen -Idist/build/global-autogen -include dist/build/autogen/cabal_macros.h -I/nix/store/3av3p9ky0lg2f1bc5jgg2sl872z7g4m9-ghc-8.10.4.20210212/lib/ghc-8.10.4.20210212/bytestring-0.10.12.0/include -I/nix/store/3av3p9ky0lg2f1bc5jgg2sl872z7g4m9-ghc-8.10.4.20210212/lib/ghc-8.10.4.20210212/base-4.14.1.0/include -I/nix/store/grcf3skqwdw35pki3d0gf7mj0flskni7-gmp-6.2.1-dev/include -I/nix/store/3av3p9ky0lg2f1bc5jgg2sl872z7g4m9-ghc-8.10.4.20210212/lib/ghc-8.10.4.20210212/integer-gmp-1.0.3.0/include -I/nix/store/3av3p9ky0lg2f1bc5jgg2sl872z7g4m9-ghc-8.10.4.20210212/lib/ghc-8.10.4.20210212/include -I/nix/store/wxb1awkkkbjp26jwqf854488qbzlkk25-libffi-3.3-dev/include -I/nix/store/3av3p9ky0lg2f1bc5jgg2sl872z7g4m9-ghc-8.10.4.20210212/lib/ghc-8.10.4.20210212/include/
error: LibLzma.hsc:44:10: fatal error: lzma.h: No such file or directory
compilation terminated.

cabal: Failed to build lzma-0.0.0.3 (which is required by
plutus-pioneer-program-week02-0.1.0.0). See the build log above for details.

Here are the steps I do:

cd into plutus-apps directory then

$ git checkout 81ba78edb1d634a13371397d8c8b19829345ce0d
$ nix-shell

Now I'm inside the nix-shell, I cd into plutus-pioneer-program's Week2 code and then run

[nix-shell:.../plutus-pioneer-program/code/week02]# cabal update
[nix-shell:.../plutus-pioneer-program/code/week02]# cabal build

That's all, the error above appears. After investigating, I think the error is caused by missing lzma.h, I installed liblzma-dev from this thread, but the error remains.
Can anyone help me out please? Thank you very much!

I am also facing the same issue. Have you found any solution?

After the command
nix-shell

execute in the shell
nix-shell -p lzma

I believe you are using the wrong git commit for plutus-apps for week02. It should be 6aff97d596ac9d59460aab5c65627b1c8c0a1528 according to  https://github.com/input-output-hk/plutus-pioneer-program/blob/main/code/week02/cabal.project#L63
In other words, you should cd into the plutus-apps directory and then:
$ git checkout 6aff97d596ac9d59460aab5c65627b1c8c0a1528
$ nix-shell

And then proceed with the rest of the process the same way you were doing before.


text:
Is the UTxO for change always the very last index of the outputs?
Given a transaction with multiple outputs, is the UTxO for the change always the very last index of the list of all outputs?
To demonstrate what I mean:
Given the following theoretical transaction
transaction
 - input #1 (100M lovelace from address XX0)
 - output idx#0 (40M lovelace to address XX1)
 - output idx#1 (50M lovelace to address XX2)
 - output idx#2 (10M lovelace change to address XX0)

Is it safe to assume the change is ALWAYS the last index of the output list?
It does make sense to me, but I need to know if I can rely on that.
Thank you!

That depends what wallet/client you're using to build the transaction. The concept of "change" is at the application level. As far as the ledger is concerned, it doesn't exist at all. All that's important is that the transaction balances.

Thanks, that makes total sense!


text:
Simulate Minting Event In EmulatorTrace
My application has a minting script and a validator script that works together. I am using EmulatorTrace to test my application.How do i simulate a minting event in EmulatorTrace?

There are plutus-contract tests, such as MustMint.hs, that demonstrate the use of each minting tx constraint: mustMintCurrencyWithRedeemer, mustMintValueWithRedeemer, mustMintCurrency & mustMintValue. Hope that helps.


text:
Use a parameterized currencySymbol within a Plutus Validator. Unsupported feature: Type constructor: GHC.Prim.ByteArray#
I have a minting policy which is parameterized by PaymentPubKeyHash and a script which checks that a token from that minting policy has been burned. The script also takes PaymentPubKeyHash as a parameter. I get an error when I try to compile it to plutus core.
Program error: GHC Core to PLC plugin: E042:Error: Unsupported feature: Type constructor: GHC.Prim.ByteArray#

It appears to be due to the fact that I called the parameterized curSymbol function within the plutus validator. Is this not allowed for some reason in plutus? Are there any ways around this? It seems quite important to be able to calculate the address of a parameterized minting policy from within a validator in order to check that a token comes from an appropriate policy.
The code I used is below:
{-# LANGUAGE DataKinds           #-}
{-# LANGUAGE DeriveAnyClass      #-}
{-# LANGUAGE DeriveGeneric       #-}
{-# LANGUAGE NoImplicitPrelude   #-}
{-# LANGUAGE OverloadedStrings   #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell     #-}
{-# LANGUAGE TypeApplications    #-}
{-# LANGUAGE TypeFamilies        #-}
{-# LANGUAGE TypeOperators       #-}
{-# LANGUAGE NamedFieldPuns      #-}
{-# LANGUAGE MultiParamTypeClasses #-}

{-# OPTIONS_GHC -fno-ignore-interface-pragmas #-}

module CheckBurned where

import           Ledger                 hiding (mint, singleton)
import qualified Ledger.Typed.Scripts   as Scripts
import qualified PlutusTx
import           PlutusTx.Prelude       hiding (Semigroup(..), unless)
import           Ledger.Value           as Value

--This minting policy requires that the transaction is signed by the minting authority. Burning is always allowed.
{-# INLINABLE mkPolicy #-}
mkPolicy :: PaymentPubKeyHash -> () -> ScriptContext -> Bool
mkPolicy authPkh () ctx = case flattenValue $ txInfoMint txInfo of
                            [(_,_,n)]
                              | n < 0 -> True --Burning is allowed.
                              | n > 0 -> traceIfFalse "not signed by authority" signedByAuthority

                            _         -> traceIfFalse "Must mint/burn exactly one type of token" False
  where
    txInfo = scriptContextTxInfo ctx
    signedByAuthority = txSignedBy txInfo (unPaymentPubKeyHash authPkh)

{-# INLINABLE policy #-}
policy :: PaymentPubKeyHash -> Scripts.MintingPolicy
policy pkh = mkMintingPolicyScript $
  $$(PlutusTx.compile [|| Scripts.wrapMintingPolicy . mkPolicy ||])
  `PlutusTx.applyCode`
  PlutusTx.liftCode pkh

{-# INLINABLE curSymbol #-}
curSymbol :: PaymentPubKeyHash -> CurrencySymbol
curSymbol = scriptCurrencySymbol . policy

--This scipt allows spending as long as it is accompanied by the burning of the corresponding token
{-# INLINABLE mkValidator #-}
mkValidator :: PaymentPubKeyHash -> () -> () -> ScriptContext -> Bool
mkValidator pkh _ _ ctx = traceIfFalse "Not correct token" consumesCorrectToken
    where
        txInfo = scriptContextTxInfo ctx
        valueMinted = txInfoMint txInfo :: Value.Value
        consumesCorrectToken = valueOf valueMinted (curSymbol pkh) "tn" == (-1) :: Bool

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

--Compiling to plutus here gives the error.
typedValidator :: PaymentPubKeyHash -> Scripts.TypedValidator Contract1Type
typedValidator pkh = Scripts.mkTypedValidator @Contract1Type
    ($$(PlutusTx.compile [|| mkValidator ||])
        `PlutusTx.applyCode` PlutusTx.liftCode pkh)
    $$(PlutusTx.compile [|| wrap ||])
  where
    wrap = Scripts.wrapValidator @() @()

This question seems closely related to Is it possible to use a parameterised CurrencySymbol inside another validator script? Unsupported feature: Type constructor: GHC.Prim.ByteArray# which didn't receive an answer. I tried to simplify the question.

The short answer is, you can't call curSymbol in mkValidator because that would involve compiling the policy and various template haskell stuff in your validator script, this cannot be done in PLC. You can instead use use Lift to pass the CurrencySymbol into mkValidator as an additional argument.


text:
Printing a plutus validators cborhex to a file
I was hoping to get some advice re printing a plutus validators cborhex to a file. Im kinda basing my logic off of an example in week03 in the pioneer program but need to make some adaptations.
Below is how i've created the validator, followed by how I'm trying to serialize and print to file:
tradeValidate :: ContractInfo -> TradeDatum -> TradeAction -> ScriptContext -> Bool
tradeValidate contractInfo@ContractInfo{..} tradeDatum tradeAction context = case tradeDatum of
    StartBid -> case tradeAction of
...etc

data Trade
instance Scripts.ValidatorTypes Trade where
    type instance RedeemerType Trade = TradeAction
    type instance DatumType Trade = TradeDatum

tradeInstance :: Scripts.TypedValidator Trade
tradeInstance = Scripts.mkTypedValidator @Trade
    ($$(PlutusTx.compile [|| tradeValidate ||]) `PlutusTx.applyCode` PlutusTx.liftCode contractInfo)
    $$(PlutusTx.compile [|| wrap ||])
  where
    wrap = Scripts.wrapValidator @TradeDatum @TradeAction

tradeValidator :: Validator
tradeValidator = Scripts.validatorScript tradeInstance

writeValidator :: FilePath -> Plutus.Validator -> IO (Either (FileError ()) ())
writeValidator file = writeFileTextEnvelope @(PlutusScript PlutusScriptV1) file Nothing . PlutusScriptSerialised . SBS.toShort . LBS.toStrict . serialise . Ledger.unValidatorScript

writeTradeValidator :: IO (Either (FileError ()) ())
writeTradeValidator = writeValidator "trade.plutus" $ tradeValidator[???]

Where I've put tradeValidator is incorrect, but I'm not sure what do put in its place
The example I'm taking from did this:
writeVestingValidator :: IO (Either (FileError ()) ())
writeVestingValidator = writeValidator "testnet/vesting3.plutus" $ validator $ VestingParam
    { beneficiary = Ledger.PaymentPubKeyHash "c5a3dc50d72f46ecca258c04bd5e3da5717863e358af7e1b361f9487"
    , deadline    = 1664683478000
    }

What specific error messages do you get? From Haskell standpoint there is an extra $ in your code, try this maybe:
writeTradeValidator :: IO (Either (FileError ()) ())
writeTradeValidator = writeValidator "trade.plutus" tradeValidator

Amazing thank you so much that was it!! :D


text:
2 Validators for one Transaction
I'm building a use case where a person can buy a token and depending on the amount of ADA spent, he gets X tokens and a Special NFT.
Each Validator represent the policy Id of these native tokens I'm creating.
Now I must prevent anyone from minting without paying and off course check if the ADA is the value of the mint
mintWithFriend :: MintParams -> Contract w FreeSchema Text ()
mintWithFriend mp = do
        let  destinations       = paymentTo mp
             referralAddr       = pubKeyHashAddress (referral destinations) Nothing
        now                     <- currentTime
        utxosReferral           <- utxosAt referralAddr
        let
            vals                =  (_ciTxOutValue <$> (snd <$> Map.toList utxosReferral))
            referralOk          =  extractLevel (getTot vals []) 0

            yacada              = Value.singleton yacadaSymbol (U.yacadaName) (U.calculateYacada $ mpAdaAmount mp) -- coins for customer
            yacadaNft           = Value.singleton yacadaNFTSymbol  (U.giveReferralNFTName (mpAdaAmount mp) now)  1 -- NFT for is base referral
            yacadaReferralNft   = Value.singleton yacadaNFTSymbol  (U.upgradeReferralNFTName (referralOk+1) now)  1 -- upgrade for the referral account
            treasuryAdas        = Ada.lovelaceValueOf $ U.treasuryAda (mpAdaAmount mp) referralOk
            referralAdas        = Ada.lovelaceValueOf $ U.referralAda (mpAdaAmount mp) referralOk
            lookups             = Constraints.mintingPolicy policy
                                    <> Constraints.mintingPolicy levelPolicy
            payment             = Constraints.mustPayToPubKey (treasury destinations) treasuryAdas
                                    <> Constraints.mustPayToPubKey (referral destinations) (referralAdas <>  yacadaReferralNft)
            mint                = Constraints.mustMintValue (yacada <> yacadaNft <> yacadaReferralNft)
            tx                  = mint <> payment

        ledgerTx <- submitTxConstraintsWith @Void lookups tx
        void $ awaitTxConfirmed $ getCardanoTxId ledgerTx

On this Off-chain contract, I'm building such transaction.
The policy and LevelPolicy are my 2 validators.
the only utxo sent are the payment.
being that I have 2 validators can I define what utxo goes for each?
{-# INLINABLE yacadaPolicy #-}
yacadaPolicy ::  () -> PlutusV1.ScriptContext -> Bool
yacadaPolicy _ ctx  =
    traceIfFalse "not ok" True

    where
        allOk :: Bool
        allOk = True

        info :: TxInfo
        info = scriptContextTxInfo ctx

        minted :: Value
        minted = txInfoMint info

        mintedValue :: [(CurrencySymbol, TokenName, Integer)]
        mintedValue = flattenValue (minted)

        -- ?? Paied amount ?? --
        -- ?? amount of yacada == minted amount ??
        -- ?? name of yacadaNFT == level given by amount of ADA && quantity == 1
        -- ?? did the treasury account received the ADA
        -- ?? did the referral NFT name correct quantity = 1??
        -- ?? did the referral received ADA and new NFT

The full source is https://github.com/cmorgado/yacada_learning
Many thanks in advancednat

being that I have 2 validators can I define what utxo goes for each?

No, both scripts have visibility of all inputs and outputs of the transaction.
You can try ensuring that unique outputs are checked for each script.

I have distinct outputs how do I see them in the validator?

Your can access transaction outputs with txInfoOutputs info


text:
How do users interact with smart contract?
In plutus playground, there is an example called “Vesting”. In the simulation, users can interact with this smart contract by click on “vest fund” or “retrieve funds”.
Now suppose that we compile this into a plutus script (Vesting.plutus) and then use cardano-cli (or other tools) to actually deploy this smart contract to the real blockchain.
How would users interact with this real-world smart contract?
To be more specific, here is the hypothetical steps:

User A send a transaction to vest funds to the contract.
User B send another transaction to retrieve funds from the contract.

The two transactions must be different. There must be some kind of parameters to indicate that the transaction is about to vest or retrieve the fund, activating different endpoint specified in the contract.
What is the different between the build of the transaction in step 1 and 2?

How would users interact with this real-world smart contract?

Actually what users interact with is the address of the smart contract, the plutus code (the code that produce the hash/address of the contract) must be attached to the transaction everytime it's used as validator of the given transaction (unless CIP-33 is being used).
Everytime an user needs to interact with the smart contract, they do it using the "address" of the contract, which is the "hash" of the contract code.
There are many libraries and tools that can be used to build transactions, PlutusTx (which Playground uses) is one of them.

What is the different between the build of the transaction in step 1 and 2?

The difference is in the constraints being used, in the step 1 the contract wallet is locking the value in the contract through mustPayToTheScript, in the step 2 the contract wallet is redeeming with collectFromScript.

You can use cardano serialization lib to write a webapp using react and CSL to build transactions for your vesting contract, like those actions for vesting funds or retrieving funds. These transaction can then be sent to blockfrost and get submitted to a cardano node.
That's how many dApps work. You can also construct the transactions on the server side, send them back to the client to be signed by the user's light wallet and then submit them to your own node. (the architecture is pretty much up to you)

As @walker-leite pointed out, you interact with the address of the validator (smart contract).
When user A send a transaction to vest funds to the contract, he actually sends the amount to the address. This is just good old sending some Ada to an address. There is no validator (smart contract) involved here.
The validator is run when the user B wants to retrieve the funds that A sent to the address. This validator code determines if user B can retrieve the funds or not.


text:
Unable to run cardano-node on Preview and Pre-Production Testnet
System Info: macOS Monterey Version 12.6. with an M1 Chip.
I'm using cardano-node 1.35.3 that is installed with the Daedalus Mainnet wallet by appending the following in my .zshrc file:
export PATH="/Applications/Daedalus Mainnet.app/Contents/MacOS:$PATH"

I followed this guide to run cardano-node: https://developers.cardano.org/docs/get-started/running-cardano/
I get the configuration files from here: https://book.world.dev.cardano.org/environments.html
As in the guide above, my directory structure looks like this:
$HOME/cardano/
├── db
├── alonzo-genesis.json
├── byron-genesis.json
├── config.json
├── shelley-genesis.json
└── topology.json
1 directory, 5 files

In this directory, I run the following command:
cardano-node run \
  --topology topology.json \
  --database-path db \
  --socket-path db/node.socket \
  --host-addr 127.0.0.1 \
  --port 1337 \
  --config config.json

When I use the configuration files for mainnet and the old testnet, the command works as expected and the node is syncing because I see output like this:
Chain extended, new tip: b4624d1ad9fa00eaf81b57fa0561f24593d11adca70b45ee967484c8d5c26efa at slot 27173

However, when using the configuration files for the preview and pre-production testnet, I get the following output/error which repeats itself and the node does not sync. How can I solve this?
[student-:cardano.node.PeerSelection:Info:52] [2022-10-07 14:09:06.10 UTC] TraceGovernorWakeup
[student-:cardano.node.PeerSelection:Info:52] [2022-10-07 14:09:06.10 UTC] TracePromoteColdPeers 50 0 (fromList [3.72.231.105:30002])
[student-:cardano.node.ConnectionManager:Info:68] [2022-10-07 14:09:06.10 UTC] TrConnectionManagerCounters (ConnectionManagerCounters {fullDuplexConns = 0, duplexConns = 0, unidirectionalConns = 0, inboundConns = 0, outboundConns = 0})
[student-:cardano.node.ConnectionManager:Info:68] [2022-10-07 14:09:06.10 UTC] TrConnectError (Just 127.0.0.1:3001) 3.72.231.105:30002 Network.Socket.connect: <socket: 29>: unsupported operation (Can't assign requested address)
[student-:cardano.node.ConnectionManager:Info:68] [2022-10-07 14:09:06.10 UTC] TrConnectionManagerCounters (ConnectionManagerCounters {fullDuplexConns = 0, duplexConns = 0, unidirectionalConns = 0, inboundConns = 0, outboundConns = 0})
[student-:cardano.node.PeerSelection:Info:52] [2022-10-07 14:09:06.10 UTC] TracePromoteColdFailed 50 0 3.72.231.105:30002 41.140901877674s Network.Socket.connect: <socket: 29>: unsupported operation (Can't assign requested address)
[student-:cardano.node.PeerSelection:Info:52] [2022-10-07 14:09:29.81 UTC] TraceGovernorWakeup
[student-:cardano.node.PeerSelection:Info:52] [2022-10-07 14:09:29.81 UTC] TracePublicRootsRequest 100 1
[student-:cardano.node.LedgerPeers:Info:50] [2022-10-07 14:09:29.81 UTC] [String "FetchingNewLedgerState",Number 0.0]
[student-:cardano.node.LedgerPeers:Info:50] [2022-10-07 14:09:29.82 UTC] [String "FallingBackToBootstrapPeers"]
[student-:cardano.node.LedgerPeers:Info:50] [2022-10-07 14:09:29.82 UTC] [String "UseLedgerAfter",Number 322000.0]
[student-:cardano.node.PublicRootPeers:Info:69] [2022-10-07 14:09:29.82 UTC] TracePublicRootRelayAccessPoint [RelayAccessDomain "preview-node.world.dev.cardano.org" 30002]
[student-:cardano.node.PublicRootPeers:Info:69] [2022-10-07 14:09:29.82 UTC] TracePublicRootRelayAccessPoint [RelayAccessDomain "preview-node.world.dev.cardano.org" 30002]
[student-:cardano.node.PublicRootPeers:Info:69] [2022-10-07 14:09:29.85 UTC] TracePublicRootResult "preview-node.world.dev.cardano.org" [(3.72.231.105,60)]
[student-:cardano.node.PeerSelection:Info:52] [2022-10-07 14:09:29.85 UTC] TracePublicRootsResults (fromList []) 1 2s

Full output here: https://gist.github.com/samuelpullely/60223a98066dd5f72c597a681021c2a3
Similar (unresolved) questions:

Cardano-Node Preview Testnet PeerSelection Error (Ubuntu 22.04 Docker container)

Running preview/preprod Cardano-node on windows (Windows)

It seems like this issue does not only appear on macOS.

When I copied and pasted text, I faced the similar problem. May be formatting matters. Try getting raw files directly from github like:
curl -O -J https://raw.githubusercontent.com/input-output-hk/cardano-world/master/docs/environments/preprod/alonzo-genesis.json

Change "/preprod/" to "/preview/" and "alonzo-genesis.json" to other names, to fit your needs.
Also in my case, I have to change host-addr to 0.0.0.0 like:
--host-addr 0.0.0.0 \

Lastly, make sure the database in db folder is NOT from the mainnet/testnet/different net. To be super-safe, just empty the db folder.

Thanks a lot, changing the host-addr worked


text:
How to use prepod with Blockfrost api
Good evening,
I am working on a crypto wallet that deals with cardano(ADA), and while testing i discovered that blockfrost api for testnet is deprecated, so i could not get testnet token to test, and later switched to prepod but i don't know how to connect blockfrost api with prepod test network, i tried reaching out to blockfrost but to no avail,please how can i use prepod with blockfrost api?
this is my cardano address addr_test1qrum7e26tfvdxgy3glpmrcsrsza4lpfqyqn0phklplm3wscunjd64pwwcfdsmdqrmxry5ma0smajh37vdp0jwzx82jpsheutwf
for legacy testnet.

There are different urls for each network.
From the doc: https://docs.blockfrost.io

please i am trying to use it with flutter
cardano_wallet_sdk: ^0.1.0-alpha.12


text:
InlineDatum on ReferenceOutput in OffChain code
I tried to use the inline datum of a reference input in the minting policy below:
{-# INLINABLE validateMinting2 #-}
validateMinting2 :: TxOutRef -> BuiltinData -> BuiltinData -> ()
validateMinting2 oref _ rawCtx =
  check $
    if not hasUsedUTXO
      then not $ cdEndContract contractData
      else True

  where
    ctx = unsafeFromBuiltinData rawCtx
    symbol = ownCurrencySymbol ctx
    info = scriptContextTxInfo ctx
    inputs = txInfoInputs info
    contractData = case filter f $ map m $ txInfoReferenceInputs info of
      [TxOut{txOutDatum}] -> case txOutDatum of
        NoOutputDatum -> traceError "NoDat"
        OutputDatumHash _ -> traceError "Hash"
        OutputDatum (Datum d) -> case fromBuiltinData @ContractData d of
          Just dat -> dat
          _        -> traceError "nothing"
      _   -> traceError "nope"
      where
        f TxOut{txOutValue} = valueOf txOutValue symbol contractDataTokenName == 1
        m inInfo = txInInfoResolved inInfo

    hasUsedUTXO :: Bool
    hasUsedUTXO
      | [_] <- filter ((oref ==) . txInInfoOutRef) inputs = True
      | otherwise                                         = False

When I use the cli to mint with reference input (--read-only-tx-in-reference) everything works as expected and the inline datum can be used, but when I try to write offchain code for this it fails with:
Contract instance stopped with error: "WalletContractError (ValidationError (ScriptFailure (EvaluationError [\"Hash\"] \"CekEvaluationFailure: An error has occurred:  User error:\\nThe machine terminated because of an error, either from a built-in function or from an explicit use of 'error'.\")))"
This error is shown when I use the following offchain code:
  pkh <- ownFirstPaymentPubKeyHash
  outRef <- getUnspentOutput
  o      <- fromJust <$> unspentTxOutFromRef outRef
  let
    policy     = mintValidator outRef
    symbol     = scriptCurrencySymbol policy
    mintValue  = Value.singleton symbol contractDataTokenName 1 <> Value.singleton symbol chunkCreationTokenName 1 <> Value.singleton symbol (chunkTokenName 0) 1
    l          = Constraints.unspentOutputs (Map.singleton outRef o) <> Constraints.plutusV2MintingPolicy policy
    constr     = Constraints.mustMintValueWithRedeemer (Redeemer $ toBuiltinData ()) mintValue <>
                 Constraints.mustSpendPubKeyOutput outRef <>
                 Constraints.mustPayWithInlineDatumToPubKey pkh (Datum $ toBuiltinData $ ChunkDatum (Address (PubKeyCredential $ unPaymentPubKeyHash pkh) Nothing)  "") (Value.singleton symbol chunkCreationTokenName 1 <> Value.singleton symbol (chunkTokenName 0) 1) <>
                 Constraints.mustPayWithInlineDatumToPubKey pkh (Datum $ toBuiltinData $ ContractData [] [] 100000 False) (Value.singleton symbol contractDataTokenName 1)
-- ... create, sign, submit ...
  ciTransaction <- fmap (txOutRefMap . fromJust) $ txFromTxId $ getCardanoTxId signed
  let
    fVal tokenName (citxo, _) = valueOf (citoValue citxo) symbol tokenName == 1
    [dataRef] = Map.keys $ Map.filter (fVal contractDataTokenName) ciTransaction
    [chunkRef] = Map.keys $ Map.filter (fVal (chunkTokenName 0)) ciTransaction

  dataOut      <- fromJust <$> unspentTxOutFromRef dataRef
  chunkOut     <- fromJust <$> unspentTxOutFromRef chunkRef
  addr <- ownAddress
  let
    dat = Datum $ toBuiltinData $ ContractData [] [] 100000 False
    mintValue2 = Value.singleton symbol (otherTokenName 0 0) 1
    l2          = Constraints.plutusV2MintingPolicy policy <> Constraints.unspentOutputs (Map.singleton chunkRef chunkOut <> Map.singleton dataRef dataOut) <> Constraints.otherData dat
    constr2     = Constraints.mustReferenceOutput dataRef <> Constraints.mustMintValueWithRedeemer (Redeemer $ toBuiltinData ()) mintValue2 <> mustSpendPubKeyOutput chunkRef <>
                  Constraints.mustPayWithInlineDatumToPubKey pkh (Datum $ toBuiltinData $ OtherDatum 0 0 0 addr 2000000) (Value.singleton "" "" 2000000 <> mintValue2) <>
                  Constraints.mustPayWithInlineDatumToPubKey pkh (Datum $ toBuiltinData $ ChunkDatum (Address (PubKeyCredential $ unPaymentPubKeyHash pkh) Nothing)  "") (Value.singleton symbol chunkCreationTokenName 1 <> Value.singleton symbol (chunkTokenName 0) 1)
-- ... create, sign, submit ...

Why does the transaction that is created in offchain code not contain the inline datum but a hash?
Is this currently possible with plutus-apps or do I still have to wait for this feature to be implemented?
If this is not possible at the moment I have one additional question: Is there a way to profile the execution cost of a script with the cardano-cli? I only know of --calculate-plutus-script-cost which produces a json file of the cost, but I also want to know which part of the script cost how much, similar to the  writeScriptsTo way.

The offline code is dependente of plutus-apps and this project lags behind the nodes features.
Look at diferente tags/branches for plutus-apps...


text:
How can I find the logo of a token in the Cardano Token Registry?
I know this is the API for accesing the Cardano Token Registry (https://tokens.cardano.org/metadata/) but I don't know how to get and process the logo image of a token from there.
Anyone?

You use https://tokens.cardano.org/metadata/{subject}/properties/logo. See the API doc.


text:
traceIfFalse is it possible to pass a string not "fixed"
Is this even possible?
traceIfFalse  ("A"++show(scriptContextTxInfo)) FoundIt

As logging onchain is just possible with this traceIfFalse ... I'm not finding a solution to make that line work

What I've done to debug Integers is to write a function that converts them into a BuiltinByteString and then decodeUtf8 it into a BuiltinString which is passed to any of the available trace functions.
I assume it could work for more complex data as well, but I have not tried that yet.
Example of what I described above:
{-# INLINABLE intBS #-}
intBS :: Integer -> BuiltinByteString
intBS i
  | i < 10    = consByteString (48 + i) emptyByteString
  | otherwise = appendByteString (intBS (divide i 10)) (intBS (modulo i 10))

-- ...
    traceIfFalse (decodeUtf8 $ intBS coolInt) $ ...
--...

Hope this helps.

This is probably not possible as the redeemer code is manipulated/examined from within a template haskell splice and you are running into what is called the "template haskell stage restriction".


text:
Missing/ No Redeemer Error when spending 2 script outputs
I am getting the following error, when I try to submit a transaction that spends 2 script outputs:
Error while submitting tx: ShelleyTxValidationError ShelleyBasedEraBabbage (ApplyTxError [UtxowFailure (FromAlonzoUtxowFail (MissingRedeemers [(Spending (TxIn (TxId {_unTxId = SafeHash "23e874d6549250c6d845031974212f87edb7f1b1d0f676afdf03cbddaf0ae9ad"}) (TxIx 0)),ScriptHash "d8feffeeee5fe079055719280d2a9603d93dc1289c2dff9912378d51")])),UtxowFailure (FromAlonzoUtxowFail (PPViewHashesDontMatch (SJust (SafeHash "0b672c4621917cc5ff6a62770cbd2841fa419603c43bb0d19d09b45ec184f995")) (SJust (SafeHash "72efce08bafc21afb779a47940e1866b53b4d33da32bc052f15ce80b2e49f5ce")))),UtxowFailure (UtxoFailure (FromAlonzoUtxoFail (UtxosFailure (CollectErrors [NoRedeemer (Spending (TxIn (TxId {_unTxId = SafeHash "23e874d6549250c6d845031974212f87edb7f1b1d0f676afdf03cbddaf0ae9ad"}) (TxIx 0)))]))))])

I am currently using the following code to create the Tx inputs:
for (let i = 0; i < sortedScriptTxInputs.length; i++) {
    const o = sortedScriptTxInputs[i];
    const txIn = TransactionInput.new(TransactionHash.from_bytes(Buffer.from(o.txId, 'hex')), o.idx);
    const redeemer = Redeemer.new(
      RedeemerTag.new_spend(),
      BigNum.from_str(`${i}`),     // NOT SURE IF THIS IS THE RIGHT WAY TO INDEX REDEEMERS ?!
      PlutusData.new_empty_constr_plutus_data(BigNum.zero()),
      ExUnits.new(
        BigNum.from_str("7000000"),
        BigNum.from_str("5000000000")
      )
    );
    const plutusWitness = PlutusWitness.new_with_ref(PlutusScriptSource.new(spendingContract), DatumSource.new_ref_input(txIn), redeemer);
    const amt = Value.new(BigNum.from_str(`${o.value.coins}`));
    txBuilder.add_plutus_script_input(plutusWitness, txIn, amt);
}

After adding collateral, I am creating the respective plutus-v2 CostModel and add it like so:
const costModel = TxBuilderConstants.plutus_vasil_cost_models().get(Language.new_plutus_v2());
if (!costModel)
    throw new Error('Missing cost model');
const costModels = Costmdls.new();
costModels.insert(Language.new_plutus_v2(), costModel);
txBuilder.calc_script_data_hash(costModels);

Observation:
If I inspect the redeemer witness set after building the Tx, I would expect to see 2 redeemers but the array only contains 1.
const tx = txBuilder.build_tx();
console.log('Witness Set before signing:');
console.log(tx.witness_set().redeemers()?.to_json());

Output
Witness Set before signing:
[
  {
    "tag": "Spend",
    "index": "1",
    "data": "{\"constructor\":0,\"fields\":[]}",
    "ex_units": {
      "mem": "7000000",
      "steps": "5000000000"
    }
  }
]

What am I missing or constructing wrongly?
My suspicion is that I either create invalid indexed redeemers or that txBuilder.calc_script_data_hash or txBuilder.build_tx does not handle multiple redeemers correctly.
Thanks for any help!

Is interesting that "index": "1"; you should have at least a redeemer with index 0;not sure at this point if indexing starts from 1 but that would be weird; what is the output if you try BigNum.from_str((i + 1).toString())

According to this post, I am using it correctly.
https://github.com/Emurgo/cardano-serialization-lib/issues/499#issuecomment-1217882349

It seems there is an issue with txBuilder#calc_script_data_hash as well as for #build_tx according to this thread:
https://github.com/Emurgo/cardano-serialization-lib/issues/536

There was a bug in the CSL lib for consuming multiple script outputs in one transaction which was resolved by https://github.com/Emurgo/cardano-serialization-lib/issues/536


text:
Get list of users addresses that minted native asset NFT
I would like to get a list of user addresses, that minted a native asset NFT. Is this possible? I do not want current holders of the NFT, but the original minting NFT holders.

Is a solution using cardano-db-sync acceptable?

@ErikdeCastroLopo yes

Here's a way using the https://blockfrost.io API:
Fist you need to get the asset id, I assume you already have this because you know which NFT you want to look up.
Then you would query all transactions of this asset using the Cardano > Assets > Asset Transactions API endpoint:
https://docs.blockfrost.io/#tag/Cardano-Assets/paths/~1assets~1{asset}~1transactions/get
This returns a list of transactions, where this asset has been involved.
[
  {
    "tx_hash": "8788591983aa73981fc92d6cddbbe643959f5a784e84b8bee0db15823f575a5b",
    "tx_index": 6,
    "block_height": 69,
    "block_time": 1635505891
  },
  {
    "tx_hash": "52e748c4dec58b687b90b0b40d383b9fe1f24c1a833b7395cdf07dd67859f46f",
    "tx_index": 9,
    "block_height": 4547,
    "block_time": 1635505987
  },
  {
    "tx_hash": "e8073fd5318ff43eca18a852527166aa8008bee9ee9e891f585612b7e4ba700b",
    "tx_index": 0,
    "block_height": 564654,
    "block_time": 1834505492
  }
]

Now you take the tx_hash of the transaction with the lowest block_height and query the Cardano > Transactions > Transaction UTxOs endpoint:
https://docs.blockfrost.io/#tag/Cardano-Transactions/paths/~1txs~1{hash}~1utxos/get
This will result in an object like this:
{
  "hash": "1e043f100dce12d107f679685acd2fc0610e10f72a92d412794c9773d11d8477",
  "inputs": [ ... ],
  "outputs": [
    {
      "address": "addr1q9ld26v2lv8wvrxxmvg90pn8n8n5k6tdst06q2s856rwmvnueldzuuqmnsye359fqrk8hwvenjnqultn7djtrlft7jnq7dy7wv",
      "amount": [
        {
          "unit": "lovelace",
          "quantity": "42000000"
        },
        {
          "unit": "b0d07d45fe9514f80213f4020e5a61241458be626841cde717cb38a76e7574636f696e",
          "quantity": "12"
        }
      ],
      "output_index": 0,
      "data_hash": "9e478573ab81ea7a8e31891ce0648b81229f408d596a3483e6f4f9b92d3cf710",
      "inline_datum": "19a6aa",
      "collateral": false,
      "reference_script_hash": "13a3efd825703a352a8f71f4e2758d08c28c564e8dfcce9f77776ad1"
    }
  ]
}

Go through the outputs of this object and find the one that contains your NFT in the list of amount objects. The address of this output is the original receiver of your NFT.


text:
How is it possible to create a mangled address (aka. franken-address) without the private stake key?
I've read a lot about mangled/franken addresses recently. A mangled address is an address, where the payment part of the address belongs to a different wallet than the stake part. This is an important thing to consider when building DApps on Cardano.
I'm wondering how it is possible to create such an address.
To create a payment address using the cardano-cli, both the private payment key and the private stake key are required:
cardano-cli address build \
    --payment-verification-key-file payment.vkey \
    --stake-verification-key-file stake.vkey \
    --out-file payment.addr \
    --mainnet

Let's say we have Alice who owns wallet A and Bob who owns wallet B.
Alice doesn't have access to the private keys of Bob, so how can Alice create an address with the payment part of her wallet A and the stake part of Bob's wallet B?
Or the other way around: How can Alice create a mangled address with Bob's payment part of wallet B and her stake part of wallet A?

The vkey are just the verification keys not your private (signing) keys which have skey suffixes. So creating a franken address only requires someones else's payment or stake vkey.

You can extract the PubKeyHash of a given address and hence you can also create a franken address combining the payment PKH with your stake PKH.

@William-BerlinPool But to spend the utxos i would still need both skeys, isn't it?

@wutzebaer To Spend a UTxO you just need the skey of the payment part of the address. The staking part is not relevant for spending.

For spending any UTxO, you either need the payment skey for the address that the UTxO belongs to, if it is a wallet address. In case of it being a script address, then the on-chain validator logic needs to pass in order for the UTxO to be spent.
Addresses are made up of one or two parts (payment part & an optional staking part). In order to create any address you'll need the verification key (vkey) of each part. All this is only applicable for shelley addresses. Byron addresses don't follow that structure.

Your cardano-cli example is correct - only the verification (public) keys are needed to build addresses, not the private keys. Therefore, we can build shelley addresses with any pair of payment.vkey and stake.vkey, regardless of whether or not they are derived from the same master seed.
"Mangled" in this case just means the payment and stake vkey's are derived from different master seeds.

ADA addresses (ignoring the bootstrap address type) consist of two components, like this (from here):
  = Addr Network (PaymentCredential c) (StakeReference c)

If you have two address, from two different wallets, you can create a franken address by taking the PaymentCredential from one address and the StakeReference from the other.

I am pretty sure its not possible to create one of these franken addresses with any of the standard tools. However, if you are relatively competent in Haskell its probably not difficult to write a tool to do it.
If you do not write Haskell, it may even be possible to do it with the JS library cardano-serialization-lib (which I have never looked at).

While a tool would ofc be helpful, the main goal of this question is to understand how it is possible to craft such an address when usually the private keys are required to create addresses.


text:
Does the hydra node automaticly contest an invalid snapshot?
Given that a participant of a hydra head posts an incorrect (not the latest) snapshot to close the head, does the hydra node automatically contest this? Or do we, the operator of that head, need to use the API to manually contest?

The hydra-node will automatically Contest any transaction it sees on the chain that tries to Close (or Contest!) the head with an invalid or not up-to-date snapshot. There is no need for the operator to do anything, but it might be useful in some scenarios to be able to do so.


text:
Script Execution Failure PT8
I am trying to transact with UTxO from a script address on the pre-production testnet.
I locked the fund ok with Datum, now I get an error when trying to consume that UTxO, it seem that the script is failing. But I am not sure how to get more information on where the problem is coming from, here is the off chain plutus code.
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveAnyClass        #-}
{-# LANGUAGE DeriveGeneric         #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses      #-}
{-# LANGUAGE OverloadedStrings          #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE NoImplicitPrelude #-}

module FaucetValidatorScript
  ( FaucetParams (..)
  , validator
  ) where

import              Data.Aeson                (ToJSON, FromJSON)
import              GHC.Generics              (Generic)
import              Schema                    (ToSchema)
import              Ledger              hiding (singleton)
import              Ledger.Address
import              Ledger.Typed.Scripts
import              Ledger.Value        as Value
import              Ledger.Ada
import qualified    PlutusTx
import              PlutusTx.Prelude    hiding (Semigroup (..), unless)
import              Prelude             (Show (..))
import qualified    Prelude                   as Pr

-- Simple Faucet validator script

-- Usage:
-- Expect one utxo at each contract.
-- Take that utxo as input
-- Create a new utxo with the "change" as output

-- This contract provides an example of using Validator Parameters.

-- For now, the Datum and Redeemer are not used in contract logic
-- Transactions will still have to match the type Integer for Datum and Redeemer
-- The context matters: we want to see that the PPBLSummer2022 token is in the transaction inputs and outputs.

data FaucetParams = FaucetParams
  { accessTokenSymbol   :: !CurrencySymbol
  , accessTokenName     :: !TokenName
  , faucetTokenSymbol   :: !CurrencySymbol
  , faucetTokenName     :: !TokenName
  , withdrawalAmount    :: !Integer
  } deriving (Pr.Eq, Pr.Ord, Show, Generic, ToJSON, FromJSON, ToSchema)

PlutusTx.makeLift ''FaucetParams

{-# INLINEABLE faucetValidator #-}
faucetValidator :: FaucetParams -> Integer -> Integer -> ScriptContext -> Bool
faucetValidator faucet _ _ ctx =   traceIfFalse "Input needs PPBLSummer2022 token"    inputHasAccessToken &&
                            traceIfFalse "PPBLSummer2022 token must return to sender" outputHasAccessToken &&
                            traceIfFalse "Faucet token must be distributed to sender" outputHasFaucetToken &&
                            traceIfFalse "Must return remaining tokens to contract"   faucetContractGetsRemainingTokens &&
                            traceIfFalse "Do we need to check datum"                  checkDatumIsOk
  where
    info :: TxInfo
    info = scriptContextTxInfo ctx

    receiverPkh :: PubKeyHash
    receiverPkh = head $ txInfoSignatories info

    allTokens :: [CurrencySymbol]
    allTokens = symbols $ valueSpent info

    inputHasAccessToken :: Bool
    inputHasAccessToken = (accessTokenSymbol faucet) `elem` allTokens

    valueToReceiver :: Value
    valueToReceiver = valuePaidTo info receiverPkh

    outputHasAccessToken :: Bool
    outputHasAccessToken = (valueOf valueToReceiver (accessTokenSymbol faucet) (accessTokenName faucet)) >= 1

    outputHasFaucetToken :: Bool
    outputHasFaucetToken = (valueOf valueToReceiver (faucetTokenSymbol faucet) (faucetTokenName faucet)) >= (withdrawalAmount faucet)

    -- The UTXO input from Faucet
    ownInput :: TxOut
    ownInput = case findOwnInput ctx of
        Nothing -> traceError "faucet input missing"
        Just i  -> txInInfoResolved i

    -- The UTXO output back to Faucet
    ownOutput :: TxOut
    ownOutput = case getContinuingOutputs ctx of
        [o] -> o -- There must be exactly ONE output UTXO
        _   -> traceError "expected exactly one faucet output"

    faucetInputValue :: Value
    faucetInputValue = txOutValue ownInput

    faucetOutputValue :: Value
    faucetOutputValue = txOutValue ownOutput

    faucetContractGetsRemainingTokens :: Bool
    faucetContractGetsRemainingTokens = (valueOf faucetInputValue (faucetTokenSymbol faucet) (faucetTokenName faucet)) - (withdrawalAmount faucet) <= (valueOf faucetOutputValue (faucetTokenSymbol faucet) (faucetTokenName faucet))

    checkDatumIsOk :: Bool
    checkDatumIsOk = True

data FaucetTypes

instance ValidatorTypes FaucetTypes where
    type DatumType FaucetTypes = Integer
    type RedeemerType FaucetTypes = Integer

typedValidator :: FaucetParams -> TypedValidator FaucetTypes
typedValidator faucet =
  mkTypedValidator @FaucetTypes
    ($$(PlutusTx.compile [||faucetValidator||]) `PlutusTx.applyCode` PlutusTx.liftCode faucet)
    $$(PlutusTx.compile [||wrap||])
  where
    wrap = wrapValidator @Integer @Integer

validator :: FaucetParams -> Validator
validator = validatorScript . typedValidator

As you can see both Datum and Redeemer are given as integers, while Datum has to be exactly the one used to get the datum-hash I guess that the redeemer integer can be any?
here is the transaction used to unlock it but which fails
CONTRACT_TXIN="7325518aff0270f7ef019236977baa8c301e8213a632996e0852480d5df196eb#1"
AUTH_TOKEN_TXIN="95b5308a55dd1648ea6e8f2325c0a7e307240aef1998777bb3ec860a3c32e55c#1"
FEE_TXIN="95b5308a55dd1648ea6e8f2325c0a7e307240aef1998777bb3ec860a3c32e55c#3"
COLLATERAL="95b5308a55dd1648ea6e8f2325c0a7e307240aef1998777bb3ec860a3c32e55c#2"
PLUTUS_SCRIPT_FILE=output/faucet.plutus
ASSET="fb45417ab92a155da3b31a8928c873eb9fd36c62184c736f189d334c.7467696d62616c"
AUTH_TOKEN="07fd9522f3ea6179415f8934ce0aa71b67fac6aa6024a59013bde6d8.506f72636f526f73736f466175636574546f6b656e"
TOKENS_BACK_TO_CONTRACT=267
CONTRACTADDR="addr_test1wrd5y9tudjkdcaxfy0cnuf042xlx4s9xm4xlq8pqdcyyxxsfr38fl"
DATUMHASH="db2b9e43ba6771c834279febfd091fd8cae78dec7ebe86fd9d729d3ba61e38e4"
SENDER="addr_test1vpjkdcxaxvt04vezk6r7vsdn22w40z094wggnpvvp47sy0cauqn90"

cardano-cli transaction build \
--tx-in $FEE_TXIN \
--tx-in $AUTH_TOKEN_TXIN \
--tx-in $CONTRACT_TXIN \
--tx-in-script-file $PLUTUS_SCRIPT_FILE \
--tx-in-datum-value 168 \
--tx-in-redeemer-value 21 \
--tx-in-collateral $COLLATERAL \
--tx-out $SENDER+"2000000 + 33 $ASSET" \
--tx-out $SENDER+"2000000 + 1 $AUTH_TOKEN" \
--tx-out $CONTRACTADDR+"2000000 + $TOKENS_BACK_TO_CONTRACT $ASSET" \
--tx-out-datum-hash $DATUMHASH \
--change-address $SENDER \
--protocol-params-file protocol.json \
--testnet-magic 1 \
--out-file unlock.raw

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 machine terminated because of an error, either from a built-in function or from an explicit use of 'error'.
Script debugging logs: PT8

I would appreciate any help on understanding where the problem comes from or direction on how to debug a plutus script.

See here, PT8 means PlutusTx.List.head: empty list
Perhaps it's because you're using head on an empty txInfoSignatories. You must use --required-signer or --required-signer-hash flags when building the transaction to embed the required signer pubkey in txbody.


text:
How to check the output datum reference in V2
The following code would work for V1:
outputDatum :: EkivalEscrowDatum
outputDatum = case transferDatum $ txOutDatumHash ownOutput >>= flip findDatum info of

    Nothing -> traceError "Transfer output datum not found"

    Just d  -> d

However, "txOutDatumHash" seems to be missing a corresponding implementation in V2.
I understand we may face inline Datum, which would not include the Hash, but backward compatibility appears to not be fully implemented on this function.
From the plutus-apps examples, I noticed a mixture of V1 modules whenever the datum was being verified.
PS: transferDatum :: Maybe Datum -> Maybe EkivalEscrowDatum

For plutus v2 you have to differentiate since inline datums could be present at a given output.
outputDatumByHash :: DatumHash -> Maybe Datum
outputDatumByHash h = findDatum h info

ownOutputDatum :: TxOut -> Maybe TransferDatum
ownOutputDatum TxOut{txOutDatum=OutputDatumHash h} = transferDatum $ outputDatumByHash h
ownOutputDatum _                                   = Nothing

outputDatum :: TxOut -> TransferDatum
outputDatum txOut = case ownOutputDatum txOut of
    Nothing -> traceError "Transfer output datum not found"
    Just d  -> d

Looking at the API:
V1's TxOut uses txOutDatumHash :: Maybe DatumHash
V2's TxOut uses txOutDatum :: OutputDatum
where data OutputDatum = NoOutputDatum | OutputDatumHash DatumHash | OutputDatum Datum
So V2 still has DatumHash but you need to also handle the possibility of OutputDatum (inline datum).


text:
TransactionValidityTranslationError: What's the valid interval for time/slot transation
I suddenly encountered this error, I had never encountered before. I was using (Protocol params and era history configuration from 2 weeks ago. It used to work for months before.
TransactionValidityTranslationError (TimeTranslationPastHorizon "PastHorizon {
pastHorizonCallStack = [(\"runQuery\",SrcLoc {srcLocPackage = \"ouroboros-consensus-0.1.0.0-a216910c01eb3712c5487a4b54690aeafd473fd59e5beff964ae947cd0bb7174\", srcLocModule = \"Ouroboros.Consensus.HardFork.History.Qry\", srcLocFile = \"src/Ouroboros/Consensus/HardFork/History/Qry.hs\", srcLocStartLine = 430, srcLocStartCol = 44, srcLocEndLine = 430, srcLocEndCol = 64}),(\"interpretQuery\",SrcLoc {srcLocPackage = \"ouroboros-consensus-0.1.0.0-a216910c01eb3712c5487a4b54690aeafd473fd59e5beff964ae947cd0bb7174\", srcLocModule = \"Ouroboros.Consensus.HardFork.History.EpochInfo\", srcLocFile = \"src/Ouroboros/Consensus/HardFork/History/EpochInfo.hs\", srcLocStartLine = 45, srcLocStartCol = 50, srcLocEndLine = 45, srcLocEndCol = 68}),(\"interpretQuery'\",SrcLoc {srcLocPackage = \"ouroboros-consensus-0.1.0.0-a216910c01eb3712c5487a4b54690aeafd473fd59e5beff964ae947cd0bb7174\", srcLocModule = \"Ouroboros.Consensus.HardFork.History.EpochInfo\", srcLocFile = \"src/Ouroboros/Consensus/HardFork/History/EpochInfo.hs\", srcLocStartLine = 39, srcLocStartCol = 9, srcLocEndLine = 39, srcLocEndCol = 52}),(\"epochInfoSlotToRelativeTime_\",SrcLoc {srcLocPackage = \"cardano-slotting-0.1.0.0-7618dff6992469ca39863ffbcc2ebdde043b2a836c21f9a4d8d0ba8fe2c8209e\", srcLocModule = \"Cardano.Slotting.EpochInfo.API\", srcLocFile = \"src/Cardano/Slotting/EpochInfo/API.hs\", srcLocStartLine = 62, srcLocStartCol = 9, srcLocEndLine = 62, srcLocEndCol = 37}),(\"epochInfoSlotToRelativeTime\",SrcLoc {srcLocPackage = \"cardano-slotting-0.1.0.0-7618dff6992469ca39863ffbcc2ebdde043b2a836c21f9a4d8d0ba8fe2c8209e\", srcLocModule = \"Cardano.Slotting.EpochInfo.API\", srcLocFile = \"src/Cardano/Slotting/EpochInfo/API.hs\", srcLocStartLine = 125, srcLocStartCol = 40, srcLocEndLine = 125, srcLocEndCol = 70}),(\"epochInfoSlotToRelativeTime_\",SrcLoc {srcLocPackage = \"cardano-slotting-0.1.0.0-7618dff6992469ca39863ffbcc2ebdde043b2a836c21f9a4d8d0ba8fe2c8209e\", srcLocModule = \"Cardano.Slotting.EpochInfo.API\", srcLocFile = \"src/Cardano/Slotting/EpochInfo/API.hs\", srcLocStartLine = 62, srcLocStartCol = 9, srcLocEndLine = 62, srcLocEndCol = 37}),(\"epochInfoSlotToRelativeTime\",SrcLoc {srcLocPackage = \"cardano-slotting-0.1.0.0-7618dff6992469ca39863ffbcc2ebdde043b2a836c21f9a4d8d0ba8fe2c8209e\", srcLocModule = \"Cardano.Slotting.EpochInfo.API\", srcLocFile = \"src/Cardano/Slotting/EpochInfo/API.hs\", srcLocStartLine = 91, srcLocStartCol = 30, srcLocEndLine = 91, srcLocEndCol = 63}),(\"epochInfoSlotToUTCTime\",SrcLoc {srcLocPackage = \"cardano-ledger-alonzo-0.1.0.0-8d084ba3551393bc3a51af041b759b56dfc986c4f3d9b8ac5ecfc8ac9b696582\", srcLocModule = \"Cardano.Ledger.Alonzo.TxInfo\", srcLocFile = \"src/Cardano/Ledger/Alonzo/TxInfo.hs\", srcLocStartLine = 233, srcLocStartCol = 9, srcLocEndLine = 233, srcLocEndCol = 41})],
pastHorizonExpression = Some (EPair (ERelToAbsTime (ERelSlotToTime
  (EAbsToRelSlot (ELit (SlotNo 73626947))))) (ESlotLength (ELit (SlotNo 73626947)))),
pastHorizonSummary = [
 EraSummary {eraStart = Bound {boundTime = RelativeTime 0s, boundSlot = SlotNo 0, boundEpoch = EpochNo 0}, eraEnd = EraEnd (Bound {boundTime = RelativeTime 89856000s, boundSlot = SlotNo 4492800, boundEpoch = EpochNo 208}), eraParams = EraParams {eraEpochSize = EpochSize 21600, eraSlotLength = SlotLength 20s, eraSafeZone = StandardSafeZone 4320}},
 EraSummary {eraStart = Bound {boundTime = RelativeTime 89856000s, boundSlot = SlotNo 4492800, boundEpoch = EpochNo 208}, eraEnd = EraEnd (Bound {boundTime = RelativeTime 101952000s, boundSlot = SlotNo 16588800, boundEpoch = EpochNo 236}), eraParams = EraParams {eraEpochSize = EpochSize 432000, eraSlotLength = SlotLength 1s, eraSafeZone = StandardSafeZone 129600}},
 EraSummary {eraStart = Bound {boundTime = RelativeTime 101952000s, boundSlot = SlotNo 16588800, boundEpoch = EpochNo 236}, eraEnd = EraEnd (Bound {boundTime = RelativeTime 108432000s, boundSlot = SlotNo 23068800, boundEpoch = EpochNo 251}), eraParams = EraParams {eraEpochSize = EpochSize 432000, eraSlotLength = SlotLength 1s, eraSafeZone = StandardSafeZone 129600}},
 EraSummary {eraStart = Bound {boundTime = RelativeTime 108432000s, boundSlot = SlotNo 23068800, boundEpoch = EpochNo 251}, eraEnd = EraEnd (Bound {boundTime = RelativeTime 125280000s, boundSlot = SlotNo 39916800, boundEpoch = EpochNo 290}), eraParams = EraParams {eraEpochSize = EpochSize 432000, eraSlotLength = SlotLength 1s, eraSafeZone = StandardSafeZone 129600}},
 EraSummary {eraStart = Bound {boundTime = RelativeTime 125280000s, boundSlot = SlotNo 39916800, boundEpoch = EpochNo 290}, eraEnd = EraEnd (Bound {boundTime = RelativeTime 157680000s, boundSlot = SlotNo 72316800, boundEpoch = EpochNo 365}), eraParams = EraParams {eraEpochSize = EpochSize 432000, eraSlotLength = SlotLength 1s, eraSafeZone = StandardSafeZone 129600}},
 EraSummary {eraStart = Bound {boundTime = RelativeTime 157680000s, boundSlot = SlotNo 72316800, boundEpoch = EpochNo 365}, eraEnd = EraEnd (Bound {boundTime = RelativeTime 158544000s, boundSlot = SlotNo 73180800, boundEpoch = EpochNo 367}), eraParams = EraParams {eraEpochSize = EpochSize 432000, eraSlotLength = SlotLength 1s, eraSafeZone = StandardSafeZone 129600}}]}")

What's the reason for the error? At given time, how do I find out the size of valid time horizon?


text:
Failing Validation on Script Address
I am trying to unlock an NFT that I locked into a script address. The unlocking succeds when I have some basic validation  rules but when I add the minterIsPaid rule below, the validitation transaction fails.
data AssetPurchase = AssetPurchase {
    nft :: !TokenName
   ,minter :: !Address
   ,minterCurrency :: !AssetClass
   ,minterAmount :: !Integer
   ,beneficiary :: !Address
   ,beneficiaryAmount :: !Integer
   ,beneficiaryCurrency :: !AssetClass
   ,collateral :: !AssetClass
   ,collateralAmnt :: !Integer
} deriving (Show, Generic, FromJSON, ToJSON)

purchaseValidator :: AssetPurchase -> () -> () -> ScriptContext -> Bool
purchaseValidator p () () ctx  = validate
    where
        validate ::  Bool
        validate =   validateTxOuts && minterIsPaid

         minterIsPaid :: Bool
         minterIsPaid = assetClassValueOf (valuePaidToAddress (minter
                        p)) (minterCurrency p) == minterAmount p

         valuePaidToAddress :: Address -> Value
         valuePaidToAddress addr = mconcat (fmap txOutValue (filter
                     (\x -> txOutAddress x == addr) (txInfoOutputs
                     (scriptContextTxInfo ctx))))
...

My parameters for deploying this contract look like this:
writeAssetPurchaseValidator = writeValidator "token/lock/mds-lock.plutus" $ validator $ AssetPurchase
                                {
                                    nft= Ledger.Value.tokenName $ TE.encodeUtf8 $ T.pack "MediSnap#06"
                                   ,minter = L.pubKeyHashAddress (L.PaymentPubKeyHash $  L.PubKeyHash $ BuiltinByteString $  TE.encodeUtf8 $ T.pack "bebe8013168a1f3607bddb3a170b0adb12400316a8bcf34b7efedf0a") Nothing
                                   ,minterCurrency = Ledger.Value.assetClass (Ledger.Value.currencySymbol $ TE.encodeUtf8 $ T.pack "") (Ledger.Value.tokenName  $ TE.encodeUtf8 $ T.pack "")
                                   ,minterAmount = 2000000
                                   ,beneficiary = L.pubKeyHashAddress (L.PaymentPubKeyHash $  L.PubKeyHash $ BuiltinByteString $  TE.encodeUtf8 $ T.pack "482421baa0219f801aa40f91dd8ec5d6ded4631a73f09b9d9b29848c") Nothing
                                   ,beneficiaryCurrency = Ledger.Value.assetClass (Ledger.Value.currencySymbol $ TE.encodeUtf8 $ T.pack "") (Ledger.Value.tokenName  $ TE.encodeUtf8 $ T.pack "")
                                   ,beneficiaryAmount = 2000000
                                   ,collateral = Ledger.Value.assetClass (Ledger.Value.currencySymbol $ TE.encodeUtf8 $ T.pack "") (Ledger.Value.tokenName $ TE.encodeUtf8 $ T.pack "")
                                   ,collateralAmnt = 2000000
                                }

My unlocking transaction is as shown:
cardano-cli transaction build-raw \
     --babbage-era \
    --tx-in 05be931d5f807650412724cb75faa7da3c898ccbeddd5b762dc8480b12ca6875#0 \
    --tx-in-datum-file "../token/lock/unit.json" \
    --tx-in-redeemer-file "../token/lock/unit.json" \
    --tx-in-script-file "../token/lock/mds-lock.plutus" \
    --tx-out $(cat ../wallets/buyer/buyer.addr)+"2130271 lovelace + 1 6669034a6d4719d62097b5ed28f81e76b80ca2a289d9a4aceabc38d2.4d656469536e61702336" \
    --tx-out $(cat ../wallets/beneficiary/beneficiary.addr)+2000000 \
    --tx-out $(cat ../wallets/minter/minter.addr)+2000000 \
    --tx-in-collateral "dc6fba11e10917236072a200c5e9e8b2c5c95d317d9b924bd736952fb5153c39#0" \
    --tx-in-execution-units="(10000000000, 14000000)" \
    --protocol-params-file "../token/lock/protocol-params.json" \
    --fee 1869729  \
    --out-file "../token/unlock/tx.body"

cardano-cli transaction sign \
    --tx-body-file "../token/unlock/tx.body" \
    --signing-key-file "../wallets/buyer/buyer.skey" \
    --$TS \
    --out-file "../token/unlock/tx.signed"

When I run this unlock transaction, I get an error which is not very helpful.
The error is:\n
CekError An error has occurred:  User error:\nThe machine terminated because of an error, either from a built-in function or from an explicit use of 'error'.
Command failed: transaction submit  Error: Error while submitting tx: ShelleyTxValidationError ShelleyBasedEraBabbage (ApplyTxError [UtxowFailure (UtxoFailure (FromAlonzoUtxoFail (UtxosFailure (ValidationTagMismatch (IsValid True) (FailedUnexpectedly (PlutusFailure "\nThe 3 arg plutus script (PlutusScript PlutusV1 ScriptHash \"a83254bf933b34d7d0072c3270a07cf1d9c87d34b01ffdf8ae29d959\") fails.\nCekError An error has occurred:  User error:\nThe machine terminated because of an error, either from a built-in function or from an explicit use of 'error'.\nThe protocol version is: ProtVer {pvMajor = 7, pvMinor = 0}\nThe data is: Constr 0 []\nThe redeemer is: Constr 0 []\nThe context is:\nPurpose: Spending (TxOutRef {txOutRefId = 05be931d5f807650412724cb75faa7da3c898ccbeddd5b762dc8480b12ca6875, txOutRefIdx = 0})\nTxInfo:\n  TxId: c5c5a5a47c7f3f204aafe3b2a2cea20ceb2fab7f1a0a3d162508ad0fe601b77d\n  Inputs: [ 05be931d5f807650412724cb75faa7da3c898ccbeddd5b762dc8480b12ca6875!0 -> - Value (Map [(,Map [(\"\",8000000)]),(6669034a6d4719d62097b5ed28f81e76b80ca2a289d9a4aceabc38d2,Map [(\"MediSnap#6\",1)])]) addressed to\n                                                                                ScriptCredential: a83254bf933b34d7d0072c3270a07cf1d9c87d34b01ffdf8ae29d959 (no staking credential) ]\n  Outputs: [ - Value (Map [(,Map [(\"\",2130271)]),(6669034a6d4719d62097b5ed28f81e76b80ca2a289d9a4aceabc38d2,Map [(\"MediSnap#6\",1)])]) addressed to\n               PubKeyCredential: 08498419e83871d01aae9c97a45218f3aedc0b963f787569ce0c1463 (no staking credential)\n           , - Value (Map [(,Map [(\"\",2000000)])]) addressed to\n               PubKeyCredential: 482421baa0219f801aa40f91dd8ec5d6ded4631a73f09b9d9b29848c (no staking credential)\n           , - Value (Map [(,Map [(\"\",2000000)])]) addressed to\n               PubKeyCredential: bebe8013168a1f3607bddb3a170b0adb12400316a8bcf34b7efedf0a (no staking credential) ]\n  Fee: Value (Map [(,Map [(\"\",1869729)])])\n  Value minted: Value (Map [])\n  DCerts: []\n  Wdrl: []\n  Valid range: (-\8734 , +\8734)\n  Signatories: []\n  Datums: [ ( 923918e403bf43c34b4ef6b48eb2ee04babed17320d8d1b9ff9ad086e86f44ec\n          , <> ) ]\n"
...
alot of text for datum hashes

Any ideas what could be goin wrong?

I've seen this message before [...] because of an error, either from a built-in function or from an explicit use of 'error' [...] when I tried running a Plutus v1 script with Plutus v2 context. Perhaps check if you're using any v1/v2 builtins unintentionally depending on your version choice.

Yep, checked all my imports, looks ok. All versioned imports have V1

First, try adding trace logs to your validator, i.e. use traceIfFalse with a unique message for each condition.
Then using cli's build cmd instead of build-raw. It runs script evaluation and prints trace log output on failure.

Nice. Adding the traceIfFalse and using build helped alot. From the error logs,  I got code PT5) and using (https://plutus.readthedocs.io/en/latest/troubleshooting.html#error-codes) ,I am thinking that the minterIsPaid function retuns a false. Now if only I can tell why..thanks!


text:
What is a MIR certificate, what does MIR mean in general?
The acronym seems to mean "move instantaneous rewards" (link), but I can't find any good ELI5 explanation on what that means, when would I require a MIR certificate, etc.

"MIR" is not a particularly good name, but I can explain the history.
It started out standing for "move ITN rewards", where "ITN" stands for the "incentivized test net". The idea of the ITN was a test network whose rewards would end up on the main network after the launch of the Shelley phase. The MIR certificates were originally designed for exactly the purpose of transferring Lovelace from the reserves on mainnet to the participants of the ITN (and requiring authorization using the existing governance mechanisms).
It eventually became clear that this mechanism would be useful for more purposes than just the ITN rewards, such as paying out Catalyst winners from the treasury. So the acronym was re-imagined to stand for "move instantaneous rewards", since they transfer funds at the next epoch boundary.
An ELI5 explanation of MIR certificates is: MIR certificates require the authorization of the existing Cardano governance mechanism, and they result in the transfer of Lovelace from the reserves or the treasury to a collection of stake credentials. (They can also move Lovelace between the reserves and the treasury.)

Thank you, the back-story helps a lot! Somebody should write the "History of Cardano for developers" :)

Not sure about the exact purpose of MIR (move instantaneous rewards) certificate but it seems to be a specific type of transaction to allow for 'transferring funds between reserves and the treasury'.
My guess would be for funding things like Catalyst projects.
This link will tell you what instantaneous rewards are.


text:
Boostraping a plutus Smart contract project
I'm trying to "play" with Plutus and write some smart contract for the sake of practicing and getting familiar with it.
My problem is I don't know how to bootstrap a smart contract project.
Starting from the Plutus page on the Cardano Developer Portal, I've watched several videos and read through the user documentation but did not find my way to create a Cardano smart contract project.
What could help me would be:

A template for a minimal Haskell project to write such contracts
Explanations on how to automatically test my smart contract
Step by step tutorial on how to go from my Haskell code to having the contract deployed on a dev or test net

I don't have a concrete answer to your question but I can tell you this is definitely something that's in the making. Perhaps an adequate starting point would be the part of Hydra project that deals with just the smart contracts:

This is the source tree for the Plutus contracts: https://github.com/input-output-hk/hydra-poc/tree/master/hydra-plutus
The contracts are unit tested here: https://github.com/input-output-hk/hydra-poc/blob/master/hydra-node/test/Hydra/Chain/Direct/ContractSpec.hs but this requires a bit of scaffolding.

I know this is probably not very helpful...

The Plutus Pioneer Program repository is very helpful to get started:

https://github.com/input-output-hk/plutus-pioneer-program/tree/main/code

There are also Youtube videos explaining the code examples here:

https://www.youtube.com/playlist?list=PLNEK_Ejlx3x0mhPmOjPSHZPtTFpfJo3Nd

It's all PlutusV1 as far as I know.

After learning the basic I just used: https://github.com/input-output-hk/plutus-starter to get all the environment I needed for building my first validators in plutus.
beware it is not updated to Vasil code

See this post
You can write tests with QuickCheck
There are many ways to achieve this. If you aren't concerned about the architecture and are just in it for learning, an easy way is by using lucid + blockfrost.

try the plutus starter project. It is a nix project,using the cardano iogx nix framework so it may take a while for your environment to come up.


text:
Why does staking happen with a delay?
In Cardano, AFAICU, at the beginning of an epoch a snapshot is taken of the end state of previous epoch to see who staked, how much and where. But it seems that that state is not used as for that current epoch but for the next one instead. Is there a particular reason for this?
E.g is it because to have time to calculate slot leaders and then let them know that they need to start producing blocks? Are there other reasons?
It seems somewhat counterintuitive that by the time one is "staking" the actual funds might be long gone, delegated to another pool or not staked at all. Though I understand that this doesn't break the system and that it's just a delay.

The stake distribution for epoch N is not used as the basis for the epoch N + 1 reward calculations because at the start of epoch N + 1 there may be a rollback that may rollback as far as later blocks of epoch N which would require a recalculation of the stake distribution.
However rollbacks are limited to a maximum of 2160 blocks, so the stake distribution for epoch N cannot be rolled back after 2160 blocks have been produced in epoch N + 1. It is therefore safe to use the epoch N stake distribution for the reward calculation for epoch N + 2.
Similarly rewards earned in epoch N + 2 are not distributed until epoch N + 4, again to avoid the possibility of a rollback.
Finally, rollbacks are part of the normal operation of a blockchain.


text:
Can't use the address that I just created using cardano-addresses
I just used cardano-addresses software to create a wallet and two addresses that can receive tADA. But I can't access any information of these address using Cardano Explorer. Or check if the tADA's where received.
addr_test1vzlz473fksrprx8g6z0d72lwj46lsrjutx69uvhq0s8yjvg6hnfrr
https://github.com/input-output-hk/cardano-addresses

You can find your address and transactions on the "Preview" testnet (not to be confused with the "Pre-Production" testnet):
https://preview.cexplorer.io/address/addr_test1vzlz473fksrprx8g6z0d72lwj46lsrjutx69uvhq0s8yjvg6hnfrr
https://preview.cexplorer.io/tx/a11dd3e1dee2a626999a3fdced8c7c49dbb3f3b89343a2e17c40185d503bb4a6
Some info on the environments:
https://book.world.dev.cardano.org/environments.html#preview-testnet

Can I put these tADA's on pre-pod?
Or I don't need that to receive the values on my address?

You can’t move them over, but you can get new tAda through the faucet here, just select the PreProd environment: https://docs.cardano.org/cardano-testnet/tools/faucet

The explorer gets these address (so they can be displayed) from the block chain. If these addresses have not received any funds, the explorer cannot know about them.


text:
CIP25 Metadata standard version 2 token name
I have seen recently that CIP25 was updated to include version 2. The main change in this is that the token name is now a bytes type whereas before it was a string.
My question is, what type actually is this? Is it a JavaScript Buffer, a byte array, a hex encoded string, or something else?

On the blockchain, the token name was never actually a string and was always bytes. Usually they are ASCII encoded, but they may also be UTF8, UTF-16 or even some other encoding.


text:
Is pure ADA put in a script address locked up forever?
I was trying out the 'always succeeds' script from the helios tutorial
(https://github.com/Hyperion-BT/Helios/blob/main/doc/tutorial_03-always_succeeds.md)
and made a mistake in the change address, so now all my funds (29281.95 ADA) ended up at the script-address:
addr_test1wpqdgpwgv7494dmuv2tzl09fwc6alyq4u08fgs45aryn3hc5r25st         | = 29311.37 |
* ba437386485a977b345f081fe8d39435947bf4c6851f87ab4bb6731127503f7b#0    | +     2.00 | Pure Ada
* ba437386485a977b345f081fe8d39435947bf4c6851f87ab4bb6731127503f7b#1    | +     1.14 | Datum
* c161c40f48aa036635fc054990ef7dd42eb5a9d954a176aed482abb2c0846c61#0    | + 29281.95 | Greatest Pure Ada
* c3fef0e132089ae508ce7e557fe804613bee7ca2ee7f29dc569a3fe633f111a7#0    | +     2.00 | Pure Ada
..
..

Is there a way to get back the value from the pure Ada tx'es?  (ie. the ones without a datum)
Because this is a script-address, I don't have any .skey for it, and I have the impression
you can only get out the ADA from the tx'es that have a datum.
Is there a way?
For the record: MAGIC = 2 / cardano-cli 1.35.3 - linux-x86_64 - ghc-8.10.

You tADA is locked forever. Luckily it is tADA, not real ADA. The preview network will be re-created in a few week anyway (after preprod, which will be reset on October 19th 2022).

Where did you get the info on the preprod and preview testnets being reset?

From the IOG's Technical Discord.

Thanks! I’m on that discord, but can’t find that announcement. Could you maybe give me a link to it? Thanks a lot

You probably don't see the SPO channels. You need to pick the SPO role in #start-here and they you will see the SPO channels. The announcement is in the #spo-announcements channel.

Thanks, got it! Little disappointing to learn about it this way as a non-spo developer and testnet user, but thanks for pointing me to it

The 'always succeeds' means you can send wrong datum/redeemer but the transaction always goes through - always succeeds.
Thus, the fund is not locked forever. Anybody, with the script, can build a transaction to get it back. There is even a warning NOT to use such script in production. Have you tried the latter part of the helios tutorial?
Or, am I missing something?

An absent datum might make those UTxOs unmoveable though.


text:
Using cardano-wallet for ingame sign in
i have built an in game User interface around Cardano-wallet.
now im looking for a way to let the player sign in using his wallet .
how can i approach it using cardano-wallet?
is there a way to let the player sign some data using his private key , then on the server side i decode it using his public key ?
( one of the solutions i tried is to let the player send 1 ADA from his wallet to a server provided address , and i monitor the transaction to verify ... but bad approach obviously ..)
thank you for your attention.

will wait for message sign / verify gets added to cardano-wallet api itself ,
https://github.com/input-output-hk/cardano-wallet/issues/3537
implementing it from scratch or doing other hacky ways will be inconvenient.

If your game is not browser based, one way to do this is to create a small website on which you let the user sign a message with a browser based wallet. The website can then send the signed message to your server.
To do this you can use the signData() method as specified in CIP-30.
Or if you have the private key of the user's wallet in your game, you can sign a message in your game and send it to the server.
On your server, you have to verify that the message is signed correctly. You can do this using the cardano-serialization-lib. More details on message signing can be found in CIP-8.
If the message is signed correctly, you can return something like an access token (e.g. a JWT) to the user.

This is a very simple example on how this could work and there are a lot of things you'd need to consider when you implement this like franken-address attacks or token lifetimes etc.

Thank you for your suggestion , i was looking for a way that wont force the user to leave the game or get interrupted from his virtual experience ( could be VR , PS5 , anywhere.. ) . https://github.com/input-output-hk/cardano-wallet/issues/3537 having the message sign-in / verify added to the cardano-wallet api itself , would do the trick. happpy to wait for that .


text:
Preview testnet transactions
I want to access an address that is on preview testnet and create transactions to spend all tADA. How can I do something like this?

The easy way: https://namiwallet.io

Install browser-extension wallet, such as Nami
Restore your wallet with the mnemonics and the passphrase
Set Nami to use preview testnet (default is mainnet)
transfer tADA to the address you so choose

The hard way: cardano-cli

Install/run cardano-node by: https://developers.cardano.org/docs/get-started/installing-cardano-node
Restore wallet and create transaction by cardano-cli like: https://developers.cardano.org/docs/integrate-cardano/creating-wallet-faucet

The not-so-hard way: https://blockfrost.dev

You first need to generate keys to derive an address from. Addresses that are already in use are not accessible unless you hold the associated signing key.
One way to get started is with the cardano-cli. See https://docs.cardano.org/cardano-testnet/getting-started


text:
Chain Indexers with Stream Endpoints
I have been taking a look at different chain indexers (or APIs to indexers) to see what's available today and how they differ - see resource list below.
Question
I still wanted to raise the question, what would be a good option for an event-based backend (not necessarily written in Haskell) that shall process on-chain events as they happen. In particular, we want to observe certain addresses and aggregate on-chain data using an CQRS / event sourcing architecture.
My current take
I wouldn't want to poll data via REST which makes Kupo and Blockfrost not an ideal candidate.
Oura looks like a great candidate but from what I see, it's not really indexing and much rather filtering on event types (like blocks, txs, assets etc.) and would still require some more processing on the backend to actually get the data I am interested in. What I like about it is that it support Node-to-Client (N2C) communication.
Scrolls as of now looks like a great candidate as it offers opinionated read-optimized views. I would imagine a Redis centered event store architecture combined with Redis Streams. The only thing I'd love support for is N2C which looks like is not yet implemented with version 0.4.2 mainly for improved performance.
Ogmios looks also very attractive as it would easily allow for a Node.js backend that could connect via websockets to directly read from the node. It's not an indexer I believe, but more an interface to the node. Hence, it requires additional filtering/ indexing in the backend similar to Oura.
Carp by dcSpark looks interesting too. It indexes and stores everything to a Postgres db, allows for N2C. Might very well be one of the strongest candidates and most likely complete in terms of development.
Lastly, Marconi looks like the best alternative to Scrolls & Carp unless I am forgetting about some other available resource. It's Haskell based and unfortunately, as of now has no event streams implemented. It will offer it in the near future.
Summary
In short, it looks like the available options are still very early in development but very promising. Nevertheless, I would appreciate feedback, things I've missed or other advice from the community!
Thanks!
Resources

Kupo
Oura
Scrolls
Marconi
Blockfrost
Ogmios
Carp

Hi there (Kupo's maintainer here)!
Given the use case you're describing, Scrolls seems the most suited solution at present -- especially because this is exactly the direction Scrolls is moving into.
We've been discussing that on several occasions with Santiago (Scrolls' maintainer), and we try to not overlap too much between Scrolls and Kupo; both solutions emerged roughly around the same time and we're now trying to make them focus on a different set of use cases.
About the N2C in Scrolls, keep in mind that the project is open source and I am sure that you'd find either the resources to implement it or, if kindly ask, you may have maintainers or community-members consider prioritizing it.
Regarding Oura & Ogmios, you're right that they are more fundamental building blocks, not indexers, but they would allow you to build your own indexer should Kupo or Scrolls not meet your needs in the end.
Carp is a good alternative to db-sync, probably overkill for small projects.
Marconi, as far as I can tell, is Kupo with less features and less documentation. I wasn't aware that this project even existed (and... now a bit baffled to be honest).

Thanks, I appreciate the feedback!

Agree with all that's been said already, just important (unfortunate) gap to highlight (since we're talking about comparison), most of the solutions are not able to fetch certain offline or historical information from ledger-state, tho that is a limitation that comes from consensus/ledger teams instead - and a very non-trivial piece of work to keep up with.
So while things like historical reward history, epoch nonce, etc may not useful to all (especially in DeFi world), other solutions (for instance Carp) unfortunately do not exactly qualify as alternative/replacement to dbsync yet - tho hoping things improve on that front all around.

Good point! I didn't particularly mention it bc we don't require those data points for the solution we're looking to build. But you're right db-sync as of now offers complete ledger state access such as rewards etc. that most other tools do not include.

An interesting follow-up conversation on this topic: https://github.com/cardano-foundation/CIPs/pull/375


text:
Ogmios Node Stopped Working
I did follow cardano-graphql guide and I was running my node smoothly for 2 months today It gave me this error and couldn't understand what is wrong with it. I restarted the container but didn't solve my problem.
CONTAINER ID        IMAGE                                                 COMMAND                  CREATED             STATUS                       PORTS                                                    NAMES
59bdf858b940        inputoutput/cardano-graphql-hasura:6.2.0              "docker-entrypoint..."   2 months ago        Up 2 months                  0.0.0.0:8090->8080/tcp                                   cardano-graphql-hasura-1
2c4608f0384f        postgres:11.5-alpine                                  "docker-entrypoint..."   2 months ago        Up 2 months                  0.0.0.0:5432->5432/tcp                                   cardano-graphql-postgres-1
2d17673d47ba        inputoutput/cardano-db-sync:12.0.0                    "/nix/store/5ghw8r..."   2 months ago        Up 2 months                                                                           cardano-graphql-cardano-db-sync-extended-1
2f8ed0c5755a        inputoutput/cardano-graphql:6.2.0-mainnet             "node index.js"          2 months ago        Up 8 weeks                   0.0.0.0:3100->3100/tcp                                   cardano-graphql-cardano-graphql-1
d26dcadce926        cardanosolutions/cardano-node-ogmios:v5.1.0-mainnet   "/root/cardano-nod..."   2 months ago        Up About an hour (healthy)   3000/tcp, 12788/tcp, 0.0.0.0:1337->1337/tcp, 12798/tcp   cardano-graphql-cardano-node-ogmios-1

Cardano went through Hard Fork event (Vasil fork) while the old node/dbsync/ogmios versions - you'd need to upgrade your components


text:
Ledger 24-word seed vs Daedalus/Yoroi 24-word seed recovery process does not generate the same ADAs addresses
Using a Daedalus/Yoroi wallet with the 24-word seed and a new Ledger Nano S Plus.
I tried to use the 24-word seed to "recover" the (daedalus) wallet in a new Ledger Nano S Plus, (using Ledger live) the addresses were not the same and obviously not the same wallets. So my questions are:
Why are not the same?. If they are BIP39, the result should be the same?
Second, if I use a new Cardano wallet in a Ledger Nano S Plus, later how can I recover the wallet only with the 24-word seed? (Assuming the hardware was lost and the Ledger company was out of bussines). Is there a way to recover the wallet not using Ledger hardware?
Thank you


text:
How to calculate ADA balance at a prior point in time?
I'm trying to calculate the ADA balance at a prior point in time using DB-Sync.
What I did was first work out what the last tx.ID number of the 10th May 22 was, which in my version of the db is 40491540.
So then I wrote this query:
select sum (value) / 1000000 as current_supply from tx_out as tx_outer
inner join stake_address sa on tx_outer.stake_address_id = sa.id
where
    not exists
      ( select tx_out.id from tx_out
       inner join tx_in on tx_out.tx_id = tx_in.tx_out_id and tx_out.index = tx_in.tx_out_index
          where tx_outer.id = tx_out.id and tx_in.tx_in_id < 40491540
      )
and tx_outer.tx_id <=40491540

However this gives me a total circulating ADA balance of 26.bn which I don't this is right - should be more like 33.7bn.
What am I doing wrong?

Ah ok I solved it. I was close. Just had to turn the inner join into a left join
select sum (value) / 1000000 as current_supply from tx_out as tx_outer
left join stake_address sa on tx_outer.stake_address_id = sa.id
where
    not exists
      ( select tx_out.id from tx_out
       inner join tx_in on tx_out.tx_id = tx_in.tx_out_id and tx_out.index = tx_in.tx_out_index
          where tx_outer.id = tx_out.id and tx_in.tx_in_id < 40491540
      )
and tx_outer.tx_id <=40491540

Your query excludes account balances (not sure why you're doing the join to stake_address here).
But if looking for total/circulating supply, you can already get those from dbsync table ada_pots (see example here ).
The supply would only change per epoch - when reserved are unlocked.

Thanks - what do you mean by "excludes account balances"? And join to stake_address is because I wanted to (ultimately) analyze the largest stake_addresses. Sorry should have explained that up top or left out the join. Ada_Pots .. useful to know!

I meant you're only looking up UTxOs, but there are rewards on accounts (that have been distributed from reserves), fundings extracted from treasury, deposits made for accounts, that you wouldnt see in tx_out table


text:
Network.Socket.connect: <socket: 11>: permission denied error accessing node.socket over shared volume mount in docker
I am putting together an application in docker (compose) that has 2 services:

Cardano Node
Web Application

Both services/containers shares the node-ipc via volume mount, when I try query tip via the web application, I am getting permission denied. This is my docker-compose.yml
version: "3.5"

services:

  cardano-node:
    container_name: cardano-node
    image: inputoutput/cardano-node:${CARDANO_NODE_VERSION}
    networks: [ my-app-network ]
    environment:
      - NETWORK=${NETWORK}
      - CARDANO_NODE_SOCKET_PATH=/ipc/node.socket
    volumes:
      - node-db:/data/db
      - node-ipc:/ipc
    logging:
      driver: "json-file"
      options:
        max-size: "200k"
        max-file: "10"

  web-service:
    build:
      context: ..
      dockerfile: docker/Dockerfile
    container_name: web-service
    tty: true
    networks: [ my-app-network ]
    volumes:
      - ../application:/home/web/application
      - node-ipc:/ipc
    environment:
      - CARDANO_NODE_SOCKET_PATH=/ipc/node.socket
    ports: [ "8080:80" ]

volumes:
  node-db:
  node-ipc:

networks:
  my-app-network:

After building the above, I shelled into the web-service container and ran the following:
./bin/cardano-cli query tip --testnet-magic 2

Getting this error:

cardano-cli: Network.Socket.connect: <socket: 11>: permission denied (Permission denied)

I checked the /ipc/node.socket exists via the shared volume mount and I can see it:
web_service@0f78c2f4136e:~/application$ ls -lah /ipc
total 8.0K
drwxr-xr-x 2 root root 4.0K Oct 19 00:13 .
drwxr-xr-x 1 root root 4.0K Oct 19 00:13 ..
srwxr-xr-x 1 root root    0 Oct 19 00:13 node.socket

Any idea why I can't seem to share the node.socket via volume mount?

According to the docs, this should be possible: https://hub.docker.com/r/inputoutput/cardano-node
Mount a volume for establishing cross-container communication via node.socket
docker run -e NETWORK=mainnet -v node-ipc:/ipc inputoutput/cardano-node
docker run -e NETWORK=mainnet -v node-ipc:/ipc inputoutput/some-node-client

The cardano-node inside the docker run as root, and created node.socket as root:
srwxr-xr-x 1 root root    0 Oct 19 00:13 node.socket

HOW TO:
METHOD 1: You can try to change the owner directly, but next time restart the docker compose, it will back to root again.
sudo chown $USER node.socket

METHOD 2: Try to run cardano-node as your user id.
add -u $(id -u ${USER}):$(id -g ${USER}) in docker run command or user: <user id>:<user group> in docker compose
METHOD 3: Remap User ID.
Here is the config guide
https://docs.docker.com/engine/security/userns-remap


text:
OffChain code for inline datum
I am trying to create a OffChain code for submitting inline datums.
gTest :: forall w s. GrabParams -> PlutusContract.Contract w s DataText.Text ()
gTest GrabParams{..} = do
    PlutusContract.logInfo @P.String $ TextPrintf.printf "------------------------------------------------------"
    PlutusContract.logInfo @P.String $ TextPrintf.printf "------------------- GTest endpoint -------------------"
    PlutusContract.logInfo @P.String $ TextPrintf.printf "------------------------------------------------------"
    maybeutxo <- findUtxoInValidator grabRedeem
    PlutusContract.logInfo @P.String $ TextPrintf.printf "datum utxos %s" (P.show maybeutxo)
    case maybeutxo of
        Nothing -> PlutusContract.logInfo @P.String $ TextPrintf.printf "Wrong guess %d" grabRedeem
        Just (oref, o) -> do
            PlutusContract.logInfo @P.String $ TextPrintf.printf "Redeem utxos %s" (P.show oref)
            let
                d = OnChain.Dat
                    {
                          ddata = grabRedeem
                        , dtype = OnChain.Test
                    }
                r = OnChain.Redeem
                    {
                        OnChain.redeem = grabRedeem
                    }
                q = 4000000
                lookups = Constraints.unspentOutputs (Map.singleton oref o) P.<>
                          Constraints.plutusV2OtherScript OnChain.validator
                tx = (Constraints.mustPayToOtherScriptWithDatumInTx OnChain.validatorHash (ScriptsLedger.Datum $ PlutusTx.toBuiltinData d) (lovelaceValueOf q)) <>
                     (Constraints.mustIncludeDatumInTx  (ScriptsLedger.Datum $ PlutusTx.toBuiltinData d)) <>
                     (Constraints.mustSpendScriptOutput oref $ ScriptsLedger.Redeemer $ PlutusTx.toBuiltinData r)
            PlutusContract.logInfo @P.String $ TextPrintf.printf "[GTEST TX] %s" (P.show tx)
            submittedTx <- PlutusContract.submitTxConstraintsWith @OnChain.Simple lookups tx
            Monad.void $ PlutusContract.awaitTxConfirmed $ LedgerTx.getCardanoTxId submittedTx
            PlutusContract.logInfo @P.String $ "collected gifts"

I even tried the Constraints.mustPayToOtherScriptWithInlineDatumInTx and still doesn't include the inline datum.

What plutus-apps tag/branch are you using?

Constraint.mustPayToOtherScriptWithInlineDatumInTx doesn't exist on main branch. Use Constraint.mustPayToOtherScriptWithInlineDatum without other datum-related constraints to avoid conflict.


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

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

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


text:
How do you interact with smartcontract on jpg.store
Does anyone know how you interact with smart contract on jpg. store
Do we need this?
https://github.com/jpg-store/current-jpg-store-contracts
if so how do we do so?

I don't think you can. Validator are sent with the transaction, so you either have the source code or their CBOR to add to your transaction.
When they move to Vasil and Plutus V2 you'll have reference scripts with that you only need to find a transaction to get the reference to the script.