text:
Unable to build project using latest version of plutus-apps using nix develop
When I run cabal repl on my project using nix develop I get the following error:
Warning: Requested index-state 2023-02-20T00:00:00Z is newer than
'hackage.haskell.org'! Falling back to older state (2023-02-19T23:48:00Z).
Warning: Requested index-state 2022-12-22T00:00:00Z is newer than
'cardano-haskell-packages'! Falling back to older state
(2022-12-13T23:38:19Z).
Resolving dependencies...
cabal: Could not resolve dependencies:
[__0] trying: cardano-node-emulator-1.2.0.0 (user goal)
[__1] unknown package: quickcheck-contractmodel (dependency of
cardano-node-emulator)
[__1] fail (backjumping, conflict set: cardano-node-emulator,
quickcheck-contractmodel)
After searching the rest of the dependency tree exhaustively, these were the
goals I've had most trouble fulfilling: cardano-node-emulator,
quickcheck-contractmodel

Here is my cabal.project file:
-- Custom repository for cardano haskell packages
-- See https://github.com/input-output-hk/cardano-haskell-packages on how to use CHaP in a Haskell project.
repository cardano-haskell-packages
  url: https://input-output-hk.github.io/cardano-haskell-packages
  secure: True
  root-keys:
    3e0cce471cf09815f930210f7827266fd09045445d65923e6d0238a6cd15126f
    443abb7fb497a134c343faf52f0b659bd7999bc06b7f63fa76dc99d631f9bea1
    a86a1f6ce86c449c46666bda44268677abf29b5b2d2eb5ec7af903ec2f117a82
    bcec67e8e99cabfa7764d75ad9b158d72bfacf70ca1d0ec8bc6b4406d1bf8413
    c00aae8461a256275598500ea0e187588c35a5d5d7454fb57eac18d9edb86a56
    d4a35cd3121aa00d18544bb0ac01c3e1691d618f462c46129271bccf39f7e8ee

index-state: 2023-02-20T00:00:00Z

-- See CONTRIBUTING.adoc for how to update index-state
index-state:
  , hackage.haskell.org 2023-02-20T00:00:00Z
  , cardano-haskell-packages 2022-12-22T00:00:00Z

packages: game

-- We never, ever, want this.
write-ghc-environment-files: never

-- Always build tests and benchmarks.
tests: true
benchmarks: true

-- The only sensible test display option, since it allows us to have colourized
-- 'tasty' output.
test-show-details: direct

allow-newer:
  -- cardano-ledger packages need aeson >2, the following packages have a
  -- too restictive upper bounds on aeson, so we relax them here. The hackage
  -- trustees can make a revision to these packages cabal file to solve the
  -- issue permanently.
  , ekg:aeson
  , ekg-json:aeson
  , openapi3:aeson
  , servant:aeson
  , servant-client-core:aeson
  , servant-server:aeson

constraints:
  -- cardano-prelude-0.1.0.0 needs
  , protolude <0.3.1

  -- cardano-ledger-byron-0.1.0.0 needs
  , cardano-binary <1.5.0.1

  -- plutus-core-1.0.0.1 needs
  , cardano-crypto-class >2.0.0.0
  , algebraic-graphs <0.7

  -- cardano-ledger-core-0.1.0.0 needs
  , cardano-crypto-class <2.0.0.1

  -- cardano-crypto-class-2.0.0.0.1 needs
  , cardano-prelude <0.1.0.1

  -- dbvar from cardano-wallet needs
  , io-classes <0.3.0.0

  -- newer typed-protocols need io-classes>=0.3.0.0 which is incompatible with dbvar's constraint above
  , typed-protocols==0.1.0.0

  , aeson >= 2

  , hedgehog >= 1.1

  , resource-pool <0.4.0.0

  , http2 <4.0.0

-- The plugin will typically fail when producing Haddock documentation. However,
-- in this instance you can simply tell it to defer any errors to runtime (which
-- will never happen since you're building documentation).
--
-- So, any package using 'PlutusTx.compile' in the code for which you need to
-- generate haddock documentation should use the following 'haddock-options'.
package plutus-ledger
  haddock-options: "--optghc=-fplugin-opt PlutusTx.Plugin:defer-errors"
package plutus-script-utils
  haddock-options: "--optghc=-fplugin-opt PlutusTx.Plugin:defer-errors"
package plutus-contract
  haddock-options: "--optghc=-fplugin-opt PlutusTx.Plugin:defer-errors"

-- These packages appear in our dependency tree and are very slow to build.
-- Empirically, turning off optimization shaves off ~50% build time.
-- It also mildly improves recompilation avoidance.
-- For dev work we don't care about performance so much, so this is okay.
package cardano-ledger-alonzo
  optimization: False
package ouroboros-consensus-shelley
  optimization: False
package ouroboros-consensus-cardano
  optimization: False
package cardano-api
  optimization: False
package cardano-wallet
  optimization: False
package cardano-wallet-core
  optimization: False
package cardano-wallet-cli
  optimization: False
package cardano-wallet-launcher
  optimization: False
package cardano-wallet-core-integration
  optimization: False

source-repository-package
  type: git
  location: https://github.com/input-output-hk/plutus-apps.git
  tag: cc144a86
  subdir:
    cardano-node-emulator
    cardano-streaming
    doc
    freer-extras
    marconi-chain-index
    marconi-core
    marconi-sidechain
    pab-blockfrost
    plutus-chain-index-core
    plutus-chain-index
    plutus-contract
    plutus-contract-certification
    plutus-e2e-tests
    plutus-example
    plutus-ledger
    plutus-pab-executables
    plutus-pab
    plutus-script-utils
    plutus-tx-constraints
    plutus-use-cases

-- Direct dependency.
-- Compared to others, cardano-wallet doesn't bump dependencies very often.
-- Making it a good place to start when bumping dependencies.
-- As, for example, bumping the node first highly risks breaking API with the wallet.
-- Unless early bug fixes are required, this is fine as the wallet tracks stable releases of the node.
-- And it is indeed nice for plutus-apps to track stable releases of the node too.
--
-- The current version is dated 2022/08/10
source-repository-package
    type: git
    location: https://github.com/input-output-hk/cardano-wallet
    tag: 18a931648550246695c790578d4a55ee2f10463e
    subdir:
      lib/cli
      lib/core
      lib/core-integration
      lib/dbvar
      lib/launcher
      lib/numeric
      lib/shelley
      lib/strict-non-empty-containers
      lib/test-utils
      lib/text-class

-- Direct dependency.
source-repository-package
    type: git
    location: https://github.com/Quviq/quickcheck-contractmodel
    tag: cc43f13f98c704e0d53dbdef6a98367918f8c5c1
    subdir:
      contractmodel

-- Should follow cardano-wallet.
source-repository-package
    type: git
    location: https://github.com/input-output-hk/cardano-addresses
    tag: b7273a5d3c21f1a003595ebf1e1f79c28cd72513
    subdir:
      -- cardano-addresses-cli
      command-line
      -- cardano-addresses
      core

-- This is needed because we rely on an unreleased feature
-- https://github.com/input-output-hk/cardano-ledger/pull/3111
source-repository-package
    type: git
    location: https://github.com/input-output-hk/cardano-ledger
    tag: da3e9ae10cf9ef0b805a046c84745f06643583c2
    subdir:
      eras/alonzo/impl
      eras/alonzo/test-suite
      eras/babbage/impl
      eras/babbage/test-suite
      eras/byron/chain/executable-spec
      eras/byron/crypto
      eras/byron/crypto/test
      eras/byron/ledger/executable-spec
      eras/byron/ledger/impl
      eras/byron/ledger/impl/test
      eras/shelley/impl
      eras/shelley/test-suite
      eras/shelley-ma/impl
      eras/shelley-ma/test-suite
      libs/cardano-ledger-core
      libs/cardano-ledger-pretty
      libs/cardano-protocol-tpraos
      libs/cardano-data
      libs/vector-map
      libs/set-algebra
      libs/small-steps
      libs/small-steps-test
      libs/non-integral

Can anyone help?

Can you share your .project file?

@FalconStakepool: I've added the cabal.project file.

Q1. Doesn't GHC comes with the Nix env binaries?
Q2. Did the original question got a solution?

Hi @user11782, please do not post questions as answers. If you have questions that are not answered here, feel free to open a new question where you describe the problem you have. This way the chance of getting help is a lot bigger.

The problem was that a ghc must be installed globally before you try to build plutus-apps.

I hope you have ran cabal update and cabal build before running cabal repl in the root folder of your project. These must be ran in the nix-shell obtained from running nix-develop in the plutus-apps folder and then navigating to your project directory.


text:
Where to find proper info on the cardano graphql
I am new to Cardano and have setup the GraphQL node
All is running, but my problem is I can not find proper info on how to actually get the data.
What I would like to query is asset data and smart contract data.
Lets say there is an Cardano DEX, they work with some smart contract and liquidity pool, i would like to get data on what pools and calculate a price from that.
Btw, I try to build a simple Cardano DEX tool with MERN stack.
Any help, any pointing to the right direction is welcome.
-- UPDATE --
So, lets say I need to calculate a pair price which is done from an liquidity pool of a DEX. How to get that data?
Or I want to get sell/buy orders from a DEX.
I know how this works for eth and bsc, all those have awesome documentation, but Cardano is not really made well for new coming dev's to the Cardano blockchain.

I'm not sure if you have explored their wiki yet, it has guide how to interact with their api:
Interacting with the API
You can also check their API Documentation:
API Documentation
They've got a bunch of samples too:
Example Queries

Hi, thanks for your answer. I know all those pages, but non give me the info I need to get the job done.

how do you like this?
i really liked the source of info here:
https://github.com/input-output-hk/cardano-graphql

That's the node I have running, but the documentation is so bad for beginners.

source: Stack Exchange

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

sort: votes


text:
How can a single Cardano Wallet have many addresses?
I'm new to Cardano and would like to know about this blockchain. I'm from Ethereum and I use Metamask as my "wallet" for it. I usually have one address only for one Metamask wallet. I'm curious to know how a Cardano wallet (say Yoroi) achieve multiple addresses when it's a single wallet only (I can make multiple wallets in Yoroi, yes, but a single wallet can generate multiple addresses, and I'm curious how that works; I'm also wondering if it's really possible in the first place and Metamask just doesn't do it).
Maybe I have misunderstood wallet addresses to receiving addresses, so any clarifications would be helpful.

Your “wallet” is really just a private key that only you know. You can use that key to deterministically generate many addresses, each address with a unique index. But no one can derive those addresses for you without knowing your private key.
This is similar to something like SSH, where you have a private/public key pair, but you can have public key 1, public key 2, public key 3, etc.
When you add your private key to Yoroi, the wallet app can regenerated all your addresses for you and check each of them for UTxOs. If it checks the first (let's say) 50, and they all have UTxOs owned by them, the wallet app will keep generating more until it doesn’t find any more funds (in theory you could use your private key outside the wallet app and generate an address for index 1000000+, and if you have funds sent to that address they might not show up on Yoroi, but you would still own them). This total at all of your addresses is your total balance.
Generating addresses like this is great for privacy, since it’s hard for people other than you to determine which addresses are associated with each other. But not entirely impossible with off-chain data.
Bitcoin works in a similar way.

Wallet addresses are public keys mathematically derived from private keys and encoded to a special format. The ability of a wallet to generate multiple addresses is determined by the implementation of a method known as Hierarchy for Deterministic Wallets (HD), originally introduced in BIP-32 for Bitcoin.
When using such a wallet, a root private key is created and, from it, multiple child public keys can be derived.  The public keys are linked to that private key which means that funds received in these addresses can be spent using that single private key. In Cardano, Yoroi is a HD wallet.
You can get some more technical details on how addresses are created in Cardano: Here and Here

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


text:
Airdrop Mechanism
I'm trying to find information about native token Airdrops. What is the mechanism?
For example, the user send 5 ADA to the wallet of the project and the smart contract will send you back (2.5 x Amount of ADA) of $NATIVETOKENS.
Is there a simple mechanism for this or it needs a smart contract?
How are distributed for example the Meld Tokens? Or the WMT?

I was also searching for this info, but I was not able to find the answer how this is done. Same mechanism is used for an example for the Spacecoins or the newest one Hosky. I do not think you need smart contract for this but I am not sure.
I think this is simply done by the bash script running on some server with synced wallet. You can basically monitor your wallet, once you will receive the ADA you can filter the wallet ID using cli and construct outgoing transaction. And that's it.

Yes that's basically a vending machine script.  There are some scripts available in github

Can you please give some examples and post a few links? Short answers get flagged as the low-quality posts.


text:
MacOS nix-shell (fail) after cd marlowe-cardano
I followed the instructions for MacOS setup from here:
How can I set up my environment for the upcoming Marlowe Pioneer Program?
... which worked well up until
cd marlowe-cardano
$ nix-shell
MacOS version: 12.3.1 Monterey.
... nix-shell worked for a while, installing until it failed:
Preprocessing library for plutus-ledger-constraints-0.1.0.0..
Building library for plutus-ledger-constraints-0.1.0.0..
[1 of 4] Compiling Ledger.Constraints.TxConstraints ( src/Ledger/Constraints/TxConstraints.hs, dist/build/Ledger/Constraints/TxConstraints.o, dist/build/Ledger/Constraints/TxConstraints.dyn_o )
[2 of 4] Compiling Ledger.Constraints.OnChain ( src/Ledger/Constraints/OnChain.hs, dist/build/Ledger/Constraints/OnChain.o, dist/build/Ledger/Constraints/OnChain.dyn_o )
[3 of 4] Compiling Ledger.Constraints.OffChain ( src/Ledger/Constraints/OffChain.hs, dist/build/Ledger/Constraints/OffChain.o, dist/build/Ledger/Constraints/OffChain.dyn_o )
: error:
: dlopen(/nix/store/7zv7cy150qlqrhn8jx4hwchmnj16c9fa-cardano-wallet-core-lib-cardano-wallet-core-2022.1.18-config/lib/links/libHSappar-0.1.8-KYad8eEAlRI90NAZOjuGzF-ghc8.10.4.20210212.dylib, 0x0005): cannot dlopen until fork() handlers have completed
[107 of 114] Compiling UnliftIO.Compat  ( src/UnliftIO/Compat.hs, dist/build/UnliftIO/Compat.o, dist/build/UnliftIO/Compat.dyn_o )
[108 of 114] Compiling Cardano.DB.Sqlite ( src/Cardano/DB/Sqlite.hs, dist/build/Cardano/DB/Sqlite.o, dist/build/Cardano/DB/Sqlite.dyn_o )
error: builder for '/nix/store/f4ybcf3n7hk2yfn375ikgz9r4l37nfa3-cardano-wallet-core-lib-cardano-wallet-core-2022.1.18.drv' failed with exit code 1;
last 10 log lines:
> [ 99 of 114] Compiling Data.Vector.Shuffle ( src/Data/Vector/Shuffle.hs, dist/build/Data/Vector/Shuffle.o, dist/build/Data/Vector/Shuffle.dyn_o )
> [101 of 114] Compiling Network.Wai.Middleware.Logging ( src/Network/Wai/Middleware/Logging.hs, dist/build/Network/Wai/Middleware/Logging.o, dist/build/Network/Wai/Middleware/Logging.dyn_o )
> [102 of 114] Compiling Network.Wai.Middleware.ServerError ( src/Network/Wai/Middleware/ServerError.hs, dist/build/Network/Wai/Middleware/ServerError.o, dist/build/Network/Wai/Middleware/ServerError.dyn_o )
> [105 of 114] Compiling Paths_cardano_wallet_core ( dist/build/autogen/Paths_cardano_wallet_core.hs, dist/build/Paths_cardano_wallet_core.o, dist/build/Paths_cardano_wallet_core.dyn_o )
> [106 of 114] Compiling Cardano.Wallet.Version ( src/Cardano/Wallet/Version.hs, dist/build/Cardano/Wallet/Version.o, dist/build/Cardano/Wallet/Version.dyn_o )
>
> : error:
>     : dlopen(/nix/store/7zv7cy150qlqrhn8jx4hwchmnj16c9fa-cardano-wallet-core-lib-cardano-wallet-core-2022.1.18-config/lib/links/libHSappar-0.1.8-KYad8eEAlRI90NAZOjuGzF-ghc8.10.4.20210212.dylib, 0x0005): cannot dlopen until fork() handlers have completed
> [107 of 114] Compiling UnliftIO.Compat  ( src/UnliftIO/Compat.hs, dist/build/UnliftIO/Compat.o, dist/build/UnliftIO/Compat.dyn_o )
> [108 of 114] Compiling Cardano.DB.Sqlite ( src/Cardano/DB/Sqlite.hs, dist/build/Cardano/DB/Sqlite.o, dist/build/Cardano/DB/Sqlite.dyn_o )
For full logs, run 'nix log /nix/store/f4ybcf3n7hk2yfn375ikgz9r4l37nfa3-cardano-wallet-core-lib-cardano-wallet-core-2022.1.18.drv'.
error: 1 dependencies of derivation '/nix/store/dvcxsznm7y2vlylprmgmxaxkrz127ng3-cardano-wallet-exe-cardano-wallet-2022.1.18.drv' failed to build
error: build of '/nix/store/0qc5jy1gq7wvfrh8cgk8simha4kcy1yw-marlowe-play-spago.drv', '/nix/store/1n6k5x1w9anmdyy8sk91jy3ccgm05vf1-haskell-language-server-wrapper.drv', '/nix/store/2nh1qzgav72nhqx3z1z9vpslykc91ql4-marlowe-run-server.drv', '/nix/store/2vwdv3q4y9x9hizcc6nrzzaxbkv9f8pc-fix-dhall.drv', '/nix/store/2xwv0nk72cjxy6hvknnvkml99il3av0p-fix-stylish-haskell.drv', '/nix/store/3713lqy701bvfk5ajxypq64jsygfzmsb-start-dashboard-server.drv', '/nix/store/3cn5w7pfgxg6l22aqvd95246v3yhhjr7-marlowe-run-generate-purs.drv', '/nix/store/5cxhfxjy2sil7nax62mckchg1xc5idk9-fix-purs-tidy.drv', '/nix/store/5zszwp9j729xijzvwcnphy26gnjifl44-updateMaterialized.drv', '/nix/store/65l907v2srfpqh1vi208mxac13l9d4x0-marlowe-run-test.drv', '/nix/store/693hfzb5rlpfkf23zgxcg57fhyz9k89a-start-chain-index.drv', '/nix/store/8lvv31qg971507d244ipfci9sjncm2q3-start-cardano-node.drv', '/nix/store/9kxgfphjxpflks2as3rv4vw4n2vsqy49-start-marlowe-run.drv', '/nix/store/dvcxsznm7y2vlylprmgmxaxkrz127ng3-cardano-wallet-exe-cardano-wallet-2022.1.18.drv', '/nix/store/gf3wry42mkylrln6j630x5cz95ckfgpi-marlowe-playground-generate-purs.drv', '/nix/store/hbrm722bkf986l20cmlsh2jdqwnalw37-marlowe-run-spago.drv', '/nix/store/hmww1licvw5ymk8vvf69a5376ly1s205-haskell-language-server-exe-haskell-language-server-1.3.0.0.drv', '/nix/store/hqma6a8a48g0lwy811b89xh93jz9dcnn-ghc-shell-for-packages-ghc-8.10.4.20210212-env.drv', '/nix/store/hvz6yfsj3azapdl4r3p92nj24rz0wrnx-pre-commit-config.json.drv', '/nix/store/i45s1bvam4xpg1ssz1kprizkzzhm7kzi-marlowe-playground-server.drv', '/nix/store/ill6y3fxqg8j75qhq4qyrbwa2p1j65a2-generate-purescript.drv', '/nix/store/kiq89kgza8shhc3qx7mxdl5lhkj7qk1y-fix-prettier.drv', '/nix/store/kw40pqdaq4vibc81c8gylkx3ikwwlmk3-blockfrost-client-lib-blockfrost-client-0.3.1.0.drv', '/nix/store/lwapgnmc48inbjdsximapbm9k9mfbc4n-marlowe-cli-exe-marlowe-cli-0.0.4.0.drv', '/nix/store/vbv7f25mjlprckimfvmf2v881l0afcrh-start-marlowe-pab.drv', '/nix/store/x006fz3vjkykqf1m96jzh54nj22zghf4-start-cardano-wallet.drv', '/nix/store/y1n8l4jznbm0q4xrlgbhly6lnd9im60s-update-client-deps.drv', '/nix/store/z6xqdvz6grjpxdkkp3k2g47zyd2hw8hq-python3-3.9.6-env.drv', '/nix/store/z9bsag150pgrskwj3pza4kbfcd53djk1-marlowe-exe-marlowe-pab-0.1.0.0.drv', '/nix/store/zbdiqa6snqkrjmdz270dggac1sd5427l-plutus-chain-index-exe-plutus-chain-index-0.1.0.0.drv' failed
... so it looks like it got hung up when trying to do:
Preprocessing library for plutus-ledger-constraints-0.1.0.0
Note i tried entering nix shell after marlowe install... and there's an "segmentation fault" error:
nix-shell marlowe-cardano/shell.nix
trace: To materialize project.plan-nix for cabal-install entirely, pass a writable path as the materialized argument and run the 'updateMaterialized' script in 'passthru'.
trace: To materialize project.plan-nix for haskell-project entirely, pass a writable path as the materialized argument and run the 'updateMaterialized' script in 'passthru'.
trace: To materialize project.plan-nix for haskell-project entirely, pass a writable path as the materialized argument and run the 'updateMaterialized' script in 'passthru'.
zsh: segmentation fault  nix-shell marlowe-cardano/shell.nix

Closing the loop on this. I was able to install Daedalus locally, and open a Marlowe terminal from the menu. This is much simpler, and it seems to work just fine. :) Advise using the CLI from Daedalus as the preferred method of local development, at least on a Mac.

Hi Aaron, you can mark this one or any other answer as correct to let everybody know your question has been answered. Cheers.

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

Mac users have to configure their nix setup a little differently than other environments. You might need to update your nix.conf file located in /etc/nix/nix.conf.
You can find the specific instructions for Mac users here: https://plutus-community.readthedocs.io/en/latest/#Environment/Build/MacOS/
And Mac M1 users here: https://plutus-community.readthedocs.io/en/latest/#Environment/Build/Mac_M1/
After updating your nix config, make sure to restart your machine and try again.

Thanks... I followed the Mac instructions precisely, and a lot worked. However, it looked like it all messed up here: Preprocessing library for plutus-ledger-constraints-0.1.0.0..
Building library for plutus-ledger-constraints-0.1.0.0.. this part failed. Hence, it doesn't appear all the tools installed/built.

Going to try Nix install directions... https://nixos.org/download.html#nix-install-macos

Closing the loop on this. I was able to install Daedalus locally, and open a Marlowe terminal from the menu. This is much simpler, and it seems to work just fine. :)


text:
Which address types are allowed for collateral inputs
Collateral inputs are required to be added to a transaction when any Plutus script is executed within that tx (i.e. spending a Plutus address utxo or minting a Plutus policy asset).
Obvious that a collateral input cannot be from a Plutus script address, as spending them would require for the script to be executed, which then would require a different collateral to be used, in case the script fails.
But what address types are allowed for collateral inputs at all? Is it only general vkey addresses or Native script addresses are allowed as well (since they themselves don't require collateral to be spent)?

The payment credential for any address in a collateral input must be a vkey credential (so not even native script).
You can see this check in the feesOK function in Figure 2 of the Babbage spec. Or here in the implementation.

Thank you, Jared!


text:
Questioning Plutus API design decision
In Lecture 10 from the Plutus Pioneer Programm there is a replica of the Uniswap Smart Contract built on top of Plutus. It is actually part of the standard Plutus use cases Plutus Uniswap
To have a better user experience and to get to know it better i wanted to build a GUI around it. If you are interested you can find it in this github repo
Now to my question.
What is the reason behind the design decision for the Status endpoint of the Plutus PAB Rest API.
In order to read the funds we have first to call the funds Endpoint which returns nothing and secondly you have to call the status endpoint.

This is the Frontend Code from Lars where he reads the funds

This makes it very difficult if you want to have concurrent calls one for the funds and one for the pools
Why is there not a dedicated status endpoint for funds and pools?

This got me wondering too. I posted a question but never got any answer: https://cardano.stackexchange.com/questions/4908/user-interaction-with-smart-contracts  It seems, the Plutus team is not active on this forum.

I just registered for the third cohort of the ppp. There i will ask this Question in the Q&A session. As soon as i know more i will post it here.

Great, I'm looking forward. I am not participating in the cohort, but I would have a lot of questions.

the link to frontend code is broken, can you please update?

Thank you @LexTRX it is updated now

The only way to read a state of the smart contract is using a contract instance status endpoint (api/contract/instance/$INSTANCE_ID/status). Other endpoints can only trigger a change of the state but they cannot return it so it's always a two step process.

This does not really answer my question.
I do already know how to read the different states. My question was why it is designed like this.
It even contradicts completely the functional approach of Haskell Language.


text:
Optimising validators with `BuiltinData -> BuiltinData -> BuiltinData -> ()` and building tx with cardano-cli
In one of your previous classes you said that some teams are optimising their contracts with this type of validator BuiltinData -> BuiltinData -> BuiltinData -> ()  and I'll refer to those contracts as "optimised" (logic inside is the same, other than resolving types from BuiltinData). I've tried doing that even with custom context ctx = PlutusTx.unsafeFromBuiltinData @CustomScriptContext rawContext and when I build scripts and calculate expected memory and CPU budget with this command
writePlutusScript filename scriptSerial scriptSBS =
  do
    case Plutus.defaultCostModelParams of
      Just m ->
        let (logout, e) = Plutus.evaluateScriptCounting Plutus.Verbose m scriptSBS []
         in do
              print ("Log output" :: String) >> print logout
              case e of
                Left evalErr -> print ("Eval Error" :: String) >> print evalErr
                Right exbudget -> print ("Ex Budget" :: String) >> print exbudget

and I get info that budget is decreased a lot for "optimised" validators
Non optimised: ExBudget {exBudgetCPU = ExCPU 15184330, exBudgetMemory = ExMemory 51100}
Optimised: ExBudget {exBudgetCPU = ExCPU 8306767, exBudgetMemory = ExMemory 28000}

But when I try to build and submit a batch (via cardano-cli transaction build and cardano-cli submit) with couple of different contacts  utxos and 1  "optimised" contracts utxos I get ExUnitsTooBigUTxO error (on submit) and it says that it exceedes memory by a lot (4000000+)
{unWrapExUnits = ExUnits' {exUnitsMem' = 16000000, exUnitsSteps' = 10000000000}}) (WrapExUnits {unWrapExUnits = ExUnits' {exUnitsMem' = 20120006, exUnitsSteps' = 8471969427}}

and when i use non optimised contract utxo in the same batch (only difference is that one utxo) my transaction goes through.
How could that be? Does cardano-cli submit uses same logic for calculation of units as I've posted above (and as transaction build), Why did transaction build go trough if it has memory issues (when I'm over limit transaction build usually informs me)? And could there be a reason to use build-raw and add custom  (ones I've received from the plutus code) exUnits, and would that help?

The last paragraph is not clear to me. Are you creating a transaction which does evaluate multiple scripts or is it only the one script for which you also calculated the budget?

It's 2 different scripts/validators in one "batch", first one is "LP" script/validator that is used in both cases (optimised and non optimised) and second is "Order" script, which is in the failing case optimised and in successful case non optimised


text:
PAB connection to public testnet or mainnet (Example/Tutorial)
Does anyone know and want to share any information on how to connect PAB to public testnet (not simulator) or mainnet? Are there any examples/tutorials for it?

You have the best instruction here https://gist.github.com/mikekeke/883d56c38e0237444ac98ae5257e174f
Also after the setup on the above link, you can use this starter project generated from the Plutus starter template just updated to work with PAB on testnet https://github.com/invictusappscom/plutus-starter-pab-testnet Here main differences from https://github.com/input-output-hk/plutus-starter are that dependencies are updated and it is added plutus-pab.yaml configuration file. Also here instead of simulator it is using the real PAB https://github.com/invictusappscom/plutus-starter-pab-testnet/blob/main/pab/Main.hs
Another useful resources:

https://github.com/input-output-hk/plutus-apps/blob/main/plutus-pab/ARCHITECTURE.adoc
https://github.com/input-output-hk/plutus-apps/tree/main/plutus-pab/test-node

Do I have to run a full node to run the PAB in the testnet?

Yes, you need to have a running testnet node. Also, wallet server and chain-index connected to the node.


text:
Testnet relay doesn't have any incoming peer connections other than my BP node
I just recently set up a stakepool on the Testnet.  I am running v1.32.1 of Cardano-node on both my relay and BP. Each node (relay and BP) are EC2 instances within the same VPC, and both are running the AWS version of Linux.  I have also verified that I can reach my relay's IP and port from the internet.  But when I run gLiveView on my relay, I only see one incoming peer connection, and both total and pending tx's are at 0.  The pool has been up and running for a couple of days now, so I am not sure if I have something misconfigured or if it just takes a bit of time for my relay to be discovered by the network?

Also, I set up the topology updater script, and when I run it manually, its successful:
{ "resultcode": "201", "datetime":"2021-12-29 22:45:01", "clientIp": "3.142.120.205", "iptype": 4, "msg": "nice to meet you" }

But when its running in cron, it always errors out:
{ "resultcode": "502", "datetime":"2021-12-29 23:33:03", "clientIp": "3.142.120.205", "msg": "invalid blockNo []" }

How would I go about troubleshooting this?
Linux Info:
Linux version 5.10.82-83.359.amzn2.x86_64
(mockbuild@ip-10-0-37-156)
(gcc10-gcc (GCC) 10.3.1 20210422 (Red Hat 10.3.1-1), GNU ld version 2.35-21.amzn2.0.1) #1 SMP Tue Nov 30 20:47:14 UTC 2021
Update:
I forgot to mention in the original post the ticker I am using is "HLTH".  Here is the link to the pool in Cardanoscan: https://testnet.cardanoscan.io/pool/614235f4d6c44cfc46a1ee16c95eb6d10008204c830d056f188e7677
I see now that my ticket isn't showing up, so maybe I have screwed up something with my metadata?
Here is the topologyUpdater.sh script I am using, I got this from the coin cashew tutorial:
#!/bin/bash
# shellcheck disable=SC2086,SC2034

USERNAME=ec2-user
CNODE_PORT=6000 # must match your relay node port as set in the startup command
CNODE_HOSTNAME="CHANGE ME"  # optional. must resolve to the IP you are requesting from
CNODE_BIN="/usr/local/bin"
CNODE_HOME=/home/ec2-user/cardano-src/relay
CNODE_LOG_DIR="${CNODE_HOME}/logs"
GENESIS_JSON="${CNODE_HOME}/testnet-shelley-genesis.json"
NETWORKID=$(jq -r .networkId $GENESIS_JSON)
CNODE_VALENCY=1   # optional for multi-IP hostnames
NWMAGIC=$(jq -r .networkMagic < $GENESIS_JSON)
[[ "${NETWORKID}" = "Mainnet" ]] && HASH_IDENTIFIER="--mainnet" || HASH_IDENTIFIER="--testnet-magic ${NWMAGIC}"
[[ "${NWMAGIC}" = "764824073" ]] && NETWORK_IDENTIFIER="--mainnet" || NETWORK_IDENTIFIER="--testnet-magic ${NWMAGIC}"

export PATH="${CNODE_BIN}:${PATH}"
export CARDANO_NODE_SOCKET_PATH="${CNODE_HOME}/db/socket"

echo Network Identifer: ${NETWORK_IDENTIFIER}
blockNo=$(cardano-cli query tip ${NETWORK_IDENTIFIER} | jq -r .block )

# Note:
# if you run your node in IPv4/IPv6 dual stack network configuration and want announced the
# IPv4 address only please add the -4 parameter to the curl command below  (curl -4 -s ...)
if [ "${CNODE_HOSTNAME}" != "CHANGE ME" ]; then
  T_HOSTNAME="&hostname=${CNODE_HOSTNAME}"
else
  T_HOSTNAME=''
fi

if [ ! -d ${CNODE_LOG_DIR} ]; then
  mkdir -p ${CNODE_LOG_DIR};
fi

curl -s "https://api.clio.one/htopology/v1/?port=${CNODE_PORT}&blockNo=${blockNo}&valency=${CNODE_VALENCY}&magic=${NWMAGIC}${T_HOSTNAME}" | tee -a $CNODE_LOG_DIR/topologyUpdater_lastresult.json

Additionally, here is my Testnet-topology.json file.  I decided to try swapping in the IP addresses of each relay, and so I could remember which ones were which I put the DNS name of the relay into the "continent" field.
    {
        "Producers": [{
                "addr": "172.31.25.89",
                "port": 6000,
                "valency": 1
        },
        {
                "addr": "relays-new.cardano-testnet.iohkdev.io",
                "port": 3001,
                "valency": 2
        },
        {
                "addr": "64.225.4.242",
                "port": 3001,
                "valency": 2,
                "continent": "relays.testnet.stakenuts.com",
                "state": "New Jersey"
        },
        {
                "addr": "34.223.107.64",
                "port": 3001,
                "valency": 2,
                "continent": "testnet-relays.onyxstakepool.com",
                "state": "Oregon"
        },
        {
                "addr": "89.162.88.186",
                "valency": 2,
                "port": 9015,
                "valency": 2,
                "continent": "testnet.adanorthpool.com",
                "state": "NO"
        },
        {
                "addr": "202.92.217.26",
                "port": 9710,
                "valency": 2,
                "continent": "testicles.kiwipool.org",
                "state": "NZ"
        }
        ]
}

I followed a mix of the stakepool course tutorial and coin cashew to get this done.  If I can't get this figured out I am probably going to tear it back down and then just start with the Guild Operators site and start from the prereqs.sh.

Seems something wrong with your topology script, you need to fix it. Maybe it has some shortened paths like ./bla.json. It should have access to testnet-shelley-genesis.json file(or maybe it called a bit different in your case) and seems this error hints that script can't access it.
Please post your topology updater script so we can fix it.
Currently when p2p is kind of really early on testnet(and it will work only with 1.33 version), you will need kind of relay on topology updater script.
When everything is fine you should see in logs something like this:
"nice to meet you"
"welcome to the topology"
"glad you're staying with us"
"glad you're staying with us"
"glad you're staying with us"
...
"glad you're staying with us"

So in your case you didn't register properly with topology script and nobody is knowing about your relays. On other hand topologyupdater is kind of optional and after some time(it can be a long time) everybody should know your relay if you registered your pool correctly. So maybe you can share your ticker too? In any case I highly recommend for beginners to use topologyupdater, so start with fixing it.

Thanks for the reply!  Just updated my original post.  I also don't see my ticker in Cardanoscan, so maybe its a metadata issue?

So there are several issues. Check here:
https://testnet.adatools.io/pools/614235f4d6c44cfc46a1ee16c95eb6d10008204c830d056f188e7677

6000 port is not unreachable from outside world. Your relay should be accessible on 600 port from everywhere, check your FW.
https://git.io/JyDWW -- is empty file, so you registered your pool with topology file what do not contain anything

Regarding topology script, can you run which cardano-cli and post it here?

without opening FW(6000 port of your relay) no other relays will be able to connect even if topology script is running as it should

Not sure if it matters, but I used my relay’s private ip, rather than the AWS public ip when I created the pool cert.  So I’m also working on fixing that.  I’ll come back and comment when i’ve been able to move it forward

Yes, you should not use private IP. Please send me which cardano-cli output, so we can fix your topology script. Plus don't forget to fix your metadata link, it is empty now.

After a fair amount of fat fingering, I finally got a pool registration transaction together with the correct metadata: https://testnet.cardanoscan.io/transaction/aa09bf8b7ca07227e01f59cd9ee313050ec705685dcb70071defe3aeb77994be?tab=poolcertificates
I am going to wait for this to take effect and if everything starts working I'll update my original question with what I had wrong as well as give you the green check mark @os11k :)

Hi, thank you! Now everything seems look right: https://testnet.adatools.io/pools/614235f4d6c44cfc46a1ee16c95eb6d10008204c830d056f188e7677. In any case I would recommend to fix topology script, seems you have incorrect this part CNODE_BIN="/usr/local/bin", what should be path where cardano-node binary is located. To check where binary is you can run which cardano-node

The topology script I posted is from the coin cashew tutorial, I actually decided to stop using that one and grabbed the topology updater script from the guild and started using that.  I let it run over night and now I have a brand new topology in my Testnet-topology.json file!  Thank you very much for all the help!

Cool, glad that you make it work. Cheers!


text:
Where can I find community governance info for Cardano?
I recently spoke to some other members in the Cardano community and I'd like to know more about governance. For example how the community can engage in meaningful discussions about the protocol and how it should and can be governed by the community. Much thanks.

The best way to learn about the CIP process is to review the CIP1: CIP process.
Discussion is mostly happening on the CIP github using the pull requests but also on bi-weekly CIP meetings.

Project Catalyst is Cardano's first major Governance product. You can submit proposals for new tools, features or improvements during the submission period of a fund cycle.
This is a community-built dashboard that aggregates a lot of important info about Catalyst.


text:
What is a round trip problem? and why using Unstable functions could cause it? (unstableMakeIsData)
Lecture 2 of plutus-pioneer-program, introduces unstableMakeIsData
In the lecture it is advised to use the Stable version in production.
Lars explains that the Unstable version does not make any guarantee that different constructor numbers will be preserved for future versions of Plutus. He further adds that:

A newer version of plutus does it in a different way it would be incompatible and you would have round trip problems (??)

I understand the incompatibility issue, sure, but what exactly is a round trip problem in this context?

The round trip problem in programming is when you have 2 conversions functions (for example toJSON and fromJSON) that should be each others inverse but aren't. So you start with a value, then convert it but when you convert it back you don't get the value again.
So in this case: say you have created this datatype:
data MyType = Yes | No

unstableMakeIsData ''MyType

Then you convert the value Yes to a value of type Data using toBuiltinData:
yesAsData :: Data
yesAsData = toBuiltinData Yes

Later with a future version of Plutus you convert yesAsData back to a value of type MyType with fromBuiltinData yesAsData and you might get back No instead!

Well explained, thank you very much!


text:
Embedding address into the datum using the CLI
I have a validator that uses Address in datum. I also have an address generated (payment.vkey, payment.skey, payment.addr, stake.vkey, stake.skey, stake.addr). I'm able to get PubKeyHash using command line like this:
cardano-cli address key-hash --payment-verification-key-file payment.vkey
That gives an addressPaymentCredential that I'm able to embed to datum when building the transaction in cli. It has the same information as (addressPaymentCredential, _). How would I go about getting a full address with addressStakingCredential in it, that is, (addressPaymentCredential, addressStakingCredential)?
I think that the JSON structure of Address in datum should be like this:
{
  "constructor": 0,
  "fields": [
    {
      "constructor": 0,
      "fields": [
        {
          "bytes": PubKeyHash
        }
      ]
    },
    {
      "constructor": 1,
      "fields": [
        {
          "bytes": StakingCredentialHash
        }
      ]
    }
  ]
}

My problem is I don't know how to get StakingCredentialHash.
TLDR: How do I embedd an Address instead of just PubKeyHash into the datum in cardano cli? I have the address credentials in payment.* and stake.* files.

why not just use the address instead of PubKeyHash in your example?

@noone392 You mean in the JSON? The whole JSON is an Address which is composed of two parts, one of them being PubKeyHash. My validator used PubKeyHash, but I'm trying to replace it with Address. I did that and now I need to change the datum JSON appropriately. Or do you mean something else?

I am not following you. The JSON file is not the address it is the whole formatting required for a datum entry. you said you said you wanted the address instead of the public key hash. So just delete "bytes": PubKeyHash  and replace with "bytes": address? or if you want to add the address then add another "fields" key

Yes, I want to transform my address into the datum entry. The JSON I provided is slightly modified output of ToData a, where a = Address(addressCredential, addressStakingCredential). In the JSON provided, I can replace PubKeyHash (which is just a placeholder there) with the output of cardano-cli address key-hash --payment-verification-key-file payment.vkey. My problem is that I can't figure out, what I need to replace the StakingCredentialHash placeholder with. I have the stake.vkey file, but I need some command to transform it in a similar manner to how I did with payment.vkey.

i really can't follow what your asking. to transform stake.vkey in the same maneer just run
"cardano-cli address key-hash --payment-verification-key-file stake.vkey"

I see the problem now, the command does not work on stake.vkey, but it needs to get stake-address instead of just address. I'll add an answer.

The problem was that I was trying to use the cardano-cli command for address to a stake-address. The command for payment credential (PubKeyHash) is correct in the question:
cardano-cli address key-hash --payment-verification-key-file payment.vkey
The correct command for staking credential should be like this:
cardano-cli stake-address key-hash --stake-verification-key-file stake.vkey
Outputs of those 2 commands can be used to build correct Address in datum.
Also, the JSON I provided in the question is incorrect, the staking credential part should be deeper than the payment credential part, you can get the correct JSON by printing the datum in emulator using a command like in an answer to this question.

So then, are you embedding an address-hash of some sort in the datum? As far as I know, you can't recreate the full address using the hashes of the constituent keys. I'm just curious - is the purpose of this to embed the address hash or some sort of address-verification method into the datum?

I think that payment credential and staking credential are just hashes, so you can verify that an output goes to an address from datum without the need to reconstruct the full address.

You write "the JSON I provided is incorrect".  Would you please paste the correct JSON? I am lost from the links and your explanation is too vague


text:
how to build new transaction based on the UTXO with NFT token?
I'm using test net. Currently, I've got the UTXO with minted token made by the simple cardano-cli tool for that.
At first step it looked like:
cardano-cli transaction build --alonzo-era --testnet-magic 1097911063 --tx-in 4225e8c9f605c08765e1c99036dd4ab684f75634934062a7e82af16131d76cd9#0 --tx-in-collateral 4225e8c9f605c08765e1c99036dd4ab684f75634934062a7e82af16131d76cd9#0 --tx-out "addr_test1vqwvs32x3wg5ea2l5tr7t93hpta8arwxllr4ey96dhl5d7sytaf9n + 998275900 lovelace + 1 1b4dc8260cbaa66b1140fad4aaac052e2e18c8da508ba6bf4efaa067.TestTokenName" --tx-out-datum-hash 45b0cfc220ceec5b7c1c62c4d4193d38e4eba48e8815729ce75f9c0ab0e4c1c0 --change-address addr_test1vqwvs32x3wg5ea2l5tr7t93hpta8arwxllr4ey96dhl5d7sytaf9n --mint "1 1b4dc8260cbaa66b1140fad4aaac052e2e18c8da508ba6bf4efaa067.TestTokenName" --mint-script-file "mint-TestTokenName.plutus" --mint-redeemer-value [] --protocol-params-file testnet-protocol-parameters.json --out-file mint-tx.raw
cardano-cli result : b'Estimated transaction fee: Lovelace 351488\n'

 cardano-cli transaction sign --tx-body-file mint-tx.raw --signing-key-file /home/user/cardano_work/cardano-node-test1_config/keys/payment1.skey --testnet-magic 1097911063 --out-file mint-tx.signed

cardano-cli transaction submit --testnet-magic 1097911063 --tx-file mint-tx.signed
Transaction successfully submitted.

after checking address I got:
cardano-cli query utxo --address addr_test1vqwvs32x3wg5ea2l5tr7t93hpta8arwxllr4ey96dhl5d7sytaf9n --testnet-magic 1097911063
                           TxHash                                 TxIx        Amount
--------------------------------------------------------------------------------------
102d73bf6e52fb42848ce085d325c9835f3a955494928c2eebe41efd63482e2f     0        1310316 lovelace + 2 6b8d07d69639e9413dd637a1a815a7323c69c86abbafb66dbfdb1aa7 + TxOutDatumNone
275644c0d040ee371495a6a963dec167f5499936adf7fd6fbc8cc0bae94e2d40     0        1372612 lovelace + TxOutDatumNone
275644c0d040ee371495a6a963dec167f5499936adf7fd6fbc8cc0bae94e2d40     1        998275900 lovelace + 1 1b4dc8260cbaa66b1140fad4aaac052e2e18c8da508ba6bf4efaa067.TestTokenName + TxOutDatumHash ScriptDataInAlonzoEra "45b0cfc220ceec5b7c1c62c4d4193d38e4eba48e8815729ce75f9c0ab0e4c1c0"
a18485d41697e664ee9f99e2bbd42d2957b88c99e90a9ea27039293c31eec8ec     0        1310316 lovelace + 2 6b8d07d69639e9413dd637a1a815a7323c69c86abbafb66dbfdb1aa7 + TxOutDatumNone

After that, I'm trying to run the same script but with a different minting policy to mint another token:
policy_id : 378e458eff0ee31583e2f1eb31e04e75d09e92fba642be06a8a80100
left money : 998275900 lovelace+1 1b4dc8260cbaa66b1140fad4aaac052e2e18c8da508ba6bf4efaa067.TestTokenName
Prepared CMD:
 cardano-cli transaction build --alonzo-era --testnet-magic 1097911063 --tx-in 275644c0d040ee371495a6a963dec167f5499936adf7fd6fbc8cc0bae94e2d40#1 --tx-in-collateral 275644c0d040ee371495a6a963dec167f5499936adf7fd6fbc8cc0bae94e2d40#1 --tx-out "addr_test1vqwvs32x3wg5ea2l5tr7t93hpta8arwxllr4ey96dhl5d7sytaf9n + 998275900 lovelace+1 1b4dc8260cbaa66b1140fad4aaac052e2e18c8da508ba6bf4efaa067.TestTokenName + 1 378e458eff0ee31583e2f1eb31e04e75d09e92fba642be06a8a80100.TokenWithMeta" --tx-out-datum-hash 45b0cfc220ceec5b7c1c62c4d4193d38e4eba48e8815729ce75f9c0ab0e4c1c0 --change-address addr_test1vqwvs32x3wg5ea2l5tr7t93hpta8arwxllr4ey96dhl5d7sytaf9n --mint "1 378e458eff0ee31583e2f1eb31e04e75d09e92fba642be06a8a80100.TokenWithMeta" --mint-script-file "mint-TokenWithMeta.plutus" --mint-redeemer-value [] --metadata-json-file meta-TokenWithMeta.json --protocol-params-file testnet-protocol-parameters.json --out-file mint-tx-TokenWithMeta.raw
cardano-cli result : Command failed: transaction build  Error: The transaction does not balance in its use of ada. The net balance of the transaction is negative: Lovelace (-365986) lovelace. The usual solution is to provide more inputs, or inputs with more ada.

cost value: -365986
Prepared CMD:
 cardano-cli transaction build --alonzo-era --testnet-magic 1097911063 --tx-in 275644c0d040ee371495a6a963dec167f5499936adf7fd6fbc8cc0bae94e2d40#1 --tx-in-collateral 275644c0d040ee371495a6a963dec167f5499936adf7fd6fbc8cc0bae94e2d40#1 --tx-out "addr_test1vqwvs32x3wg5ea2l5tr7t93hpta8arwxllr4ey96dhl5d7sytaf9n + 997909914 lovelace+1 1b4dc8260cbaa66b1140fad4aaac052e2e18c8da508ba6bf4efaa067.TestTokenName + 1 378e458eff0ee31583e2f1eb31e04e75d09e92fba642be06a8a80100.TokenWithMeta" --tx-out-datum-hash 45b0cfc220ceec5b7c1c62c4d4193d38e4eba48e8815729ce75f9c0ab0e4c1c0 --change-address addr_test1vqwvs32x3wg5ea2l5tr7t93hpta8arwxllr4ey96dhl5d7sytaf9n --mint "1 378e458eff0ee31583e2f1eb31e04e75d09e92fba642be06a8a80100.TokenWithMeta" --mint-script-file "mint-TokenWithMeta.plutus" --mint-redeemer-value [] --protocol-params-file testnet-protocol-parameters.json --metadata-json-file meta-TokenWithMeta.json --out-file mint-tx-TokenWithMeta.raw
cardano-cli final result : Command failed: transaction build  Error: The transaction does balance in its use of ada, however the net balance does not meet the minimum UTxO threshold.
Balance: Lovelace 0
Offending output (change output): addr_test1vqwvs32x3wg5ea2l5tr7t93hpta8arwxllr4ey96dhl5d7sytaf9n +
Minimum UTxO threshold: Lovelace 999978
The usual solution is to provide more inputs, or inputs with more ada to meet the minimum UTxO threshold

Can anyone give a hint on how to construct a minting transaction based on UTXO with minted value?
Does it relate to this issue: https://github.com/input-output-hk/cardano-node/issues/3364?

It might help anyone else.

use cardano-node/cardano-cli 1.31.0 It supports multi asset
Token names in that version are hex strings(not programmatically can get by: https://codebeautify.org/hex-string-converter)

Example:
Initial state:
cardano-cli query utxo --address addr_test1vqwvs32x3wg5ea2l5tr7t93hpta8arwxllr4ey96dhl5d7sytaf9n --testnet-magic 1097911063
                           TxHash                                 TxIx        Amount
--------------------------------------------------------------------------------------
102d73bf6e52fb42848ce085d325c9835f3a955494928c2eebe41efd63482e2f     0        1310316 lovelace + 2 6b8d07d69639e9413dd637a1a815a7323c69c86abbafb66dbfdb1aa7 + TxOutDatumNone
275644c0d040ee371495a6a963dec167f5499936adf7fd6fbc8cc0bae94e2d40     0        1372612 lovelace + TxOutDatumNone
275644c0d040ee371495a6a963dec167f5499936adf7fd6fbc8cc0bae94e2d40     1        998275900 lovelace + 1 1b4dc8260cbaa66b1140fad4aaac052e2e18c8da508ba6bf4efaa067.54657374546f6b656e4e616d65 + TxOutDatumHash ScriptDataInAlonzoEra "45b0cfc220ceec5b7c1c62c4d4193d38e4eba48e8815729ce75f9c0ab0e4c1c0"
9dec871d095c5ec88dd727f0bdafc9d854a366593e0777dcf56b3ee776d51ffe     0        1000000000 lovelace + TxOutDatumNone
a18485d41697e664ee9f99e2bbd42d2957b88c99e90a9ea27039293c31eec8ec     0        1310316 lovelace + 2 6b8d07d69639e9413dd637a1a815a7323c69c86abbafb66dbfdb1aa7 + TxOutDatumNone

Build transaction with new minting:
cardano-cli transaction build --alonzo-era \
--testnet-magic 1097911063 \
--tx-in 275644c0d040ee371495a6a963dec167f5499936adf7fd6fbc8cc0bae94e2d40#1 \
--tx-in-collateral 275644c0d040ee371495a6a963dec167f5499936adf7fd6fbc8cc0bae94e2d40#1 \
--tx-out "addr_test1vqwvs32x3wg5ea2l5tr7t93hpta8arwxllr4ey96dhl5d7sytaf9n + 997909914 lovelace+1 1b4dc8260cbaa66b1140fad4aaac052e2e18c8da508ba6bf4efaa067.54657374546f6b656e4e616d65 + 1 378e458eff0ee31583e2f1eb31e04e75d09e92fba642be06a8a80100.546f6b656e576974684d657461" \
--tx-out-datum-hash 45b0cfc220ceec5b7c1c62c4d4193d38e4eba48e8815729ce75f9c0ab0e4c1c0 \
--change-address addr_test1vqwvs32x3wg5ea2l5tr7t93hpta8arwxllr4ey96dhl5d7sytaf9n \
--mint "1 378e458eff0ee31583e2f1eb31e04e75d09e92fba642be06a8a80100.546f6b656e576974684d657461" \
--mint-script-file "mint-TokenWithMeta.plutus" \
--mint-redeemer-value [] \
--protocol-params-file testnet-protocol-parameters.json \
--metadata-json-file meta-TokenWithMeta.json \
--out-file mint-tx-TokenWithMeta.raw
cardano-cli std out : Estimated transaction fee: Lovelace 365986

I've built a docker image that does this stuff automagically for you.
https://github.com/berlinpool/cnft-utxo


text:
eUTXO transaction model Vs Account Based Transaction Model
What are the benefits of Cardano's eUTXO transaction model compared to Ethereum's account-based transaction model? Are there any significant differences?

There is a nice blog post bu IOG: Cardano’s Extended UTXO accounting model – built to support multi-assets and smart contracts that discusses the difference between two models.
For a more in depth comparison, I recommend the UTxO- vs account-based smart contract blockchain programming paradigms paper.
To sum UTXO up:

A UTXO is the output of a previous transaction, which can be spent in
the future
UTXO chains have no accounts. Instead, coins are stored as
a list of UTXOs, and transactions are created by consuming existing
UTXOs and producing new ones in their place
Balance is the sum of
UTXOs controlled by a given address
UTXOs resemble cash in that they
use ‘change’, and are indivisible (UTXOs are used whole)

To sum up the Account/Balance model:

This accounting model resembles how a bank operates
Users have accounts that hold their coin balance
It is possible to spent partial balances
The concept of change does not apply

Link only answers are often subject to rot into dead links with time. Maybe you could edit to briefly list the most important points according to you.

I hope a scientific paper will not rot in time :) but I moved the points to the answer.

It already happened with scientific parpers: publisher reorganizing the structure of publishing site. Then link to papers were falling in the void of a 404 error.

Oh, I hope arXiv never disappears, but you are right - I uploaded the paper to IPFS :) and moved the main points to the post.

Something I'd note about the EUTxO model is that state machines for smart contracts and state channels can be embedded in the UTxO themselves. This significantly changes the way a smart contract model would operate on the network. From my understanding, while with balance based smart contracts you can have two smart contracts interact with each other, that isn't possible with EUTxO smart contracts. Instead with EUTxO you would compose the smart contracts together and they'd operate as one unified contract for 1 Tx instead.

I am sure there is a lot of documentation around it. But just to scratch the surface:

Both are not same at all.
ETH fees is charged even for failed transactions. But in eUTXO, your fees is collected only if your transaction succeeds. This alone is huge.
Smart contracts developed in eUTXO model are much more dependable, reliable than the account model.
I am sure you already know that ETH only went with account model because they could not think of a way to make smart contracts work with the Bitcoin's UTXO model.

But it is a really interesting comparing both Account and UTXO. Links are there above in some other comments.

this is indeed a great answer! tks!

The EUTXO model also makes it much easier to scale. Charles talks about that in this great video -- the take-away here is that Cardano will be much easier to scale than Ethereum.


text:
OutputTooSmallUTxO error
I'm following these steps and I get the OutputTooSmallUTxO error.
Not sure what I missed from the steps but here's my parameters and the error as a whole.
tokenname1="Testtoken"
tokenname2="SecondTesttoken"
tokenamount="100000000"
output="0"
fee="300000"
txhash="8a7e45c02cf25cb1b9870fbcc87b61d61cefb514ccfb960bcc7651023ea7ffb2"
txix="0"
funds="1000000000"
policyid=$(cat policy/policyID)
cardano-cli transaction build-raw
--fee $fee
--tx-in "$txhash#$txix"
--tx-out $address+$output+"$tokenamount $policyid.$tokenname1 + $tokenamount $policyid.$tokenname2"
--mint="$tokenamount $policyid.$tokenname1 + $tokenamount $policyid.$tokenname2"
--minting-script-file policy/policy.script
--out-file matx.raw
fee=$(cardano-cli transaction calculate-min-fee --tx-body-file matx.raw --tx-in-count 1 --tx-out-count 1 --witness-count 1 --testnet-magic 1097911063 --protocol-params-file protocol.json | cut -d " " -f1) (This was not incluted in the tutorial and i added it from a block post i found here in reference to a similar issue)
cardano-cli transaction build-raw
--fee $fee
--tx-in "$txhash#$txix"
--tx-out $address+$output+"$tokenamount $policyid.$tokenname1 + $tokenamount $policyid.$tokenname2"
--mint="$tokenamount $policyid.$tokenname1 + $tokenamount $policyid.$tokenname2"
--minting-script-file policy/policy.script
--out-file matx.raw
cardano-cli transaction sign
--signing-key-file payment.skey
--signing-key-file policy/policy.skey
--testnet-magic 1097911063 --tx-body-file matx.raw
--out-file matx.signed
cardano-cli transaction submit --tx-file matx.signed --testnet-magic 1097911063
Command failed: transaction submit  Error: Error while submitting tx: ShelleyTxValidationError ShelleyBasedEraAlonzo (ApplyTxError [UtxowFailure (WrappedShelleyEraFailure (UtxoFailure (OutputTooSmallUTxO [(Addr Testnet (KeyHashObj (KeyHash "63c7e6f65c0185e0afa19657977c86e663873143569b665d23f532ea")) StakeRefNull,Value 0 (fromList [(PolicyID {policyID = ScriptHash "68d7df6ec365f5d9885c451e58e8994741c1970211c01843703f6136"},fromList [("SecondTesttoken",100000000),("Testtoken",100000000)])]),SNothing)]))),UtxowFailure (WrappedShelleyEraFailure (UtxoFailure (ValueNotConservedUTxO (Value 1000000000 (fromList [(PolicyID {policyID = ScriptHash "68d7df6ec365f5d9885c451e58e8994741c1970211c01843703f6136"},fromList [("SecondTesttoken",100000000),("Testtoken",100000000)])])) (Value 177601 (fromList [(PolicyID {policyID = ScriptHash "68d7df6ec365f5d9885c451e58e8994741c1970211c01843703f6136"},fromList [("SecondTesttoken",100000000),("Testtoken",100000000)])])))))])
antonis@adastp:~/tokens$ echo $cardano-cli transaction submit --tx-file matx.signed --testnet-magic 1097911063^C
--tx-in
addr_test1vp3u0ehktsqctc905xt909musmnx8pe3gdtfkejay06n96shpzd3t+0+100000000 68d7df6ec365f5d9885c451e58e8994741c1970211c01843703f6136.Testtoken + 100000000 68d7df6ec365f5d9885c451e58e8994741c1970211c01843703f6136.SecondTesttoken
--tx-out
8a7e45c02cf25cb1b9870fbcc87b61d61cefb514ccfb960bcc7651023ea7ffb2#0

Looks like you don't account for change return value (your $output variable which is zero).
Your transaction spends some UTxO to pay the fee but the rest of this UTxOs ADA has to go somewhere (hence the value not conserved error).
I think you need to look up the ADA value of the --tx-in "$txhash#$txix" (your $funds variable?) and subtract fee from it, which is the unspent ADA you get back.

Thanks I was missing the output=$(expr $funds - $fee)

Nice! Please mark the question as answered :-)


text:
`cardano-tracer`: `VersionMismatch` error during handshake
Good day. I'm trying to see how cardano-tracer works in depth and for tests I'm trying to connect it to the node created by cardano-testnet, but getting this error:
"cardano-tracer, connection with \"/tmp/nix-shell.rnSoi4/testnet-test-21056d614f5c271d/socket/node-spo1\" failed: HandshakeError (VersionMismatch [] [32777,32778,32779,32780,32781,32782,32783,32784])"

I'm building everything from sources with Nix from the tag 8.7.3.
Then using this command to start testnet:
cabal run cardano-testnet -- cardano --babbage-era --testnet-magic 1234

After network is up, I'm following Local Scenario part of the dicumentation with ConnectTo option.
Config looks something like this:
{
  "networkMagic": 1234,
  "network": {
    "tag": "ConnectTo",
    "contents": [
      "/tmp/nix-shell.rnSoi4/testnet-test-21056d614f5c271d/socket/node-spo1"
    ]
  },
  "logging": [
    {
      "logRoot": "/path/to/tracer-logs",
      "logMode": "FileMode",
      "logFormat": "ForMachine"
    }
  ],
  "rotation": {
    "rpFrequencySecs": 15,
    "rpKeepFilesNum": 5,
    "rpLogLimitBytes": 5000,
    "rpMaxAgeHours": 1
  }
}

Then I start tracer with
cabal run cardano-tracer -- -c /path/to/active-tracer-config.json

And this is the output I'm getting:
{"at":"2024-01-29T08:00:15.411851532Z","ns":"Tracer.ParamsAre","data":{"ConfigPath":"/path/to/active-tracer-config.json","MinLogSeverity":null,"StateDir":null,"kind":"TracerParamsAre"},"sev":"Info","thread":"4","host":"Omen"}
{"at":"2024-01-29T08:00:15.412203051Z","ns":"Tracer.ConfigIs","data":{"Config":{"ekgRequestFreq":null,"hasEKG":null,"hasForwarding":null,"hasPrometheus":null,"hasRTView":null,"loRequestNum":null,"logging":[{"logFormat":"ForMachine","logMode":"FileMode","logRoot":"/path/to/tracer-logs"}],"metricsComp":null,"network":{"contents":["/tmp/nix-shell.rnSoi4/testnet-test-21056d614f5c271d/socket/node-spo1"],"tag":"ConnectTo"},"networkMagic":1234,"rotation":{"rpFrequencySecs":15,"rpKeepFilesNum":5,"rpLogLimitBytes":5000,"rpMaxAgeHours":1},"verbosity":null},"kind":"TracerConfigIs"},"sev":"Info","thread":"4","host":"Omen"}
{"at":"2024-01-29T08:00:15.412205245Z","ns":"Tracer.InitStart","data":{"kind":"TracerInitStarted"},"sev":"Info","thread":"4","host":"Omen"}
{"at":"2024-01-29T08:00:15.4122078Z","ns":"Tracer.EventQueues","data":{"kind":"TracerInitEventQueues"},"sev":"Info","thread":"4","host":"Omen"}
{"at":"2024-01-29T08:00:15.412443698Z","ns":"Tracer.InitDone","data":{"kind":"TracerInitDone"},"sev":"Info","thread":"4","host":"Omen"}
{"at":"2024-01-29T08:00:15.413581843Z","ns":"Tracer.StartedLogRotator","data":{"kind":"TracerStartedLogRotator"},"sev":"Info","thread":"7","host":"Omen"}
"cardano-tracer, connection with \"/tmp/nix-shell.rnSoi4/testnet-test-21056d614f5c271d/socket/node-spo1\" failed: HandshakeError (VersionMismatch [] [32777,32778,32779,32780,32781,32782,32783,32784])"

What could be wrong here?
From RTView docs it looks like node need to be run with --tracer-socket-path-accept option maybe? Is there a way to set this for cardano-testnet node?

Manage to make it work in AcceptAt mode with preprod node, where node initiates prortocol, but ConnectTo still throws an error during handshake


text:
Validator fails comparing two (assumed equivalent) PubKeyHashes
I have a simple validator script that checks if a transaction is signed by a specific public key with the hash: 12f2f3e44e6e310abc78802d7078ec1fd0fa220ff47ad1bdb43397e2
{-# INLINABLE getHolder #-}
getHolder :: PubKeyHash
getHolder = PubKeyHash "12f2f3e44e6e310abc78802d7078ec1fd0fa220ff47ad1bdb43397e2"

{-# INLINABLE mkValidator #-}
mkValidator :: BuiltinData -> BuiltinData -> ScriptContext -> Bool
mkValidator _ _ ctx = txSignedBy (scriptContextTxInfo ctx) getHolder

The validator always fails when attempting to spend an output with the correct key using the CLI, --required-signer is being used. The transaction is never built.

I attempt to log the txInfoSignatories in the validator using the following code:
{-# INLINABLE mkValidator #-}
mkValidator :: BuiltinData -> BuiltinData -> ScriptContext -> Bool
mkValidator _ _ ctx = traceError $ decodeUtf8 $ getPubKeyHash $ P.head signatories
    where
        info :: TxInfo
        info = scriptContextTxInfo ctx

        signatories :: [PubKeyHash]
        signatories = txInfoSignatories info

Even though the decoding function throws an error, I still get the following:
The provided Plutus code called 'error'.
Caused by: [
  (builtin decodeUtf8)
  (con bytestring #12f2f3e44e6e310abc78802d7078ec1fd0fa220ff47ad1bdb43397e2)
]

Which shows that the correct key hash is in the script context, but the way the hash is constructed by the script context is clearly not the same as the one I've made and I'm not sure how to proceed.
Thanks!
EDIT: In fact, this happens to any validator I try to use that compares scriptContextTxInfo with any compile time input I give it. The bytestrings that I hardcode are never seen as equal to the bytestrings in scriptContextTxInfo. The validator traces leave me completely in the dark as my code seems to be identical to other examples that apparently work.

I've ran into similar issue. You can try to use fromHex function form Ledger.Bytes module, which will return the pubkeyhash as bytes representation.
This answer helped me with this.

Thanks, this worked!


text:
How to provide Datum value using serialization lib
I am consuming a script output and also create a new one at the same script address. The validator script requires the output producer to provide the datum value due to making assertions on it.
Therefore, I would like to know how can I provide a datum value for creating an output using the cardano serialization lib and not just the datum hash!
The only thing I saw was something called TransactionBuilder.set_auxiliary_data() but I am not sure whether that fits what I need.
Thanks for any advice in the right direction.
Currently I am doing something like this which obviously only provides the datum hash - not the value.
txBuilder.add_output(
    TransactionOutputBuilder.new()
        .with_address(scriptAddress)
        .with_data_hash(hash_plutus_data(myDatum))
        .next()
        .with_value(Value.new(amount))
        .build()
);

Thanks to Sebastien, there is an open issue for this.
Github Feature Request
Besides, one can attach the datum separately to the tx witness set, like so for example:
const datums = PlutusList.new();
datums.add(datumOfCurrentOutputToBeConsumed);
datums.add(datumOfNewOutputToBeCreated);

const transactionWitnessSet = TransactionWitnessSet.new();
transactionWitnessSet.set_plutus_data(datums);

I have the same issue and I write a comment in the cardano-serialization-lib repo. I hope it helps:
Reference: https://github.com/Emurgo/cardano-serialization-lib/issues/443#issuecomment-1195619916
There are two problems; first, the extra data isn't taken into account in the fee calculation and the second one is that you can't calculate automatically the script data hash with the tx builder if you are not calling a script redeemer.
For the fee calculation, I create a dummy WitnessSet and put the datums inside. When the witness set is ready, I use it to calculate the final length and I add this "extra fee" to the transaction builder configuration.
const plutusList = CSL.PlutusList.new()
selection.outputs.forEach(output => {
    if (output.plutusData) {
        plutusList.add(output.plutusData)
    }
})

const witness = CSL.TransactionWitnessSet.new()
witness.set_vkeys(CSL.Vkeywitnesses.new())
witness.set_plutus_data(plutusList)

const txBuilder = CSL.TransactionBuilder.new(CSL.TransactionBuilderConfigBuilder.new()
    .coins_per_utxo_word(CSL.BigNum.from_str(protocolParameters.coinsPerUtxoWord.toString()))
    .fee_algo(CSL.LinearFee.new(CSL.BigNum.from_str(protocolParameters.minFeeCoefficient.toString()),
        CSL.BigNum.from_str((protocolParameters.minFeeConstant + protocolParameters.minFeeCoefficient * witness.to_bytes().length).toString())))
    .key_deposit(CSL.BigNum.from_str(protocolParameters.stakeKeyDeposit.toString()))
    .max_tx_size(protocolParameters.maxTxSize)
    .max_value_size(protocolParameters.maxValueSize)
    .pool_deposit(CSL.BigNum.from_str(protocolParameters.poolDeposit.toString()))
    .build())

In the fee_algo method, I multiply wintess.to_bytes().length by minFeeCoefficient to add the extra fee necessary. The good part of this solution is that you can continue using the transaction builder as before.
The final step is to add the script data hash at the end just before calling buildTx(). The challenge is that you can't use the method calc_script_data_hash, so you have to calculate and set it. In my case, I use this lines:
if (plutusList.len() > 0 ) {
    const scriptDataHash = CSL.hash_script_data(CSL.Redeemers.new(), CSL.TxBuilderConstants.plutus_vasil_cost_models(), plutusList)
    txBuilder.set_script_data_hash(scriptDataHash)
}

txBuilder.add_change_if_needed(CSL.Address.from_bech32(address))

Remember to set the script data hash before calling add_change_if_needed, otherwise the hash will not be included in the fee.


text:
LightWallet: Empty array for (await api.getUsedAddresses() || await api.getUnusedAddresses() || [])
I am working on a light wallet integration. The recommended way of integrating with wallets is defined in CIP30.
When I select Nami and call:
(await api.getUsedAddresses() || await api.getUnusedAddresses() || [])
everything works fine and I receive at least one wallet address - a non empty array. But using the same code for eternl/ ccvault I always receive an empty array.
Is this a missing implementation error on their end or a mistake on my end?
getChangeAddress() works fine for both wallets.
Here some code snippets for more context:
export const isBrowser = () => typeof window !== "undefined";
export type Cardano = {
  [key: string]: {
    name: string;
    icon: string;
    version: string;
    api?: WalletApi,
    enable: () => Promise<WalletApi>;
    isEnabled: () => Promise<boolean>;
  };
};

export const getCardano = (): Cardano | undefined => {
  const cardano = isBrowser() && window.cardano;
  return cardano;
};

and then later in the app:
async (actions, target, { getStoreActions }) => {
      const walletName: string = target.payload;
      const cardano = getCardano()!;
      const api = await cardano[walletName]!.enable();
      const addresses = (await api.getUsedAddresses()
                      || await api.getUnusedAddresses()
                      || []);
{...}

Thanks to Marcel - founder of eternl I've found my mistake.
await api.getUsedAddresses() actually returns an empty array - I thought both calls return undefined and it defaults to [].
After calling await api.getUsedAddresses() and await api.getUnusedAddresses() separately they both work as expected since my test wallet currently does not have used addresses.


text:
How to check if validator ran inside minting policy
I want to check within a minting policy whether a specific spending validator script is being run by checking if I can find an input that belongs to that spending validator's script address.
If there is an easier way please let me know but I am running in to the following problem:
I have a function that returns a Maybe of the transaction input matching my spending validator.
scriptInput :: Maybe TxInInfo
scriptInput =
    let isScriptInput i = (isScriptAddress . txOutAddress . txInInfoResolved) i
        xs = [i | i <- txInfoInputs info, isScriptInput i]
    in
        case xs of
            [i] -> Just i
            _   -> Nothing

isScriptAddress :: Address -> Bool
isScriptAddress
    Address { addressCredential=ScriptCredential vh
            , addressStakingCredential=Nothing
            } = vh == scriptValidatorHash -- comes from validator definition in same file
isScriptAddress _ = False

When I replace the vh == scriptValidatorHash with True I get no interpreter error, but if I leave it as described above I get the following error:
GHC Core to PLC plugin: E042:Error: Unsupported feature: Type constructor: GHC.Prim.ByteArray# Context: Compiling type: GHC.Prim.ByteArray# Context: Compiling data constructor type: GHC.Natural.NatJ# Context: Compiling type: GHC.Natural.Natural Context: Compiling data constructor type: PlutusCore.Core.Type.Version Context: Compiling type: PlutusCore.Core.Type.Version ann Context: Compiling data constructor type: UntypedPlutusCore.Core.Type.Program Context: Compiling type: UntypedPlutusCore.Core.Type.Program PlutusCore.DeBruijn.Internal.DeBruijn PlutusCore.Default.Universe.DefaultUni PlutusCore.Default.Builtins.DefaultFun () Context: Compiling type: Plutus.V1.Ledger.Scripts.Script Context: Compiling type: Plutus.V1.Ledger.Scripts.Validator Context: Compiling data constructor type: Ledger.Typed.Scripts.Validators.TypedValidator Context: Compiling type: Ledger.Typed.Scripts.Validators.TypedValidator a Context: Compiling type: Ledger.Typed.Scripts.Validators.TypedValidator a -> ...

It turns out directly referencing the spending validator hash computes the hash of the spending validator which runs the PLC plugin again. That leads to problems of some kind. Therefore the best solution for referencing script hashes inside scripts is by lifting them with the help of PlutusTx.liftCode and PlutusTx.applyCode.
So I made the following changes to my minting policy to get it to work:
I am passing along an address parameter which allows me to check  for equality - essentially, making my minting policy a parameterized policy.
{-# INLINABLE mkMintPolicy #-}
mkMintPolicy :: Address -> ScriptAction -> ScriptContext -> Bool
mkMintPolicy addr sa ctx =
    ...
    isScriptAddress :: Address -> Bool
    isScriptAddress a = a == addr
    ...

policy :: Scripts.MintingPolicy
policy = mkMintingPolicyScript $
    $$(PlutusTx.compile [|| wrap ||])
    `PlutusTx.applyCode` PlutusTx.liftCode mySpendingValidatorAddress
    where
        wrap addr = Scripts.wrapMintingPolicy $ policy addr


text:
Cannot find wrapMintingPolicy after updating to latest release of plutus-apps
I've just checked out the latest release of the plutus-apps repository and ensured to copy the respective cabal.project dependencies (including their commit hashes). But I get a weird error, I didn't receive running it with the older version.
src/Contract/MyPolicy.hs:44:43: error:
    • Not in scope: ‘Scripts.wrapMintingPolicy’
      Module ‘Ledger.Typed.Scripts’ does not export ‘wrapMintingPolicy’.
    • In the Template Haskell quotation
        [|| \ oref' tn'
              -> Scripts.wrapMintingPolicy $ mkMyPolicy oref' tn' ||]
      In the typed splice:
        $$(PlutusTx.compile
             [|| \ oref' tn'
                   -> Scripts.wrapMintingPolicy $ mkMyPolicy oref' tn' ||])
   |
44 |     $$(PlutusTx.compile [|| \oref' tn' -> Scripts.wrapMintingPolicy $ mkMyPolicy oref' tn' ||])

Usually, the Ledger.Typed.Scripts modules exported the wrapMintingPolicy function.
Source 1
cabal.project:
source-repository-package
  type: git
  location: https://github.com/input-output-hk/plutus-apps.git
  tag: v1.0.0-alpha1

...

source-repository-package
  type: git
  location: https://github.com/input-output-hk/plutus
  tag: a56c96598b4b25c9e28215214d25189331087244

You could try to replace Scripts.wrapMintingPolicy with Scripts.mkUntypedMintingPolicy
...

import Plutus.Script.Utils.V1.Typed.Scripts qualified as Scripts

...
$$(PlutusTx.compile
             [|| \ oref' tn'
                   -> Scripts.mkUntypedMintingPolicy $ mkMyPolicy oref' tn' ||])

Thanks a lot! I really appreciate it! It looks like all of these wrappers are being removed with the new Plutus version.
Just found this commit:
https://github.com/input-output-hk/plutus-apps/commit/91ee6f5b9d2cb6c620803ee367a2d1a145d63b48


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

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

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

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

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

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

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

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

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

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

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


text:
How to compare BuiltinByteStrings onchain?
I want to check on-chain if a given TokenName is of a specific pattern, for example:

aaa1
aaa2
aaa3

I have something like this, but it throws an interpreter exception:
checkValidMint :: TokenName -> Integer -> Bool
checkValidMint tn count  = tn == (TokenName $ "aaa" <> (integerToByteString count))

integerToByteString :: Integer -> BuiltinByteString
integerToByteString n
    | n == 0 = "0"
    | n == 1 = "1"
    | n == 2 = "2"
    | n == 3 = "3"
    | n == 4 = "4"
    | n == 5 = "5"
    | n == 6 = "6"
    | n == 7 = "7"
    | n == 8 = "8"
    | n == 9 = "9"
    | otherwise = integerToByteString (n `P.divide` 10) P.<> integerToByteString (n `P.modulo` 10)

Update 2
Also tried:
integerToByteString n
            | (Builtins.equalsInteger n 0) = "0"
            | (Builtins.equalsInteger n 1) = "1"
            | (Builtins.equalsInteger n 2) = "2"
            | (Builtins.equalsInteger n 3) = "3"
            | (Builtins.equalsInteger n 4) = "4"
            | (Builtins.equalsInteger n 5) = "5"
            | (Builtins.equalsInteger n 6) = "6"
            | (Builtins.equalsInteger n 7) = "7"
            | (Builtins.equalsInteger n 8) = "8"
            | (Builtins.equalsInteger n 9) = "9"
            | otherwise = integerToByteString (n `PlutusTx.Prelude.divide` 10) PP.<> integerToByteString (n `PlutusTx.Prelude.modulo` 10)

I keep getting an interpreter error:
GHC Core to PLC plugin: E042:Error: Unsupported feature: Use of Haskell Integer equality, possibly via the Haskell Eq typeclass Context: Compiling expr: GHC.Integer.Type.eqInteger# Context: Compiling expr: GHC.Integer.Type.eqInteger# x Context: Compiling expr: GHC.Integer.Type.eqInteger# x y Context: Compiling expr: case GHC.Integer.Type.eqInteger# x y of wild [Occ=Once] { __DEFAULT -> GHC.Prim.tagToEnum# @ GHC.Types.Bool wild } Context: Compiling expr: \ (y [Occ=Once] :: GHC.Integer.Type.Integer) -> case GHC.Integer.Type.eqInteger# x y of ...

This is how I've done the integer conversion in the past. Might need some minor updating:
{-# INLINEABLE intToString #-}
intToString :: Integer -> Builtins.String
intToString i = Prelude.foldr Builtins.appendString "" strings
  where
    ints = intToInts i
    strings = map (Builtins.charToString . intToChar) ints

{-# INLINEABLE intToChar #-}
intToChar :: Integer -> Haskell.Char
intToChar i
  | (Builtins.equalsInteger i 0) = '0'
  | (Builtins.equalsInteger i 1) = '1'
  | (Builtins.equalsInteger i 2) = '2'
  | (Builtins.equalsInteger i 3) = '3'
  | (Builtins.equalsInteger i 4) = '4'
  | (Builtins.equalsInteger i 5) = '5'
  | (Builtins.equalsInteger i 6) = '6'
  | (Builtins.equalsInteger i 7) = '7'
  | (Builtins.equalsInteger i 8) = '8'
  | (Builtins.equalsInteger i 9) = '9'
  | otherwise = '0' -- Fix this

Then instead of checkValidMint, you can just check that the expected amount of your new token is included in the output value in the policy ctx, like here in the Uniswap example.

Unfortunately, I cannot get this code to run. It seems like charToString is not part of the API anymore. And String has been replaced with BuiltinString.
I am not sure how to make use of this code. Any other suggestions?

Make sure you are using INLINEABLE on your code, try using equalsInteger instead of ==, and see where that lands you. You might need to dig and see what methods on char there are instead of charToString. I'd need to do some digging to say for sure what all has changed.

You may want to checkout the utils package I used for the open source cardano lottery located here: https://github.com/lley154/cardano-lottery/blob/main/src/Utils.hs.   This code has been tested and works on the testnet.
Also, there was a similar post that may help if you having issues and need to be aware of the encoding of builtinbytestrings in plutus.  How to get a base 16 hex BuiltinString from getTxId

After testing out many different variations, changing imports to make sure the correct functions of Prelude and PlutusTx.Prelude are used, I've found the problem:

I made sure this pragma is present: {-# LANGUAGE NoImplicitPrelude #-}
I imported both Preludes in a qualified way:

import           PlutusTx.Prelude as PP
import           Prelude          as P

which let's me clearly distinguish what operators to use when it comes to Integer comparisons. I subsequently replaces all == with either PP.== for on-chain and P.== for off-chain code.

Lastly, I found one more error where I used Integer pattern matching on-chain like so:

checkMint :: String -> Integer -> Bool
checkMint s (1)  = ...
checkMint s (-1) = ...
checkMint _ _    = False

The pattern matching seems to default to P.== for this on-chain code, so I replace it with an if-then-else and it worked fine.
checkMint s amt =
    if amt PP.== 1 then ...
    else if amt PP.== -1 then ...
    else ...


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

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

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

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

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

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

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

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

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

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


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

Kupo
Oura
Scrolls
Marconi
Blockfrost
Ogmios
Carp

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

Thanks, I appreciate the feedback!

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

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

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


text:
Easy way to list IPFS directory contents
I have an image directory that I've posted to IPFS with a large number of images in it. When I try to query the directory using an IPFS HTTP gateway, I get a gateway timeout error as I assume the quantity of files is so high. I am using:
https://gateway.ipfs.io/ipfs/bafybeiakb6sdfohwdw7dtdbe..../directory

Is there a simple way to CURL this directory easily into a json file, or some other method where I can get the file list? I also have IPFS downloaded and installed on my Ubuntu server, but can't figure out how to list the files within this directory through there either...

Might be worth checking if the cloudflare IPFS gateway works for you to get access to the directory.
Check out this link here.


text:
InvalidCertificate error running the cardano-node (v 1.35.7) static binary
I'm trying to run the cardano-node static binary with the following command:
cardano-node run \
  --topology environments/topology.json \
  --database-path db \
  --socket-path ipc/node.socket \
  --host-addr 127.0.0.1 \
  --port 3001
  --config environments/config.json

But no matter the configuration options, it's always shutting down with the following error:
[Framey:cardano.node.ChainDB:Info:5] [2023-04-12 08:39:37.16 UTC] Started opening Volatile DB
[Framey:cardano.node.ChainDB:Info:5] [2023-04-12 08:39:37.16 UTC] Opened vol db
[Framey:cardano.node.ChainDB:Info:5] [2023-04-12 08:39:37.16 UTC] Started opening Ledger DB
[Framey:cardano.node.ChainDB:Info:5] [2023-04-12 08:39:37.16 UTC] Replaying ledger from genesis
[Framey:cardano.node.ChainDB:Info:5] [2023-04-12 08:39:37.16 UTC] Closed Immutable DB.
[Framey:cardano.node:Critical:5] [2023-04-12 08:39:37.16 UTC] fromList [("error",String "could not create initial ChainValidationState: InvalidCertificate\nCallStack (from HasCallStack):\n  error, called at src/Ouroboros/Consensus/Byron/Ledger/Ledger.hs:133:19 in ouroboros-consensus-byron-0.1.0.1-A6Uz6cpocu3BICcYhLnc6M:Ouroboros.Consensus.Byron.Ledger.Ledger"),("kind",String "ConsensusStartupException")]

Shutting down..

cardano-node: could not create initial ChainValidationState: InvalidCertificate
CallStack (from HasCallStack):
  error, called at src/Ouroboros/Consensus/Byron/Ledger/Ledger.hs:133:19 in ouroboros-consensus-byron-0.1.0.1-A6Uz6cpocu3BICcYhLnc6M:Ouroboros.Consensus.Byron.Ledger.Ledger

What does this mean? And more importantly, how can it be fixed?
I'm using the latest binary (1.35.7) with the preview network configs on Linux (Ubuntu 22.04).
UPDATE:
It seems to be a bug in the tarball binary distribution: https://github.com/input-output-hk/cardano-node/issues/5076
UPDATE 2:
Bug confirmed. 1.35.6 does work as expected.

How much RAM do you have? Its unlikely to run in less that 16G.

I've got 64 GB of ram, so that's definitely not the issue. I run nodes using docker, sometimes two or three together.


text:
How to determine the number of actual "transactions" in a transaction?
You may have seen some of the online discussions on Twitter about Cardano TPS (Transactions Per Second) count. It lead me down the rabbit hole of trying to see if I could calculate TPS more accurately. I have listed my findings below but want to get them vetted.
Assumption: A true "transaction" refers to the transfer of value between one person and the next. We will exclude native assets from this for the time being.
Cardano allows for a many to many relationship. Many addresses sending to many addresses. In the Bitcoin world this is known as cojoining or mixing. It is pretty normal to see inputs coming from more than one address on the Cardano blockchain.
There appears to be no easy / clear cut way to calculate TPS but there are the following rules of thumb:

Exclude any UTxOs that were consumed an hour of being created - see
early spend on page 8 to understand why.
You then have to determine which of the UTxOs are "change outputs". In the case of 1 input to many outputs, this can be determined fairly easily. However in the case of multiple inputs from different addresses going to multiple output addresses this seems impossible. It seems that Cardano is set up like a coin mixer in this regard.

Do you agree, and any ideas / suggestions?

Here is the final answer I went with
https://reddspark.blog/2022/12/11/transactions-within-transactions/
Open to critique.

I think that you are mixing a couple of concepts here.
In Cardano, same as Bitcoin, a transaction can take various inputs (consume UTxOs) and produce various outputs (new UTxOs to be used by future transactions).
This means I can transfer tokens to 20 different people in the same transaction and that does not mean that I am creating 20 transactions. I will only get one transaction hash (you can check this in any explorer, such as Cardanoscan). So, for TPS, that will count as one, not 20, because the TPS concept is related to the validation of the transaction on chain and not to how many UTxOs you are consuming to create it.
So, under this scenario and with the assumption you have, I think you will find it quite hard (not to say impossible) to determine how many of those UTxOs are really going to one person to another (you will have to know, for example, if one of the output addresses does not belong to the sender of the transaction - maybe they have another wallet? - so you can exclude that one as well). If that wallet does not belong to an SPO or someone publicly exposed, then this won't be possible.

You reminded me I actually answered my own question after I asked this, on my blog: https://reddspark.blog/2022/12/11/transactions-within-transactions/


text:
No relay IP at https://explorer.mainnet.cardano.org/relays/topology.json after more than 2 weeks
I have to say, that i have already done 1 SPO about month ago, and all was fine.
Today i have struggling with another one that i have to set up.
All looks like fine, but i can't see mine realay IP on https://explorer.mainnet.cardano.org/relays/topology.json and no metter what i do.. (First SPO relay was there really quick)
So please help me to figure out what is wrong now..
ScreenShots (let me know if need any more)

All looks like fine, but i can't see mine realay IP on https://explorer.mainnet.cardano.org/relays/topology.json and no metter what i do

That URL only fetches relays that are registered as part of pool registration and can be reached publicly - besides, it is refreshed to catch peers publicly twice a week (might have changed since). So if you have modified your pool registration details to include your new relay, and your pool is reachable publicly - you might want to wait for a few days before trying to query that URL.
Your outbound topology.json file or subscription to topology Updater is irrelevant to be listed on the mentioned link.

RdLrT thansk for anwser. I'm a little be confused, so it's no metter if my relay ip is not there? It's still will work correctly and produce blocks?
I ask it, cose all tutorials says that i have to be in that list, before continue set up SPO. In another words if you not in that list, your SPO will not produce block or will produce but no rewards will be generated..
P.S. It's new SPO with 1 bp and 1 relay. It's not extend currenct SPO with another relay.

Btw that file last update was: last-modified: Thu, 22 Sep 2022 20:29:47 GMT or last-modified: Thu, 01 Sep 2022 14:00:21 GMT it's depends what file loaded (cose there is 2 different files). It's obviously is something wrong with that..

You need incoming peers (be it via topologyUpdater or other manual peering arrangements with different SPOs) - but the link you're looking at isn't a source of truth, and the peers that appear in the list are as mentioned in the reply