text:
"'Inputs do not conform to this spec or are otherwise invalid.'" - extract balance from smart contract
I'm implementing a smart-contract in Plutus and I'm with a doubt. For example, Ethereum has some function only to owners, that enables to implement a withdraw of balance for only owner addresses.
I know, that in the script validator, I can put a clause that is true only with a specific public key hash. And I already implemented that. And it works... but only if I locked ADA or NFT through the smart contract itself. Imagine that I sent an NFT or ADA with the nami directly to the address... this way, I receive "'Inputs do not conform to this spec or are otherwise invalid.'". It is normal? There is a way to solve this? Or it is possible at least?
Thanks.

to my understanding, you created a new UTxO at the smart contract address just by sending a Value to it
the message you receive tells us there is something strange in the way you construct the "withdrawal" method
my intuition is that the method is trying to construct a transaction with a single UTxO form the Validator, while in this case, you have two of them
this might happen due to some particular TxConstraint you set
when you "deposit" through the smart contract you are spending the previous UTxO and creating a new one, by just sending funds you spend nothing and create a new one
to handle both cases the off-chain code should create a transaction with all the UTxO of the validator as input and the on-chain should check that all previous TxOut present at the validator address before the transaction where included (plus checking that at least 1 UTxO goes back to itself if you want to keep it "alive")

But for example, if the smart contract has only some ADA remaining, it is possible to withdraw? If I don't have a redeemer for that? I mean, it is possible to have a function in order to the owner can withdraw all?

with the redeemer you can set a specific one that only checks the public key hash, this way you enter god-modeù; without the redeemer it depends from the smart contract logic; you can still add something like if phk == owner_phk then True else -- smart contrac logic


text:
Can't create ```TokenName``` using ```tokenName``` with error ```GHC Core to PLC plugin: E042:Error: Unsupported feature: ...```
I'm not sure is relevant but the code in question is for a generic Validator (with Datums and Redeemers) used to get a forwarded minting policy
the problem should be clear from the title, I can't get to construct a TokenName value starting form a ``ByteString```
I assume the rror is dued to the plutus-tx-plugin library so all the ghc-options specified in the troubleshooting section for the Plutus documentation are enabled (without much success)
the error I get is the following
GHC Core to PLC plugin: E042:Error: Unsupported feature: Type constructor: GHC.Prim.Char#
Context: Compiling type: GHC.Prim.Char#
Context: Compiling data constructor type: GHC.Types.C#
Context: Compiling type: GHC.Types.Char
Context: Compiling type: GHC.Base.String
Context: Compiling expr: PlutusTx.Base.$ @ GHC.Base.String
Context: Compiling expr: PlutusTx.Base.$
                           @ GHC.Base.String @ Plutus.V1.Ledger.Value.TokenName
Context: Compiling expr: PlutusTx.Base.$
                           @ GHC.Base.String
                           @ Plutus.V1.Ledger.Value.TokenName
                           (PlutusTx.Base..
                              @ Data.ByteString.Internal.ByteString
                              @ Plutus.V1.Ledger.Value.TokenName
                              @ GHC.Base.String
                              Plutus.V1.Ledger.Value.tokenName
                              Data.ByteString.Char8.pack)

and keeps expanding for a while...
I know for sure (by commenting out) the code causing this is the following:

NOTE: I've commented out everything related to collectionCurrencySymbol from the moment that is causing problems too and I'll likely change it, any idea is welcome but is not the main point of the question

 expectedTokenName :: Value.TokenName
 expectedTokenName =  Value.tokenName $ "My Awesome NFT collection #" <> integerToBS8 datumCounter

 -- collectionCurrencySymbol :: Value.CurrencySymbol
 -- collectionCurrencySymbol = (Value.mpsSymbol . Ledger.mintingPolicyHash . mkForwardingMintingPolicy ) (Ctx.ownHash ctx)

singleTokenMinted :: PTxP.Bool
singleTokenMinted =
  case Value.flattenValue (txInfoMint ( Ctx.scriptContextTxInfo ctx) ) of
    [( mintedCurrencySym , mintedTokenName , mintedAmount )] ->
      -- mintedCurrencySym == collectionCurrencySymbol   PTxP.&&
      mintedTokenName   == expectedTokenName          PTxP.&&
      mintedAmount      == 1
    _                                                        ->
      traceError "minting more than 1 AssetClass"

where integerToBS8 is as simple as :
{-# INLINEABLE integerToBS8 #-}
integerToBS8 :: Integer -> BS8.ByteString
integerToBS8 int
    | int == 0 = BS8.pack "0"
    | int == 1 = BS8.pack "1"
    | int == 2 = BS8.pack "2"
    | int == 3 = BS8.pack "3"
    | int == 4 = BS8.pack "4"
    | int == 5 = BS8.pack "5"
    | int == 6 = BS8.pack "6"
    | int == 7 = BS8.pack "7"
    | int == 8 = BS8.pack "8"
    | int == 9 = BS8.pack "9"
    | otherwise = integerToBS8 ( int `div` 10 ) <> integerToBS8 ( int `mod` 10 )

some conventions I use
import qualified Data.ByteString.Char8       as BS8
import qualified Ledger.Contexts as Ctx
import qualified Ledger.Value as Value
import qualified Ledger
import PlutusTx.Prelude as PTxP

It seems to me GHC just doesn't like raw strings (since OverloadedStrings is just adding silently a bunch of pack form the IsString typeclass where needed)
any idea on what's wrong?

tokenName is not meant to be used on-chain
see this closed issue
due to the fact of :t tokenName being ByteString -> TokenName ( and not BuiltinByteString -> TokenName) the correct way to build dynamically a TokenName is by using the TokenName constructor itself (and NOT the helper function)

source: Stack Exchange

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

sort: votes


text:
Is it possible for clients to mint my nft collection on their own?
For eth:
Create smart contract minter

Deploy that contract into the blockchain

Make API calls on that deployed contract thru your website

Client will click mint button -> API mint interaction to smart contract

As for cardano this is seemingly complex, this is my understanding so far (are they correct?)
Cardano node must be running on your machine

Interact with node using cardano cli, start minting at this point

Get all minted token and start distributing it to people

With this I am the one minting all of the tokens and distribute it to people, is there a way to do it like in eth?

You don't need to run your own node, if you don't want to. You can always use an API service like Blockfrost to interact with the blockchain instead. This is also how light wallets like MetaMask, Nami wallet etc. read on-chain data and submit transactions. You can use such a service on your own backend, too.
As for minting and distributing there are many ways you can go about. Cardano is special in that you don't even need smart contracts for minting, which makes it much easier.
You also don't need to pre-mint; you can mint on-demand. So without using smart contracts, but with your own backend service running, a setup could look like this:
When the buyer hits the buy button:

Generate a minting transaction that needs to be signed by both, you (your backend service) and the buyer (eg using this lib: https://github.com/Emurgo/cardano-serialization-lib/blob/4f1d87524be5e792baabb038d15ca60cd2d39edb/doc/getting-started/minting-nfts.md)
Once the buyer signs the transaction (eg via Nami wallet), have it passed to your backend for verification, signing and submission to the network (eg via Blockfrost)

Within that single transaction you can have:

User mint NFT into their own wallet
User pays you amount x for the NFT
User pays for network fee

(You can of course also use smart contracts for minting / distributin of your NFTs; the articles in this answer might help you get started: https://cardano.stackexchange.com/a/4426/4627)

It seems that blockfrost doesn't have any apis for minting. https://cardano.stackexchange.com/questions/3726/minting-a-nft-collection-with-blockfrost

You mint a token by submitting a „minting transaction“ through the  tx submit endpoint. That transaction needs to be created either in the browser or in your backend beforehand.

I am not sure, why you need the NFT creation to be signed by your backend. The NFT belongs to the person who is minting and hence being signed by him should be enough or not ? Or else we are centralising the whole thing and adds extra unnecessary work. Pls correct me ... with arguments.

The question is about an "nft collection" owned by the op, and such a collection usually shares the same minting policy, so you can verify authenticity (check which nft really belongs to this original collection). This policy would usually restrict who can mint nfts that belong to this collection and hence you'd likely have a central authority providing this signature (the key for this should be kept safely on the backend). Technically though you're right in that you can mint nfts also in the wild without any such measure.

But is imposible to add random characters image with this right? since user can see tha transaction that they are signing... unless using some source of randomless... wich i currently do not know any...

Yea that’s right. Depending on your use case one idea to solve for randomness could be to sell a „random“ lottery ticket token first and have that secretly tied to an NFT that the user can claim in a second transaction

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


text:
What does it mean when a block with 0 transactions is appended to the blockchain?
E.g. this block has 0 transactions
Is there any technical/ strategic reason for appending such a block to the blockchain?
To make my question more explicit: Why is the block created despite there is no transaction?

In order to understand this you have to understand how mining works and this is generally applicable to all blockchains. With mining there are two main types, PoW (proof of work) and PoS (proof of stake).
Regardless of the method employed miners compete to solve blocks. In the case of PoS miners stake funds and one is selected to solve or "mine" a block based on their stake. With PoW miners compete based on finding the lowest hash value below a certain threshold.
In both cases however miners get rewarded for solving a block. They usually get a portion or all of the transaction fees for the transactions included in that block so will include as many as they can or the highest paying ones but there is also usually a reward for solving the block so miners will try to solve it even if there are no transactions.
With solo mining a miner will get all of the block reward and eligible transaction fees for solving it. In the case of pooled mining miners get rewarded a portion of rewards based on their submitted shares out of all shares after a block is solved. But in both cases there's competition for solving blocks so miners will include empty blocks if no transactions are present.

But why would the cardano system want to choose a staking pool to validate a block when there is no transactions to validate to begin with? Wouldn't it be wasting rewards (from the point of view of the cardano system)?

@Aqqqq That's not really how it works. With any decentralised system there's a consensus mechanism. With PoW this relies on miners submitting blocks as they are mined and if 50% of validators accept a block as valid it gets added to the chain. With PoS this is still the same except it's interval based. So it's not so much choosing but based on rules and there's no rule that a block can't be empty. There may also be reasons that allowing empty blocks encourages contributors making the system more secure. Unless you move to a fee based system only where there's no incentive to mine empty blocks.

Thank you for your answer. Can you give me a source that cardano's PoS is interval based?

The Cardano protocol is set to try and produce blocks every 20 seconds on average
https://developers.cardano.org/docs/stake-pool-course/introduction-to-cardano/

This just means that no transactions happened between the previous block (5387367 at 02/25/2021 5:54:30 PM) and the actual block (5387367 at 02/25/2021 5:54:31 PM).
This behaviour does not affect rewards either: transaction fees are combined together at the end of the epoch and added to the amount of reserves that are being split among the stake pools. This way, it doesn't matter how many transactions a block has in it from a consensus protocol perspective.

But why is the block created despite there is no transaction?

I think this has to do with the fact that the cardano PoS consensus protocol is timed based. Each slot has a fixed schedule and slot leaders can propose their blocks at these slots. Now why slots? Since their is no race in PoS their needs to be a schedule at which block need to be published. The who gets the right of these slots is done via VRF (see https://vincenthz.github.io/ouroboros-vrf-explanation/)

I was just asked to review an answer to this question and thought a different viewpoint might be beneficial to new devs.
I'm sure that you will have heard of the block size wars at some point. This was an event in which the bitcoin community was divided into two camps to keep the same block size or increase it. The key point here is that in the bitcoin protocol blocks have a consent frequency at which they are made. If you multiply this frequency by the number of transactions in a block you get how many transactions a blockchain can process. The problem is that if each transaction takes up some space in a block and blocks have limited space in them meaning there's a cap on transactions. Increasing block size would up that limit.
Now Ethereum has a different approach in which the frequency of blocks is set but the size of blocks is variable (higher usage means bigger blocks). In Cardano we have a different approach in which we have slots and can put the blocks into the slots. Now it's possible to have empty slots i.e. slots with no blocks.
If you understand all that then its should be clear that always having empty blocks appended to the network would prevent transactions from happening and make the chain come to a halt. So it can be considered as an attack on the network.
There is another thing that would tell you why some actors are incentives to make blocks with no transactions in them. That is that in some networks miners are asked to make temporary blocks from the mempool which would be added to the chain if the node making the block wins the right to do so. All temp blocks by the nodes that did not win are discarded.
Now you should be able to conclude that these nodes would be incentivised to put less computational resources into processing the transactions in the mempool and more into winning the round.
That leads to the conclusion that when a block with no transactions is added it normly means one of 3 things:

No transactions in the mempool i.e. no accounts trading value;

An Attack on the Network Is occurring;

Someone gamed the system.

Note: this is in addition to the answer by @Prom not in spite of it. When you combine both answers you get the full picture.

Just to be sure: what is the relationship between makingg the temp blocks and winning the round? Is it the case that the more temp blocks are made, the more likely you would win the round?


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:
Dynamic number of participants in smart contracts
Sample use case: For a DAO smart contract, we would like to add members to a DAO over time. What is the best way to ensure that this can be done. Because in Marlowe the "PARTY" to the contract is defined at the beginning.
One solution can be to issue a certain number of role tokens in the contract. And over a period of time, to distribute these role tokens to DAO participants. But then the question, comes is how do we create multiple role tokens in marlowe contract, for a single "Party". In this case then we create a role called "DAO member" and issue say 1000 tokens for this role.
Any help appreciated ?

Your approach of pre-minting role tokens would work, but with a couple of limitations:

Each role token should probably have a unique name ("DAO Member 1", "DAO Member 2", etc.) so that participants can be separately identified in the Marlowe contract. Otherwise, it would be difficult to prevent the same token holder from voting multiple times.
There is a practical limit to how many roles a Marlowe contract can have. The history of choices made by the contract's roles is stored on-chain in the Plutus Datum of the contract's eUTxO. The Cardano network protocol limits how large a transaction can be, so that effectively limits the number of roles that could participate in a contract. The precise limit depends upon the length of the role-token names and other factors.
Contracts involving many roles tends to be very large. To fit such contracts on the Cardano blockchain, one needs to use a technique called Merkleization, which is supported by the Marlowe language and command-line tool. Using Merleization for a DAO might involve writing some moderately complex off-chain code to manage the Merkleized continuations of the contract.

Overall, Marlowe contracts aren't well suited for use as a DAO. It can work for some use cases for small DAO's, but not for arbitrarily large DAOs. For large DAOs, a Plutus solution or a hybrid Plutus+Marlowe solution would probably be better.

I've never used marlowe before, so I'm not sure the following solution can be implemented in marlowe, but this is certainly something possible.
in theory, you could store a list of "DAO members" on the smart contract's datum, however, practically this isn't possible due to the protocol's transaction size limit.
what you can do is implement a minting policy that mints your "DaoMember" coins (or NFTs) and then require that token to be present in the transaction that interacts with your DAO smart contract.
if the "DaoMember" token is present then the user has access to the member-level smart contract functionalities, if not we treat the user as a regular one with restricted access.
in all this the minting policy is open to mint/burns


text:
Using `curSymbol` function in Validator script
supposed I have a mintingpolicy script (simple one time minting policy, parameterizing TxOutRef) and a validator script. I want to validate if the token with correct CurrencySymbol is spent in a validator script by passing in TxOutRef.
-- Inside the validator script
spentToken :: TxOutRef -> PaymentPubKeyHash -> TokenName -> Bool
spentToken otOref pkh tn = assetClassValueOf (valuePaidTo info $ unPaymentPubKeyHash pkh) (assetClass (curSymbol otOref) tn) == 1

-- Inside the minting policy script
curSymbol :: TxOutRef -> CurrencySymbol
curSymbol = scriptCurrencySymbol . policy

However, it is not compiled: GHC Core to PLC plugin: E042:Error: Unsupported feature: Type constructor: GHC.Prim.Addr#
The closest issue I could find is this: Hardcoding currency symbol and token name in validator script. But seems it is about hardcoding strings, but not passing parameters to get the CurrencySymbol for validation. Appreciate any clues!

Would be good to have more context but looks like the problem could be with how you produce the CurrencySymbol. Is policy inlineable? If you want the current minting policy's currency symbol when use ownCurrencySymbol. If you want another script's currency symbol when pass it in as parameter.

The use case is I want to make sure the token spent is minted through a one-time minting policy. Thus, I want another script’s currency symbol. Since the currency symbol is dynamic (depends on the txOutRef supplies as parameter), it could not be obtained and pass it in as parameter beforehand. Lars answered this question on a live PPP Q&A session saying this is not working at the moment. I am looking for if there is any work around which could perform similar effect. Thanks anyway for suggesting!


text:
How do I add the staking part of an address in OffChain code
I am currently on tag: v2022-04-06 of plutus-apps and was wondering how to create Lookup and Constraints for a typedValidator that checks whether the input was returned to the script with the correct staking credential. I was hoping to find someone here that could tell me if that is currently possible or not.
In processConstraint it also looks like it just uses Address.scriptHashAddress to generate the address for this constraint, which does not include any staking credentials. (on tag v2022-04-06)
I have seen a few commit messages in plutus-apps for a new constraint via
mustPayToOtherScriptAddress for a later release, but maybe it is already possible and I am just looking in the wrong place.
This is what I currently have written: (it pays to the script but validation fails because it doesn't pay to an address with staking credentials)
      l         = Constraints.typedValidatorLookups factoryV <>
                  Constraints.otherScript (Scripts.validatorScript factoryV) <>
                  Constraints.mintingPolicy policy <>
                  Constraints.unspentOutputs utxos

      tx        = Constraints.mustPayToTheScript datum (nftValue) <>
                  -- ?? Constraints.mustPayWithDatumToPubKeyAddress (scriptAddress factoryV) (Nothing) datum (nftValue) <>
                  Constraints.mustMintValue chunkValue <>
                  mconcat [Constraints.mustPayToOtherScript chunkVHash (Datum $ PlutusTx.toBuiltinData (ChunkDatum x)) singleCVal | x <- [start..(start+n-1)]] <>
                  Constraints.mustSpendScriptOutput ((Map.keys utxos) !! 0) r
  unbalanced <- adjustUnbalancedTx <$> mkTxConstraints l tx

In factoryV I just check for the existance
    checkStakingCredential :: Bool
    checkStakingCredential = case addressStakingCredential . txOutAddress $ factoryOutput of
      Just _ -> True
      _       -> False

I figured out a way to do this.
After looking at the implementation of adjustUnbalancedTx I came up with the following:
-- adjust the contracts address to use the given staking credential in the given UnbalancedTx
adjustContractAddress ::
  ValidatorHash ->
  StakingCredential ->
  UnbalancedTx -> UnbalancedTx
adjustContractAddress vH sK =
    over (tx . Tx.outputs . traverse) adjust
  where
    adjust :: TxOut -> TxOut
    adjust txOut = txOut
      { txOutAddress=
        if (addressCredential . txOutAddress) txOut == ScriptCredential vH
        then Address (ScriptCredential vH) (Just sK)
        else txOutAddress txOut
      }

using the function above I can now adjust my transaction by changing how I construct it as follows:
unbalanced <- adjustContractAddress (Scripts.validatorHash factoryV) (StakingHash $ PubKeyCredential somePubKeyHash) <$> adjustUnbalancedTx <$> mkTxConstraints l tx

I hope this will be useful for some of you ;)


text:
Possible to run cardano-node on marlowe pioneer testnet using docker-compose
I wanted to run the cardano-node, marlowe pioneer testnet on Ubuntu using docker.
wget https://raw.githubusercontent.com/input-output-hk/cardano-wallet/master/docker-compose.yml
NETWORK=???????? docker-compose up -d

Anyone know what NETWORK we can use to access the pioneer testnet ?
I only know mainnet, testnet
this could imply that we use some sort of private testnet ?
sidenote:
I would like to know if we can do all these course material using mainnet too perhaps,
that would lean close towards the real use of smart-contracts deployment and utilization ?

In the context of this marlowe pioneer program this question is irrelevant.
There is a nix-shell environment that you can use instead.
setup your Ubuntu OS
sudo apt update && sudo apt upgrade -y
sudo apt install curl xz-utils -y

sh <(curl -L https://nixos.org/nix/install) --daemon
nix-shell -p nix-info --run "nix-info -m"
nix-env --version

sudo vi /etc/nix/nix.conf
# add the following content to the end of the file and save

substituters = https://hydra.iohk.io https://iohk.cachix.org https://cache.nixos.org/
trusted-public-keys = hydra.iohk.io:f/Ea+s+dFdN+3Y/G+FDgSq+a5NEWhJGzdjvKNGv0/EQ= iohk.cachix.org-1:DpRUyj7h7V830dp/i6Nti+NEO2/nhblbov/8MW7Rqoo= cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY=
experimental-features = nix-command flakes
allow-import-from-derivation = true

sudo systemctl restart nix-daemon.service

download and startup nix-shell with marlowe tools
git clone https://github.com/input-output-hk/marlowe-cardano.git
cd marlowe-cardano
git checkout marlowe-pioneers
nix-shell
start-marlowe-run

Notice you now have a tmux multiple windows system syncing, wait for it to finish
You can find the node.socket with
sudo find / -name '*node.socket'

then setup with
export CARDANO_NODE_SOCKET_PATH=/tmp/node.socket
export CARDANO_TESTNET_MAGIC=1567

My advice is that the docker-compose solution is only working for a specific set of networks only: mainnet or testnet
These only include cardano-cli and cardano-wallet
Then you can use the binary executable files from the proper nix-shell paths that can be found here:
sudo find /nix/store -wholename '*/bin/cardano-cli'
sudo find /nix/store -wholename '*/bin/marlowe-cli'
sudo find /nix/store -wholename '*/bin/cardano-wallet'

I assume you're looking for marlowe-pioneers (reference here ).
I am not a big fan of docker/nix myself (for not so "micro" services) - so not testing it out beforehand, but that should be the right ID. If you'd want to look at configs/genesis/topology files yourself, you can find them here.

owh interesting
I tried but get this
service "cardano-node" refers to undefined volume node-marlowe-pioneers-db: invalid compose project```
owh ok I see the docker compose file is not including the marlowe-pioneers db

Ye - shouldn't be too difficult to customise to other networks, can update those configs/genesis mounts seperately

Let's try to edit the code below for it to work perhaps
original docker-compose from github copied below for editing
(problem is that the docker image does not have the config file)
[STATUS: editing, not yet working]
version: "3.5"

services:
  cardano-node:
    image: inputoutput/cardano-node:1.34.1
    environment:
      NETWORK:
    volumes:
      - node-${NETWORK}-db:/data
      - node-ipc:/ipc
    restart: on-failure
    logging:
      driver: "json-file"
      options:
        compress: "true"
        max-file: "10"
        max-size: "50m"

  cardano-wallet:
    image: inputoutput/cardano-wallet:2022.5.27
    volumes:
      - wallet-${NETWORK}-db:/wallet-db
      - node-ipc:/ipc
    ports:
      - 8090:8090
    entrypoint: []
    command: bash -c "
        ([[ $$NETWORK == \"mainnet\" ]] && $$CMD --mainnet) ||
        ([[ $$NETWORK == \"marlowe-pioneers\" ]] && $$CMD --testnet /config/${NETWORK}/marlowe-pioneers-byron-genesis.json) ||
        ($$CMD --testnet /config/${NETWORK}/genesis-byron.json)
      "
    environment:
      CMD: "cardano-wallet serve --node-socket /ipc/node.socket --database /wallet-db --listen-address 0.0.0.0"
      NETWORK:
    restart: on-failure
    logging:
      driver: "json-file"
      options:
        compress: "true"
        max-file: "10"
        max-size: "50m"

volumes:
  node-mainnet-db:
  node-testnet-db:
  node-alonzo-purple-db:
  node-marlowe-pioneers-db:
  wallet-mainnet-db:
  wallet-testnet-db:
  wallet-alonzo-purple-db:
  wallet-marlowe-pioneers-db:
  node-ipc:
  node-config:

cardano-cardano-node-1    | [Error] Managed configuration for network marlowe-pioneers does not exist

cardano-cardano-wallet-1  | [cardano-wallet.main:Error:4] [2022-06-07 12:25:19.71 UTC] Failed to parse Byron genesis configuration. You may want to check the filepath given via --genesis and make sure it points to a  valid JSON Byron genesis file. The genesis file must be Byron, not Shelley as it used to feed the wallet with the initial blockchain parameters. Here's (perhaps) some helpful hint: GenesisDataIOError /config/marlowe-pioneers/genesis-byron.json: openBinaryFile: does not exist (No such file or directory)

Hello, Due to the nature of StackExchange (posting possible answers to questions and fixes to the problem) the current state of your response it not suitable to this site. Its more of a github issue post conversation or a blog type post. I would suggest submitting it to one of those sites or changing it to highlight that the reason you don't belive its possible is the lack of the config file. Also if this is made during the time your still working on an answer please finish testing things locally and update the post to include all the result and be written in the form of an direct answer.

I agree, I will think about cleaning up this question, since I have been playing with nix-shell instead, you can only use this docker-compose file for mainnet and public testnet nothing else. And trying to get the marlowe-pioneer node running fails because the topology file has a wrong relay hostname.
https://hydra.iohk.io/build/14528927/download/1/index.html
docker run -p 127.0.0.1:3001:3001 --volume $PWD/configuration:/configuration inputoutput/cardano-node run --topology /configuration/marlowe-pioneers-topology.json --config /configuration/marlowe-pioneers-config.json

NETWORK=???
Get's translated, to the "magic-id" parameter in the cardano-cli.
The number you are looking for is 1567
And we will look at it in more detail in Lecture 7 "marlowe-cli"

Marlowe CLI requires access to a Cardano node,
I don't want to use Daedalus but use a docker-compose hosted cardano-node and cardano-wallet on mainnet and marlowe-pioneer testnet in order to manipulate transactions and wallets using python. It works on python for the mainnet, but I don't know how to get it to work on any other testnet ?
Your response as far as setting up a mart contract is probably correct but not in line with my current problem

[myVM01:cardano.node.DnsSubscription:Warning:53] [2022-06-08 17:03:28.32 UTC] Domain: "relays.marlowe-pioneers.dev.cardano.org" Failed to start all required subscriptions
[myVM01:cardano.node.DnsSubscription:Debug:53] [2022-06-08 17:03:29.33 UTC] Domain: "relays.marlowe-pioneers.dev.cardano.org" Restarting Subscription after 1.26569077s desired valency 2 current valency 0
[myVM01:cardano.node.DnsSubscription:Debug:53] [2022-06-08 17:03:38.06 UTC] Domain: "relays.marlowe-pioneers.dev.cardano.org" Starting Subscription Worker, valency 2


text:
How To Optimise Daedalus Syncing?
So I started using my Daedalus Node as the node (instead of the direct build) for the cardano-cli, but it always takes forever to sync and I am wondering if I misconfigured something or if there's a better setup.
Can you please share your Daedalus optimisations/Configs?
Thanks

To help others with a similar issue, can you list for system specs and the time it has taken so far. It would be good to know your RAM size, SSD or HDD, and network speed via fast.com or similar.

As Erik mentioned, Daedalus is a full node and thus requires downloading the chain from peers and validating it locally on your machine. However, if you already have a trusted copy of the chain (either from previously syncing a full node or some other source), you can manually copy it into Daedalus' state directory. Doing this will speed things up because Daedalus will only have to validate the provided chain instead of downloading the whole thing from genesis. Of course, it will also have to download whatever is needed to extend the provided chain's tip to the current tip.
First, launch Daedalus, and click on Help > Daedalus Diagnostics. Under the "Core Info" section, the "Daedalus State Directory" specifies the filepath that Daedalus uses on your computer. In this directory should be a folder titled chain, containing 3 subdirectories: immutable, ledger, and volatile, as well as 2 files: lock and protocolMagicId.
Next, shutdown Daedalus, then replace the 5 assets in the chain folder with the other 5 found in your local copy of the chain (they should all have the same filenames as mentioned above). Also, make sure the chain folder and files have appropriate permissions (chmod 775 for chain).
Restart Daedalus and enjoy a faster sync!

Man your Daedalus knowledge is impressive you seem to be answering all my questions. A well-deserved upvote and tick.

Define "forever".
Sorry, but there are no tweaks to make it faster. If there were, they would be the default.
Please remember that Daedalus is a "full node". That means it downloads and stores the complete blockchain history, which on my full synced Linux machine uses disk store of 67 Gig for mainnet. I have not done a full sync with Daedalus recently, but I suspect it would be about 24 hours to sync.
There are however some thing that might help, like use a recent machine with at last 16G of RAM, use an SSD disk (which is faster than the older electro-mechanical ones, have a decent network connection.


text:
How to Run A DB Sync Server On Daedalus?
So I have been trying to do some fun things with Daedalus, and realised I should be able to query the node from it. This makes me wonder how to set up a limited database / querying system for my own needs out of Daedalus? Kinda like a smaller blockfrost.

The node by itself is stripped down of resources to keep active records of history, so the expectation that you could query node from Daedalus to have similar capability as cardano-db-sync (which maintains kinda everything from chain, as well as from ledger events, alongwith historical view). Thus, the resource requirements from dbsync are expected to be much more.
DB Sync v13 will allow you to stop querying ledger-state data which will shave off ~8-10GB (at the expense of not saving off-chain calcs coming from ledger-state). Instead if you're after creating small-scoped utility while not being able to spend much resources, you can look at projects below:

Ogmios / Kupo
Oura / Scrolls

Of course - the more you want to store and manage historically, higher the resources required will be

You can run cardano-db-sync, but be aware that is a rather heavy weight application that requires lots of RAM (ie 32 Gig) and will take about a week to sync.

32 GB will not be enough if you are also running cardano-node on the same machine. Or you will need to add a lot of swap...

Yeah looked at the repo this is not a viable option, for my computer and its over speced to train AI. That means I Have more Storage and RAM then most people.

@George-APEXStakePool I run a node and db-sync in a VM with 18 Gugabytes (16 was not enough).

@ErikdeCastroLopo If you run it long enough, you will see that one of them will eventually be killed with OOM error. It happened to me last week on a VM with 32 GM RAM. I upgraded it to 40 GB RAM and I also increased the swap (which was only 4 GB).


text:
Is there a Python Version of Cardano Node-CLI JavaScript Library?
I know JS, but I have other code written in python that I want to use in conjunction with the node. Is there a Python 3.xxxx SDK/Library/Module that will do everything the JS can?
Heres what is written about the JS Version: https://developers.cardano.org/docs/get-started/cardanocli-js

I know you are asking for a python library interacting with a node, but let me tell you there is a very comprehensive python library with which you don't need to run a node yourself.
You can find a list of it's features in the README https://github.com/cffls/pycardano/
For completeness, there are a few python libraries wrapping a cardano node and interacting with the cli. I haven't used any of those and I am not sure what features they support exactly, but here you go:

https://github.com/emesik/cardano-python
https://github.com/input-output-hk/cardano-clusterlib-py
https://gitlab.com/viper-staking/cardano-tools


text:
Cardano GraphQL change default ip
I did run the cardano-graphql in a server and now it's sync but I'd like to send requests from local to server ip. I did open the port on AWS but couldn't figure it out where and how to change the default path. I did check docker_compose.yaml file but couldn't find something like 127.0.0.1 or localhost. I'd like to change it to 0.0.0.0 but not sure which file should I configure to access outside requests.

The issue is solved. After typing docker ps I realize that db_sync is not working properly and keeps restarting. Deleting RESTORE_SNAPSHOT parameter while starting graphql solved my issue it syncs from the genesis.


text:
NFT Support For Marlowe
A Marlowe contract for a bank loan is linked here:
This was homework for Marlowe Pioneers - Lesson 4.
If you run the contract in the Marlowe Playground you will see that if the borrower makes all the payments on time then the bank returns all the ADA to the borrower and the contract ends. Returning the money to the borrower seems to simulate the bank is giving the borrower a title to a property. I am wondering if giving an NFT to represent the property deed is already possible using Marlowe. If not, then I am wondering when NFT support is going to be added to Marlowe.
I think that it may be possible to do this now or in the future because of the stackexchange post linked here. Is this something that should be added to the ACTUS demos?
Is it possible to expand the Marlow contract linked above to deliver an NFT representing a property deed if the borrower makes all the payments on time? If so, will we be taught this skill?
Much thanks

Thanks to Hernan Rajchert, the contract linked above now uses a native token as seen in his solution below.

Marlowe already has the notion of MultiValue asset, which is what you need to trade custom tokens. Instead of using the ADA token, use one that represent your deed.
The minting of that NFT is done outside of Marlowe, but after you have it, you can put it into a Marlowe contract with a Deposit.

Useful link: https://docs.cardano.org/native-tokens/learn


text:
Convert Stake Key to Address
I am tiring to use Cardano Sterilization Lib to get the Stake/Usable address from Stake Hash or Address Hash.
https://adaex.org/address/addr1q8d27ughqsqras7k9wnr4dlustzjlhadhe9rf6t3tr90u5yc4vxfxvmpr0hfktjc7md2n8er05tnurr676n6yq7khcnss8msq0/all-addresses#data
Address Hash: 01daaf711704003ec3d62ba63ab7fc82c52fdfadbe4a34e97158cafe5098ab0c9333611bee9b2e58f6daa99f237d173e0c7af6a7a203d6be27
Stake Key Hash: e198ab0c9333611bee9b2e58f6daa99f237d173e0c7af6a7a203d6be27
I saw Convert xpub public key from ccvault to bech32 or acct_ public key which showed a way but I couldn't get it to work.
wasm.StakeCredential.from_bytes(new TextEncoder().encode("98ab0c9333611bee9b2e58f6daa99f237d173e0c7af6a7a203d6be27"))
returns  Deserialization failed in StakeCredential because: Invalid cbor: not the right type, expected Array' byte received Text'.
Thanks!

You can try with this line:
wasm.StakeCredential.from_bytes(
 Buffer.from("98ab0c9333611bee9b2e58f6daa99f237d173e0c7af6a7a203d6be27", "hex")
)

Alternatively, you can try using from_keyhash method. This method expects to receive a Ed25519KeyHash, which you can build from the given Stake Key Hash, all in the same instruction, like this:
wasm.StakeCredential.from_keyhash(
 wasm.Ed25519KeyHash.from_bytes(
  Buffer.from("e198ab0c9333611bee9b2e58f6daa99f237d173e0c7af6a7a203d6be27", "hex")
 )
)


text:
How can I check the origin of a Token?
A smart contract minted a Token and send it to my wallet, after a time has passed how can I check if that smart-contract in specific did mint the token?

the token is present in your wallet as "<policy-id>.<token-name-hex-ascii>"
if you want to check only for a specific smart contract (minting policy) to be the one which minted the token just get the hash of the smart contract and compare it to the "<policy id>"
if the minting policy hash corresponds to the policy id then that's your smart contract
if that is not the case but you still want to know which smart contract was used you could do the following:

check the transaction that sent you the token

if that transaction did not mint the token then that token must have come from somewhere else

(go to 1) going back you'll find a transaction that minted the token and in that transaction, the smart contract (minting policy) must be included in order to be executed. here is your smart contract


text:
Is possible to create a cNFT that depends on 'proof of ownership' in order to be own by a wallet?
I'm thinking on a way to create a cNFT that requires 'proof of ownership' to be minted and own by a wallet, by proof of ownership I refer to something the receipt owns and can pass to others or loss, like a house or a car (let's imagine that the Oracle for that is piece of cake to implement) and when these things change owners or are destroyed in a way that satisfies an oracle the cNFT returns(?) to the owner of the Policy ID (or are invalidated somehow allowing them to be minted again).
I know cNFTs cannot be passed unless the wallet owner approves a transaction where these assets are moves to another Cardano ADA wallet address, so when the current owner gives up ownership of the things used in an ownership challenge the minted cNFT should change hands too without depending on the current cNFT owner.
Furthermore, I know smart contracts can own assets, but I don't know if wallets can own smart contracts, or even if owning a smart contract that owns a cNFT is the way to go. Is there a recommended way to go about something like this?

To my understanding, by "proof of ownership" you are referring to the user owning a physical object, and this smart contract should keep track of the real-world ownership via NFTs.
before I keep answering there is an important key concept that cannot be ignored
You do not have access to the entire blockchain data while using a validator
let me explain:
in Solidity, by standard, you have access to something like
MyTokenContract.balanceOf( address )

where "address" might not even ever have interacted with the smart contract.
in Plutus, you could access such information only via an oracle.
Without oracle, you can only access information regarding the current transaction or previous transactions if the relevant data is explicitly exposed via the Datum (which is meant to be the state of the smart contract).
the balanceOf is only an example, but for this reason, you cannot move (or block) other user's assets via smart contract.
simulate the account model
the "smart contract that owns the cNFT" is the way to go.
this is because this way you are "centralizing" the NFT ownership to the smart contract.
you could then have a map from Address (or PublicKeyHash) to MintingPolicyHash (which is the policy-id of your NFT) in your state (Datum)
so that only that address has the control of that NFT in that smart contract,
but the smart contract can do whatever he wants with the NFT.
own a smart contract
You can't really "own" a smart contract but you could implement what I like to call "God-mode" for a specific Address (or PublicKeyHash)
this can be done in your smart contract logic like so:
{-# LANGUAGE OverloadedStrings #-}
-- OverloadedStrings needet to easly construct a constant PubKeyHash

import Plutus.V1.Ledger.Contexts as Ctx
import Ledger.Crypto ( PubKeyHash )

scLogic :: MyDatum -> MyRedeemer -> ScriptContext -> Bool
scLogic datum redeemer ctx =
    if Ctx.txSignedBy (Ctx.scriptContextTxInfo ctx) (PubKeyHash "<owner public key hash (hex)>")

    then True -- the owner is signing the Tx, god-mode active

    else -- implement smart contract logic for anyone else

just to clarify, it is the other way around, the physical object determines who owns the NFT (either because someone owns the physical object used in the proof of ownership challenge, or it does not exist anymore, i.e.: the physical object was destroyed)
I'm assuming that an oracle can be implemented to verify ownership of the physical object via a challenge to keep the question simple.


text:
What is this Pop Up Screen on Cardano Documentation?
When searching the docs it helps to use ctrl + F to find something fast, however, when I use it on the plutus docs I get a weird pop-up screen I'm not used to. (Image Below)
My Questions are:

What is this screen?
Why does it pop up?
Can It help me in any way / what use does it have?
Is there a way to stop it from poping up?

link to a page this has happened on: https://playground.plutus.iohkdev.io/doc/haddock/plutus-ledger-api/html/Plutus-V1-Ledger-Contexts.html

What is this screen?
that window comes by default with the haddock documentation
I think it should work as a quick "go-to" however for PlutusTx the links do never work (at least to my experience)
Why does it pop up?
by pressing Ctrl+F you are searching for some text in the DOM of the page
that window is located on top of the main content at the ```ħtml`` level so the search goes there first
Can It help me in any way / what use does it have?
It can give you a quick overview of what's on the page however the clicking on the Types usually doesn't work so it's not that useful
Is there a way to stop it from poping up?
not by the webpage functionalities but you can remove it from the page by running the following javascript code in the browser console

you can open the browser console by pressing F12 or  Ctrl+Shift+J or by the three dots on the top left of the browser searching for Developer tools

document.getElementById("synopsis").remove()

this will remove the window only for the current page, refreshing or re-access the page will have the window once again


text:
GraphQL syncing takes too much time
Hello everyone I did follow this guide to run GraphQL with docker-compose: https://github.com/input-output-hk/cardano-graphql
However, inputoutput/cardano-db-sync:12.0.0 is syncing super slow
CONTAINER ID   IMAGE                                                 COMMAND                  CREATED        STATUS                PORTS                                                                       NAMES
ad0aea43554e   inputoutput/cardano-db-sync:12.0.0                    "/nix/store/5ghw8rqx…"   28 hours ago   Up 28 hours                                                                                cardano-graphql_cardano-db-sync-extended_1
23ebbe6aeed1   inputoutput/cardano-graphql-hasura:6.2.0              "docker-entrypoint.s…"   5 days ago     Up 5 days             0.0.0.0:8090->8080/tcp, :::8090->8080/tcp                                   cardano-graphql_hasura_1
fb2d31b115f3   postgres:11.5-alpine                                  "docker-entrypoint.s…"   5 days ago     Up 5 days             0.0.0.0:5432->5432/tcp, :::5432->5432/tcp                                   cardano-graphql_postgres_1
537147f0d16a   inputoutput/cardano-graphql:6.2.0-mainnet             "node index.js"          5 days ago     Up 28 hours           0.0.0.0:3100->3100/tcp, :::3100->3100/tcp                                   cardano-graphql_cardano-graphql_1
7c47cba2732c   cardanosolutions/cardano-node-ogmios:v5.1.0-mainnet   "/root/cardano-node-…"   5 days ago     Up 5 days (healthy)   3000/tcp, 12788/tcp, 0.0.0.0:1337->1337/tcp, :::1337->1337/tcp, 12798/tcp   cardano-graphql_cardano-node-ogmios_1

I did check the CPU and Memory usage CPUs are at 30% usage and RAM is 27.7/32GB.
After 28 hours it's still at 36.65% and gets slower (it was going faster at the beginning).
{
    "data": {
        "cardanoDbMeta": {
            "initialized": false,
            "syncPercentage": 36.65
        }
    }
}

This is how I start docker I was getting errors so removed RESTORE_SNAPSHOT parameter to retrieve it from the genesis. (I don't know whether the problem is related with it or not).
export NETWORK=mainnet &&\
docker pull inputoutput/cardano-graphql:6.2.0-${NETWORK} &&\
docker pull inputoutput/cardano-graphql-hasura:6.2.0 &&\
docker pull cardanosolutions/cardano-node-ogmios:v5.1.0-${NETWORK} &&\
docker-compose up -d &&\
docker-compose logs -f

The typical question for this would have been, what is your node and dbsync status, has it gone through a crash recently, etc. But use of < 6 GB out of 32 sounds like your node itself is not yet in sync , atleast as of the time you created the post.
Thus, the question instead would be - What are your baseline expectations for time it'd take to sync node and then dbsync? I'd expect it to take more than a day (perhaps 1.5-2.5) to sync node alone, and then depending on your IO throughput (check db sync sys requirements ), it could take further. The time taken for a particular epoch may be longer gradually as the chain adoption and use cases increase.
Furthermore, if you have restarts/crash during the sync process, it can make your experience substantially worse.
Lastly, when using Snapshots before, you were downloading an already synched to recent epoch snapshot of underlying Postgres DB, but if your node is behind DBSync by few epochs, this could also end up rolling back your DB instead of synching further.

The node is in sync right now but after 47 hours db is still at 39.66% I mean yesterday it came from 0 to 34 in 24 hours but now 5% in 23 hours. Is there anything I can do? Should I try to start with restore snapshots? Thank you for your assistance sir.

You can start by checking DBSync logs, uptime of pod/containers (if there was a restart, you'd be adding more hours every time), measure actual IOPs - if it matches upstream.
To be sure, you mean your node wasnt in sync yesterday, but has caught up now - is that correct?
Assuming the tip % is calculated in slots, for the first 34% you were actually in Byron era - which had 21600 slots per epoch (5 days), and much simpler. With shelley, you have 432000 slots per epoch, thus % distribution (besides, gradually staking, assets, scripts got unlocked) - so sync would be much slower from there on.

The node is in sync for 5 days. Is there any difference in terms of speed for Byron and Shelley? or is it just the epoch size that makes it look way slower?

Here is the logs of db-sync: https://imgur.com/jGVX1Ha

node is in sync for 5 days
The resource consumption in OP suggests otherwise.

the epoch size that makes it look way slower
Tip based % is slower as explained in previous reply.

Logs: Last extract of dbsync image is not exactly helpful.
Also, parts of initial reply (eg: actual IOPs requirements) are still to be answered.
We often see docker users hit such issues w/resource sizing or gaining app ops experience to troubleshooting individual components - usually more suitable candidates for discord/tg platforms instead of SE (which works for Q&A/discussion formats).

Sir it's been 3 days since db is syncing and it's still at 52.16% it was 55.20% yesterday. It's moving super slow and lags behind instead of going forward. How long will it take? Will it get faster after some point? I really didn't understand whats the problem.

Just waiting without addressing the other points mentioned in replies above will likely not help you much


text:
Why can't I use the same wallet more than once in Plutus Playground?
I'm currently testing my app in the "Plutus Playground" and the simulation will not let me call an endpoint from the same contract more than once.
When I try to use the same wallet, the simulation does not register the call (as seen below).

have you tried adding a wait action after the second call? the emulated blockchain may take some slots to produce a new block


text:
Multiple policies associated with the same token/nft
We want to associate multiple policy ids with the same token/nft. Is this possible?

as @Fermat already answered

Currently Value is parametrized by a currency symbol and a token name. Here the currency symbol is not arbitrary, it is the hash of the minting policy script. This script determines under which conditions the tokens under this policy can be minted or burned.

so NO you cannot have multiple policy ids for the same token since then we wouldn't know how to properly mint/burn it.
what you could do instead is to associate multiple validators to the policy which is supposed to mint or burn you token or NFT.
as an example say you want to check for validatorA and validatorB to both have signed the transaction (therefore have been executed with success) and validatorC to succeed in order to burn
your minting policy would look like this:
mintingPolicyLogic :: BuiltinData -> ScriptContext -> Bool
mintingPolicyLogic _red ctx =
    if isMinting then
        validatorASucceeded &&
        validatorBSucceeded
    else
        validatorCSucceeded
    where
        validatorSucceded :: ValidatorHash -> Bool
        validatorSucceded valHash = forwardToValidator valHash () ctx

        validatorASucceeded = validatorSucceded <insert validatorA hash here>
        validatorBSucceeded = validatorSucceded <insert validatorB hash here>
        validatorCSucceeded = validatorSucceded <insert validatorC hash here>

        isMinting = case Value.flattenValue (LedgerApi.txInfoMint txInfo) of
            [] -> False
            [( _sym, _tn, amount )] -> amount > 0
            _ -> traceError "multiple mints per tx not allowed"

forwardToValidator docs

NOTE: the script provided is by no mean production ready, lots of improvements can (and should) be made, the script is here for educational purposes only

Note that a mintingPolicy only uses a redeemer and the context, not a datum.

@Fermat you're rigth, my bad

Currently Value is parametrized by a currency symbol, a tokenname and the amount of tokens of this type(1). Here the currency symbol is not arbitrary, it is the hash of the minting policy script. This script determines under which conditions the tokens under this policy can be minted or burned.
To answer your question, it depends. If you want tokens with the same Tokenname and different policies, then yes. But if you want one token with currency symbol x and tokenname y that you can mint via multiple minting policies that both hash to x, then no.
Perhaps you could specify what you want to do with the token? If you just want two condition that both can mint/burn you could always combine two minting policies to get one policy.


text:
How to get the history of an NFT or NFT Series from blockfrost?
Hi is there a quick API call to get the transaction history of a specific NFT or collection of NFTs in BlockFrost?

Yes, there’s an endpoint for the asset transactions here:
https://docs.blockfrost.io/#tag/Cardano-Assets/paths/~1assets~1{asset}~1transactions/get
and also one for mint & burning history here:
https://docs.blockfrost.io/#tag/Cardano-Assets/paths/~1assets~1{asset}~1history/get

{asset}=nft asset id ?

Yes it’s the policy id combined with the hex encoded asset name, simply concatenated.
Example from the docs:
b0d07d45fe9514f80213f4020e5a61241458be626841cde717cb38a76e7574636f696e

is there a quick way to get the hex-encoded assetname?

You can just strip off the first 56 characters and you're left with the hex encoded asset name, eg using substring: asset.substring(56)

combination of the policy_id and hex encoded asset_name needs to be provided as an input parameter for this endpoint:
Blockfrost - Specific Asset


text:
How to Securely Serialise a Plutus Smart Contract Endpoint?
Assuming I made an arbitrary smart contract and want to serialise the endpoint after I have the validator hash and address hash, what should I do to ensure that the serialisation is as safe as possible?
are there steps I should follow to make minimum security guarantees or some software I can use to test it? How do I know that the serialisation is done correctly?

The current format of the question is a bit vague. Could you try to rephrase it? Are you trying to assert if you contract is safe to use from a design perspective? Or if the serialization does what it is meant to do?

Okay thanks for the input, I'll rewrite it when I'm on my laptop

before I can answer there is an important distinction that must be done
on-chain code can be serialized, off-chain code stays "off the chain" so there is nothing to serialize
so if you are searching for a way to serialize your off-chain code (which can be written in any language, from Haskell with the Contract monad to javascript thanks to the cardano-serialization-library) unfortunately there is nothing to do
serialize the on-chain code
from the chain point of view there is no difference between Validators and MintingPolicy(ies) and StakeValidator
all of them are Scripts for the chain, treated differently based on the ScriptPourpose of that transaction
so you first need to get the raw Script of your smart contract
you can do that with the following functions (all form Plutus.V1.Ledger.Api module)
unValidatorScript :: Validator -> Script
getMintingPolicy :: MintingPolicy -> Script
getStakeValidator :: StakeValidator -> Script

once you have your Script the process is always the same
Script has an instance of the Srialize typeclass which conviniently exposes the serialise function:
serialise :: forall a. Serialise a => a -> ByteString

then we need to strictly evaluate the byte-string and make sure the values do fit in shorts types, this can be done by concatenating the following two functions
import qualified Data.ByteString.Short          as SBS
import qualified Data.ByteString.Lazy           as LBS

-- LBS.toStrict :: ByteString -> ByteString
-- SBS.toShort :: ByteString -> ShortByteString
asStrictBS :: ByteString -> ShortByteString
asStrictBS = SBS.toShort . LBS.toStrict

then we have to specify how to interpret the ShortByteString we have:
-- PlutusScriptSerialized is a constrctor
PlutusScriptSerialized :: ShortByteString -> PlutusScript PlutusScriptV1

and finally get our Script into a file, which can be done thanks to the writeFileTextEnvelope from the Cardano.Api.SerialiseTextEnvelope module:
writeFileTextEnvelope :: forall a.
HasTextEnvelope a =>
FilePath
-> Maybe TextEnvelopeDescr -> a -> IO (Either (FileError ()) ())

I usually do all this whit the following utility funciutons:
getAndWriteScript :: ( willBeScript -> Ledger.Script ) -> FilePath -> willBeScript -> IO (Either (FileError ()) ())
getAndWriteScript getScript filePath =
--                          PlutusScript PlutusScriptV1 instance of HasTextEnvelope
    writeFileTextEnvelope @(PlutusScript PlutusScriptV1) filePath
    Nothing -- Maybe TextEnvelopeDescr ( Nothing => default )
    . PlutusScriptSerialised . SBS.toShort . LBS.toStrict . serialise . getScript

writeMintingPolicy :: FilePath -> Scripts.MintingPolicy -> IO (Either (FileError ()) ())
writeMintingPolicy = getAndWriteScript Ledger.getMintingPolicy

writeValidator :: FilePath -> Scripts.Validator -> IO (Either (FileError ()) ())
writeValidator = getAndWriteScript Ledger.unValidatorScript

Also have a look at https://playground.plutus.iohkdev.io/doc/haddock/plutus-ledger-api/html/Plutus-V2-Ledger-Api.html#v:validateScript. This functions checks if a SerializedScript is correctly serialized.


text:
Homework for lecture # 5
How do I review the homework for lecture 5?  There is no folder 'lecture05' in https://github.com/input-output-hk/marlowe-pioneer-program/tree/main/code/src

Here is the homework for Lecture 5.


text:
Is there a way to see which Plutus code is deployed on a specific script address?
On Ethereum, for example, there is a way to see the Solidity code that is deployed in a specific address (as long as the code gets verified).
Is there a way to achieve this same behaviour in Cardano?

Edit

I just realized I misunderstood your question, you are searching for a way to get the Plutus code starting from an address, not to get and address from your Plutus code!
I'm leaving the old answer below just in case it can help
Last answer

In Cardano, you need to include the serialized Plutus script in your transaction to interact with it so it is assumed you have/know the code of the smart contract you want to interact with

as soon the Vasil hard fork goes through you should be able to refer to the script from a previous transaction (this doesn't change the fact you know where your script is so you know where to get it)

so by protocol there should be nothing like that
however, if you go on sites like https://cardanoscan.io and search for a specific smart contract address you should be able to see on the bottom of the page two tabs: Transactions and Script
the script is visible only if the smart contract is verified there as in Ethereum
Old answer

using cardano-cli

once you have your serialized smart contract (which you can obtain as described in this other answer)
you can run
cardano-cli address build --$your_net --payment-script-file path/to/your-validator.plutus.json

where your-validator.plutus.json is the output of writeFileTextEnvelope in the answer cited above
this will print out the corresponding validator address
using PlutusTx

in the Ledger.Typed.Scripts module there is a validatorAddress function that is so defined:
validatorAddress :: TypedValidator a -> Address

once you have an Address you can use show on it in order to get a string, or if you want just print it to the standard output you can use print

NOTE: if you have an untyped Validator rather than a TypedValidator a, and you still want to use the PlutusTx way, you could use:
unsafeMkTypedValidator :: Validator -> TypedValidator Any


text:
How To Explain Monterrey Expansion and Hard coded ADA values?
I have heard the term Monterrey Expansion used to talk about the ADA supply, but my understanding is that the total amount of ADA is fixed.
How can you have a hardcoded value for a upper bound on ADA and have an expanding supply of ADA at the same time?

Without repeating what's in the documentation already , monetary expansion refers to a percentage of ADA unlocked from reserves to distribute to treasury and stake rewards right before each epoch transition. It does not change the upper bound max-supply of ADA.


text:
Cannot wrap my head on NFTs
I am running through the Plutus Pioneer Program and I have reached week 5. Also as a reference, I will use the LobsterChallenge repository. I am a bit confused about how NFTs work for the Cardano blockchain.
From what I understood and me asking in the discord channel when making the policy we accept a TxOutRef as a parameter to the policy.
That's all fine, but let's say I want to have 10000 users to mint my collection. Then I need to provide users a way to build, sign, and submit a transaction (To my knowledge I build the off-chain code, and with PAB I provide endpoints the construct everything? Please do correct me If I am wrong as it's still fuzzy for me).
So the off-chain code chooses a TxOutRef from the user's wallet and generates the policy (currency Symbol) by passing the UTXO when compiling the policy
curSymbol :: TxOutRef -> TokenName -> CurrencySymbol
curSymbol oref tn = scriptCurrencySymbol $ policy oref tn

So hopefully I gave some info about what I am talking about and will start with the questions:

Doesn't the curSymbol function return a different currency symbol every time? When that is the case, how do I know that a wallet has been minted from my collection? Do I store this currency symbol in my databases as a reference to the wallet?
What stops a user from getting my code in a public repository and initiating a transaction with a different UTXO
How do I limit mints? Do I mint all 10000 NFTs to a script I create and allow only for the script to mint more (so nobody can try and initiate the policy). And minting 10000 NFTS, wouldn't that require 10000 UTXOs? From what I understand in a UTXO there must be at least 1.25 ADA
I tried understanding the horrorcubes scripts . But got more confused from the:

data CounterDatum = CounterDatum {
        cdValue :: !Integer, -- ^ The current counter value.
        cdLimit :: !Integer  -- ^ The value limit, after this limit is reached, this eUTXO can not be spent again.
    } deriving (Show, Generic, FromJSON, ToJSON)

What do they mean by "The value limit, after this limit is reached, this eUTXO can not be spent again.".
Isn't the purpose of a UTXO to never be spent again?
I think these are my questions for now. Thanks a lot to the people who will respond!

I totally understand your confusion, in my opinion as explained in the plutus pioneer program is totally unclear the concept of NFT.
identify an NFTs in Cardano

each (fungible) token "collection" is uniquely identified by its AssetClass, which is nothing more than a PolicyHash(equivalent to the policy-id) and a TokenName together
a Non Fungible Token is a Fungible token with a total supply of 1
from the moment that a series of tokens are identified by both the PolicyHash and the TokenName, in order to make the AssetClass unique at the very least one between the PolicyHash and the TokenName has to be unique.
examples:

HOSKY is a fungible token because the Billions of tokens circulating do have all the same PolicyHash and the TokenName

SpaceBudz are an NFT collection because all the tokens do have the same PolicyHash but different (and unique) TokenNames (thanks to the number at the end)

an Oracle identifier is an NFT because is generally created thanks to a MintingPolicy parametrized by  a TxOutRef

MintingPolicy parametrized by  a TxOutRef

in the plutus pioneer program, the given minting policy is guaranteed to make an NFT because a TxOutRef can exist only once and never again (but is NOT the only way to make an NFT as specified above)
so when you do something like
type MyRawRedeemer = BuiltinData

myMintingPolicy :: TxOutRef -> MyRawRedeemer -> ScriptContext -> Bool
myMintingPolicy outRef _reedemer ctx =
    isUTxOSpent && totalSupplyOf1
    where
        isUTxOSpent :: Bool
        isUTxOSpent = -- check between the tx inputs

        totalSupplyOf1 :: Bool
        totalSupplyOf1 = case flattenValue ( txInfoMint ( scriptContextTxInfo ctx ) ) of
            [] -> False -- nothing to mint (should never happen)
            [( sym, _tokenName, amount )] -> -- single asset class minted
                sym == ownCurrencySymbol ctx &&
                amount == 1
            _ -> traceError "multiple assets mints not allowed"

you are sure that this minting policy will be valid only for that transaction and never again, and by checking amount == 1 you are sure that the sìtotal supply is, and will ever be, 1

Thank you for your answer! I think I was pretty much focused on the TxOutRef parameterization and how it would work.
But I checked the projects you pointed out in the answer and used SpaceBudz to understand the code, but for me, I couldn't find their off-chain code and found only their market. So went deeper and found out this gem
Which I think for me gives me a lot of insight, on how I could implement my own NFT collection.
Thanks again!

the offchain code can be written in any language as long the output is compatible with the protocol. in spacebudz the marketplace is the off-chain code, and it is written in javascript thanks to the cardano-serialization-lib

I see. I didn't know that.
Thank you again!


text:
How to consume and produce new UTXO to same script with different Datum?
I am trying to consume old UTXO at stript and produce new one with new Datum.
Validator is validating ok but not sure why new utxo with updated datum is not available.
current utxos holds one utxo with Datum DAccept
this is how i am constructing tx
let tx = collectFromScript  utxos redeemer  <>  Constraints.mustPayToTheScript DRecv tAmt

TxConstraint looks something like this
TxConstraints {
  txConstraints = [MustIncludeDatum (Datum {getDatum = Constr 2 []})], # constr 2 = DRecv
  txOwnInputs = [
     InputConstraint {icRedeemer = ReceiveItem \"key_C1\", icTxOutRef = TxOutRef {
       txOutRefId = a3d3cac6f6c2c2c9152baaa97e1f807dbdeee3ff7f1b47d0cfc1d3b6329091e5, txOutRefIdx = 1}
     }],
   txOwnOutputs = [
      OutputConstraint {ocDatum = DRecv, ocValue = Value (Map [(,Map [(\"\",20000000)])])}
   ]
}

Redeemer looks something like this
 ReceiveItem k ->
   traceIfFalse  "Must output DRecv datum" (isScriptOpHasDatum DRecv)  &&
   traceIfFalse  "Must have Datum" (dtm == DAccept)  &&

 scriptOutput :: TxOut
 scriptOutput = case getContinuingOutputs ctx of
   [o] -> o
     _ -> traceError "More than one outputs"

 scriptOutputDtm :: Maybe  DeliveryStatus
     scriptOutputDtm = do
       dtmHash <-  txOutDatum  scriptOutput
      Datum d <-  findDatum dtmHash info

     PlutusTx.fromBuiltinData  d

 isScriptOpHasDatum :: DeliveryStatus -> Bool
 isScriptOpHasDatum d = scriptOutputDtm  == Just d

above redeemer is working fine but tx is not producing new output with DRecv Datum

could you please share what the isScriptOpHasDatum function is doing?

@Michele sure its just checks if datum is there in output. added code

Issue was in another validation i was not calculating inputs correctly, its solved now thanks.

Hi Piyush, it will help us a lot if you can share with the community the solution to your problem in a post. Thank you.

my issue was i didn't log much Trace in TraceConfig so it was not giving another TraceError above code is fine


text:
What is the best way to query stake pools by ticker?
As a developer, I'd like to have a service that retrieves the information of a stake pool based on its ticker (or all the stake pools with that ticker, I know there can be duplicates).
I'm thinking that with graphql I need to query first the list of stakePools (which is huge) and then filter that by ticker, which is inside the metadata of the pool.
Is there a way to do this in a more performing way or a service already solving this for me?

The list of stake pools should only be a couple of thousand which is tiny in comparison to number of blocks or even worse the number of transactions.
It can be done with a relatively simple SQL query on the database maintained by cardano-db-sync.

Is it possible to query the ticker of a pool directly from the db? Or should I have to get first the URL of the metadata? I understand that the ticker is not a field in the stake pools database. Am I right? Thank you.

The ticker is stored in the db. You want the ticker_name field of the pool_offline_data table,


text:
How to completely uninstall Daedalus from Linux?
What is the most easy and straight-forward way of uninstalling Daedalus from Linux?

Access the terminal and run the following group of commands depending on the instance of Daedalus you want to uninstall.
Mainnnet
chmod -R +w ~/.daedalus
rm -rf ~/.local/bin/daedalus-mainnet
rm -f ~/.local/share/applications/Daedalus-mainnet.desktop
rm -rf ~/.config/Daedalus\ Mainnet
rm -rf ~/.local/share/Daedalus/mainnet

Flight
chmod -R +w ~/.daedalus
rm -rf ~/.local/bin/daedalus-mainnet_flight
rm -f ~/.local/share/applications/Daedalus-mainnet_flight.desktop
rm -rf ~/.config/Daedalus\ Flight
rm -rf ~/.local/share/Daedalus/mainnet_flight

Testnet
chmod -R +w ~/.daedalus
rm -rf ~/.local/bin/daedalus-testnet
rm -f ~/.local/share/applications/Daedalus-testnet.desktop
rm -rf ~/.config/Daedalus\ Testnet
rm -rf ~/.local/share/Daedalus/testnet

All Networks at once
chmod -R +w ~/.daedalus
rm -rf ~/.local/bin/daedalus* ~/.daedalus
rm -f ~/.local/share/applications/Daedalus*.desktop
rm -rf ~/.config/Daedalus*
rm -rf ~/.local/share/Daedalus


text:
Get Transaction History Given Policy ID using Blockfrost API
What's the best say to get the transaction history of an NFT collection given the policy id? I looked into Asset Transactions but this requires both policy ID and the asset ID. Is there something else I am missing? Or should I loop through each asset and see if there is a transaction? Seems super tedious though..
https://cardano-mainnet.blockfrost.io/api/v0/assets/{asset}/transactions

Unfortunately Blockfrost currently requires the concatenated policy and asset name to query asset transactions but you can use the Koios API instead with just the policyId since the asset name is optional.


text:
How to specify the Cardano address for BlockFrost Transaction Endpoint?
Hi im trying to call this https://docs.blockfrost.io/#tag/Cardano-Addresses/paths/~1addresses~1{address}~1transactions/get from some code I wrote (images attached below) and get a None or Empty value returned.
I am using the receiving address from my wallet and am wondering if I'm using the wrong address? how should I find the right one?
Below is the output of some print statements I wrote:
endpoint:
addresses/addr1q8mw47vt7kf69ze5x92luhrxvk0p2vpd0emvhlg704u7cttdrr3j8j5k5yacga4ckv6lnx4p0la57q7nf24eszqk0r2q59elsd/transactions
Full Request:
https://cardano-mainnet.blockfrost.io/api/v0/addresses/addr1q8mw47vt7kf69ze5x92luhrxvk0p2vpd0emvhlg704u7cttdrr3j8j5k5yacga4ckv6lnx4p0la57q7nf24eszqk0r2q59elsd/transactions
Returned Value: None

Going by your question I will assume you are trying to get the transaction history of your wallet? The endpoint you are using requires an address previously associated with a transaction, and an unused receiving address won't return anything.
Your wallet consists of multiple UTxOs across multiple addresses, and that information is persisted locally by the wallet software so it's easy to obtain details like the transaction history. However in the context of statelessly querying Blockfrost you will have to retrieve all these addresses using the Account associated addresses
endpoint and then query the transactions per address. It might be a little easier using the Koios API because the resource takes an array of addresses but there is no easy way to achieve what you want at the moment.


text:
How to convert Cardano Address?
Cardano has a number of different types of address from receiving address to enterprise address and many others.
My question is in two parts:

where can I find an exhaustive list of all address types?

given an address how can I get all other address connected to it?

Example given a receive address how do I get the stake address or the address blockfrost uses?

About address formation and extracting Stake keys, you can read the CIP-0019

*Edit: this was reply to old question (about address, not address type) : This question does not make sense - you can have close to infinite addresses, you can only query addresses that have been used on chain (even then, you should be able to work your workflow logic a bit better than to scan millions of addresses on chain). If you're only interested in grabbing stake key from an address already on chain i.e. has a transaction against it - while using blockfrost, use this endpoint.As regards address types, you can find the CIP above for common ones , while all concepts listed in docs here

You can use the left sidebar on API docs for available endpoints, for the specific query for Account, you can use this endpoint.

Slightly changed the question, does it make better sense now? What else do you think adds confusion? I'm happy to change it as the question might help someone else later on

Yip - question now is correct (tho now my answer to point 1 doesnt make sense) =] edited the reply accordingly

Thanks man appricate that


text:
Socket permission denied when running cardano node as linux service
I've successfully setup and running cardano node from terminal. Now I've setup cardano node to run as service(systemd, Ubuntu) so that I don't have to run the command all the time and have a terminal always open. From journalctl log all looks good, and I have check tip is reached using explorer.cardano.org. However, I now get error when using cardano-cli and I cannot figure out why...
Details
Cardano-cli error message
Network.Socket.connect: <socket: 11>: permission denied (Permission denied)
ls command

srwxr-xr-x 1 root root      0 juni  26 23:45 node.socket=

.service file
[Unit]
Description=Runs cardano-node mainnet
After=network-online.target
StartLimitIntervalSec=0
[Service]
Type=simple
Restart=always
RuntimeMaxSec=432000
User=root
ExecStart=/home/toby/cardano-scripts/run-cnode-main.sh
[Install]
WantedBy=multi-user.target
run-cnode-main.sh
#!/bin/bash
#Start cardano-node on mainnet
/home/toby/.local/bin/cardano-node run --config /home/toby/cardano-main/mainnet-config.json --database-path /home/toby/cardano-main/db/ --socket-path /home/toby/cardano-main/db/node.socket --host-addr 127.0.0.1 --port 1337 --topology /home/toby/cardano-main/mainnet-topology.json

Stop using root (for interactive as well as systemd startup user), it's a terrible idea to run applications
You cannot (*should not) run something as another user and point to paths in your own $HOME folder, this will more often than not only lead you to permission errors.
I assume node.socket= was a typo, if not - your start command does not match $CARDANO_NODE_SOCKET_PATH environment variable.

While you can now address the state by recursively fixing permissions, you've likely populated environment variables, build caches, profiles, etc across a mix of root and toby user, you might want to start from scratch and not run anything to do with cardano-node.

Thanks for the reply!

Okay, I am no linux expert:) I just followed some tutorial online, however I saw that there were some cardano tutorials that created an own user for cardano node. I will look into that.

Noted.

This was actually not a typo. I found this a bit weird, because I could not recall the socket filename had an = when running command line directly. However, now I don't understand why I do not get a "cannot find socket" error instead... My $CARDANO_NODE_SOCKET_PATH points to a file without the =

If there are online tutorials using root, I think it's potentially good to highlight bad practices to them (if they've a way to contact on their pages).
About 3, if it wasnt a typo, then perhaps one of your earlier attempts to run cardano-node may have accidentally had an = sign after socket. Once you stop all instances of node running, you should be alright

Okay, I will try to delete the db folder and have a new go for scratch. Thanks for the input @RdLrT!


text:
Stuck in cardano node
Running any cardano-cli command returns this error,Cardano-node is already running in another terminal,CARDANO_NODE_SOCKET_PATH is set in environment variable. Confirmed through echo. It leads to node.socket file white_check_mark eyes raised_hands

Did you update your terminal with source ~/.bashrc?

Verify that your current user can read the socket file with ls -l $CARDANO_NODE_SOCKET_PATH

As per my comment, verify that your current user can see the socket file with ls -l $CARDANO_NODE_SOCKET_PATH
The error that you see will be due to either:

The node is not running (but you confirmed that it is running so not that)
Environment variable CARDANO_NODE_SOCKET_PATH is not set for the current user (but you confirmed that it has a value)
CARDANO_NODE_SOCKET_PATH having a value that is different to the actual path of the socket file

Most likely is option 3 which could be due to a typo when setting CARDANO_NODE_SOCKET_PATH
Another possibilty is that the current user might not have permission to read the socket file, but the error normally states if there is a permissions issue so I don't think it's that in your case.


text:
How can I see if an UTxO holds an NFT in the postgres DB?
Is it possible to find out if an UTxO on the tx_out postgres table holds an NFT? OR in generell which kind of asset this UTxO holds?
Thank you!

Assuming that an NFT is implemented as a multiasset (pretty sure that is not the only way) then this is relatively trivial:
select * from ma_tx_out where tx_out_id = <insert your tx_out id here> ;


text:
How To Get All Transactions of Associated With an Address In A Given Interval?
okay so given some reciving address such as addr1qxq7k07cnt8vstdmygu7lpw0tyyssu4trs27qq6f7xjpmvrdrr3j8j5k5yacga4ckv6lnx4p0la57q7nf24eszqk0r2q9axgqv how can I use a service like BlockFrost (or any other API) to get a list of all transactions associated with that address during a time interval between T and T+N ?
I am only concerned with some parts of the data and don't require the full info (i.e. not like Cardano Scan). The things I'm interested in are:

time of the transaction
assets received/sent (only the ones that moved not the full UTXO list)
Counter Party Address
quantity of each token moved

Have  a look at https://github.com/txpipe/oura or https://github.com/txpipe/scrolls

Okay thanks I'll do that

I had a look, but I would like to ask if there's anything for python. I have already written a lot of code in python that I want to easily be compatible with.

The address mentioned does not have any transactions associated with it.
If you're talking about transactions against account (not addresses, you can derive account by decoding bech32, and extracting keys as already asked in this post ):

get list of addresses known on chain using account address (example here )
Post those addresses to grab transaction (example here
Post returned tx to query tx_info (example endpoint here, where you can also specify _after_block_height and use verticle/horizontal filters to extract only information you need)


text:
How to create an unspent UTXO with specific value
I want to create a script (smart-contract) utxo with a specific number of tokens (it can be an output of a transaction before) in cardano-serialization-lib - javascript. I need this utxo to be part of a future output of a transaction. How can I do this?
-- Scenario to explain better --
Imagining a scenario where we have a smart contract feeded with 1000 tokens. Then, I want to send 30 tokens for a client (when he claims these tokens). If I want to have an UTXO with only these 30 tokens, I have to create an output before that transaction (for example, when the user locks an asset, the output for the smart contract will be the asset + 30 tokens), but these tokens are not an input from the client, is "from smart contract to smart contract".

You can follow this example on how to generate a transaction using Cardano Serialization Lib.
For your specific question, focus on the following section of the code that will help you create an output with the ada value you like:
// add output to the tx
txBuilder.add_output(
    CardanoWasm.TransactionOutput.new(
    shelleyOutputAddress,
    CardanoWasm.Value.new(CardanoWasm.BigNum.from_str('1000000'))
    ),
);

If you also like to add assets to that output, you can try this code:
  const outputAddress = CardanoWasm.Address.from_bech32(toAddress);

  var txOutputBuilder = CardanoWasm.TransactionOutputBuilder.new();
  txOutputBuilder = txOutputBuilder.with_address(outputAddress);
  var txOutputAmountBuilder = txOutputBuilder.next();

  const multiAsset = CardanoWasm.MultiAsset.new()

  const assets = CardanoWasm.Assets.new()
  assets.insert(
    CardanoWasm.AssetName.new(Buffer.from(assetName, "hex")), // Asset Name
    CardanoWasm.BigNum.from_str(amount) // How much to send
  );
  multiAsset.insert(
    CardanoWasm.ScriptHash.from_bytes(Buffer.from(policy, "hex")), // PolicyID
    assets
  );

  txOutputAmountBuilder = txOutputAmountBuilder.with_asset_and_min_required_coin(multiAsset, CardanoWasm.BigNum.from_str(params.data.genesis.alonzo.lovelacePerUTxOWord.toString()))
  const txOutput = txOutputAmountBuilder.build();

This second example is more in line with what is being used recently to create transactions and outputs in Cardano (TransactionOutputBuilder object).

Hey! Thanks for your answer. I was wondering if I explain well my question, because I already have this code. However, I want to create an output of a smart contract (a script) that will be an UTXO (without input provided), I mean, an output to the smart contract itself. Then, I can use this UTXO with this specific number of tokens to send to a client that is interacting with the smart contract.

I added a scenario on the question to be more easier to explain what I want

But... can't you just create the UTxO with the 30 tokens + the asset when the user "locks" that asset? That way, you will have generated a new UTxO with 30 tokens + 1 locked asset + some ada, in that same smart contract, for future use at some point in time.

BTW, you can't generate an output without an input since UTxOs are static: they only get spent by a trigger. The triggers are the inputs.

Yes Falcon, it is that I want (30 tokens + the asset + some ada). But this way I have to make some thing like: input -> 1000 tokens from smart contract ; output -> 30 tokens to smart contract ? but I have to spent the rest to the smart contract? how can I make this?

You don't have to spend the rest of the UTxO in the smart contract if you do that. You can just consume the UTxO with 1000 tokens and generate the one you need with 30 tokens (as I explained before). Then the remaining 970 tokens will be automatically sent to ANOTHER UTxO, in the same contract, as change for your transaction. Is this clear?

Yes @Falcon thanks. In the continuation of this question, I made a new one : https://cardano.stackexchange.com/q/8606/6611 if you can help me I will appreciate it.


text:
How can db-sync "match" a data_hash to specific outputs?
Looking at the db-sync schema, I see the tx_out table has a data_hash column, but I can't make sense of why this column is not on the tx table instead. From the Alonzo CDDL, I can see the scripts are part of the transaction_witness_sets, which is part of the block, so I don't see how one could match a script data from a witness to an output in a transaction.

According to CDDL, the transaction output itself has a data_hash: https://github.com/input-output-hk/cardano-ledger/blob/37322df14d44d1370e8a72b677815d64a92baa00/alonzo/test/cddl-files/alonzo.cddl#L73
PS: I can't believe I missed that...


text:
Metadata and Mithril
From my understanding you need to run a full node to add metadata to a txn.
Will it be possible to do this without a full node using Mithril?

You do not need a full node to add metadata to a transaction. Most wallets have this function, for example the wallet Eternl has it.

ok great thanks for clearing up.


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 Convert Old Plutus Scripts to Vasil Reference Scripts?
One of the fun things, the Vasil hardfork gives us is the ability to reduce the size of transactions and so put more of them into a block (speeding up the chain).
My question is how to change the preexisting Plutus smart contracts I have written to take advantage of this? I think the following would be nice to have if you could point me to them please:

example of an old plutus contract and its vasil counterpart (highlighting the changes made and why)

A list of all possible changes I could make.

The existing V1 Plutus script just needs to be recompiled and serialised as V2. See this example of a minting policy serialised as both V1 and V2 for guidance, https://github.com/james-iohk/plutus-scripts/blob/master/src/TokenNamePolicy.hs.
Then you can create an output with the V2 script attached to be referenced in a transaction. See example using cardano-cli here: https://github.com/input-output-hk/cardano-node/blob/master/scripts/babbage/example-babbage-script-usage.sh


text:
What is the purpose of use using Cardano-graphql & hasura in the same stack?
I'm in the process of writing some software that will connect to the Cardano networking such as signing transactions & querying historical chain data. During my search for a solution I came across Hasura, which I planned to hook up postgres (using cardano-db-sync as well) to.
Later down the road I found Cardano-graphql in the inputoutput github account & noticed in the reference docker file here that the developers have also chosen to include Hasrua which is also a graphql api.
What is the purpose of this? Do I need both? What is the benifit of using cardano-graphql & hasura as shown in the docker-compose.yml file.

Hasura is a cloud service where you can deploy cardano-graphql in a very easy and straight forward way, since it is oriented to graphql APIs.
So no, you don't need both.
cardano-graphql is very expensive to use in matter of resources so depending on the type of queries you want to do to the blockchain, maybe you need a service like Blockfrost.


text:
How to convert Address type variable to get "addr_testXXX" format address?
In plutus endpoint, I want to convert Address type value to get addr_testXXX format address.
I have try :
import Cardano.Api  ( SerialiseAddress (deserialiseAddress, serialiseAddress) )
  ...
-- here, var 'testAddr' is of 'Address' type
printf "ledger address is: %s"  $ show $ serialiseAddress testAddr

but it raised error when compiling:
    • No instance for (SerialiseAddress
                         plutus-ledger-api-0.1.0.0:Plutus.V1.Ledger.Address.Address)
        arising from a use of ‘serialiseAddress’

From google, I found this: https://github.com/functionally/mantis/blob/1cd121202452dcc1bce56ed4b4f41f0e880c9d04/src/Mantra/Wallet.hs#L56
It seem that I should convert Address to AddressAny, but don't know how to.
Any help will be appreciated!

Have you tried converting using this: https://github.com/input-output-hk/cardano-node/blob/master/cardano-api/src/Cardano/Api/Address.hs#L455

I think you actually want toAddressAny : https://github.com/input-output-hk/cardano-node/blob/master/cardano-api/src/Cardano/Api/Address.hs#L470

Here is a demo in Java:
public String swapAddress(String address) {
    byte[] bech = Bech32.decode(address).data;
    byte[] conv = Utils.convertBits(bech, 5, 8, false);
    conv = Bytes.sub(conv, 0, conv.length - 1);
    int networkId = conv[0] & 0x0F;
    String hrp = "";
    if (networkId == 0) {
        hrp = "addr";
        networkId = 1;
    } else {
        hrp = "addr_test";
        networkId = 0;
    }
    conv[0] = ((byte) networkId);
    byte[] data = Utils.convertBits(conv);
    return Bech32.encode(hrp, data);
}

You can find the convertBits here and Bech32 here.
For Cardano, Bech32 #152 & #153 are unnecessary.

Thanks for your kindly help. But I write plutus code and looking forward to haskell example.

Recently I am also looking at this issue as well, digging around different resources and find out 3rd Cohort PPP's week6, where Lars has demonstrated how to do it: https://github.com/input-output-hk/plutus-pioneer-program/blob/main/code/week06/src/Week06/Utils.hs
In particular, I just tried out it works to get the PaymentPubKeyHash from Bech32 Address through the below code snippet.
unsafeReadAddress :: String -> Plutus.Address
unsafeReadAddress s = fromMaybe (error $ "can't parse " ++ s ++ " as an address") $ tryReadAddress s

credentialLedgerToPlutus :: Ledger.Credential a StandardCrypto -> Plutus.Credential
credentialLedgerToPlutus (ScriptHashObj (Hash.ScriptHash h)) = Plutus.ScriptCredential $ Plutus.ValidatorHash $ toBuiltin $ hashToBytes h
credentialLedgerToPlutus (KeyHashObj (KeyHash h))       = Plutus.PubKeyCredential $ Plutus.PubKeyHash $ toBuiltin $ hashToBytes h

tryReadAddress :: String -> Maybe Plutus.Address
tryReadAddress x = case deserialiseAddress AsAddressAny $ pack x of
    Nothing                                      -> Nothing
    Just (AddressByron _)                        -> Nothing
    Just (AddressShelley (ShelleyAddress _ p _)) -> Just Plutus.Address
        { Plutus.addressCredential        = credentialLedgerToPlutus p
        , Plutus.addressStakingCredential = Nothing
        -- , Plutus.addressStakingCredential = stakeReferenceLedgerToPlutus s
        }

getCredentials :: Plutus.Address -> Maybe (Plutus.PaymentPubKeyHash, Maybe Plutus.StakePubKeyHash)
getCredentials (Plutus.Address x y) = case x of
    ScriptCredential _   -> Nothing
    PubKeyCredential pkh ->
      let
        ppkh = Plutus.PaymentPubKeyHash pkh
      in
        case y of
            Nothing                        -> Just (ppkh, Nothing)
            Just (Plutus.StakingPtr _ _ _) -> Nothing
            Just (StakingHash h)           -> case h of
                ScriptCredential _    -> Nothing
                PubKeyCredential pkh' -> Just (ppkh, Just $ Plutus.StakePubKeyHash pkh')

unsafePaymentPubKeyHash :: Plutus.Address -> Plutus.PaymentPubKeyHash
unsafePaymentPubKeyHash addr = maybe (error $ "script address " ++ show addr ++ " does not contain a payment key") fst $ getCredentials addr

i.e. I skipped the staking credential part coz seems part of the code is deprecated, still under investigation. But the PaymentPubKeyHash part works fine for me.

You can use the function (1) in Cardano.Api,
makeShelleyAddress :: NetworkId → PaymentCredential → StakeAddressReference → Address ShelleyAddr

The resulting address of type Address ShelleyAddr has an instance of SerialiseAddress (2) so you can use
serialiseAddress ∷ Address ShelleyAddr → Text

on it.


text:
How to Access Secret Key Hash and PKH from a web wallet?
So I'm making a Dapp that uses the user's secret key to encrypt the data. It also allows another user to encrypt something else using their public key hash, but how do I get the key pairs from the web wallet integrated with my Dapp?

You can't directly access private keys of your users; those should reside safely in their wallet only.
There is, however, a way you can have their wallet use those keys to sign data that you pass over.
This is described in CIP 30: https://cips.cardano.org/cips/cip30/#apisigndataaddraddresspayloadbytespromisedatasignature
You call this function in the browser like so:
window.cardano.signData(Address, HexMsgToSign)

The wallet will then open a window showing the message and asking the user to sign, and return the signature.

You can't access the secret/private key of a wallet connected to your web site.


text:
How to store scripts using blockfrost?
Greeting!
I got that Blockfrost has API to get plutus script hash but how to store those scripts hashes?
P.S. if I got script hash, can I build and send transaction using script's hash and Blockfrost?

You can't store scripts using blockfrost.
blockfrost only queries the blockchain and has an endpoint to submit transactions.
when you retrieve a script hash using blockforst you are querying the blockchain
in order to "store" a script on-chain you first have to interact with that script so that the blockchain knows it exists.
the section 6 of lesson 3 of the plutus-pioneer-program iteration 3 shows you how to create such a transaction using cardano-cli


text:
Is it possible to consume a script UTxO in the same block?
Let's say I lock some ADA at a script address. Someone who knows the redeemer value can unlock this ADA. Is it possible to include a redeeming tx in the same block as the tx which locks the ADA at the script address? Provided that the script tx was first in the mempool? Or is it necessary to wait at least for 1 confirmation before the ADA can be unlocked from the script address?

If the first output is in the mempool, you can use it in a subsequent transaction without the node throwing an error. However, there is no assurance that both transactions will be part of the same block.

When would be such case that both the transactions wouldn't be included in the same block? For example under heavy blockchain load?

I'm not sure of the exact scenario, I believe it works like first come first serve basis, so    all trxs in mempool may not fit in one block