text:
How are airdrops sent to token holders when NFTs do not belong to contracts?
Since NFTs on Cardano do not belong to a contract, how can token holders be rewarded with an airdrop? Do they need to request it themselves by showing proof of ownership?

Having the NFT on an UTxO on your address is the proof of ownership.
How the token holders receive an airdrop (automatically or only after claiming it) only depends on how the one doing the airdrop wants to do it.

I should have formulated my question better: is there a way for those airdropping to know the owners of the tokens? I do not see how this could work on Cardano. In Ethereum each NFT-owner would be known through the contract

By owner you mean the person holding the NFT?

Yes, that is what I meant. Is there a record of who owns what?

No, the persons owning the wallets are not known. Is there any blockchain where that is public information?

It is very easy to do. All NFTs are named [poliyID].[TokenName]. Simply put that into cardanoscan.io and you can see the wallet that holds any particular NFT. You then just mint (airdrop) a new token into that wallet. Done.
Take for example this blockowl:
3f4360edd7f689b637b44587150e71453a51ba29655336ff374c201c.BlockOwlsStake001
If you put the above into CardanoScan and click Top Holders, you will find the wallet it lives in:
addr1q87xqs5duasp4ehuec9gasy9qptt7zhweg046gh9pa7nmax6yxvvxd5qhurea4rvlj6a8c35twc0654l48avkn79z3mq46yfdm


text:
What are the steps in producing a block in Cardano?
I would love a high-level overview suitable for a beginner that covers collecting transactions, proposing a block, propagating the block, and then finally verifying it.

Here's a five-minute video by Andrew Westberg talking about just this.
In short, the steps are as follows:

A signed transaction is submitted to the mempool of the local cardano-node.
mempools are constantly being synced between the nodes' peers
A stake pool makes a new block by taking all the transactions in their mempool and appending it to the tip of their chain. TX's included in this block are then cleared from their mempool.
Other nodes see the stake pool has an extra block (and hence a longer chain), so they verify the block's legitimacy, and add it to their chain. TX's in the new propagating block are also cleared from everyone's mempool.
Repeat until the network is synced.

Hope this helps!

source: Stack Exchange

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

sort: votes


text:
Is there any risk in sharing my rewards address?
I want to test ẗhe Maladex Rewards calculator but they ask me to enter my rewards address. Is there any conceivable risk in doing so?

The only risks associated with sharing any kind of public/verification keys or addresses have to do with de-anonymization. If you are concerned with Maladex, your ISP, a traffic sniffer, or any other entity possibly linking your rewards address with your IP address, then you might have something to worry about. However, assuming you aren't massively evading taxes, living in an oppressive regime, or have some other target on your back, there is very little  risk to your funds when sharing your rewards address.
If however any of the above do apply to you, or you prefer to stay on the ultra-paranoid side, there are still options. You can use cardano-db-sync to query chain information from your own running node, including the reward history for a given stake address.
Another option is to learn how to access the internet in a truly anonymous fashion, and use third parties like Maladex that way. Warning: this is a deep dark rabbit hole, not for the faint of heart. If you are interested though, I'd recommend starting with The Hitchhiker’s Guide to Online Anonymity.

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


text:
Is the fact that EUTXO can use scripts to lock/unlock UTXOs really a difference from the UTXO model?
In the EUTXO explainer it says that

[The EUTXO model] generalizes the concept of ‘address’ by using the lock-and-key analogy. Instead of restricting locks to public keys and keys to signatures, addresses in the EUTXO model can contain arbitrary logic in the form of scripts. For example, when a node validates a transaction, the node determines whether or not the transaction is allowed to use a certain output as an input. The transaction will look up the script provided by the output's address and will execute the script if the transaction can use the output as an input.

But isn't this the same as locking/unlocking scripts as used in Bitcoin? I understand Cardano's scripts are more sophisticated, but that is a difference of degree.

EUTXO stands for (Extended Unspent Transaction Output), the mechanism is, in spirit, the same as Bitcoin UTXO (Unspent Transaction Output) but very much improved.
The first difference is between scripting languages, Bitcoin uses Script which is a very primitive scripting language and has around 90 available OP Codes for use. Cardano uses Plutus which is essentially Haskell, a very powerful functional programming language.
The second difference is the information the script has to work with, Bitcoin script does not have access to the context information of the transaction, the user locking funds in a Bitcoin UTXO provides a partial Bitcoin Script, and the spender must complete the Script in a way that the Script leaves the value true on the stack after the execution ends, but the script is blind to the details of the transaction (the script has access to the signatures, but not the details about how the value is being transferred between parties), for example:
OP_HASH256 6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000 OP_EQUAL

This script will hash twice the given data with SHA-256 (see OP_HASH256) and compare the result to the embedded hash (in this case the data is Genesis block header).
A Cardano Plutus script on the other hand has full access to everything that is going on in the transaction, how the ADA is moving, signatures etc:
-- | A pending transaction. This is the view as seen by validator scripts, so some details are stripped out.
data TxInfo = TxInfo
    { txInfoInputs      :: [TxInInfo] -- ^ Transaction inputs
    , txInfoOutputs     :: [TxOut] -- ^ Transaction outputs
    , txInfoFee         :: Value -- ^ The fee paid by this transaction.
    , txInfoMint        :: Value -- ^ The 'Value' minted by this transaction.
    , txInfoDCert       :: [DCert] -- ^ Digests of certificates included in this transaction
    , txInfoWdrl        :: [(StakingCredential, Integer)] -- ^ Withdrawals
    , txInfoValidRange  :: POSIXTimeRange -- ^ The valid range for the transaction.
    , txInfoSignatories :: [PubKeyHash] -- ^ Signatures provided with the transaction, attested that they all signed the tx
    , txInfoData        :: [(DatumHash, Datum)]
    , txInfoId          :: TxId
    -- ^ Hash of the pending transaction (excluding witnesses)
    } deriving stock (Generic, Haskell.Show, Haskell.Eq)

And the third difference is the introduction of the concept of Datum and Reedemer, Datums are linked to EUTXOs and are useful to keep track of state, and Reedemer is data that can be provided to the EUTXO when we want to unlock it, both Datums and Redeemers can be arbitrary data structures.
This is a good resource from the Plutus Pioneer Program that goes into detail on how the EUTXO model work:
https://www.youtube.com/watch?v=bfofA4MM0QE
The EUTXO in general it's more expensive and powerful.

Very good explainer. I still think that the text I quoted is misleading; UTXOs in the UTXO model can be locked with scripts. I think it would be better if the Cardano docs were rewritten to explain how much more powerful Cardano's scripts are rather than claim that the difference is the possibility of using scripts.
I guess the EUTXO definition they use comes from a time when bitcoin did not support locking UTXOs with scripts, only (hashed) public keys.

Yes, but the Bitcoin blockchain does not store a datum on-chain. So the concept is similar but you are very limited what you can do with those scripts.


text:
Failed to build and install cardano-wallet on ubuntu
I'm trying to build and install cardano-wallet on ubuntu according to https://developers.cardano.org/docs/get-started/installing-cardano-wallet/#building-and-installing-the-node
But once I run the below command,
stack build --test --no-run-tests
I'm getting this error.
Received ExitFailure 128 when running
Raw command: /usr/bin/git reset --hard f827a4321e42f528e25f6079f7af3eb18f10d391
Run from: /tmp/with-repo8046/cloned
Standard error:

fatal: Could not parse object 'f827a4321e42f528e25f6079f7af3eb18f10d391'.

Any idea?

What is your ubuntu version?

Try maybe git fetch and then try one more time that command?

Seems something is broken. :) I will try to reach out developers. Seems cardano-ledger repository don't have necessary commit.

I'm getting exactly the same error here, at object f827a4321e42f528e25f6079f7af3eb18f10d391 (using Ubuntu 20.04.2)

i'm using Ubuntu-20.04 with WSL2 on Windows 10.

I retried today and it worked.

This commit was referencing a pull request branch of cardano-ledger that was closed: jc/benchmark/1-29-0-with-time. A new branch was pushed to resolve this called cardano-wallet/deps-for-node-1.30.1
This is a weird oddity with GitHub where it will refuse to give you an archive for a commit, even if it's aware of it if it's been orphaned and no longer exists in an open branch.


text:
Do I need to validate for minADAUTxO output in Smart Contract validator?
I have a spending validator that currently expects an output with an NFT to be recreated at its own address.
Is it necessary to also include a check whether the output's value has a greater equal ADA balance of minAdaTxOut (minAdaTxOut Reference)
Or is this done by the 2 phase node validation process?

In theory no; In practice maybe.
If min ada is not present in each output then the Tx will fail regardless of validator.
But. Min ada as implemented in Plutus is hardcoded to 2 ada. This is not how min ada works. Min ada is calculated against the size (of data) of the utxo. More than three NFTs? that'll be more than 2 Ada  required in the same utxo.
If your using constraints then you'll need to bear this in mind,
since these details may really matter https://github.com/input-output-hk/plutus-apps/blob/c4cc9ee1add8f421e57789befb6a0c90621801f1/plutus-ledger-constraints/src/Ledger/Constraints/OnChain.hs#L123
How to calculate min ada is a bit convoluted. Why isnt a function in plutus-apps for it? No idea. Why wasn't it implemented properly... ?
You can extract the logic from here https://docs.cardano.org/native-tokens/minimum-ada-value-requirement/


text:
Building a transaction using Nami api wallet and cardano-client-lib
I am trying to build a transaction with the libary of cardano-client-lib (java sdk).
Inorder to build a transaction one needs to provide an account object which can only be created with the mnemonic phase, which is clearly a problem.
I thought of using Nami wallet API as a walkaround, but seems unable to get the specific instance of the wallet in java.  is there a way to build a transaction in java with nami api?
thanks.

Nami is a web wallet and injects its API into your website. It is not supposed to work with desktop applications but only with web apps. I recommend you to build your app with react + typescript + emurgo/cardano-serialization-lib-browser. That is how I built this minting app

Another option:
Transaction can be built in Java backend and then sent to Nami for signing.
Here's a sample code for Multi-sig token mint where
(Not exactly same but similar approach can be used for your scenario)

Mint Transaction is built in Java backend
Sign by Nami extension in the browser
Send the witness back to Java backend
Assemble transaction again with other witnesses in Java backend and submit the final transaction

MultiSigTokenMint With Java + Nami

I don't think you can get the wallet instance from Nami as the whole point of a wallet is to hide the private key and pass transactions visually to the user so that she can approve and submit them.
I would rather try the other way and look if your java library has methods to generate an unbalanced transaction that can be passed to the Nami wallet. Such a method would only need the wallet's UTxOs and the address of the recipient.
But I also have no clue on which libraries do this. It is very difficult at the moment to find anything useful on the subject.

I have done this function, don't know if it will help you.
Two projects are required:
cardano-client-examples
https://github.com/zjavax/cardano-client-examples-zx/blob/main/src/main/java/cn/zjavax/BuildWithJavaBackend.java

public class BuildWithJavaBackend extends BaseTest {
    public static void main(String[] args) throws AddressExcepion, CborSerializationException, ApiException {
        new BuildWithJavaBackend().transfer();
        System.exit(1);
    }

    public void transfer() throws CborSerializationException, ApiException, AddressExcepion {
//        String senderMnemonic = "kit color frog trick speak employ suit sort bomb goddess jewel primary spoil fade person useless measure manage warfare reduce few scrub beyond era";
        String senderAddress = "addr_test1qqxnp3khzm7kcj9t23hskehat7428ghsenk0pfew4rqy5v9frnmht7uwrl073q4jvq20z82kh4rksyns540azhndqexqpvhgqr";
        String receiverAddress1 = "addr_test1qqwpl7h3g84mhr36wpetk904p7fchx2vst0z696lxk8ujsjyruqwmlsm344gfux3nsj6njyzj3ppvrqtt36cp9xyydzqzumz82";

        Output output1 = Output.builder()
                .address(receiverAddress1)
                .assetName(LOVELACE)
                .qty(adaToLovelace(1))
                .build();

        TxBuilder txBuilder = (output1.outputBuilder()
                .buildInputs(createFromSender(senderAddress, senderAddress))
        )
                .andThen(feeCalculator(senderAddress, 1))
                .andThen(adjustChangeOutput(senderAddress, 1));

        Transaction signedTransaction = TxBuilderContext.init(utxoSupplier, protocolParamsSupplier).build(txBuilder);

        System.out.println("txHexDraft=\"" +signedTransaction.serializeToHex()+"\"");

    }
}

cardano-walletconnector-demo

The result of calling cc wallet:

@Satya（don't know how @）


text:
Nami wallet address format to addr_test1 format
lets say i have the following address for recieving funds:
addr_test1qzu70xm8hsez6nvmpgk4gjf48ev0y2hw5w7nf8xaxc658lzwczusckqvzzg630pxnzwj3pqza5q4c8r504ffq6v2zh6qgznxt7
when i try and get the wallet address  (by using Berry-Pool nami wallet) i get:
00b9e79b67bc322d4d9b0a2d5449353e58f22aeea3bd349cdd363543fc4ec0b90c580c1091a8bc26989d288402ed015c1c747d5290698a15f4
how can i go from 00b9e79b67bc322d4d9b0a2d5449353e58f22aeea3bd349cdd363543fc4ec0b90c580c1091a8bc26989d288402ed015c1c747d5290698a15f4
to addr_test1qzu70xm8hsez6nvmpgk4gjf48ev0y2hw5w7nf8xaxc658lzwczusckqvzzg630pxnzwj3pqza5q4c8r504ffq6v2zh6qgznxt7
Thank you

Also you can use Cardano Serialization Lib https://github.com/Emurgo/cardano-serialization-lib
with the class Adress and the method Address.toBech32() :
let HexAddress = "00b9e79b67bc322d4d9b0a2d5449353e58f22aeea3bd349cdd363543fc4ec0b90c580c1091a8bc26989d288402ed015c1c747d5290698a15f4"

console.log(Address.from_bytes(Buffer.from(HexAddress,"hex")).to_bech32())

this is exactly what i was looking for. is there a way to use this library in vuejs?

They are encoded in different formats as the followings:
Bech32 Format:

addr_test1qzu70xm8hsez6nvmpgk4gjf48ev0y2hw5w7nf8xaxc658lzwczusckqvzzg630pxnzwj3pqza5q4c8r504ffq6v2zh6qgznxt7

Hex Format:

0b9e79b67bc322d4d9b0a2d5449353e58f22aeea3bd349cdd363543fc4ec0b90c580c1091a8bc26989d288402ed015c1c747d5290698a15f4

IOHK provides an executable and haskell lib for that in this repo.
To Hex,
bech32 <<< addr_test1qzu70xm8hsez6nvmpgk4gjf48ev0y2hw5w7nf8xaxc658lzwczusckqvzzg630pxnzwj3pqza5q4c8r504ffq6v2zh6qgznxt7

To Bech32,
bech32 addr_test <<< 00b9e79b67bc322d4d9b0a2d5449353e58f22aeea3bd349cdd363543fc4ec0b90c580c1091a8bc26989d288402ed015c1c747d5290698a15f4


text:
How to do on-chain Integer pattern matching?
I want to do Integer pattern matching on-chain but always get an error:
GHC Core to PLC plugin: E042:Error: Unsupported feature: Use of Haskell Integer equality, possibly via the Haskell Eq typeclass Context: Compiling expr...

It seems to relate to this piece of code:
checkMint :: Integer -> Bool
checkMint (1)  = True
checkMint (-1) = True
checkMint _    = False

It seems that it uses the Prelude Integer equality operator instead of PlutusTx.Prelude. But how can I change that instead of rewriting the function and make it us PlutusTx.Prelude (==) instead?

Have you tried adding the pragma {-# LANGUAGE NoImplicitPrelude #-} ? This make sure that the standard prelude is not imported. This prevents the use of the Haskell Eq type class instead of the Plutus one.

Yes, good point. It was indeed the problem of using the standard haskell == pattern match. I resolved it by slightly rewriting this function bc I still need the Haskell Prelude in my code.

There is problem with pattern matching on Integer types according to Input Output Global. The Plutus compiler will currently reject any pattern matching on Integer types.
Therefore the best solution is to adjust the code in the following way:
checkMint :: Integer -> Bool
checkMint i
    | i == 1    = True
    | i == -1   = True
    | otherwise = False


text:
Best ways to create UTxO snapshots at epoch boundary
I would like to create snapshots of the set of UTxOs at the end of each epoch for a particular address.
What would be best ways to do something like that?
Constraints/ Ideas
The current tools I am aware of is just querying the address' UTxOs using the cardano-cli. But I'd like ensure that I get the exact UTxO set of a specific address at the start of the next epoch and using the cli seems error prone since rollbacks may happen or my node may not have all UTxOs synched during epoch boundaries.

A relatively simple bit of SQL should allow you to grab this from cardano-db-sync. IN the git repo there is a file doc/interesting-queries,md that may give some clues.

Thanks to Erik I've found a query for historical queries for a UTxO set of a specific address that can be found here:
Get historical UTxO set for given timestamp


text:
TxOutRefNotFound when using Plutus.Contract.Wallet (getUnspentOutput)
I am trying to get a UTxO of the current wallet, use it to mint a token via the OneShotCurrency type, but I keep getting the following Error:
(TxOutRefNotFound (TxOutRef {txOutRefId = b2f06756e65c009ced73c87919e4f8dd0e640b002a247083354f7122f82d312f, txOutRefIdx = 10}))
Here are my lookups and tx construction. Thanks for any help!
[...]
do
    ppkh   <- ownPaymentPubKeyHash
    oref   <- getUnspentOutput
    utxos  <- utxosAt (pubKeyHashAddress ppkh Nothing)
    let
        pol  = curPolicy $ OneShotCurrency { curRefTransactionOutput=(txOutRefId oref, txOutRefIdx oref), curAmounts=(PlutusTx.AssocMap.singleton myTokenName 1) }
        mVal = Value.singleton (scriptCurrencySymbol pol) myTokenName 1
        d    = [...]
        lookups       = Constraints.unspentOutputs utxos                            <>
                        Constraints.mintingPolicy pol                               <>
                        Constraints.typedValidatorLookups validatorInstance
        tx            = Constraints.mustSpendPubKeyOutput txOutRef                  <>
                        Constraints.mustPayToTheScript d (mVal <> Ada.adaValueOf (getAda 3000000))  <>
                        Constraints.mustMintValue mVal                              <>
                        Constraints.mustBeSignedBy ppkh
    ledgerTx <- submitTxConstraints validatorInstance tx
    awaitTxConfirmed $ getCardanoTxId ledgerTx
    logInfo @P.String "Initialized"
[...]

More context is needed. Did you run this contract using PAB (plutus-pab) or using plutus-contract emulator? When you're saying "current wallet", what are you referring to?

I ran it using the plutus-contract emulator.

The txOutRef variable is undefined. Is it actually oref?


text:
How to burn Cardano token after the 'invalid after' passes?
My token policy script is:
all:
    [
        {
           invalidAfter: 40951072
        },
        {
           pubKey: "36ed345d252a242ad67072db79e5736866fa58ebe3fd782739208ef6"
        }
    ]

Since the slot already passes it looks like I can't burn tokens by cardano-cli 'mint' anymore. The error I get is:
Command failed: transaction submit  Error: Error while submitting tx: ShelleyTxValidationError ShelleyBasedEraAlonzo (ApplyTxError [UtxowFailure (WrappedShelleyEraFailure (ScriptWitnessNotValidatingUTXOW (fromList [ScriptHash "6c6d152385ada4cc7606a31090ac37ac267b0b5e2e37ecaf6b47d146"])))])
I wonder is there any other 'best practice' to burn the token?

As Isaac stated, transaction with this policy is not possible anymore. But that does not mean it is not possible to publicly make assets unavailable. There is a great post on the Cardano form that goes in-depth on different types of burning methods [1]. Note that these tokens send to such addresses still exists but can't be transferred anymore by anyone.

You could send it to a wallet you control then destroy any record of your credentials :)

It does not answer the case since I need to 'destroy' them publically. So anyone could be sure that it was burned.

It's impossible to get the policy script to validate since the validity interval has passed. There is actually no way to burn the token because Cardano was designed that way. Take a video of yourself transferring it to a hardware wallet then smashing it with a hammer :)


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

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

What do I do wrong here?

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

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

It worked out. Thank you.

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

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


text:
How to add multiasset as input to txBuilder?
I'm trying to add lovelaces + native assets to input as multiAsset. However I get Inputs do not conform to this spec or are otherwise invalid.
Here is my code:
    const assetsToSend = this.S.MultiAsset.new();
    const assets = this.S.Assets.new();
    const policyStr = "17830caa477d5eac7a4b6c123d98fa232e6e921368b01b7cd0bdfce6"

    const assetStr = "17830caa477d5eac7a4b6c123d98fa232e6e921368b01b7cd0bdfce641414441";
    const assetName = this.S.AssetName.new(Buffer.from(assetStr.slice(56), "hex"));

    // creating asset value for lovelaces
    const assetsValue = this.S.Value.new(
        this.S.BigNum.from_str('1500000')
    )

    // Inserting Native token
    assets.insert(
        assetName,
        this.S.BigNum.from_str('123')
    );

    // Adding asset to multiasset
    assetsToSend.insert(
        this.S.ScriptHash.from_bytes(Buffer.from(policyStr, "hex")),
        assets
    );
    // Setting value with multiasset
    assetsValue.set_multiasset(assetsToSend)

    txBuilder.add_input(
        this.S.Address.from_bech32("addr_test1qqcula4fd6nr92zx2jyl59eqy574f8uhg98dhfys7zer23p03az6tzlxgrxk5a9ev6taetv6ljkyr7rcx4rljm7qya2syeq06w"),
        this.S.TransactionInput.new(
            this.S.TransactionHash.from_bytes(
                Buffer.from("707c0ad2499b278e48bc8e42b902ec8ccea8e83e87175f57f4349241cd5a8417", "hex")
            ), // tx hash
            0, // index
        ),
        assetsValue
        // this.S.Value.new(this.S.BigNum.from_str('1500000'))
    );

The code I described above is okay to pass multiassets to TX inputs. It have worked for me with cardano-serialization-lib 10.0.1 .


text:
How to optimize Plutus smart contracts?
Context
I'm creating scripts with hardcoded parameters in my smartcontract and I would like to reduce footprint of them to reduce transaction fees. Right now i'm doing so using parameterized smartcontracts. I can't provide source but I read or heard somewhere that using parameterized smartcontracts use up a lot of ExMemory. When building plutus scripts i'm using evaluateScriptCounting which after compilation shows me ExCPU and ExMemory of my script. So far I have found the only way to hardcode parameters without using parameterized smartcontracts with BuiltinByteStrings is doing something like this:
{-# INLINABLE flattenBuiltinByteString #-}
flattenBuiltinByteString :: [BuiltinByteString] -> BuiltinByteString
flattenBuiltinByteString [] = emptyByteString
flattenBuiltinByteString (x:xs) = appendByteString x (flattenBuiltinByteString xs)

{-# INLINABLE getPkh #-}
getPkh :: PubKeyHash
getPkh = PubKeyHash { getPubKeyHash = flattenBuiltinByteString [ consByteString x emptyByteString |x <- [128,164,244,91,86,184,141,17,57,218,35,188,76,60,117,236,109,50,148,60,8,127,37,11,134,25,60,167]]}

I was expecting that this way I would get lower ExCPU and ExMemory units. But I did some tests and to my surprise my smartcontract without parameterized parameters was bigger!
Tests

ExCPU -> 8366313, ExMemory -> 28200. Plain always succeeds.
ExCPU -> 8366313, ExMemory -> 28200. BuiltinByteString, no checks, no datum.
ExCPU -> 9080865, ExMemory -> 30600. Parameterized no checks, no datum.
ExCPU -> 9438141, ExMemory -> 31800. Parameterized no checks, added typed datum with 4 fields.
ExCPU -> 10152693, ExMemory -> 34200. Parameterized 4 checks against typed datum.
ExCPU -> 11135202, ExMemory -> 37500. BuiltinByteString 4 checks against typed datum.

Questions

My flattenBuiltinByteString is doing the flattening foldr style which is ineffective and I suppose is why i'm having such big jump in ExMemory units. I was looking for foldl' in Plutus library but couldn't find anything. Does Plutus have something simillar to seq so that I could make my own foldl' implementation?
Are there other more effective ways to flatten BuiltinByteString list on-chain?
What over tricks I could do besides using BuiltinData types instead of my own custom typed data types to optimize my smartcontracts?
Should I even be bothering with optimizations like this, whats the upper ExCPU and ExMemory limit?

I am building a dApp myself and I am running into similar issues related to hitting the current mainnet's maxTxExUnits upper boundaries of exUnitsMem and exUnitsSteps.
In regards to question 4:
You can find the current upper limits by querying your cardano node for protocol parameters like so:
cardano-cli query protocol-parameters $MAGIC --out-file protocol-parameters.json

The limits can be found under: maxTxExecutionUnits
I resolved some of my issues related to exceeding the ExMemory upper limit by:

simplifying/ optimizing the contract logic
removing traceIfFalse statements or at least decreasing long log message string down to error codes
using Bang Pattern in let-bindings
avoid exhaustive case patterns and instead rely on Plutus' throwing an error for a missing pattern match

There are many more resources you can read below for further possible code improvements to optimize your script.
Sources:

MinSwap Article
Plutonomicon

The biggest decrease in mem usage I was able to achieve is by pattern matching against function inputs - especially when it comes to ScriptContext.
Try to always pattern match unless you really need every field inside a given type. Good examples for that are TxOut, Maybe types and any of your datums

Mlabs created excelent tool to quickly check and analyse size of smartcontracts. Github repo is here


text:
How to get information about UTxOs which created locking transaction on the on-chain?
I would like to create a smartcontract which makes sure that only the same person who made specific locking transaction can unlock that same specific transaction or to put it into simpler terms if Bob locks his Ada then smartcontract must ensure that only Bob can unlock his locked Ada.
I think in TxInfo one of the txInfoInputs UTxO should contain information about locking transaction. But from data definition of txInfoInputs :: [TxInInfo] field:
data TxInInfo = TxInInfo
    { txInInfoOutRef   :: TxOutRef
    , txInInfoResolved :: TxOut
    } deiriving stock (Generic, Haskell.Show, Haskell.Eq)

I can't tell how exactly could I get public key hash of source address or something else which could give me information for validation if unlocking transaction is being made by the same person who made locking transaction.
Another way I can think of is to add sender address into Datum but I can't think of a way how to ensure secure Datum creation process so that for example when Bob is creating transaction to luck funds in smartcontract Alices address as a receiver doesn't appear in Datum
So is it even possible, to create such smartcontract which would take information of locking transaction and by using that information validate if smartcontract funds can be unlocked?

In TxOut you have a field txOutAddress that you can use for this:
data TxOut = TxOut {
  txOutAddress   :: Address,
  txOutValue     :: Value,
  txOutDatumHash :: Maybe DatumHash
}

Use it to extract the pubkeyhash:
pkh = toPubKeyHash $ txOutAddress txOut

And then in the smart contract check if the transaction is signed by it:
txSignedBy (scriptContextTxInfo ctx) pkh


text:
How does one-time minting policy actually work?
In week 5 of plutus-pioneer-program with NFT example this plutus minting policy code is provided:
{-# INLINABLE mkPolicy #-}
mkPolicy :: TxOutRef -> TokenName -> () -> ScriptContext -> Bool
mkPolicy oref tn () ctx = traceIfFalse "UTxO not consumed"   hasUTxO           &&
                          traceIfFalse "wrong amount minted" checkMintedAmount
  where
    info :: TxInfo
    info = scriptContextTxInfo ctx

    hasUTxO :: Bool
    hasUTxO = any (\i -> txInInfoOutRef i == oref) $ txInfoInputs info

    checkMintedAmount :: Bool
    checkMintedAmount = case flattenValue (txInfoForge info) of
        [(cs, tn', amt)] -> cs  == ownCurrencySymbol ctx && tn' == tn && amt == 1
        _                -> False

Script validates if minted NFT is 1. Here are my questions regarding one-time minting:

Is this an example of a one-time policy script which is referenced in Cardano documentation here ?
If this is a one-time minting policy, how does it ensure that only one and only NFT is to be minted with this minting policy? What stops me of instead minting many NFS with single transaction creating many transactions to mint many NFTS one by one?
If this is not a one-time minting policy, how does one-time policy actually look like? How does it ensure that only one token or NFT is to be minted in Cardano network?
Is it possible and if so how to secure the total amount to be minted with minting policy? How would simplest example of that plutus script code look like?
Is it possible to create such minting policy, that it allow to mint only if total minted token amount is not reached and if so how?
Is it possible to create such minting policy, that total amount to be minted is dependent on the time (slot). For example by Monday total amount minted can be 10000, but by Tuesday it can be 20000?

Yes, this is an example of a "one-time minting policy" referred to in the Cardano documentation.
The policy ensures that only one NFT is minted by a combination of i) being parametrised with a specific UTxO that needs to be consumed by the transaction (checked by hasUTxO) and ii) checking that the total mint quantity is 1. As all UTxOs are unique, this policy can only succeed one time and then never again. The parametrisation ensures that the NFT currency symbol depends on this UTxO, so that if you define the same policy with another UTxO it would not be the same NFT.
I did not understand the question in bullet point 4.
To get a minting policy that allows to mint up to a total fixed supply, I would combine the policy with a script UTxO that keeps track of the minted value in the datum. You need to put an NFT in this script UTxO as well and the minting policy would need to check the presence of it in the transaction and delegate the validation to the script. The script can then check the newly minted value and apply some logic, like checking the weekday. But it would be much easier to just mint the total quantity in one transaction and then distribute the tokens with another mechanism.

Is it possible to read Datum values in UTXO from plutus policy script?

Minting policies also get a ScriptContext passed to. Through this context you can access the datums of the transaction inputs and outputs.


text:
How to get PubKeyHash of an address without vkey?
How to get Address -> PubKeyHash without vkey just with addr like addr_test1wrf230u95zr26lut09mchmt82d235v6335jvszme2jevklslg5lfz?
It must be possible, because when you build unlocking transaction from smartcontract locked funds  with cardano-cli transaction build ... you pass --change-address parameter which doesn't require vkey like cardano-cli address key-hash command does. Smartcontract manages to get PubKeyHash from provided addr_... which it can get from txOutputs :: [txOut]

You can see the CDDL spec for full details: https://github.com/input-output-hk/cardano-ledger/blob/master/eras/shelley/test-suite/cddl-files/shelley.cddl
In the case of a payment base address (the most common address on the chain at the moment), the address when converted from bech32 -> hex will have a prefix of 00 (on testnet, 01 on mainnet), followed by the payment credential, followed by the stake credential. The payment and stake credentials are hashes of those pubkeys.
Here's an example output (and cardano-address inspect output so you can see an example matching the pieces):
cardano-address address inspect <<< addr_test1qrkgclg3rsz8v8hnv2sqxmfk3yl87p9dme906h4ru859j9z076sepqv0ms7pud50lrgfh3e72jrysy5wawg4hqgmzfrsvgallu
{
    "stake_reference": "by value",
    "stake_key_hash_bech32": "stake_vkh1flm2ryyp3lwrc83k3ludpx788e2gvjqj3m4ezkuprvfywejlp0j",
    "stake_key_hash": "4ff6a190818fdc3c1e368ff8d09bc73e548648128eeb915b811b1247",
    "spending_key_hash_bech32": "addr_test1ajx86yguq3mpaumz5qpk6d5f8elsftw7ft74aglpapv3g07qz53",
    "address_style": "Shelley",
    "spending_key_hash": "ec8c7d111c04761ef362a0036d36893e7f04adde4afd5ea3e1e85914",
    "network_tag": 0

bech32 <<< addr_test1qrkgclg3rsz8v8hnv2sqxmfk3yl87p9dme906h4ru859j9z076sepqv0ms7pud50lrgfh3e72jrysy5wawg4hqgmzfrsvgallu
00ec8c7d111c04761ef362a0036d36893e7f04adde4afd5ea3e1e859144ff6a190818fdc3c1e368ff8d09bc73e548648128eeb915b811b1247

Check out cardano-addresses, and scroll to the "how to inspect address" section


text:
How to know which module to import?
Let's say my smartcontract needs BuiltinData.
Quicksearch in documentation reveals that BuiltinData is in:

Plutus.V1.Ledger.Api
Plutus.V2.Ledger.Api
PlutusTx.Builtins.Internal
PlutusTx
PlutusTx.Builtins
PlutusTx.Prelude
...

How to know which include I should add? Which ones are preferred and why?

Some of these are reexported versions of others. This means some of them are not necessary. Also PlutusTx.Prelude should be included in all projects as it maps types into PlutusTx which complies with the bytecode that runs on the chain.
This means if your Data type is in PlutusTx.Prelude, you should not need the other modules in general. The exception is if other parts of your code use that module.


text:
Using custom datum for `mustPayToOtherScript` in off-chain code
Lets say I on-chain i have a Datum like so:
data RandomDatum = RandomDatum {
   { tn :: !TokenName
   , cs :: !CurrencySymbol
   , nn :: !Integer
   } deriving (Show)

Off chain I'm trying to form and submit transaction with:
...
let dat = RandomDatum {
       tn = ""
     , cs = ""
     , nn = 1
    }
    constraints = Constraints.mustPayToOtherScript vh dat val

ledgerTx <- submitTxConstraintsWith lookups constraints

But my compilation always fails, because dat is not of type Datum.
I have also tried:
constraints = Constraints.mustPayToOtherScript vh (Datum $ PlutusTx.toBuiltinData dat) val

Question
How could I convert RandomDatum imported from my on-chain code file?

I dig more into this and now I think it doesn't work because PlutusTx.unstableMakeIsDatafails to generate required instances for FromData

Problem was I didn't provide correct type to submitTxConstraintsWith call.
If this was code from Plutus Pioneer Program week one where there is a definition:
data Auctioning
instance Scripts.ValidatorTypes Auctioning where
    type instance RedeemerType Auctioning = AuctionAction
    type instance DatumType Auctioning = AuctionDatum

Call should look like this:
ledgerTx <- submitTxConstraintsWith @Auctioning lookups constraints

Also datum needs deriving (Show, Generic, ToJSON, FromJSON) for serialization
data RandomDatum = RandomDatum {
   { tn :: !TokenName
   , cs :: !CurrencySymbol
   , nn :: !Integer
   } deriving (Show, Generic, ToJSON, FromJSON)

As far as I know your datum types are required to conform the Data type.
Try:
PlutusTx.makeIsDataIndexed ''RandomDatum [ ('RandomDatum, 0) ]

{...}
let randomDatum = RandomDatum { ...params... }
    tx          = mustPayToTheScript randomDatum $ Ada.lovelaceValueOf amount
{...}

Maybe I'm missing some Haskell Language pragma which is required for this? What pragrams are required for this? I do have PlutusTx.makeIsDataIndexed in separate on-chain code file but I still get this error.

@KugisMugis In that case, can you post complete on chain and off chain code?


text:
Emulator trace throws `BuiltinEvaluationFailure of UnIData` error with simple minting policy
Source
https://github.com/tomazvila/plutus_minting_test
Problem
Running smart contract with simple minting use case fails to mint.
Error
Slot 00001: *** CONTRACT STOPPED WITH ERROR: "\"WalletContractError (ValidationError (ScriptFailure (EvaluationError [] \\\"BuiltinEvaluationFailure of UnIData\\\")))\""

Setup
cardano_node@demoserver:~/coreapp_testing/new_repo$ uname -a
Linux demoserver 5.4.0-100-generic #113-Ubuntu SMP Thu Feb 3 18:43:29 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux
cardano_node@demoserver:~/coreapp_testing/new_repo$ cabal --version
cabal-install version 3.6.2.0
compiled using version 3.6.2.0 of the Cabal library
cardano_node@demoserver:~/coreapp_testing/new_repo$ ghc --version
The Glorious Glasgow Haskell Compilation System, version 8.10.7

How to run
cardano run trace

Problem was that Minting script is expecting Integer as a redeemer:
mkPolicy :: TxOutRef -> Integer -> ScriptContext -> Bool
mkPolicy utxo _ ctx = validate

And off-chain code with:
TxConstraints.mustMintValueWithRedeemer unitRedeemer val

call passes unitRedeemer. Validator tries to deconstruct unitRedeemer to Integer and throws an error.
Bonus: Constraint.mustMintValue passes unitRedeemer by default


text:
How to implement Vesting smartcontract with time period longer than 36 hours?
Context
In third weeks plutus pioneer lecture lars said that Vesting period shouldn't be longer than 36 hours. He argued that this is because time is calculated in slots on-chain and that this parameter might change in the future:

There is one slight complication that Ouroboros, the consensus protocol powering Cardano, does not use POSIX time; it uses slots. Plutus uses real time, so we need to be able to convert back and forth between real time and slots. Right now, the slot length is one second. Knowing that, it is easy to go back and forth between real time and slot numbers. However, this could change in future through a parameter change via a hard fork. And, of course, we can't know that in advance.

We do not know right now what the slot length will be in 10 years, for example. This
means that we must not have a definite upper bound. We know what the slot length will be
in the next 36 hours because if there's a change in protocol parameters, then we know that at least 36 hours in advance.You can not specify arbitrary time ranges in the transaction interval. It must only be at most 36 hours in the future, or it can be indefinite.

I would like to implement vesting smartcontract but for much longer time periods, for example 9 months.
Problem
Right now I see two ways to implement restriction by time:

Use txInfoValidRange by specifying transaction valid range. However I see a huge problem here or maybe I just dont' understand tx valid range correctly. Lets say that validator is of alwayssucceeds type but with added tx valid range check. I don't get it how to guarantee that funds are to be locked until specified SLOT, since in this case anyone can build transaction with w/e --invalid-before SLOT parameter they want.

data VestingDatum = VestingDatum
   { deadline    :: POSIXTime
   } deriving Show

{-# INLINABLE mkValidator #-}
mkValidator :: VestingDatum -> () -> ScriptContext -> Bool
mkValidator dat () ctx = traceIfFalse "deadline not reached" deadlineReached
 where
   info :: TxInfo
   info = scriptContextTxInfo ctx

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

Provide some kind of time NFT from oracle.

Questions

What is currently the best way to implement Vesting with longer than 36 hours time periods?
How likely is 1 SLOT == 1 Second parameter to change in the future, when and by how much?
Does universal time NFT oracle exist in Cardano ecosystem?
Is there a way to provide restriction that for funds to be unlocked from the smartcontract transaction must have specific --invalid-before SLOT parameter?

Lars is right. There is no guarantee that 1 slot remains equal to 1 second because a parameter update could happen at any time and be applied for future epochs. There are currently no plans to change this and I don't know why it would be changed from 1 second. I also don't know of any specific time oracles, but you're right in thinking this is a viable option.

"anyone can build transaction with w/e --invalid-before SLOT parameter they want.".

This is not true. In your example, deadlineReached will return true provided the transaction's --invalid-before SLOT is equal to or greater than deadline (once converted) regardless of the transaction's upper bound. You cannot submit a transaction with a higher --invalid-before SLOT than the current slot because ledger's phase-1 validation, which is performed for free before any plutus validator script is run, would reject it.


text:
Is it possible to validate on-chain if two different wallet addresses come from the same person?
My goal is:
I would like to create a smart contract which would verify if unlocking transaction comes from the same person as the wallet address which is known before hand.
What I have tried:
I have went trough https://developers.cardano.org/docs/integrate-cardano/creating-wallet-faucet/ and https://github.com/input-output-hk/Alonzo-testnet/blob/main/Alonzo-solutions/exercise3/e3SampleSolution.md exercises to understand cardano transactions and wallets better. I have also created my own Yoroi wallet and played around a bit with transactions.
I have also tried looking for functions which could do verification with wallet addresses in Plutus API, but couldn't find anything.
What I got from all of this is that because cardano wallet is created with a single recovery phrase it should be possible to trace down if different wallet addresses belong to the same person.
How I think solution should work:

Transaction comes in into smart contract
Smart contract takes wallet address from which this transaction came
Smart contract checks if already known wallet address (for sending funds to) belongs to the same person as the owner of unlocking transaction wallet

Things I don't quite get it:

Can smart contract on-chain code go trough blockchain to check wallets pub-keys for validation and if so how?
Is the txSignedBy :: TxInfo -> PubKeyHash -> Bool the only function which can be used on-chain to check ownership?
Is it possible to get wallet address from TxInfo in smart contract?
Can PubKeyHash be retrieved from wallet address on-chain and off-chain?

I don't expect an honest well though out answer to all of these questions, but if anyone could lead me a even a little bit on how to achieve my goal I would be really thankful.

I came accross this and was wondering how the currently held Sundaeswap vote is doing this to cast votes only once. Nothing to do with SC but with staking addresses, you might wanna check this topic, maybe it helps: https://cardano.stackexchange.com/questions/3786/finding-related-addresses-and-total-balance-of-wallet-for-any-given-address


text:
When is Contract instance actually finished running?
I'm trying to write tests for my smart contracts.
I want to test if my contract has finished running by using this predicate:
-- | A 'TracePredicate' checking that the wallet's contract instance finished
--   without errors.
assertDone
    :: forall contract w s e a.
    ( Monoid w
    , IsContract contract
    )
    => contract w s e a
    -> ContractInstanceTag
    -> (a -> Bool)
    -> String
    -> TracePredicate
assertDone contract inst pr = assertOutcome contract inst (\case { Done a -> pr a; _ -> False})

But i'm getting this at the beginning of the test:
    Outcome of Wallet W872c:
      False
    Failed 'asserting contract is done'
    Test failed.
    Emulator log:
    [INFO] Slot 0: TxnValidate a43ac4a162e963b6ccdbece83f96cabefd53df73c8de6b242aedbeb2ca8b8f80
    [INFO] Slot 1: 00000000-0000-4000-8000-000000000000 {Wallet W872c}:

and at the end of the test:
    [INFO] Slot 5: 00000000-0000-4000-8000-000000000001 {Wallet W872c}:
                     Contract log: String "End of contract"
    [INFO] Slot 5: 00000000-0000-4000-8000-000000000001 {Wallet W872c}:
                     Contract instance stopped (no errors)
      src/Plutus/Contract/Test.hs:270:
      Check if contract is done

    Use -p '/Check if contract is done/' to rerun this test only.

1 out of 2 tests failed (0.19s)
Test suite myTests: FAIL

I have put: logInfo @String "End of contract" at the end of my contract so we can clearly see that all of my statements written in my Contract instance goes trough.
I was expecting assertDone to return me True, since no error was thrown, but I still got a False.
So the question is, why my contract is not producing Done output and is still waiting for input?
data Outcome e a =
    Done a
    -- ^ The contract finished without errors and produced a result
    | NotDone
    -- ^ The contract is waiting for more input.
    | Failed e
    -- ^ The contract failed with an error.
    deriving (Eq, Show)


text:
How to reduce tx size using typed Plutus script with Vasil fork PlutusV2?
With the recent Vasil fork script references allow to reduce transaction size. Even though Vasil has been already launched on the testnet I could not find information on how to reduce the size of typed Plutus scripts. The only lead I have found is this repository, but it only has examples on how to use PlutusV2 with untyped scripts.
How to reduce tx size using typed Plutus script with Vasil fork PlutusV2?

https://github.com/perturbing/vasil-tests/blob/main/referencing-scripts-cip-33.md. Here is an example of a typed plutus script V2.

The common understanding is that reference scripts & reference inputs allow for making some transactions smaller as they would not need to include the full script when spending an output governed by a Plutus script.

Yes I know, but for that AFAIK you need PlutusV2 code, which typed scripts I can't find!

I don't think that reference scripts dictate use of PlutusV2, but the library / framework you use to create transactions needs to support these features.
For example: https://github.com/input-output-hk/cardano-node/blob/9f1d7dc163ee66410d912e48509d6a2300cfa68a/cardano-api/src/Cardano/Api/Script.hs#L1410-L1417 in the cardano-api library.


text:
How to resume DB sync for Preview Testnet
I am using a remote Linux V-Server with 2-VCores, 120GB storage and 4GB RAM where I want  to run a Preview Testnet in my remote machine.
I have access to this machine using ssh
While running the preview testnet, a db folder and a node.socket will be created
cardano-node run +RTS -N2 --disable-delayed-os-memory-return -I0.3 -Iw600 -A16m -F1.5 -H2500M -T -S -RTS \
    --topology topology.json \
    --database-path db \
    --socket-path node.socket \
    --port 3001 \
    --config config.json

After few hours of download, I get Error in my terminal
Read from remote host IP_ADDRESS: Connection reset by peer
Connection to IP_ADDRESS closed.
client_loop: send disconnect: Broken pipe

This probably related to my SSH configuration. But when I tried to resume dowload using same command of cardano-node run
[cardano.#ekgview.realizeFrom:Error:5] [2024-11-04 05:52:55.98 UTC] EKGView backend disabled due to initialisation error: EKGServerStartupError "Network.Socket.bind: resource busy (Address already in use)"
[cardano.#ekgview.realizeFrom:Error:5] [2024-11-04 05:52:55.98 UTC] EKGView backend disabled due to initialisation error: EKGUnknownStartupError "capacity has to be greater than 0\nCallStack (from HasCallStack):\n  error, called at libraries/stm/Control/Concurrent/STM/TBQueue.hs:87:16 in stm-2.5.2.1-73cd:Control.Concurrent.STM.TBQueue"

cardano-node: capacity has to be greater than 0
CallStack (from HasCallStack):
  error, called at libraries/stm/Control/Concurrent/STM/TBQueue.hs:87:16 in stm-2.5.2.1-73cd:Control.Concurrent.STM.TBQueue 48103912     30688    222824  0.000  0.001    0.117    0.155    1   56  (Gen:  1)
     1896                      0.000  0.000

      77,482,216 bytes allocated in the heap
         609,976 bytes copied during GC
         222,824 bytes maximum residency (1 sample(s))
          63,896 bytes maximum slop
            2517 MiB total memory in use (0 MiB lost due to fragmentation)

                                     Tot time (elapsed)  Avg pause  Max pause
  Gen  0         1 colls,     1 par    0.035s   0.036s     0.0358s    0.0358s
  Gen  1         1 colls,     0 par    0.000s   0.001s     0.0005s    0.0005s

  Parallel GC work balance: 3.57% (serial 0%, perfect 100%)

  TASKS: 8 (1 bound, 7 peak workers (7 total), using -N2)

  SPARKS: 0 (0 converted, 0 overflowed, 0 dud, 0 GC'd, 0 fizzled)

  INIT    time    0.001s  (  0.002s elapsed)
  MUT     time    0.080s  (  0.116s elapsed)
  GC      time    0.035s  (  0.036s elapsed)
  EXIT    time    0.004s  (  0.004s elapsed)
  Total   time    0.121s  (  0.159s elapsed)

  Alloc rate    971,074,865 bytes per MUT second

  Productivity  66.1% of total user, 73.2% of total elapsed

How could resume download using the existing DB

I found a tip https://forum.cardano.org/t/updated-a-relay-to-1-23-0-getting-ekgview-error-any-workaround-or-is-this-a-bug/42664/9 that have solved this error by simply cheking if there is a cardano process still runing and then kill it


text:
Does Cardano support Dynamic CNFTs?
Can we use offchain data through something like ChainLink and channel it to CNFTs to have them change in real time accordingly? Have got a great idea for a dynamic NFT project, but just want to know it's possible on Cardano first.

You would probably want to use native Plutus smart contracts for that.
Imagine a contract that accepts an NFT, burns it and mints a new one, with new properties.

Is it still an NFT if you can burn and mint it at will?

Yes, as long as it keeps to be non-fungible at all time.

Ok, thanks. Think my idea might be a bit too ambitious for that. Unsure it's possible without a hell of a lot more knowledge than I have, or at all. Cheers.

Every real time change would require burning and minting, meaning multiple TXs back to wallets that own one, all needing to be accompanied with ADA from somewhere. Will need to rethink.


text:
Creating transactions: is it required to send all utxos as inputs and outputs
I'm developing some raw tx server-side scripts and dealing with ValueNotConservedUTxO errors. If I create a transaction from a specific address, must I create inputs for all the utxos and then add the ones I'm not sending elsewhere to a change address?
Hopefully I'm just missing a key understanding else I really don't understand why such a waste of blockchain data would be part of the plan.

No, you don't have to create inputs for all utxos at an address; but for every utxo you do add as an input, you need to spend it in full (i.e. including assets that may be included), so your outputs and inputs add up correctly (apart from the transaction fee).


text:
Cardano Serialization: How does Ed25519KeyHash work
I'm trying to get cardano-serialization-lib working without up-to-date docs (https://github.com/Emurgo/cardano-serialization-lib/blob/master/doc/getting-started/generating-transactions.md). The example for making a transaction is outdated and the method .from_bech() doesn't exist on PrivateKey property.
Since the txBuilder.add_key_input() function is expecting an ed25519 hash, i thought it could be good to use Ed25519KeyHash but I am getting rust errors somewhere in the wasm hand-off.
Can anyone explain how to generate a root key and properly pass into the txBuilder.add_key_input() function?
Ultimately my goal to to generate and sign transactions from javascript without running a node and sync'd wallet. Any suggestions are welcome comments.
const cardano = (async () => { return await import('@emurgo/cardano-serialization-lib-browser') })()

let cw = cardano.then(async x => {
  console.log(x, x.Bip32PrivateKey);
  function harden(num) {
    return 0x80000000 + num;
  }

  const rootKey = x.Bip32PrivateKey.from_bech32("xprv17qx9vxm6060qjn5fgazfue9nwyf448w7upk60c3epln82vumg9r9kxzsud9uv5rfscxp382j2aku254zj3qfx9fx39t6hjwtmwq85uunsd8x0st3j66lzf5yn30hwq5n75zeuplepx8vxc502txx09ygjgx06n0p");

  const accountKey = rootKey
    .derive(harden(1852)) // purpose
    .derive(harden(1815)) // coin type
    .derive(harden(0)); // account #0

  const utxoPubKey = accountKey
    .derive(0) // external
    .derive(0)
    .to_public();

  const stakeKey = accountKey
    .derive(2) // chimeric
    .derive(0)
    .to_public();

  console.log({ rootKey, accountKey, utxoPubKey, stakeKey })
  console.log(rootKey, x.PrivateKey.generate_ed25519(accountKey))

  const txBuilder = x.TransactionBuilder.new(
    // all of these are taken from the mainnet genesis settings
    // linear fee parameters (a*size + b)
    x.LinearFee.new(x.BigNum.from_str('44'), x.BigNum.from_str('155381')),
    // minimum utxo value
    x.BigNum.from_str('1000000'),
    // pool deposit
    x.BigNum.from_str('500000000'),
    // key deposit
    x.BigNum.from_str('2000000')
);
// const prvKey = x.PrivateKey.from_bech32("ed25519e_sk16rl5fqqf4mg27syjzjrq8h3vq44jnnv52mvyzdttldszjj7a64xtmjwgjtfy25lu0xmv40306lj9pcqpa6slry9eh3mtlqvfjz93vuq0grl80");
txBuilder.add_key_input(
    new x.Ed25519KeyHash(rootKey),
    x.TransactionInput.new(
        x.TransactionHash.from_bytes(
            Buffer.from("8561258e210352fba2ac0488afed67b3427a27ccf1d41ec030c98a8199bc22ec", "hex")
        ), // tx hash
        0, // index
    ),
    x.Value.new(x.BigNum.from_str('3000000'))
);
  console.log({txBuilder});
  return x
})```

  [1]: https://github.com/Emurgo/cardano-serialization-lib/blob/master/doc/getting-started/generating-transactions.md

In lieu of up-to-date documentation, the best approach is to look at how current projects are using the library. E.g. https://github.com/Berry-Pool/nami-wallet/blob/main/src/api/extension/index.js

Thanks for the attention. Feel free to edit your comment into an answer and I'll be happy to upvote


text:
Developing on Cardano as a beginner
Is there a roadmap to learn Cardano Development as a beginner? I checked the Cardano Developer Portal but I could not find the following:

What is the order in which one should learn things? For instance: is the order learn Haskell, then Pluto, then Marlo, then X, ...correct
Resources that has helped former beginners with and without practical application (I know for Haskell, there is "Learn you a Haskell" recommendation on the portal.
Useful github links for simple projects people have done?
Is Haskell the only way to develop on Cardano? I asked because Haskell has the reputation of being a very difficult language, and thus could a be barrier for a beginner interested in Cardano.

Anyway useful resource recommendation for a beginner is welcome.
Thanks

Let me try to answer.
I am working on building Privacy focused Distributed Deep Neural Net learning called DeepchainAda. I started with stakepool on Cardano and before that I read some of the IOHK research papers and map it to my knowledge of distributed systems
Now I believe in learning ground-up so I have started Video series on Blockchain+Machinelearning and Haskell

What is the order in which one should learn things? For instance: is the order learn Haskell, then Pluto, then Marlo, then X, ...correct

{answer} I would recommend starting from basics of blockchain and why Cardano. Then focus on what you want to build. Start with accounting models using eUTXO and try to understand this. Then you can follow the Haskell->Plutus path. Marlow is a DSL aka domain specific language. So if you have application in finance domain then you can look at that directly. You can also explore the blockfrost support for python and other languages to see if it helps solve the task you are working on. However if your main intention is to become a Cardano developer then knowledge of Plutus is better

Resources that has helped former beginners with and without practical application (I know for Haskell, there is "Learn you a Haskell" recommendation on the portal.

{answer} There is essential Cardano https://iohk.io/en/blog/posts/2021/04/30/the-essential-cardano-list-a-new-resource-for-the-community/
Emurgo also has course on Professional Blockchain Developer. https://emurgo.io/blog/sign-up-now-for-emurgo-academys-cardano-blockchain-developer-program

Useful github links for simple projects people have done?

{Answer} Again the above link can help

Is Haskell the only way to develop on Cardano? I asked because Haskell has the reputation of being a very difficult language, and thus could a be barrier for a beginner interested in Cardano.

{Answer} No, there are support for other languages. Solidity is going to be supported by the milkomeda sidechain and similarly with IELE support (early 2022) you will be able to develop in any language like Java script, Python etc
I suggest you watch the youtube video https://www.youtube.com/watch?v=k8a6tX53YPs
Please note Haskell is not a difficult language if you try and understand the basics of functional programming. Infact many imperative programming language kind of support some of the functional programming concepts.
As I said before I have a video series (1 on Blockchain and other on Haskell) which is kind of ongoing and you can find the details about that in https://www.deepchainada.com/

Thank you. Very helpful

I think enrolling in Emurgo's Cardano Associate Developer and Cardano Professional Developer Program would be very helpful. Each program is $500. The courses are well structured and personally, I think the course fee is reasonable considering what you will learn from the course.
The Associate Program takes you through the fundamentals of blockchain and Cardano in particular. The last section of the course is all about programming in Haskell.
The Professional program is more focused on Plutus.


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

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

cardano-cli transaction calculate-min-required-utxo

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

  Calculate the minimum required UTxO for a transaction output.


text:
How to connect to Testnet on Blockfrost API with blockfrost-js
I am getting an error connecting to the Blockfrost API with blockfrost-js

"Network token mismatch. Are you using token for the correct network?
See https://docs.blockfrost.io/#section/Available-networks."

I went to blockfrost.io and requested a API key for the testnet, but I still have this error. What to do?

To connect to the Testnet with blockfrost-js initialize it like this:
const API = new BlockFrostAPI({
  projectId: 'YOURAPIKEYFORTESTNET',
  isTestnet: true
});


text:
Is it possible to use a parameterised CurrencySymbol inside another validator script? Unsupported feature: Type constructor: GHC.Prim.ByteArray#
I am having trouble using a parameterised CurrencySymbol inside another validator script. It seems to work (not shown here) when the currency symbol is unparametrised but not otherwise:
GHC Core to PLC plugin: E042:Error: Unsupported feature: Type constructor: GHC.Prim.ByteArray#
Context: Compiling type: GHC.Prim.ByteArray#
Context: Compiling data constructor type: GHC.Integer.Type.BN#
Context: Compiling type: GHC.Integer.Type.BigNat
Context: Compiling data constructor type: GHC.Natural.NatJ#
Context: Compiling type: GHC.Natural.Natural
Context: Compiling data constructor type: PlutusCore.Core.Type.Version
Context: Compiling type: PlutusCore.Core.Type.Version ann
Context: Compiling data constructor type: UntypedPlutusCore.Core.Type.Program
Context: Compiling type: UntypedPlutusCore.Core.Type.Program
                           PlutusCore.DeBruijn.Internal.DeBruijn
                           PlutusCore.Default.Universe.DefaultUni
                           PlutusCore.Default.Builtins.DefaultFun
                           ()
Context: Compiling type: Plutus.V1.Ledger.Scripts.Script
Context: Compiling type: Plutus.V1.Ledger.Scripts.MintingPolicy
Context: Compiling type: Plutus.V1.Ledger.Scripts.MintingPolicy
                         -> Data.ByteString.Internal.ByteString
Context: Compiling definition of: Ledger.Scripts.mintingPolicyHash1
Context: Compiling expr: Ledger.Scripts.mintingPolicyHash1
Context: Compiling expr: Ledger.Scripts.mintingPolicyHash1
                           (TestContract.tokenPolicy oref nm)
Context: Compiling expr: \ (nm [Occ=Once]
                              :: Plutus.V1.Ledger.Value.TokenName) ->
                           Ledger.Scripts.mintingPolicyHash1
                             (TestContract.tokenPolicy oref nm)
Context: Compiling expr: \ (oref [Occ=Once] :: Plutus.V1.Ledger.Tx.TxOutRef)
                           (nm [Occ=Once] :: Plutus.V1.Ledger.Value.TokenName) ->
                           Ledger.Scripts.mintingPolicyHash1
                             (TestContract.tokenPolicy oref nm)
Context: Compiling expr: (\ (oref [Occ=Once]
                               :: Plutus.V1.Ledger.Tx.TxOutRef)
                            (nm [Occ=Once] :: Plutus.V1.Ledger.Value.TokenName) ->
                            Ledger.Scripts.mintingPolicyHash1
                              (TestContract.tokenPolicy oref nm))
                         `cast` (<Plutus.V1.Ledger.Tx.TxOutRef>_R
                                 ->_R <Plutus.V1.Ledger.Value.TokenName>_R
                                 ->_R Sym (PlutusTx.Builtins.Internal.N:BuiltinByteString[0]) ; Sym (Plutus.V1.Ledger.Value.N:CurrencySymbol[0])
                                 :: GHC.Types.Coercible
                                      (Plutus.V1.Ledger.Tx.TxOutRef
                                       -> Plutus.V1.Ledger.Value.TokenName
                                       -> Data.ByteString.Internal.ByteString)
                                      (Plutus.V1.Ledger.Tx.TxOutRef
                                       -> Plutus.V1.Ledger.Value.TokenName
                                       -> Plutus.V1.Ledger.Value.CurrencySymbol))
Context: Compiling definition of: TestContract.tokenSymbol
Context: Compiling expr: TestContract.tokenSymbol
Context: Compiling expr: TestContract.tokenSymbol oref'_a3cNp
Context: Compiling expr: TestContract.tokenSymbol
                           oref'_a3cNp tn'_a3cNq
Context: Compiling expr: TestContract.mkTestValidator
                           (TestContract.tokenSymbol oref'_a3cNp tn'_a3cNq)
Context: Compiling expr: \ (tn'_a3cNq
                              :: Plutus.V1.Ledger.Value.TokenName) ->
                           TestContract.mkTestValidator
                             (TestContract.tokenSymbol oref'_a3cNp tn'_a3cNq)
Context: Compiling expr: \ (oref'_a3cNp :: Plutus.V1.Ledger.Tx.TxOutRef)
                           (tn'_a3cNq :: Plutus.V1.Ledger.Value.TokenName) ->
                           TestContract.mkTestValidator
                             (TestContract.tokenSymbol oref'_a3cNp tn'_a3cNq)
Context: Compiling expr at "test-contract-0.1.0.0-inplace:TestContract:(116,9)-(116,94)"

Here are my imports:
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE PartialTypeSignatures #-}
{-# LANGUAGE StandaloneKindSignatures #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -Wno-partial-type-signatures #-}
{-# OPTIONS_GHC -w #-}
-- {-# OPTIONS_GHC -fno-specialise #-}
-- {-# OPTIONS_GHC -fno-strictness #-}
-- {-# OPTIONS_GHC -fno-ignore-interface-pragmas #-}
-- {-# OPTIONS_GHC -fno-omit-interface-pragmas #-}
-- {-# OPTIONS_GHC -fobject-code #-}

module TestContract where

import Data.Kind (Type)
import Ledger.Interval qualified as Interval
import Ledger.Contexts qualified as Context
import Ledger.Crypto qualified as Crypto
import Ledger.Scripts qualified as Scripts
import Ledger.Typed.Scripts qualified as Scripts
import Ledger.Typed.Scripts.Validators qualified as Validator
import Ledger.Tx qualified as Tx
import Plutus.V1.Ledger.Ada qualified as Ada
import Plutus.V1.Ledger.Api qualified as Api
import Plutus.V1.Ledger.Address qualified as Address
import Plutus.V1.Ledger.Time qualified as Time
import Plutus.V1.Ledger.Value qualified as Value
import PlutusTx qualified
import PlutusTx.AssocMap qualified as Assoc
import PlutusTx.Prelude ((&&), (<=))
import PlutusTx.Prelude qualified as Plutus
import PlutusTx.TH qualified as PlutusTx
import Prelude (undefined, ($), (.))

Below, I've defined a policy that always returns True, the real logic is more complicated but the error message is the same. It's essentially identical to the NFT minting policy from Plutus Pioneers lecture 5 - hence TxOutRef and TokenName as inputs. As mentioned earlier, removing these 2 parameters is fine for compilation (deleting any necessary lifting).
{-# Inlineable mkTokenPolicy #-}
mkTokenPolicy :: Tx.TxOutRef
              -> Value.TokenName
              -> ()
              -> Context.ScriptContext
              -> Plutus.Bool
mkTokenPolicy oref nm ()
  scriptContext@Context.ScriptContext {scriptContextTxInfo = scriptContextTxInfo} =
    Plutus.True

tokenPolicy :: Tx.TxOutRef -> Value.TokenName -> Scripts.MintingPolicy
tokenPolicy oref nm =
  Scripts.mkMintingPolicyScript
    ($$(PlutusTx.compile [|| \oref' tn' -> Scripts.wrapMintingPolicy (mkTokenPolicy oref' tn') ||])
      `PlutusTx.applyCode`
    PlutusTx.liftCode oref
      `PlutusTx.applyCode`
    PlutusTx.liftCode nm)

{-# Inlineable tokenSymbol #-}
tokenSymbol :: Tx.TxOutRef -> Value.TokenName -> Value.CurrencySymbol
tokenSymbol oref nm =
  Context.scriptCurrencySymbol (tokenPolicy oref nm)

The tokenSymbol is just a parametrised CurrencySymbol of the NFT. The problematic code appears to be below when I try to compile this.
{-# Inlineable typedValidator #-}
typedValidator :: Tx.TxOutRef -> Value.TokenName -> Scripts.TypedValidator TestData
typedValidator oref nm =
  Scripts.mkTypedValidator @TestData
    ($$(PlutusTx.compile [|| \oref' tn' -> mkTestValidator (tokenSymbol oref' tn') ||])
       `PlutusTx.applyCode`
       PlutusTx.liftCode oref
       `PlutusTx.applyCode`
       PlutusTx.liftCode nm)
    $$(PlutusTx.compile [|| wrap ||])
  where
    wrap = Scripts.wrapValidator

The last line of the error:
Context: Compiling expr at "test-contract-0.1.0.0-inplace:TestContract:(116,9)-(116,94)"

is complaining about this line:
$$(PlutusTx.compile [|| \oref' tn' -> mkTestValidator (tokenSymbol oref' tn') ||])

I am defining TestData slightly differently, hence the absent type application in wrap. Prior to this bug, when my currency symbol was unparametrised, the below definition worked.
type (:--:) :: Type -> Type -> Type -> Type
newtype (redeemer :--: datum) a = Foo a

instance Scripts.ValidatorTypes ((redeemer :--: datum) a) where
  type RedeemerType ((redeemer :--: datum) a) = redeemer
  type DatumType ((redeemer :--: datum) a) = datum

data TestData
  deriving
    (Scripts.ValidatorTypes)
    via (TestAction :--: TestDatum) TestData

although this is equivalent to (with type application in wrap):
-- data TestData
-- instance Scripts.ValidatorTypes TestData where
--   type RedeemerType TestData = TestAction
--   type DatumType    TestData = TestDatum

I didn't provide any detail on mkTestValidator, nor my redeemer or datum. The reason being I only had issues after parameterising.
The error message seems to suggest the prohibited use of Natural. I'm not aware of direct usage in my code, but in https://alpha.marlowe.iohkdev.io/doc/haddock/plutus-core/html/UntypedPlutusCore-Core-Type.html Version is defined to use Natural, and Version is contained in Program. Is there a restriction on PLC when using a validator script defined above?
Plutus tag: 9879b31579d0deb863f3cdf27f93419deec3b4bb


text:
Using Cardano for authentication/signin
I am wondering: Is there another way to authenticate a user (wallet) on Cardano instead of sending ADA?
Obviously a beginner question, but I am just starting to wrap my head around all of this :)

Theoretically yes, you can ask wallets like Nami to sign an arbitrary piece of information for you and verify that signature against the addresses pub key hash.  Since this transaction would not have been submitted to the blockchain, no fees should be involved.  Note, I haven't tried this myself.
For Nami, check out the call to signData on this page https://github.com/Berry-Pool/nami-wallet.
In fact, CIP-8, explores doing this on a more official basis, https://github.com/cardano-foundation/CIPs/blob/master/CIP-0008/CIP-0008.md

Wouldn't this introduce trust into a trustless system? By that I mean you are asking someone to sign something and have them trust that you will just disregard it and not submit it. You would also need to be very transparent about what was being signed. With that said, I would be very interested to see if this would work.

No.  Because they are signing an arbitrary piece of information and not a real transaction, this cannot be submitted to the blockchain.  The information would need to contain enough information for the signature to be verified.  As for the contents of what was being signed, I would agree, this should be made transparent to the user.

Right, but wouldn't they be trusting you that it is in fact an arbitrary piece of information and not a real transaction? In other words, what keeps you from saying it is X but it is actually Y?

Today possibly.  But as wallets mature, I would be surprised if wallets didn't prompt you with some clue as to what you were signing.

So I just checked and it looks as Nami does present different messages depending on whether you're signing a tx or arbitrary data, so that's a step in the right direction.

Short Answer: A transaction needs to be singed with the owner's private keys.
Explanation: To be able to authenticate a user to a wallet, you need them to prove they have the private keys to that wallet. In order to do that, you need them to sign a transaction, which could be the sending Ada method you mentioned. There could be an opportunity to prove this identification with other types of signing transactions, but those will still have a transaction fee, thus costing Ada. Update: As pointed out by Matt Ho, you could potentially not submit the TX to the blockchain and therefore not have to pay the transaction fee. However, this could introduce a level of trust in the trustless system. Without testing this, it is hard to know the details of this.
Solution: Atala PRISM is an identity solution worth exploring. Although it is still in development, this will be a way to manage identity.https://atalaprism.io/app


text:
Not in scope: type constructor or class ‘PaymentPubKeyHash’ - Week 1 Pioneers Exercise
I'm trying to compile the week 1 code on plutus playground hosted locally, but I'm getting this error:
 error:
    Not in scope: type constructor or class ‘PaymentPubKeyHash’
   |
57 |     { aSeller   :: !PaymentPubKeyHash
   |

              ^^^^^^^^^^^^^^^^^

This is the code that originates the compilation error:
data Auction = Auction
    { aSeller   :: !PaymentPubKeyHash
    , aDeadline :: !POSIXTime
    , aMinBid   :: !Integer
    , aCurrency :: !CurrencySymbol
    , aToken    :: !TokenName
    } deriving (P.Show, Generic, ToJSON, FromJSON, ToSchema)

I have followed the steps on the week1 videos, but I'm getting this error, any help is welcomed. Thank you.

What gitrev of plutus-apps are you using? Can you gist your entire code file? I'm guessing either a version mismatch or a typo.

@SamuelLeathers I just got it working. I ran cabal update in the week1 code folder and the code compiled. Thank you.

Also, I was running the plutus playground on a old version of plutus repository not plutus-apps

import Ledger.Address qualified as Address          (Address, PaymentPubKeyHash(..))
import PaymentPubKeyHash .


text:
Is there complete cardano-cli documentation?
Hello all I can find is the cardano-cli help and
https://github.com/input-output-hk/cardano-node/blob/master/doc/reference/cardano-node-cli-reference.md/
I am trying to get information on things like what --tx-out-datum-embed-file FILE does

This is a cop-out answer, but in my experience there surest place to go for answers is to read the source code directly.

I'm trying to learn this too. I could not find any further documentation other than the cardano-cli command help. This is pretty extensive and useful. Every command argument seems to have built-in help. So, for instance, to get help with building a transaction, issue the command cardano-cli transaction build. The help for this includes some info on the --tx-out-datum-embed-file FILE arguments.


text:
cardano db-sync won't authenticate to postgres?
Trying to get db sync to do the initial database setup. I have this running on another ubuntu 20 box, and I trying to recreate it from scratch with all of the same versions and this time I am getting an error trying to run it
Running : migration-1-0000-20190730.sql
psql: error: fe_sendauth: no password supplied
ExitFailure 2

i know that it seems the pgpass file because when I run
PGPASSFILE=config/pgpass-mainnet scripts/postgresql-setup.sh --createdb

It recognizes the username I put in there. And the password is in there as well
Here is the db sync command I am running:
PGPASSFILE=/home/user/cardano-db-sync/config/pgpass-mainnet \
  /home/user/cardano-db-sync/db-sync-node/bin/cardano-db-sync \
      --config /home/user/cardano-db-sync/config/mainnet-config.yaml \
      --socket-path /var/ada/node.socket \
      --state-dir /home/user/cardano-db-sync/ledger-state/mainnet \
      --schema-dir /home/user/cardano-db-sync/schema/ \

which results in the following response
[db-sync-node:Info:6] [2022-03-25 03:22:50.40 UTC] Schema migration files validated
[db-sync-node:Info:6] [2022-03-25 03:22:50.40 UTC] Running database migrations
[db-sync-node:Info:6] [2022-03-25 03:22:50.40 UTC] Enviroment variable DbSyncAbortOnPanic: False
ExitFailure 2

Errors in file: /tmp/migrate-2022-03-25T032250.log

and the log file is what contains the authentication error.. my pgpass looks like
/var/run/postgresql:5432:cexplorer:username:'userpass'

I have also tried using localhost and 127.0.0.1. I notice when running
PGPASSFILE=config/pgpass-mainnet psql cexplorer

it asks me to authenticate for my current user, NOT the user in the mgpass file but when running the previous command for creating db it asks me the password for the correct user in the pgpass file. Both users can log into postgres regardless and actually have the same password at the moment. Any clues would be appreciated this is with cradno-db-sync 12.0.2 the latest node release.

Sorry, this is totally a PostgreSQL setup issue and nothing at all to do with db-sync. You might get some more information by running:
PGPASSFILE=config/pgpass-mainnet scripts/postgresql-setup.sh --check

If that doesn't give you any clues I would read up on user authentication in the PostgreSQL documentation.

ok ty I will look into this


text:
cardano-db-sync error
When following the instruction here
https://github.com/input-output-hk/cardano-db-sync/blob/master/doc/building-running.md
I get an error at the last line
PGPASSFILE=config/pgpass-mainnet db-sync-node/bin/cardano-db-sync \
    --config /home/user/relay/mainnet-config.yaml \
    --socket-path /home/user/relay/node.socket \
    --state-dir /home/user/relay/db \
    --schema-dir schema/

the error is
FatalError {fatalErrorMessage = "readSyncNodeConfig: Error parsing config: AesonException \"Error in $: key \\\"NetworkName\\\" not found\""}

Any any help or direction is appreaciated. Thank you

Make sure you are using the right config file. The error is indicating that the config file you are using does not have the NetworkName parameter.

how do I determine if it is the right one? its the one that comes default with cardano-node latest release repo.

I linked the proper one in my answer. You need the config for db-sync not cardano-node

thank you that was pretty dumb of me for not check for that file name ....

You need to use a db-sync config file, not a cardano-node one. You can get the correct configuration file for mainnet/testnet networks here: https://hydra.iohk.io/build/8111119/download/1/index.html. That link is found in the cardano-node release notes under downloads -> configuration files


text:
Q&A English Auction- if a wallets under bids then provides a valid bid, why doesn't it count the second good bid?
if you set up the english auction with three wallets and do the following:

Wallet 1 min bid 10
Wallet 2 bids 15
wallet 3 bids 9
wallet 3 bids 20
wallet 1 closes
It will got to wallet 2 and wallet three's second bid never shows up. Is this a bug or intended?

It is a bug in the off-chain code. In step 3 in your example, wallet 3 bids under the minimum. This throws an error which triggers a bug that causes all subsequent bids from wallet 3 to be ignored.
It happens on lines 280-281 when the error is thrown.
If you replace those 2 lines with this, it should work:
if (bpBid < minBid d)
  then logError @P.String $ printf "bid lower than minimal bid %d" (minBid d)
  else do

Credit to @kindofdev for showing me the fix.


text:
DB-Sync insanely slow
So i built the latest node and db-sync releases from source. My node works great it was fully synced fairly quickly. the db-sync got to around %78 and then started going insanely slow. I still have about 400GB free, only using about 30/48GB of memory.
This is
ubuntu 22 with
db sync 13.1.1.3
node 8.7.2
ghc 8.10

It updates about .01% everyday. So its just barely faster then the new transactions on the node each day. I have little script that compares the latest slot number between the node and the database. At this rate it wouldn't be updated for over 3 years
I don't have any errors I can find. the hard drive space and memory don't seem to be leaking. Any thoughts as to what the problem might be or how it can be optimized?

Is you disk storage for the database directly attached or network attached. Network attached storage is specifically advised against https://github.com/IntersectMBO/cardano-db-sync#system-requirements

yeah, its a local hoard drive, everything is on the same OS/hardrive, including the postgres server. It updated quick until about 75%, then just slowed down.

Does your machine meet the system requirements in the document above? Are you on an SSD drive rather than an electro-mechanical one? Is this dedicated hardware or something like an AMazon AWS system? Please provide comprehensive info about your setup.

Its my home server. Its just a virtual box image. where I allocated 48 GB of memory and about 900 GB on a SSD that is supposed to be around 300+MB/S. Its not an M2 SSD but a SATA SSD. I allocated 4 cores of my 8 core processor.

I should note the Drive symbol is always 100% lit, even though its not really filling up any more space. Even if it were magnetic, It would be filling the space 100x faster then it currently is

Your system seems very similar to mine. MIne is a KVM virtual machine writing to a SATA SSD drive. One thing I do know about SSDs is that writes seem to slow down as the number of write cycles increases (I killed an SSD during the development of db-sync). If yours a new or an old SSD? You still have not shared details of the host machine that the VM runs on (dstat maybe?)). This seems like a system performance issue rather than a db-sync issue.

That's fair. My host machine has 64 gb of ddr4 memory, 8core ryzen 9 processor, and about 5 different hard drives. IMO this is a dbsync problem. It should be faster then this on a magnetic drive. I should say, just to experiment I moved the VM to a different hard drive with no changed results. IMO DB sync is just doing stuff way to inefficiently. I have decided to move to Kupo


text:
How to run testnet node and mainnet node on background at the same time?
After searching for a while, didn’t find any post regarding this.
I know running node for testnet and mainnet use different configuring files, and on the cardano developer portal, they are showing the same port. But can I run both testnet and mainnet relay node on background (I assume I’d need to change the port number)?
Do I need to make two different cardano-run process?
In that case, it is ok when I run cardano-cli commands just change different network, like testnet-magic ***/–mainnet? Is the rest command the same?
I currently run the testnet as a systemd service, I can definitely just go ahead and run a mainnet node as another service on the background, but I want to ask before head, in case I would messed up the configurations on my server.

Yes, you would need two separate cardano-node processes, each with their own configuration and their own disk storage directory.
When using cardano-cli  you will need to connect to the correct local domain socket for the network you want to connect to.
Eg for mainnet:
export CARDANO_NODE_SOCKET_PATH=/path/to/mainnet/db/node.socket
cardano-cli ....

or for testnet:
export CARDANO_NODE_SOCKET_PATH=/path/to/testnet/db/node.socket
cardano-cli ....

Thanks for your answer!
If I do that, every time I switch between testnet and mainnet, I need to update this socket variable CARDANO_NODE_SOCKET_PATH, it there a way that it can be done automatically?
I see some others suggest use two different linux accounts, it's essentially the same as changing this socket environment variable to me.

You can write two trivial bash scripts, with -mainnet and -testnet in the names and setting the CARDANO_NODE_SOCKET_PATH.


text:
Plutus starter cabal build issue
Running the instructions at https://github.com/input-output-hk/plutus-starter#readme
After opening the container in VSCode, and attempting to run the following in the terminal.
[devcontainer]$ cabal build
Killed
[devcontainer]$ cabal update
Killed

Container is hosted on an M1 Macbook Air with 4GB allocated to docker.
Admittedly, I am new to Haskell and Cardano, so it's not yet apparent to me if this may be a resources issue or something in the plutus starter project.

Have exact same issue on M1 Pro.

I believe there are some compatibility problems with M1s and Docker. It might be worth trying to run Cabal through nix-shell instead.

Continuing to work through nix-shell on an M1 system, but I'll accept this answer if I get it going.

Yesterday i found out that if you do a cabal build with limited amount of cpus cabal build --jobs=1 you get quite far but after building for like 2 hours ... it gets killed after all ... seems to be a docker issue with ressource management i think!


text:
How can I pinpoint a specific UTxO using ContractModel
I'm trying to create a contract where a TxOutRef is supplied to it which tells it a specific UTxO to use in the contract. This seemed fine until I started working with ContractModel. I can't find any way to pass on information about UTxOs that I create. nextState allows me to update the state, but I can't get any contract related info there. perform lets me get info from the contracts, but doesn't let me update the state.

Hopefully I'm understanding your question correctly. I'm hearing two things here:
How do I include a specific UTxO in a transaction required by a script?
Here is an example of off-chain code including an arbitrary UTxO to create "one shot", single issued currency.
In this case it doesn't matter which UTxO it is, as long as the TxOutRef (txOutRef) referenced in the OneShotCurrency (thisCurrency) is spent with the minting transaction:
    let theCurrency = mkCurrency txOutRef amounts
        ...
        mintTx      = Constraints.mustSpendPubKeyOutput txOutRef
                        <> Constraints.mustMintValue (mintedValue theCurrency)

How do I to choose a specific UTxO "that I created?"
One way is how the oracle is grabbed from the ContractHandle in the Oracle example. The Oracle value is stored in the ContractHandle monad as a Last and can be grabbed inside the runtime context with the getOracle function.
The logic for actually finding the UTxO is the the findOracle function here.
An alternative approach is in the Uniswap example. An NFT is created with Currency.mintContract and then immediately used as the NFT (c) for the Factory Datum here:
tx   = mustPayToTheScript (Factory []) $ unitValue c

This approach avoids managing the UTxO directly.


text:
How can I get a POSIXTime in the Contract monad?
I don't see any way to use IO in Contract and I don't see any functions for getting a POSIXTime from the things I can get within Contract.

there is a currentTime function in Plutus.Contract.Request with the signature
currentTime :: forall w s e. AsContractError e => Contract w s e POSIXTime


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.

Can you tell me a example of the script for Linux in js to send such transaction.

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:
Transaction lifecycle
Working to understand transaction lifecycle. Some understanding of Bitcoin transaction lifecycle perhaps helps here. That is, a transaction is originated from a client request to a node. This node then broadcasts the transaction to all nodes. Once a certain number (51%?) have affirmed that the transaction is valid (well-formed) then nodes may begin mining this transaction. (This step is of course different, as in Cardano the staking algorithm would run, not a mining algorithm.) However, once a successful block is mined/wins staking, the successful node broadcasts the block. All nodes then begin confirming the block (for example by hashing the chain plus the new block and comparing this value to one provided by the successful node). Once a certain number of nodes (51%?) have confirmed the block, all nodes sink the chain to their local database. Finally the mining/staking reward is awarded to the successful node.
Undoubtedly I have oversimplified and perhaps misstated some steps. But the question is: how close is this to describing transaction lifecycle in Cardano? Is it possible to verbally summarize transaction lifecycle in a way that is mostly comprehensive?

This is indeed oversimplified, but is in principle how a transaction makes it from node to mempool to block.
I addressed a similar version of this question here, and Andrew Westberg also made a great video explaining it.
You can read more about transactions on Cardano at Emurgo's UTXO blog post.

Accepting this answer. Thanks for the external links they are helpful.


text:
How to get Integer from Cardano.Ledger.BaseTypes.TxIx
I am using the following function from the Plutus pioneer program:
stakeReferenceLedgerToPlutus :: Ledger.StakeReference StandardCrypto -> Maybe Plutus.StakingCredential
stakeReferenceLedgerToPlutus (StakeRefPtr (Ptr (SlotNo x) y z)) = Just $ StakingPtr (fromIntegral x) (fromIntegral y) (fromIntegral z)

But the latest release of Plutus-apps seems to require a change, because fromIntegral y does not work anymore. See error below:
error:
    • No instance for (Integral Cardano.Ledger.BaseTypes.TxIx)
        arising from a use of ‘fromIntegral’
    • In the second argument of ‘StakingPtr’, namely ‘(fromIntegral y)’

The same is true for fromIntegral z but for Cardano.Ledger.BaseTypes.CertIx.
Any help is appreciated.

The problem is that on the LHS you have:
StakeRefPtr (Ptr (SlotNo x) y z)

but StakeRefPtr is defined (in cardano-ledger repo, file libs/cardano-ledger-core/src/Cardano/Ledger/Credential.hs) as:
   | StakeRefPtr !Ptr

and Ptr is defined as:
data Ptr = Ptr !SlotNo !TxIx !CertIx

and TxIx is defined as:
newtype TxIx = TxIx Word64

That means, to get your code closer to working you should try:
stakeReferenceLedgerToPlutus :: Ledger.StakeReference StandardCrypto -> Maybe Plutus.StakingCredential
stakeReferenceLedgerToPlutus (StakeRefPtr (Ptr (SlotNo x) (TxIx y) z)) = Just $ StakingPtr (fromIntegral x) (fromIntegral y) (fromIntegral z)

You probably also need to do the same for the z which is defined as a:
newtype CertIx = CertIx Word64

Thanks! Pattern matching to get the wrapped type makes complete sense.


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.


text:
In which node is a wallet connected?
I have a question
A node is needed to execute a transaction, but in which node are these wallets connected to execute a transaction?
all wallets are tied to a node? or can that specific wallet be connected to a chosen node or a public node?
for example, daedalus downloads a whole node, so I might guess that the transaction is running on the same daedalus node, but yoroi does not install any node on the user's pc, so where is that transaction sent to be validated?

You're correct - Daedalus runs a full node on the local PC, so transactions initiated on Daedalus are submitted through the local running node. The same is true for transactions submitted using cardano-cli or cardano-wallet - they use a locally running node.
For other wallet software(s) like Yoroi, Nami, etc that are browser extensions, they submit transactions via remote nodes administered on some back-end servers.

I can't speak for yoroi, but nami is another light wallet.
It interfaces with the chain using the blockfrost api.
This handles talking to the nodes.
Nami now lets you point it at a node of your choice
https://twitter.com/pernistoken/status/1485563609560551428
Other light wallets do something analogous.


text:
Why are some Plutus types defined multiple times in different packages?
I would like to know why certain types are defined multiple times in different packages and whether that's suppose to dictate which types to use for on-chain code and which for off-chain code?
Example: Address type exists in the following packages:
Plutus.V1.Ledger.Address
Ledger.Address

The second is just re-exporting.
Using the imports of the form Ledger.Address will mean bumping versions wont require lots of edits of V1 to V2 .
This may or may not be desirable. Depends on your context.