text:
I want to build a transaction to send Assets using cardano serialization lib
I want to transfer asset instead of ADA using cardano serialization Lib. I am new to cardano blockchain.
I recently transferred ADA's build a transaction using this link so far
https://github.com/Emurgo/cardano-serialization-lib/blob/master/doc/getting-started/generating-transactions.md.
But can't find any possible way to transferred the assets.

This is the code I use to send multiple assets with @emurgo/cardano-serialization-lib-nodejs:
import * as CardanoWasm from "@emurgo/cardano-serialization-lib-nodejs";

export async function buildMultiAssetTx(
  fromAddress: string,
  toAddress: string,
  policy: string,
  assetName: string,
  amount: string,
  privateKey: CardanoWasm.PrivateKey
) {

  const params = await getParameters();

  const linearFee = CardanoWasm.LinearFee.new(
    CardanoWasm.BigNum.from_str(params.data.genesis.shelley.protocolParams.minFeeA.toString()),
    CardanoWasm.BigNum.from_str(params.data.genesis.shelley.protocolParams.minFeeB.toString())
  );

  const txBuilderConfig = CardanoWasm.TransactionBuilderConfigBuilder.new()
    .fee_algo(linearFee)
    .pool_deposit(CardanoWasm.BigNum.from_str(params.data.genesis.shelley.protocolParams.poolDeposit.toString()))
    .key_deposit(CardanoWasm.BigNum.from_str(params.data.genesis.shelley.protocolParams.keyDeposit.toString()))
    .max_value_size(params.data.genesis.alonzo.maxValueSize)
    .max_tx_size(params.data.genesis.shelley.protocolParams.maxTxSize)
    .coins_per_utxo_word(CardanoWasm.BigNum.from_str(params.data.genesis.alonzo.lovelacePerUTxOWord.toString()))
    .build();

  // instantiate the tx builder with the Cardano protocol parameters - these may change later on
  const txBuilder = CardanoWasm.TransactionBuilder.new(txBuilderConfig);

  const unspentOutputs = await getTxUnspentOutputs(fromAddress);

  // pointer address
  const shelleyChangeAddress = CardanoWasm.Address.from_bech32(fromAddress);

  const minter = CardanoWasm.Address.from_bech32(toAddress);

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

  const multiAsset = CardanoWasm.MultiAsset.new()

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

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

  txBuilder.add_output(txOutput)

  // add a keyhash input - for ADA held in a Shelley-era normal address (Base, Enterprise, Pointer)
  txBuilder.add_inputs_from(unspentOutputs, 3); // LargestFirstMultiAsset

  // set the time to live - the absolute slot value before the tx becomes invalid
  const slot = await getSlotNo();
  txBuilder.set_ttl(slot.data.cardano.tip.slotNo + 10000);

  // calculate the min fee required and send any change to an address
  txBuilder.add_change_if_needed(shelleyChangeAddress)

  // once the transaction is ready, we build it to get the tx body without witnesses
  const txBody = txBuilder.build()
  const txHash = CardanoWasm.hash_transaction(txBody);
  const witnesses = CardanoWasm.TransactionWitnessSet.new();
  const vkeyWitnesses = CardanoWasm.Vkeywitnesses.new();
  const vkeyWitness1 = CardanoWasm.make_vkey_witness(txHash, privateKey);

  vkeyWitnesses.add(vkeyWitness1);

  witnesses.set_vkeys(vkeyWitnesses);
  witnesses.set_native_scripts(CardanoWasm.NativeScripts.new());

  // create the finalized transaction with witnesses
  const transaction = CardanoWasm.Transaction.new(
    txBody,
    witnesses,
    undefined, // transaction metadata
  );

  return toHexString(transaction.to_bytes());

}


text:
How to know wallet name by wallet Address?
I am fetching the data of  ADA rate in USD through api(https://studio-api.nmkr.io/v2/GetAdaRates) and I want to fetch the some data of related to wallet like its wallet name, wallet image, wallet current balance, ADA rates in USD . So is there any api for this?

What do you mean by "fetch the same data but related to wallet"? The rate of ADA in USD is the same for every wallet. Maybe you want to get rate in USD but of other tokens instead?

I am getting the ADA rates from nmkr.io which i am using to get current price fluctuations in rates of ADA.

If you're looking for a simple API to get data from the Cardano Blockchain, you can use Koios or Blockfrost. You can use these APIs to get the wallet balance for example.
Cardano wallets don't have a name or an image/icon, therefore you can't get a these from any API.
Unless you're referring to an Adahandle, in that case you can look for a native asset from the Adahandle policy in the wallet.

source: Stack Exchange

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

sort: votes


text:
Catalyst App still showing Fund9 and connection in progress
Fund10 due on 5 Apr, 2023, 13:00
but the catalyst iPhone app is showing Fund9 and connection in progress.
How can I confirm that I could vote for the next round?

The Voting app is inactive at the moment. It will receive an update soon in anticipation of a vote before Fund10.
In addition to this, that date for the start of Fund10 is not accurate: there is no specific timeline just yet. Tho they are getting close to the next steps. They have started sharing some information during past two town halls that affect Fund10 outlook. There will be a vote between Fund10 to formally endorse the direction and everything else.

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


text:
Successfully built cardano-node 1.35.7 but still getting version cardano-node and cardano-cli 1.35.3
I followed the iohk instructions to update my cardano-node to version 1.35.7. It built the node with no errors. However when I run cardano-node --version, cardano-cli --version, I get 1.35.3.
I've checked that my config, topology, etc files are correct. No clue what to do. Any help would be appreciated.

Your link to the "iohk instructions" links to the git repo, so I am not really sure which instructions you are talking about.
Assuming you are on Linux, you can run the command which cardano-node and which cardano-cli to figure out where these programs are installed/located. My suspicion is that they are installed in different locations.

Thank you for your help. I actually did not completely follow instructions. I missed this step which @Nic_T2H pointed out. Thank you both!

Building the cardano-node and cardano-cli doesn't mean that your service is using it.
To install the new binaries, copy them from inside the git folder to the folder where the cardano-node.service is looking for binaries to use:
sudo cp $(find ./dist-newstyle/build -type f -name "cardano-node") <DestinationPath>/cardano-node
sudo cp $(find ./dist-newstyle/build -type f -name "cardano-cli") <DestinationPath>/cardano-cli

than check that the new version is installed:
cardano-cli version
cardano-node version

Once you are sure about the new version, restart your cardano-node service.
Full documentation about the update procedure: link

Thank you so much, this was exactly it. I assumed incorrectly and did not do this step. All fixed now!


text:
Node never begins to sync, hangs at certain point
Haven't started my node for 6 months (testnet) so I cleared the container to start another sync from scratch, keep getting this weird error & the node won't start adding new chain tips
cardano-node.1-35-2      | [62f086c7:cardano.node.DnsSubscription:Warning:58] [2023-04-05 14:35:25.81 UTC] Domain: "relays-new.cardano-testnet.iohkdev.io" Failed to start all required subscriptions
cardano-node.1-35-2      | [62f086c7:cardano.node.DnsSubscription:Warning:58] [2023-04-05 14:40:15.77 UTC] Domain: "relays-new.cardano-testnet.iohkdev.io" Failed to start all required subscriptions
cardano-node.1-35-2      | [62f086c7:cardano.node.DnsSubscription:Warning:58] [2023-04-05 14:40:25.87 UTC] Domain: "relays-new.cardano-testnet.iohkdev.io" Failed to start all required subscriptions
cardano-node.1-35-2      | [62f086c7:cardano.node.DnsSubscription:Warning:58] [2023-04-05 14:40:35.89 UTC] Domain: "relays-new.cardano-testnet.iohkdev.io" Failed to start all required subscriptions
cardano-node.1-35-2      | [62f086c7:cardano.node.DnsSubscription:Warning:58] [2023-04-05 14:40:35.89 UTC] Domain: "relays-new.cardano-testnet.iohkdev.io" Failed to start all required subscriptions
cardano-node.1-35-2      | [62f086c7:cardano.node.DnsSubscription:Warning:58] [2023-04-05 14:40:35.89 UTC] Domain: "relays-new.cardano-testnet.iohkdev.io" Failed to start all required subscriptions
cardano-node.1-35-2      | [62f086c7:cardano.node.DnsSubscription:Warning:58] [2023-04-05 14:40:35.89 UTC] Domain: "relays-new.cardano-testnet.iohkdev.io" Failed to start all required subscriptions
cardano-node.1-35-2      | [62f086c7:cardano.node.DnsSubscription:Warning:58] [2023-04-05 14:40:35.89 UTC] Domain: "relays-new.cardano-testnet.iohkdev.io" Failed to start all required subscriptions
cardano-node.1-35-2      | [62f086c7:cardano.node.DnsSubscription:Warning:58] [2023-04-05 14:40:35.89 UTC] Domain: "relays-new.cardano-testnet.iohkdev.io" Failed to start all required subscriptions
cardano-node.1-35-2      | [62f086c7:cardano.node.DnsSubscription:Warning:58] [2023-04-05 14:40:35.89 UTC] Domain: "relays-new.cardano-testnet.iohkdev.io" Failed to start all required subscriptions
cardano-node.1-35-2      | [62f086c7:cardano.node.DnsSubscription:Warning:58] [2023-04-05 14:40:35.89 UTC] Domain: "relays-new.cardano-testnet.iohkdev.io" Failed to start all required subscriptions

I start my container with NETWORK=testnet docker compose --file node-compose.yml up am I not supposed to use NETWORK=testnet anymore? This link says there are preview & pre-prod testnets but when I use that instead of testnet I get an error.
What could be going wrong here? What has changed?

The legacy Cardano testnet has been decommissioned, you need to use preview or preprod.

I ended up upgrading my node from 1.35.2 to 1.35.7 & using preprod.


text:
Lucid npm throws error
I am trying to run the Lucid app. In /code/Week03/lucid directory, when I run npm install I get these errors:
npm ERR! code 126
npm ERR! path /workspace/code/Week03/lucid/node_modules/utf-8-validate
npm ERR! command failed
npm ERR! command sh -c node-gyp-build
npm ERR! /usr/bin/env: 'node': Permission denied

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2023-04-06T11_15_43_098Z-debug.log

Any solution to this error?

You just need to change ownership of 'node'.
https://stackoverflow.com/questions/70931624/usr-bin-env-node-permission-denied
sudo chown $USER /usr/bin/env/node


text:
nodes stopping because of Bus error: 10
All I can find online is that Bus error: 10 means it's trying to reach a memory space that isn't there.  The testnet/preprod/mainnet nodes start up fine but stop shortly after with either Bus erro:10 or sometimes I get segmentation fault: 11.  What is going on?

I have same problem. Running MacBook Pro. The node worked fine for a long time but then suddenly when started it gets the ”bus error: 10” or the ”segmentation fault”. Tried update to latest 1.35.7 cardano node and also reinstall the whole node. Doesn’t work.
Would really appreciate some help with this.

Was having the same issue, building version 8.1.2 with GHC 9.2.8 instead resolved for me.


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:
Creating a malicious validator script whose hash equals that of an existing validator script
what is preventing an adversary to find (in many hours) a nonce that would make a malicious validator script to have the same hash and address of my validator script, and then submit it with cardano-cli in a transaction that unlocks at once all the utxos held at that address? Would this take (in average) a year with 8 or 16 of today's CPUs? 10 years? 1000 years?

Can you share more information about what you are trying to do?

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

By adding a constant to a malicious script (let's call this constant "nonce") and by changing its value, one can obtain a different hash for the malicious script and so after many different attempts, can find a value for nonce such that the malicious script has the same hash (and address) of my genuine validator. If I originally provided only the hash of my validator and not the script itself, then one could in theory substitute it with the malicious script and override my genuine validator. So the question is:

how long could it take in average to a computer with 16 of today's CPUs, given a malicious script,  to find a nonce such that the hash and the address of the malicious script is the same hash and address of my genuine validator?

Actually, This is an interesting question. I would like to share my thought about this. I don't know if I made mistakes somewhere. Please just consider it as a reference.
Problem:
we want to consume all UTxOs locked at a validator address without knowing the validator script or without qualifying it.
Approach:
we could try to create our malicious script that always returns to True. However, Cardano will always check if the hash value of the actual script is the same as the hash value of the provided script when we submit the consuming transaction. So in our malicious script, we could add a random line such as nonce = 1, nonce = 2, nonce = 3 and so on until the hash value of our script is the same as the actual script.
My calculation:
As far as I know, the validator address is also the hash value of the script. I tried to take a sample validator address which is from plutus-pioneer-program (see here), it seems to be the shortest address type. addr_test1wqag3rt979nep9g2wtdwu8mr4gz6m4kjdpp5zp705km8wys6t2kla. although I am not sure how the hash function is implemented, I can see all characters could be 0-9 or a-z and the length of the address 1wqag3rt979nep9g2wtdwu8mr4gz6m4kjdpp5zp705km8wys6t2kla is 54. Based on this idea, I calculated the number of all possible cases of the hash value as the following
Total possible cases = (10 + 26)  54  cases
Where

10 is for 0-9
26 is for a-z
54 is the length of the address (is also the length of the hash value of the validator).

I am not really sure about the speed of today's CPU. let's say that 8 CPUs could handle 10^9 check (including compiling and running the malicious programs to take the hash value and check if it's expected) per second.
the result will be: (10+26)  54  / 109 / 3600 / 24 / 365 ~ 3.48 * 10  67  years.
It's a rough estimation, that's possible to have the case that some nonce value lead to the same hash value. for instance, nonce = 1 and nonce = 123978231231 return the same hash value, we need to check even more. Otherwise, in case we could find the result during the checking process soon, we don't need that long time.
Hope this is helpful!


text:
Official IOG Cardano Node Course Documentation Error - Node Won't Start
I am following along with the new Official IOG Cardano Node Course:
https://cardano-course.gitbook.io/cardano-course/

I am stuck at Video 3 at 6 minutes and 8 seconds in.
https://youtu.be/YlUljmlCPYs?t=368

I started with a new WSL setup with Ubuntu 22.04.
I used the nix setup method shown in video 2.
There was no indication of any problems.
Then I ran the following command to start the node.
js@LAPTOP-NGQPLDGT:~/preview$ cardano-node run --topology topology.json --database-path db --socket-path node.socket --port 3001 --config config.json

This produced the following error message:
cardano-node: FatalError {fatalErrorMessage = "Cardano.Node.Run.handleSimpleNodeP2P.readTopologyFile: Is your topology file formatted correctly? Expecting P2P Topology file format. The port and valency fields should be numerical. If you specified the correct topology file make sure that you correctly setup EnableP2P configuration flag. Error in $: key "LocalRoots" not found"}

It should work if I followed the directions exactly because I used the topology file that was supplied with the course. I am reporting the issue here because if I followed the directions accurately then there is an issue with the course materials which must be fixed.
I am curious to know if there is anyone else using Windows Subsystem for Linux setup with Ubuntu 22.04 who has followed video 2 in the series and what was the result?
Any ideas?
Much thanks.

The following is the contents of the topology file. It was retrieved using the following command as per course instructions found at this link here.

wget https://book.world.dev.cardano.org/environments/preview/topology.json

{
  "localRoots": [
    {
      "accessPoints": [],
      "advertise": false,
      "valency": 1
    }
  ],
  "publicRoots": [
    {
      "accessPoints": [
        {
          "address": "preview-node.world.dev.cardano.org",
          "port": 30002
        }
      ],
      "advertise": false
    }
  ],
  "useLedgerAfterSlot": 322000
}

This appears to be your topology file. You're probably running the p2p enabled config, but using the old topology format. Edit config.json and set "EnableP2P": false, or remove the parameter totally. If that's not enabled, post your topology file (hiding your IPs), so we can look at it. Your p2p local roots needs to look like the following:
  "localRoots": [{
    "accessPoints": [
      {"address": "your blockproducer/relay IP or domain name", "port": 6000}
    ],
    "advertise": false,
    "valency": 1
  },{
   "accessPoints": [
     {"address": "if you have a second relay", "port": 6000}
   ],
   "advertise": false,
   "valency": 1
  }],

If you're certain P2P is not enabled in your config, then you could try the old format (and by old I mean about 2 weeks old now and is still used by the majority).
{
  "Producers": [
    {
      "addr": "BP/Relay IP or domain name",
      "port": 6000,
      "valency": 1
    },
    {
      "addr": "If you have a second",
      "port": 6000,
      "valency": 1
    }
  ]
}

Thanks @PREEB, I didn't see anything about EnableP2P. I posted the contents of the topology file in the body of my original question. Thanks for having a look.

@JohnShearing I updated my answer above. Looks like you're using the "preview" version of the config.json, which in fact does have   "EnableP2P": true,

Ultimately the following text in the topology.json file worked when setting EnableP2P": false in the config.json file all as @PREEB suggested.
{
  "Producers": [
    {
      "addr": "preview-node.world.dev.cardano.org",
      "port": 30002,
      "valency": 1
    }
  ]
}

The URL to use was found here and it had to be pasted into a file of the format suggested by @PREEB
So I followed the directions in the course correctly but the file topology.json file I was directed to use was not correct and the P2P setting in the config.json file was set to true when it must be set to false.
I hope this can be corrected in the documentation so that others will not have the same problem when working through the course. Otherwise I am really enjoying the course and learning a lot.
I see the GitHub repository is here.
I will reach out to the creator.
Much thanks.


text:
Are validator script parameters secure? (lobster challenge)
Since script params are compiled into the validator, this means that if you have the script cbor you can see what the param value is, right? Hence they would not be suitable to store data you don't want available on chain?
context
The reason I'm asking is because I had a look at the lobster challenge (https://github.com/input-output-hk/lobster-challenge) posted by iohk a while back and they mentioned that they used a script parameter to add their "secret random" number when the contract was compiled, which would be used to offset the final value.
My intuition says if you had access to the script cbor(which you can get from blockfrost now) you would have been able to find out what their number was and if you were the last voter, have your pick of the name? Them using this method made me question whether having the cbor is enough - I'm not familiar with what's involved in decompiling plutus core cbor.
Thanks.

As you can imagine I'm not too fussed about whether the lobster naming was exploitable, more curious for the sake of learning.

Yes, if you had the script CBOR before, you could have used it to extract the seed and hack the challenge.
With aiken, which at this time was probably not available, you can do:
echo "591021010000332323233223...12330010030021120011" > lobster.cbor
aiken uplc unflat lobster.cbor -c
grep "con integer" lobster.uplc

and get the result:
                            [ i_930 (con integer 582757474857012117487873) ]
                      (con integer 1219)
                    (con integer 500)

and identify the 500 as the number of votes (known), the 1219 as the number of names (known) leaving only the 582757474857012117487873 as the secret number.

Thanks! Although surely the participants would have needed to supply the script CBOR to the validator when submitting their transactions?

Yes, true, it was the same contract to reveal and to vote.
I remembered it as two different contracts, in this case it would have been safe.
I'll add how one can find the constants from the cbor to the answer.

Cool, thanks for clarification. Also great addition to the answer!


text:
Lucid Error "End of input in bytes"
I am running the simple vesting script from PPP for the first time with Lucid and I continuosly get an error which doesn't give me much to understand what could realistically be the source of.
the validator goes:
data MisteryDatum = MisteryDatum
    { beneficiary1 :: PubKeyHash
    , beneficiary2 :: PubKeyHash
    , deadline     :: POSIXTime
    }

unstableMakeIsData ''MisteryDatum

{-# INLINABLE mkMisteryValidator #-}
mkMisteryValidator :: MisteryDatum -> () -> ScriptContext -> Bool
mkMisteryValidator dat () ctx =
    traceIfFalse "Benificiary1 did not sign or to late" checkCondition1 ||
    traceIfFalse "Benificiary2 did not sign or is to early" checkCondition2
    where
        txInfo :: TxInfo
        txInfo = scriptContextTxInfo ctx

        txValidRange :: POSIXTimeRange
        txValidRange  = txInfoValidRange txInfo

        checkCondition1 :: Bool
        checkCondition1 = txSignedBy txInfo (beneficiary1 dat) &&
                          contains (to (deadline dat)) txValidRange

        checkCondition2 :: Bool
        checkCondition2 = txSignedBy txInfo (beneficiary2 dat) &&
                          contains (from (1 + deadline dat)) txValidRange

while the Lucid function that causes the error is:
async function claimVestedFunds(): Promise<TxHash> {
  const dtm: Datum = Data.to<VestingDatum>(datum,VestingDatum);
  const utxoAtScript: UTxO[] = await lucid.utxosAt(vestingAddress);
  const ourUTxO: UTxO[] = utxoAtScript.filter((utxo) => utxo.datum == dtm);

  if (ourUTxO && ourUTxO.length > 0) {
      console.log(ourUTxO)
      const tx = await lucid
          .newTx()
          .collectFrom(ourUTxO, Data.void())
          .addSignerKey(beneficiaryPKH)
          .attachSpendingValidator(vestingScript)
          .validFrom(Date.now())
          .complete();

      const signedTx = await tx.sign().complete();
      const txHash = await signedTx.submit();
      return txHash
  }
  else return "No UTxO's found that can be claimed"
}

I checked date and beneficiary many times and they are correct, the only problem could be that I am using the same address public key for both benificiary1 and benificiary2. But that shouldn't be a problem right?
Anyway the function above shows the right UTxO
[
  {
    txHash: "a1d743f6a6c795dff9a5691ee25f1831485dd59f57476d6d9260691aaf65c3e6",
    outputIndex: 0,
    assets: { lovelace: 8700000n },
    address: "addr_test1wznyv36t3a2rzfs4q6mvyu7nqlr4dxjwkmykkskafg54yzs735734",
    datumHash: undefined,
    datum: "d8799f581ccecc6981a300d41fac6ae169c569a297c2837b1d8988762034ba4a65581ccecc6981a300d41fac6ae169c569a2...",
    scriptRef: null
  }
]

At this point something in the validation fails before the transaction is even sent and I receive the followign error:
error: Uncaught (in promise) "Redeemer (Spend, 0): end of input bytes"

I don't understand what could cause it as everything seem right and the error isn't articulated enough to give me precise indications, but what seem to cause that error is the line .collectFrom(ourUTxO, Data.void()) which seem fine to me as the UTxO is the right UTxO and the redeemer has to be void.

Review your vestingScript in Lucid. It's supposed to be structured as follows:
const vestingScript: SpendingValidator = {
    type: "PlutusV2",
    script: "590b30590b2d010000323……”,
};

However, after compiling, the JSON output is formatted differently:
{
    "type": "PlutusScriptV2",
    "description": "",
    "cborHex": "590b30590b2d010000323……"
}

Quoted from the answer linked below:
The error tells you that there is an error but you don't catch it. This is how you can catch it:
claimVestedFunds().then(response => {
    console.log(response);
}).catch(e => {
    console.log(e);
});

https://stackoverflow.com/questions/37624322/uncaught-in-promise-undefined-error-when-using-with-location-in-facebook-gra

thanks, but even then all it tells me is "Redeemer (Spend, 0): end of input bytes"

@user3755529 I wonder if it's possible your line for filtering is not working? This line const ourUTxO: UTxO[] = utxoAtScript.filter((utxo) => utxo.datum == dtm); Are you getting a valid utxo every time?

yes, the console.log at the beginning of the if always shows the right UTxO

@user3755529 Can you try a couple things? Preferably 1 at a time to narrow it down. 1. Instead of passing Data.void() into collectFrom, set a const and pass it in like follows const Redeemer = () => Data.void();
2. You are calling complete() twice on the same tx. I'm guessing you just need to do this once.
3. I would also try not passing Data.void() at all, since it's supposed to be optional. It looks like the lucid code checks if it's undefined, so really it should work without passing anything.

oh wow, yes, that seem to work, I get another error after at submit stage, need to look on it, but it seem the previous error is gone and I pass validation, thanks!

although now when I use const Redeemer = () => Data.void(); it tells me encoding/hex: invalid byte: (return new Error(.. and when I put nothing the transaction fails saying it lacks a redeemer .. (ApplyTxError [UtxowFailure (FromAlonzoUtxowFail (MissingRedeemers ..

@user3755529 Can you post the entire error for the invalid byte issue? Might be a red herring tho. The complete() call should come directly after the sign() call. I should have mentioned that before when I said you only needed one. Sadly Lucid's docs are sparse. I would also try it without validFrom. In its entirety ```
const Redeemer = () => Data.void();
const tx = await lucid
.newTx()
.collectFrom(ourUTxO, Redeemer)
.addSignerKey(beneficiaryPKH)
.attachSpendingValidator(vestingScript);
  const signedTx = await tx.sign().complete();```

if I don't use complete in the first variable tx I get TypeError: tx.sign is not a function       const signedTx = await tx.sign().complete()

error: Uncaught (in promise) Error: encoding/hex: invalid byte: (
return new Error(
^
at errInvalidByte (https://deno.land/std@0.100.0/encoding/hex.ts:15:10)
at fromHexChar (https://deno.land/std@0.100.0/encoding/hex.ts:35:9)
at decode (https://deno.land/std@0.100.0/encoding/hex.ts:78:15)
at decodeString (https://deno.land/std@0.100.0/encoding/hex.ts:110:10)
at fromHex (https://deno.land/x/lucid@0.9.1/src/utils/utils.ts:577:10)

at https://deno.land/x/lucid@0.9.1/src/lucid/tx.ts:80:41
at Tx.complete (https://deno.land/x/lucid@0.9.1/src/lucid/tx.ts:534:13)
at claimVestedFunds (file:///workspace/code/Week04/lecture/homework1.ts:97:34)
at async file:///workspace/code/Week04/lecture/homework1.ts:112:13

@user3755529 Looks like the line above this error is missing. The carat ^ is pointing to the actual char thats bad. Is there a line above this error that you can paste here.
Error: encoding/hex: invalid byte: ( return new Error( ^ at errInvalidByte
Maybe try changing the collectFrom to this.
.collectFrom([ourUTxO], Redeemer)

the ^ is pointing at n  in new Error


text:
Typed redeemer in a minting policy
I could not make the typed redeemer in the following minting policy work.  The redeemer was supposed to be data MintAction = Mint | Burn.  (I settled with the workaround type MintAction = Bool, with False representing Mint and True representing Burn.)
I get the error:
    * GHC stage restriction:
        instance for `UnsafeFromData
                        MintAction' is used in a top-level splice, quasi-quote, or annotation,
        and must be imported, not defined locally
    * In the first argument of `(.)', namely `mkUntypedMintingPolicy'
      In the Template Haskell quotation
        [|| mkUntypedMintingPolicy . emurgoMintingPolicyT ||]
      In the first argument of `PlutusTx.compile', namely
        `[|| mkUntypedMintingPolicy . emurgoMintingPolicyT ||]'

How to fix my minting policy?
{-# LANGUAGE DataKinds             #-}
{-# LANGUAGE DeriveAnyClass        #-}
{-# LANGUAGE DeriveGeneric         #-}
{-# LANGUAGE FlexibleContexts      #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NoImplicitPrelude     #-}
{-# LANGUAGE OverloadedStrings     #-}
{-# LANGUAGE ScopedTypeVariables   #-}
{-# LANGUAGE TemplateHaskell       #-}
{-# LANGUAGE TypeApplications      #-}
{-# LANGUAGE TypeFamilies          #-}
{-# LANGUAGE TypeOperators         #-}
{-# LANGUAGE NumericUnderscores    #-}

module Minting where

-- import           Data.Aeson          (ToJSON, FromJSON)
-- import           GHC.Generics        (Generic)
import qualified PlutusTx
import qualified PlutusTx.AssocMap as M
import           PlutusTx.Prelude       as TxPrelude hiding (unless)
import           Plutus.Script.Utils.Typed (mkUntypedMintingPolicy)
import           Plutus.V1.Ledger.Value
import           Plutus.V2.Ledger.Api
import           Plutus.V2.Ledger.Contexts as V2LC

-- data MintAction = Mint | Burn
--   deriving (Generic, FromJSON, ToJSON)
-- PlutusTx.unstableMakeIsData ''MintAction

-- | A workaround since I could not make 'data MintAction = Mint | Burn' work
type MintAction = Bool

treasuryValHash :: ValidatorHash
treasuryValHash = ValidatorHash "deadbeef"

mintingCost :: Integer
mintingCost = 75_000_000

symbolValueOf' :: CurrencySymbol -> Value -> (Integer, Integer)
symbolValueOf' cs v = case M.lookup cs (getValue v) of
  Nothing        -> (0, 0)
  Just csTokens -> (minted, burned)
    where
      minted = foldr sum' 0 . M.toList $ M.filter (>0) csTokens
      burned = foldr sum' 0 . M.toList $ M.filter (<0) csTokens
      sum' = \(_, a) b -> a + b

{-# INLINABLE emurgoMintingPolicyT #-}
-- | Typed minting policy
emurgoMintingPolicyT :: TxOutRef -> MintAction -> V2LC.ScriptContext -> Bool
emurgoMintingPolicyT oref redeemer ctx =
  let
    info             = scriptContextTxInfo ctx
    (minted, burned) = symbolValueOf' (ownCurrencySymbol ctx) (txInfoMint info)
  in
    case redeemer of
      -- 'False' stands for 'Mint'
      False ->   minted == 1
              && burned == 0
              && (any (\txo -> case addressCredential . txOutAddress $ txo of
                          PubKeyCredential _  -> False
                          ScriptCredential vh -> vh == treasuryValHash &&
                            valueOf (txOutValue txo) adaSymbol adaToken >= mintingCost) $
                      txInfoOutputs info)
              && (any (\txIn -> txInInfoOutRef txIn == oref) $ txInfoInputs info)
      -- 'True' stands for 'Burn'
      True  -> minted == 0 && burned < 0

-- | Minting policy compiled to Plutus Core
policy :: TxOutRef -> MintingPolicy
policy oref = mkMintingPolicyScript $
  $$(PlutusTx.compile [|| mkUntypedMintingPolicy . emurgoMintingPolicyT ||])
  `PlutusTx.applyCode`
  PlutusTx.liftCode oref

It compiles. So, in what way does this policy not work and what are you doing to produce that result?

Thanks for the reply.  It does not seem to compile.  I edited my post adding the error message.

This is to do with the use of Template Haskell. You can do this to prevent the error:
policy :: TxOutRef -> MintingPolicy
policy oref = mkMintingPolicyScript $
  $$(PlutusTx.compile [|| wrap ||])
  `PlutusTx.applyCode`
  PlutusTx.liftCode oref
  where
    wrap = mkUntypedMintingPolicy . emurgoMintingPolicyT


text:
Expecting one more argument to ‘RedeemerType’
My code is here
marketConstraints :: Market -> TxConstraints (RedeemerType -> ScriptContext -> Bool) (DatumType, ())
marketConstraints market = mustValidateIn (to $ scriptAddress market)

I am not sure how to do to correct this errors.
src/MarketState.hs:58:87: error:
   • Expecting one more argument to ‘RedeemerType’
      Expected a type, but ‘RedeemerType’ has kind ‘* -> *’
    • In the first argument of ‘TxConstraints’, namely
        ‘(RedeemerType -> ScriptContext -> Bool)’
      In the type signature:
        marketConstraints :: Market
                             -> TxConstraints (RedeemerType
                                               -> ScriptContext -> Bool) (DatumType, ())
   |
58 | marketConstraints :: Market -> TxConstraints (RedeemerType -> ScriptContext -> Bool) (DatumType, ())
   |                                               ^^^^^^^^^^^^

src/MarketState.hs:58:87: error:
    • Expecting one more argument to ‘DatumType’
      Expected a type, but ‘DatumType’ has kind ‘* -> *’
    • In the second argument of ‘TxConstraints’, namely
        ‘(DatumType, ())’
      In the type signature:
        marketConstraints :: Market
                             -> TxConstraints (RedeemerType
                                               -> ScriptContext -> Bool) (DatumType, ())

This is entirely related to Haskell. The kind of (->) is * -> * -> * thus in your type signature, both left-hand & right-hand side of -> must have kind * but some of your parameters such as RedeemerType & DatumType are higher kinded. If you are new to all this "kind" jargon, I would suggest this blog post on it.


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 use ownPubKey and RedeemerType and DatumType
My code is here.
{-# LANGUAGE DeriveAnyClass        #-}
{-# LANGUAGE DataKinds             #-}
{-# LANGUAGE DeriveGeneric         #-}
{-# LANGUAGE ScopedTypeVariables   #-}
{-# LANGUAGE TemplateHaskell       #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeOperators         #-}

module MarketState (
  createMarket
)where

import Plutus.Contract as Contract
import Control.Monad (void)
import Control.Applicative
import Data.Aeson (ToJSON, FromJSON)
import GHC.Generics (Generic)
import Schema (ToSchema)
import Data.String (String)
import Data.Text (Text)
import qualified PlutusTx
import Ledger (PubKeyHash(..))
import qualified Plutus.V1.Ledger.Ada as Ada
import Ledger.Constraints (TxConstraints)
import Ledger.Contexts (ScriptContext)
import Ledger.Typed.Scripts (DatumType, RedeemerType)

-- Define the market parameters
data MarketParams = MarketParams {
  event :: String,
  outcomes :: [String],
  fees :: Integer
} deriving (Generic, ToJSON, FromJSON, ToSchema)

PlutusTx.makeLift ''MarketParams

-- Define the smart contract logic
data Market = Market {
  params :: MarketParams,
  creator :: PubKeyHash
} deriving (Generic, ToJSON, FromJSON, ToSchema)

PlutusTx.makeLift ''Market

-- Create a function to deploy the smart contract
createMarket :: MarketParams -> Contract w s Text ()
createMarket params = do
  pk <- PubKeyHash <$> ownPubKey
  let market = Market params pk
  void $ submitTxConstraints (marketConstraints market) (tx market)
  logInfo $ "Market deployed at " <> show (address market)

-- Define the market constraints
marketConstraints :: Market -> TxConstraints (RedeemerType -> ScriptContext -> Bool)(DatumType, ())
marketConstraints market = mustValidateIn (to $ scriptAddress market)

-- Define the transaction logic
tx :: Market -> TxConstraints () ()
tx market = mustSpendScriptOutput (scriptTxOut $ market) (Redeemer $ PlutusTx.toBuiltinData BuyShares)
         <> mustPayToPubKey (creator market) (Ada.lovelaceValueOf $ fees $ params market)

I am a Plutus Smart Contract beginner. I don't sure how to fix this error. Please help me to fix the error.
src/MarketState.hs:58:47: error:
    • Expecting one more argument to ‘RedeemerType’
      Expected a type, but ‘RedeemerType’ has kind ‘* -> *’
    • In the first argument of ‘TxConstraints’, namely
        ‘(RedeemerType -> ScriptContext -> Bool)’
      In the type signature:
        marketConstraints :: Market
                             -> TxConstraints (RedeemerType
                                               -> ScriptContext -> Bool) (DatumType, ())
   |
58 | marketConstraints :: Market -> TxConstraints (RedeemerType -> ScriptContext -> Bool) (DatumType, ())
   |                                               ^^^^^^^^^^^^

src/MarketState.hs:58:87: error:
    • Expecting one more argument to ‘DatumType’
      Expected a type, but ‘DatumType’ has kind ‘* -> *’
    • In the second argument of ‘TxConstraints’, namely
        ‘(DatumType, ())’
      In the type signature:
        marketConstraints :: Market
                             -> TxConstraints (RedeemerType
                                               -> ScriptContext -> Bool) (DatumType, ())
   |
58 | marketConstraints :: Market -> TxConstraints (RedeemerType -> ScriptContext -> Bool) (DatumType, ())

RedeemerType and DatumType both require the data type to be specified, e.g. RedeemerType Integer.
If you use AllowAmbiguousTypes language extension you can do, e.g. RedeemerType a.


text:
Query and extract NFT metadata from a cardano-node instance (without db-sync)
Is there a way to query NFTs and extract NFT metadata from a cardano-node instance without using db-sync?

No, the transactional metadata are not part of the ledger state.

Thanks for the reply. Then, is there a way to scan the ledger directly? Are any of the db-* binaries in the tarball able to this? I need something that doesn't require 40GB of RAM, so db-sync is not an option. And it also needs to be able to run independently, without external services. My last resort would be Carp.

Sadly, I do not think that information is stored anywhere by the cardano-node. Cardano-db-sync or tools like Blockfrost actually has to reply all the blocks to extract it. Try maybe looking at Kupo.

I didn't know Kupo, looks great. That could be a useful tool. In the meantime, I've been considering other approaches to make it work with db-sync and even Blockfrost. Thanks again!


text:
Unlock NFT from smart contract by Cardano-serialization-library
I am trying to implement the Unlocking of NFT from an "always true" smart contract. I am using the Cardano serialization library for this. I can lock the NFT successfully, but when i unlock the NFT then i get the issue of Fee imbalancing issue i think. Maybe i am missing something and stuck on this.
I am facing this error
""transaction submit error ShelleyTxValidationError ShelleyBasedEraBabbage (ApplyTxError [UtxowFailure (UtxoFailure (FromAlonzoUtxoFail (ValueNotConservedUTxO (Value 1297310 (fromList [(PolicyID {policyID = ScriptHash \"80786e0ffb709cf2da414f0496be530a129c23f18c7a493abbf8589c\"},fromList [(61727445796573,1)])])) (Value 2050770 (fromList [(PolicyID {policyID = ScriptHash \"80786e0ffb709cf2da414f0496be530a129c23f18c7a493abbf8589c\"},fromList [(61727445796573,1)])])))))])""
Given below is my code for unlocking NFT.
    assetName = undefined,
    assetPolicyId = undefined,
    storeWalletSelected = undefined,
    transactionHashLocked = undefined
  ) {

    const txBuilder = await this.initTransactionBuilder();
    const ScriptAddress = this.sLib.Address.from_bech32(this.addressScriptBech32);
    const walletAddress = await this.getAddress()
    const shelleyChangeAddress = this.sLib.Address.from_bech32(walletAddress)
    const protocolParams = this.getProtocolParameters();

    let multiAsset = this.sLib.MultiAsset.new();
    let assets = this.sLib.Assets.new()
    assets.insert(
      this.sLib.AssetName.new(Buffer.from(assetName, "hex")), // Asset Name
      this.sLib.BigNum.from_str(this.assetAmountToSend.toString()) // How much to send
    );

    multiAsset.insert(
      this.sLib.ScriptHash.from_bytes(Buffer.from(assetPolicyId, "hex")), // PolicyID
      assets
    );

    txBuilder.add_input(
      ScriptAddress,
      this.sLib.TransactionInput.new(
        this.sLib.TransactionHash.from_bytes(Buffer.from(transactionHashLocked, "hex")),
        this.transactionIndxLocked.toString()),
      this.sLib.Value.new_from_assets(multiAsset)
    ) // how much lovelace is at that UTXO

    txBuilder.set_fee(this.sLib.BigNum.from_str(Number(this.manualFee).toString()))

    const scripts = this.sLib.PlutusScripts.new();
    scripts.add(this.sLib.PlutusScript.from_bytes(Buffer.from(this.plutusScriptCborHex, "hex"))); //from cbor of plutus script

    // Add outputs
    const outputValStr = Number(this.manualFee).toString();

    let txOutputBuilder = this.sLib.TransactionOutputBuilder.new();
    txOutputBuilder = txOutputBuilder.with_address(shelleyChangeAddress);
    txOutputBuilder = txOutputBuilder.next();
    txOutputBuilder = txOutputBuilder.with_asset_and_min_required_coin(
      multiAsset,
      this.sLib.BigNum.from_str(protocolParams.coinsPerUtxoWord)
    )

    const txOutput = txOutputBuilder.build();
    txBuilder.add_output(txOutput)

    // once the transaction is ready, we build it to get the tx body without witnesses
    const txBody = txBuilder.build();

    const collateral = await this.getCollateral(storeWalletSelected);
    const inputs = this.sLib.TransactionInputs.new();
    collateral.forEach((utxo) => inputs.add(utxo.input()) );

    let datums = this.sLib.PlutusList.new();
    // datums.add(PlutusData.from_bytes(Buffer.from(this.state.datumStr, "utf8")))
    datums.add(this.sLib.PlutusData.new_integer(
      this.sLib.BigInt.from_str(this.datumStr)))

    const redeemers = this.sLib.Redeemers.new();

    const data = this.sLib.PlutusData.new_constr_plutus_data(
        this.sLib.ConstrPlutusData.new(
          this.sLib.BigNum.from_str("0"),
          this.sLib.PlutusList.new()
        )
    );

    const redeemer = this.sLib.Redeemer.new(
      this.sLib.RedeemerTag.new_spend(),
      this.sLib.BigNum.from_str("0"),
      data,
      this.sLib.ExUnits.new(
        this.sLib.BigNum.from_str("7000000"),
        this.sLib.BigNum.from_str("3000000000")
      )
    );

    redeemers.add(redeemer)

    //Tx witness
    const transactionWitnessSet = this.sLib.TransactionWitnessSet.new();

    transactionWitnessSet.set_plutus_scripts(scripts)
    transactionWitnessSet.set_plutus_data(datums)
    transactionWitnessSet.set_redeemers(redeemers)

    const costModel = this.sLib.TxBuilderConstants.plutus_vasil_cost_models().get(this.sLib.Language.new_plutus_v1())

    const costModels = this.sLib.Costmdls.new();
    costModels.insert(this.sLib.Language.new_plutus_v1(), costModel);

    const scriptDataHash = this.sLib.hash_script_data(redeemers, costModels, datums);
    txBody.set_script_data_hash(scriptDataHash);

    txBody.set_collateral(inputs)

    const baseAddress = this.sLib.BaseAddress.from_address(shelleyChangeAddress)
    const requiredSigners = this.sLib.Ed25519KeyHashes.new();
    requiredSigners.add(baseAddress.payment_cred().to_keyhash())

    txBody.set_required_signers(requiredSigners);

    const tx = this.sLib.Transaction.new(
      txBody,
      this.sLib.TransactionWitnessSet.from_bytes(transactionWitnessSet.to_bytes())
    )

    let txVkeyWitnesses = await this.wallet.signTx(Buffer.from(tx.to_bytes(), "utf8").toString("hex"), true);
    txVkeyWitnesses = this.sLib.TransactionWitnessSet.from_bytes(Buffer.from(txVkeyWitnesses, "hex"));

    transactionWitnessSet.set_vkeys(txVkeyWitnesses.vkeys());
    const signedTx = this.sLib.Transaction.new(tx.body(), transactionWitnessSet);

    const submittedTxHash = await this.wallet.submitTx(Buffer.from(signedTx.to_bytes(), "utf8").toString("hex"));
    console.log('Tx Hash NFT Reedemed: ', submittedTxHash);
    return submittedTxHash
  }

The protocol Parameters used in this are
getProtocolParameters () {
   return {
     linearFee: {
         minFeeA: "44",
         minFeeB: "155381",
     },
     minUtxo: "34482",
     poolDeposit: "500000000",
     keyDeposit: "2000000",
     maxValSize: 5000,
     maxTxSize: 16384,
     priceMem: 0.0577,
     priceStep: 0.0000721,
     coinsPerUtxoWord: "34482",
   }
 }

The manual fee variable is
this.manualFee = 900000

Kindly suggest me some solution if you find any.

I have tried the txBuilder.add_change_if_needed(addr)  but it didnt work. Can you please tell me, that can a NFT alone be locked in a smart contract? Like i have tried that by sending the nft to smart contract by using function
txOutputBuilder.with_asset_and_min_required_coin(
      multiAsset,
      this.sLib.BigNum.from_str(protocolParams.coinsPerUtxoWord)
    )

So NFT gets locked with some minimal ADA of about 1.30593 (maybe its because of coinsPerUtxoWord).
But when i wanna unlock that NFT from smart contract, how should i specify that minimal amount in my txInput as its according to coinsPerUtxoWord. And when i set the NFT alone in input, then the transaction gets unbalance, and shows the issue of imbalanced input and output of tx. I think this got imbalance because at output it requires some ADA for fee whereas i am passing NFT asset in input.
To resolve this i have tried to pass UTXOS in txInput by using
const txUnspentOutputs = await this.getTxUnspentOutputs();
 txBuilder.add_inputs_from(txUnspentOutputs, 3)

and also i used later
txBuilder.add_change_if_needed(shelleyChangeAddress)
so that the change gets back to the changeAddress
But again its showing me the issue of
""transaction submit error ShelleyTxValidationError ShelleyBasedEraBabbage (ApplyTxError [UtxowFailure (UtxoFailure (FromAlonzoUtxoFail (ValueNotConservedUTxO ( Value 9996312330 (fromList [(PolicyID {policyID = ScriptHash \"80786e0ffb709cf2da414f0496be530a129c23f18c7a493abbf8589c\"},fromList [(617274426c61636b6e5768697465,1)])])) ( Value 9994984850 (fromList [(PolicyID {policyID = ScriptHash \"80786e0ffb709cf2da414f0496be530a129c23f18c7a493abbf8589c\"},fromList [(617274426c61636b6e5768697465,1)])]))))),UtxowFailure (UtxoFailure (FromAlonzoUtxoFail (FeeTooSmallUTxO (Coin 798505) (Coin 171969))))])""
I think the main issue is in this line of code i.e.  txOutputBuilder = txOutputBuilder.with_asset_and_min_required_coin(multiAsset, this.sLib.BigNum.from_str(protocolParams.coinsPerUtxoWord))
of txOutput as given. But i dont know what to use instead of this nor i found any useful reading resource regarding it.
let txOutputBuilder = this.sLib.TransactionOutputBuilder.new();
    txOutputBuilder = txOutputBuilder.with_address(shelleyChangeAddress);
    txOutputBuilder = txOutputBuilder.next();

    txOutputBuilder = txOutputBuilder.with_asset_and_min_required_coin(multiAsset, this.sLib.BigNum.from_str(protocolParams.coinsPerUtxoWord))
  const txOutput = txOutputBuilder.build();

    txBuilder.add_output(txOutput)
    console.log("txBuilder after adding output: ", txBuilder)

Can you please help me out in this, I think i am a bit close just missing some points maybe. Your little guidance can be quite helpful. Thanks

As of today the Cardano Serialization Library is no longer maintained and you shouldn't rely on it.
The closest to the CSL is the Cardano Multiplatform library that still relies on Rust + WASM.
If you don't want to load 10 MB of WASM in your web app you can also try cardano-ledger-ts(for the types) + plu-ts-offchain(for the transaction builder)
npm install @harmoniclabs/cardano-ledger-ts @harmoniclabs/plu-ts-offchain

Looks like the error is telling you that you have a utxo problem. Your inputs must match your outputs. This could be that they're mismatched, or you're missing the input altogether. https://iohk.zendesk.com/hc/en-us/articles/900001220843-Transaction-errors-ValueNotConservedUTxO
I would also look at add_key_input as defined in the example here: https://github.com/Emurgo/cardano-serialization-lib/blob/master/doc/getting-started/minting-nfts.md
It seems like you're only setting the collateral with the inputs, but never actually setting the utxo's as input for the transaction.

Sorry i didn't get it what you are trying to mention. Like i do have set the txInput txBuilder.add_input(       ScriptAddress,       this.sLib.TransactionInput.new(         this.sLib.TransactionHash.from_bytes(Buffer.from(transactionHashLocked, "hex")),         this.transactionIndxLocked.toString()),       this.sLib.Value.new_from_assets(multiAsset)     )
Also i am setting the UTXO. and yes i know there is some imabalance in my inputs and outputs but i am unable to figure it out that how do i resolve this because i am new to cardano and this is the CSL modified code.

@duaaazhar Ah ok, good. So you know it's a balance issue. To find the balance issue ... I would console.log() any time you set a value in the script, and keep a running sum so you can compare that with the utxo's you're adding in. Then you should be able to find the mismatch. However, maybe try something like txBuilder.add_change_if_needed(addr) and see if that doesn't just resolve the issue. I looked here for some reference. https://github.com/Emurgo/cardano-serialization-lib/issues/285

Hi @PREEB , I have answered this in the reply to my question. Can you please help me out in that query?
Thanks in Advance.


text:
Lucid Cardano Datum Error
I'm trying to build lucid to connect with cardano smartcontract from scratch using webpack, but I always getting this error related to datum data
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'Symbol(TypeBox.Modifier)'
this error referring to this datum data
const VestingDatum = L.Data.Object({
    beneficiary: L.Data.String,
    deadline: L.Data.BigInt
});

the error is gone when I deleting this VestingDatum but the script still not working because it need the VestingDatum data  ,
am I missing something ? and how to solve this problem ?

Looks like L.Data.BigInt doesn't exist in the code. You'll have to choose L.Data.Integer or another type to support what you need. For that matter, I don't see L.Data.String either. The data types available are inside the Data object starting around line 38 in the source listed below.
This is what they suggest to use in place of your current needs.
| bigint // Integer
| string // Bytes in hex

https://deno.land/x/lucid@0.10.1/src/plutus/data.ts?source#L38
Update:
const VestingDatum = L.Data.Object({
    beneficiary: L.Data.Bytes(),
    deadline: L.Data.Integer()
});

https://github.com/spacebudz/lucid/blob/c4da80a93ba70dde47c02e31036631e8be494620/src/examples/typed_data.ts#L12

Hi @PREEB, it's still not working, I use L.Data.Integer, now the error is Error: Could not serialize the data: Unsupported type, I also use L.Data.bigint but got another error TypeError: Cannot read properties of undefined (reading 'Symbol(TypeBox.Modifier)')

@ErwinKurnia I added an update to my answer. You'll need to change both data types. The link below is to an example where I found that.

Hi @PREEB, now I change it to beneficiary: L.Data.Bytes() and deadline: L.Integer(), now the error is lucid_cardano__WEBPACK_IMPORTED_MODULE_3__.Integer is not a function and error export 'Integer' (imported as 'L') was not found in 'lucid-cardano, I use "lucid-cardano": "^0.9.1"

The error is gone now, after I explicitly import Data using import {Blockfrost, Data, Lucid}  from 'lucid-cardano'; thank you @PREEB


text:
Is there a standart way to sync off-chain metadata (assets, tokens, mints) like cardano-db-sync does with on-chain data (epochs, blocks etc)?
I have running cardano-node-ogmios:v5.6.0_1.35.5 in couple with cardano-db-sync:13.1.0.0 (docker-compose.yml) and looking for the solution to sync off-chain assets localy. Is there any standart solution for that?
I've noticed that some assets (27200 items) have been copied localy to postgres database by service cardano-graphql-background:8.0.0 but have no idea why only 27200 assets and either I can copy more assets using this service?
I would greatly appreciate any help.


text:
UnsafeFromData instance for custom type
I want to use a custom type for one of my policy parameters, which will be applied by a tool like Lucid.
Example of param:
data CoinParams = CoinParams {
    policyOwner :: PubKeyHash,
    tokenName :: TokenName
}

My policy will then look like this:
policy :: CoinParams -> () -> ScriptContext -> Bool
policy ... = ...

Before compilation I wrap the policy:
                    vvv
wrappedPolicy :: BuiltinData -> BuiltinData -> BuiltinData -> ()
wrappedPolicy params = wrapPolicy (policy $ unsafeFromBuiltinData params)
               ^^                                     ^^^           ^^

But this won't work because there is no UnsafeFromData CoinParams instance(required to use unsafeFromBuiltInData). I'm struggling to understand how to implement the instance because I'm not sure how to 'destructure' BuiltinData to map it to my custom type. Could anyone assist? Thanks

In order to programmatically generate "FromData" and "ToData" instances for custom data types we have the function unstableMakeIsData present in PlutusTx (https://github.com/input-output-hk/plutus/blob/master/plutus-tx/src/PlutusTx/IsData/TH.hs#L131). This is a TemplateHaskell function which takes the name of the type. In your case it
will be like so: unstableMakeIsData ''CoinParams
Hope this helps.

thanks, I wasn't aware that's what it's doing behind the scenes.


text:
How does Oracle execute update operations?
I've read the Oracle implementation recently via https://plutus-pioneer-program.readthedocs.io/en/latest/pioneer/week6.html.
As I understand, Oracle has 2 primary operations the following

Use: an Oracle UTxO will be used to execute a transaction
Update: As part of the EUTxO model/blockchain, every data in the chain are immutable, meaning Oracle data can't be updated itself. It requires update operations to update the data. For instance ADA/USD ratio rate.

Due to the update operation, there are 2 questions that come to my mind. Could anyone please help to explain this to me, please?

How frequently will Oracle data be updated? I think there would have different answers for different scenarios, but I don't know any specific cases in practice yet. It would be good if you could help to estimate costs for them based on scenarios.
I suppose we have the off-chain part to send transactions for updating Oracle data. So what will happen if the off-chain part is broken? For instance, ADA/USD ratio rate can't be updated and smart contracts keep using the old rate.

If you have any idea about the way Indigo https://indigoprotocol.io/ (or any other launched products on the Cardano ecosystem) implement their Oracle, It would be very appreciated if you could add them here.
Thank you very much!

Since Indigo has just open-sourced their smart contracts including Oracle. I've just found answers to my questions.
Question 1: How frequently will Oracle data be updated?
Answer: It depends on protocols, for the specific cases of Indigo is once per hour at launch as stated in their whitepaper. "Periodically, Indigo receives price data from the outside world via Oracles. The rate at which price feeds are updated is configurable, and at launch will be set to once per hour."
Question 2: what will happen if the off-chain part is broken? For instance, ADA/USD ratio rate can't be updated and smart contracts keep using the old rate.
Answer: As I checked Indigo’s source code, they added an expiry time for update operations in the datum. Thus, in case price feeds are not being updated for a longer time than the expiry time, the UTxOs will not be validated to consume unless price feeds are refreshed.
see, https://github.com/IndigoProtocol/indigo-smart-contracts/blob/main/src/Indigo/Contracts/Oracle/Common.hs#L44-L64
data OracleParams = OracleParams
  { -- | Owner of the Oracle - the PubKeyHash that can
    -- update the authentic Oracle output with NFT
    opOwner :: Spooky.PubKeyHash,
    -- | the time offset by which a time approximation is considered valid
    opBiasTime :: POSIXTime,
    -- | the time how long the oracle is active
    opExpirationTime :: POSIXTime
  }
  deriving (Generic, P.Show, ToJSON, FromJSON, P.Eq, P.Ord, OpenApi.ToSchema)

PlutusTx.makeLift ''OracleParams
PlutusTx.makeIsDataIndexed ''OracleParams [('OracleParams, 0)]

data OracleDatum = MkOracleDatum
  { -- | Price in lovelace with decimal places
    odPrice :: OnChainDecimal,
    odExpiration :: POSIXTime
  }
  deriving stock (P.Show, Generic)
  deriving anyclass (ToJSON, FromJSON)


text:
playground-common package giving 'Failed to build scrypt-0.5.0' error
I'm trying to run my own little smart contract in the plutus-pioneer-program [fourth iteration] docker container and I'm having some problems. I've just added an extra folder alongside the other weeks. I've built this same code on other environments just fine but I got a new laptop with an M2 chip recently so my setup all broke and I figured running it in this environment would be the fastest way forward. I've narrowed the issue down to the playground-common package that my build depends on. The problem is that when I run cabal build all in my folder I get this error:
Build log (
/root/.cabal/logs/ghc-8.10.7/scrypt-0.5.0-833a2feabba78b918876049577f7c64bc2870cc56e8d7720fba2aa8ea196973a.log
):
Configuring library for scrypt-0.5.0..
cabal-3.6.2.0: Missing dependency on a foreign library:
* Missing (or bad) header file: crypto_scrypt.h
This problem can usually be solved by installing the system package that
provides this library (you may need the "-dev" version). If the library is
already installed but in a non-standard location then you can use the flags
--extra-include-dirs= and --extra-lib-dirs= to specify where it is.If the
library file does exist, it may contain errors that are caught by the C
compiler at the preprocessing stage. In this case you can re-run configure
with the verbosity flag -v3 to see the error messages.
If the header file does exist, it may contain errors that are caught by the C
compiler at the preprocessing stage. In this case you can re-run configure
with the verbosity flag -v3 to see the error messages.

cabal: Failed to build scrypt-0.5.0 (which is required by
elysium-contract-0.1.0.0). See the build log above for details.

I havent changed anything else in the project other than adding an additional folder under code. Has something changed with the playground-common package?
I also tried adding this configuration to a cabal.project.local file, but no luck:
flags: -scrypt
tests: False
benchmarks: False
optimization: 2

Using cabal version 3.4, base ^>=4.14.1.3.0
Other config:
                     , base ^>=4.14.1.3.0
                     , bytestring
                     , cardano-api
                     , containers
                     , data-default
                     , playground-common
                     , plutus-ledger-api
                     , plutus-tx-plugin
                     , plutus-tx
                     , serialise
                     , text
  default-language:    Haskell2010
  ghc-options:         -Wall -fobject-code -fno-ignore-interface-pragmas
                       -fno-omit-interface-pragmas -fno-strictness
                       -fno-spec-constr -fno-specialise -fexpose-all-unfoldings
                       -fplugin-opt PlutusTx.Plugin:defer-errors

I have had this issue with setting up the environment on aarch64 M1 Mac, even within a Ubuntu VM on the same chip. The scrypt component fails due to its current support being limited to x86. More details can be found in this GitHub issue. https://github.com/informatikr/scrypt/issues/8
The best way around it is either a x86 machine or an x86 VM. I have setup mine as remote server. Life is easier this way
If someone did want to try to build it on a aarch64 I would recommend somehow making the build use this fork https://github.com/SupercedeTech/scrypt which is compatible

You are missing a C header file. Specifically, the part of the error message:
* Missing (or bad) header file: crypto_scrypt.h
This problem can usually be solved by installing the system package that
provides this library (you may need the "-dev" version). If the library is
already installed but in a non-standard location then you can use the flags.

On Debian based Linux systems (eg Debian, Ubuntu, Mint and probably others),
you can used apt-file to find which packages provides the file:
> apt-file search crypto_scrypt.h
libnode-dev: /usr/include/nodejs/src/crypto/crypto_scrypt.h

so that installing the libnode-dev package (part of nodejs):
sudo apt install libnode-dev

will sort your problems out.

Hey thanks for your reply! When i run apt-file search crypto_scrypt.h nothing comes back, and installing libnode-dev didnt change the error message unfortunately :(

Are you on Debian or a Debian derived system? If so, which one?

My machine is a mac with m2 chip, but cabal is running in docker and this is the info about the image:
cat /etc/os-release
VERSION="20.04.5 LTS (Focal Fossa)"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 20.04.5 LTS"
VERSION_ID="20.04"

If you are running in docker supposedly its supposed to act just like Ubuntu on x86-64 . Maybe you need to add the universe and multiverse repos for Ubuntu.

Just checked, they're both already enabled :/

The Ubuntu version you are using is from 2020 (VERSION="20.04.5 LTS (Focal Fossa)"), Maybe try the most recent LTS version which should be 22.???.

hey I upgraded to 22.04 and now a whole bunch of other packages are broken/cant be found too and the scrypt error remains the same.. im wondering if i should try running cabal a different way >.< this is crazy complicated

Which packages? Haskell packages or others?

Here are the new errors:
: error:
Warning: Couldn't figure out LLVM version!
Make sure you have installed LLVM between [9 and 13)
ghc: could not execute: opt-10
cabal: Failed to build scrypt-0.5.0 (which is required by
elysium-contract-0.1.0.0)
Failed to build streaming-commons-0.2.2.1 (which is required by
elysium-contract-0.1.0.0)
Failed to build x509-store-1.6.7 (which is required by
elysium-contract-0.1.0.0)
Failed to build zlib-bindings-0.1.1.5 (which is required by
elysium-contract-0.1.0.0)

opt --version
Ubuntu LLVM version 14.0.0

Optimized build.
Default target: aarch64-unknown-linux-gnu
Host CPU: (unknown)

If these are non-Haskell packages (ie LLVM) this is an Ubuntu problem.


text:
Why is writeToScript reporting that my script costs 0 resources?
I have the following minting script:
{-# INLINABLE verify_mint #-}
script :: () -> V2.ScriptContext  -> Bool
script () _ = (3::Integer) == 2+1

and the following off-chain code to mint a token:
trace :: Trace.EmulatorTrace ()
        trace = do
            Extras.logInfo @Haskell.String "Starting..."
            handle <- Trace.activateContractWallet Test.w1 contract

            Trace.callEndpoint @"mint" handle ()
            Functor.void $ Trace.waitNSlots 5

        contract :: Contract () Schema Text ()
        contract = do
            Contract.logInfo @Haskell.String "Waiting..."
            Contract.selectList [ mint ] >> contract

        mint :: Promise () Schema Text ()
        mint  = Contract.endpoint @"mint" $ \() -> do
            let constraint = Constraints.mustMintCurrency (Scripts.mintingPolicyHash policy) "ABC" 1
            tx <- Contract.submitTxConstraintsWith @TScripts.Any (Constraints.plutusV2MintingPolicy policy) constraint
            Functor.void $ Contract.awaitTxConfirmed (Ledger.getCardanoTxId tx)
            Contract.logInfo @Haskell.String "Minted!"

However when I run writeToScript as follows:
let cmd = Scripts UnappliedValidators
    let config = ScriptsConfig "keystore-stats" cmd
    Haskell.print =<< writeScriptsTo config "x" trace Default.def

I get the following result:
(Sum {getSum = 0},ExBudget {exBudgetCPU = ExCPU 0, exBudgetMemory = ExMemory 0})

How can this be? Shouldn't minting require some resources?

It should. writeScriptsTo is buggy at the moment (not sure why, probably a placeholder has been set while we were working on it and we forgot to change it afterwards).
I'm creating a ticket to fix it.

Is there any other way to find out how much resources my script is taking in the meantime?

I didn't try it but you can use plutus profiling directly.

But how do I obtain the uplc executable? Running "cabal build" in the plutus-apps directory results in an error.


text:
Tx consuming script fails with: Caused by: (unConstrData #44000de140)... Third data argument, does not decode to a context when burning an NFT
I've this tx trying to submit to cardano-node 1.35.5:
[encoded data, 22964 characters]

Where there are two scripts one for minting policy and the other for spending. I'm getting this error (sorry no enough characters for the error's text):

It basically says cannot call the spending script since cannot create the script context:
The third data argument, does not decode to a context....
The scripts signature are like this:
userTokenValidate :: BuiltinByteString -> BuiltinByteString -> Policy -> ValidatorHash -> Action -> ScriptContext -> Bool

referenceTokenValidate :: BuiltinByteString -> BuiltinByteString -> Policy -> DatumMetadata -> RefAction -> ScriptContext -> Bool

and this is the relevant data types:
data DatumMetadata = DatumMetadata {
                     metadata :: BuiltinData
                   , version :: Integer
                   , extra :: BuiltinData
}
instance Eq DatumMetadata where
    {-# INLINABLE (==) #-}
    (==) :: DatumMetadata -> DatumMetadata -> Bool
    DatumMetadata m v e == DatumMetadata m' v' e' = m == m' && v == v' && e == e'
makeLift ''DatumMetadata
makeIsDataIndexed ''DatumMetadata [('DatumMetadata, 0)]

data RefAction = Burn | Move | Upgrade
makeLift ''RefAction
makeIsDataIndexed ''RefAction [('Burn, 0), ('Move, 1), ('Upgrade, 2)]

data Action = MintNFT | BurnNFT | MintExtra
makeLift ''Action
makeIsDataIndexed ''Action [('MintNFT, 0), ('BurnNFT, 1), ('MintExtra, 2)]

Notice the first 3 parameters where parameterized for referenceTokenValidate and the 4 first for userTokenValidate so the final scripts passing to the tx are like "regular" scripts.
Here is the datum from the UTxO I want to spend it (it was created with data hash and real data in the witness set): https://preprod.cardanoscan.io/datumInspector?datum=d8799fa7446e616d655054616e676f434950303036382330313145696d6167655835697066733a2f2f516d53696e53595559526f3841437443583572636a526864413961476631564d734a413531514b677a326e57476449636f707972696768745054616e676f63727970746f2032303233466172746973744b54616e676f63727970746f496d656469615479706543706e674a636f6c6c656374696f6e5654616e676f63727970746f20436f6c6c656374696f6e4774776974746572582068747470733a2f2f747769747465722e636f6d2f74616e676f5f63727970746f0180ff. It was created like this:
...
const rawMetadata = Seed.buildPlutusData(token.metadata);
const plutusMetadata = PlutusData.from_json(JSON.stringify(rawMetadata), 1)
const fields = PlutusList.new();
fields.add(plutusMetadata);
fields.add(PlutusData.new_integer(BigInt.from_str(version.toString())));
fields.add(PlutusData.from_json(JSON.stringify(Seed.buildPlutusData(extra)), 1));
const plutusData = PlutusData.new_constr_plutus_data(
    ConstrPlutusData.new(toBigNum(0), fields)
)
plutusData.to_hex()

using CSL I put it in the invalid tx this way (also tried the commented line):
// const pData = PlutusData.new_constr_plutus_data(ConstrPlutusData.from_hex(inputData));
const pData = PlutusData.from_hex(inputData);

Tacking a closer look to the tx cbor structure I noticed the datum and redeemers are like this:
4: [
    121([
        {'name': 'TangoCIP0068#011', 'image': 'ipfs://QmSinSYUYRo8ACtCX5rcjRhdA9aGf1VMsJA51QKgz2nWGd', 'copyright': 'Tangocrypto 2023', 'artist': 'Tangocrypto', 'mediaType': 'png', 'collection': 'Tangocrypto Collection', 'twitter': 'https://twitter.com/tango_crypto'},
    1,
    []
    ])
],
5: [[1, 0, 122([[]]), [1943838, 544610828]], [0, 1, 121([[]]), [1943838, 544610828]]]

And from the error we have this:
he data is: Constr 0 [Map [(B \"name\",B \"TangoCIP0068#011\"),(B \"image\",B \"ipfs://QmSinSYUYRo8ACtCX5rcjRhdA9aGf1VMsJA51QKgz2nWGd\"),(B \"copyright\",B \"Tangocrypto 2023\"),(B \"artist\",B \"Tangocrypto\"),(B \"mediaType\",B \"png\"),(B \"collection\",B \"Tangocrypto Collection\"),(B \"twitter\",B \"https://twitter.com/tango_crypto\")],I 1,List []]
The redeemer is: Constr 0 [List []]

So no sure why cannot create the script context though.

The script context error can be a red herring. Double check for any reason why a script data may not be successfully deserialised.

Hi @james, I've no clue at this point what is happening, what should I look for? This is how my script is serialized:
referenceTokenValidateInstance :: Validator referenceTokenValidateInstance = Validator $ fromCompiledCode ($$(compile [|| wrap ||]))   where     wrap label222 label100 policy = mkUntypedValidator $ referenceTokenValidate (unsafeFromBuiltinData label222) (unsafeFromBuiltinData label100) (unsafeFromBuiltinData policy)  The minting script works and the only difference is mkUntypedMintingPolicy instead of mkUntypedValidator

I don't see how it could be expected to work if the only difference is the function being used because minting expects (r -> sc -> Bool) whereas spending requires (d -> r -> sc -> Bool).  It's not apparent to me what the cause of your problem is. I can take a look if you are willing to give me full read access to the codebase.


text:
Which would be the future language for writing smart-contract?
As we might know well-known approaches for writing smart contracts on Cardano are using Plutus Tx or Marlowe based on specific requirements. However, according to the growth of the Cardano community, many new choices for writing smart contracts appear. Could Plutus Tx be a good choice in the future?
List of possible tools:

Plutus Tx
Marlowe
OsPhin - Python
Plu-ts - Typescript
Aiken- new language (Rust compiler)
Helios - new language (Javascript compiler)
etc

Do you mean PlutusTx for point 1?

Yes, I've updated it. Thank you

PlutusTx inherits its qualities from Haskell, and thus has many of the same benefits/drawbacks:
Pros: auditability, maintainability, and upgradeability of code.
Cons: developers' unfamiliarity with functional programming. High resource usage.

PlutusTx is especially useful when safety and correctness are the #1 priority, such as in massive DeFi dApps or any other mission critical system.
On the other hand, PlutusTx is relatively resource-hungry (in terms of script execution units), which limits the size of deployable contracts. Although it may be possible to address some of these limitation through optimizations/changes to Plutus Core (i.e. CIP-38, CIP-85 and others), newer languages like Aiken and Plu-ts offer a lighter-weight execution budget and greater accessibility to a broader set of developers.
Non-turing complete DSLs like Marlowe offer even greater developer accessibility via low-code or even no-code contract deployment.
TLDR; all of these are just tools in the toolbox. All (or most) of them will be future smart contract langugaes.

Aiken and PlutusTx both compile down to Plutus Core, which is the language understood and executed by a Cardano node. There is no inherent reason why PlutusTx should be more resource hungry than any other newer language. The question why it obviously is much more resource hungry can only be answered by the Cardano developer team.

Marlowe... or its descendants/variations ;-)
I would like to emphasize the difference between Marlowe and all the other solutions and later on focus on Marlowe. I'll even allow myself to speculate a bit about its possible future:

All the other languages compile down to a "binary (lambda?) blob" (Plutus Core) and that is how they end up on the chain.

Binary blobs of a Turing-complete program are generally hard to understand. It seems rather infeasible to build a generic tool for binary programs (considering issues like the halting problem etc.), which could analyze them and answer questions about what will happen in the future if I join the contract.

Marlowe doesn't compile to anything (by design!). It is interpreted on the chain, merely serialized and placed into the Datum..

Marlowe is limited and non Turing complete. You can analyze and discover a lot of properties of the contract statically.

Marlowe is severely limited on purpose. We are playing with peoples money here. It requires more thinking to design some contracts. Some contracts are just impossible in Marlowe (like "open auction"). But if you assume some "sensible" limits (do I have to support more than 1000 rounds in this auction? can I limit participants to some known group?) you can do a lot with it.

The Marlowe interpreter V1 will be a single identifier of a constant script (after its release, the Marlowe interpreter should be present on the chain as a reference script). So given an UTxO with a script hash and datum you are able to decode the whole picture of Marlowe interpreter state (there are some optional nuances about "role token" minting but we can ignore them in this discussion).

Marlowe is a pretty simple DSL and it can be produced from any programming language which supports JSON (json encoding is part of the official spec: https://github.com/input-output-hk/marlowe/releases/download/v3-rc2/specification-v3-rc2.pdf - page 62, Appendix E).

When you build a dapp (in any language!) you could on your backend or even frontend(!) have a template of a Marlowe contract which it can fill in with values (like addresses, amounts, timeouts etc.) dynamically.

Learning curve for Marlowe seems to be pretty low. Interestingly Marlowe pretty nicely integrates with the UTxO model. A step ("user action") in a contract is usually translated to a transaction on the chain. A programmer can possibly transfer Marlowe knowledge between projects written in different languages, frameworks etc. (like we do with SQL or HTML/CSS knowledge).

Marlowe contract execution runtime which takes care of the deployment on the chain and monitors the chain is also in a pre-release phase. It exposes pretty simple REST API which can be naturally integrated into any project.

What could it mean in practice?

The audit's cost for a Marlowe-based solution should be much lower. Everyone has access to a set of static analysis tools for Marlowe. An audit may even be unnecessary in simpler scenarios.

The operational costs and business risks of Marlowe-based solution should be also lower - more developers can pick it up and learn etc.

Developers like to talk about performance and expresivness but I hope that in the domain of financial contracts they can see the value in the DSL which is limited but provides guarantees.

Because Marlowe is present on the chain as a 'source code' contracts could be visualized by wallets, explorers etc. In such a case user could just pick a dapp contract and possibly check the contract and answer a lot of questions himself before signing any tx.

Marlowe is not the only possible DSL which we could have. We can imagine other more expressive (with less guarantees? harder to visulaize?) or less expressive (easier to understand and visulaize) languages which we can build using this kind of interpreter pattern which gives the contract its transparent nature.


text:
Chain error when attempting to start cardano-node
I try to start cardano-node with the following command
./cardano-node run \
    --topology testnet/topology.json \
    --database-path testnet/db/ \
    --socket-path testnet/db/node.socket \
    --host-addr 127.0.0.1 \
    --port 1337 \
    --config testnet/config.json

However I get the following error:
[workstat:cardano.node:Critical:5] [2023-04-19 19:48:24.04 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")]

What's happening?

Check this out. Appears to be a bug. https://cardano.stackexchange.com/questions/11032/invalidcertificate-error-running-the-cardano-node-v-1-35-7-static-binary


text:
Blockfrost policy/metadata api issues
I am trying to get the metadata for the policy ID
but every Blockfrost gives error saying "invalid path"
I am able to get data related to assest using:
"https://cardano-preprod.blockfrost.io/api/v0/assets/2a384dc205a97463577fc98b704b537f680c0eba84126eb7d5857c865050424c32303233796f75726561636865645261686174"
but I am not able to get any information for this policy ID: 2a384dc205a97463577fc98b704b537f680c0eba84126eb7d5857c86
and when I used https://cardano-preprod.blockfrost.io/api/v0/metadata/txs/labels/721
i could not find the required metadata with policy ID: 2a384dc205a97463577fc98b704b537f680c0eba84126eb7d5857c86
HOW DO I ACCESS METADATA (721) FOR POLICY ID: 2a384dc205a97463577fc98b704b537f680c0eba84126eb7d5857c86
there are around 15 object expected to be return form this policy ID

To get a list of assets with specific policy ID, use the /assets/policy endpoint.
For your example, it is https://cardano-preprod.blockfrost.io/api/v0/assets/policy/2a384dc205a97463577fc98b704b537f680c0eba84126eb7d5857c86.

this will get me the list of assets for that policy id, how do I get the metadata for those policy id.

policy id doesn't have metadata, only assets might have in this case


text:
Create a smart contract in Marlowe from A to Z
What is the process of building a smart contract in Marlowe from start to deployment and first main net transaction? I know that there's blockly and Marlowe playground. But I can't figure out the step-by-step algo of doing it from the docs.
Here's what I want to build:
Bob deposits 100 iUSD Ann deposits 10 iUSD, if event "1" happens Ann gets 105 iUSD, Tom gets 5 iUSD else if event "2" happens Bob gets 100 iUSD, Tom gets 10 iUSD.
Events will be triggered in the frontend.
Thanks for help!

Guidance on building a Marlowe contract and running it on mainnet is split into two pieces because Marlowe is a blockchain-agnostic language but it is also implemented on Cardano. Playground lets one simulate Marlowe contracts in the abstract while Runtime lets one execute them concretely on the Cardano blockchain.

The Concepts tutorials teach the Marlowe language and walk through examples.
The Guides exemplify using the Marlowe Starter Kit, which is freely available on https://demeter.run/ for use without installing any software.

Regarding your specific example, the sixth lesson of the starter kit shows how to build a simple front end for a Marlowe contract.

I feel more comfortable using VS code on my PC than https://demeter.run/ I hope that doesn't break anything. I would be running smart contracts from frontend later anyway.
A very high level question correct me if I'm wrong. Smart-contract building algo looks something like this:

Build SC in Blockly.
Test SC in Runtime.
Import it into the App bundle
Production build
Deploy optimized bundle to prod server.

Demeter Run provides convenience, but the starter kit and other examples should work fine if one is using a local Marlowe Runtime or some other service provider.


text:
What means this line of script
What this means on cardano token time lock?
all: [
      {
         invalidAfter: 99336691

The script cannot be used to mint assets once slot 99336691 has passed.

Only can not mint? Or can not transter assets?

A simple script can be used for: locking utxos at an address where all spending conditions are defined by the script, and the same conditions can also be applied to restrict minting/burning of tokens under a common policy. Have a read of https://github.com/input-output-hk/cardano-node-wiki/wiki/simple-scripts


text:
How can I receive, earn or stake Cardano without buying it on an exchange first?
I'm interested in participating in the Cardano ecosystem, and I'm looking for ways to receive, earn or stake ADA without initially buying it on a cryptocurrency exchange.
I understand that with resources such as powerful hardware and electricity, one can mine cryptocurrencies like Bitcoin and Ethereum, effectively earning these coins. However, I'm interested in Cardano and wondering if there's an equivalent process for it.
I understand that Cardano uses a Proof-of-Stake consensus mechanism which is fundamentally different from the Proof-of-Work mechanisms used by Bitcoin and Ethereum.
Here are my questions:
Given the lack of traditional mining in the Cardano ecosystem, is there an alternative way to earn ADA without an initial capital investment?
Is it possible to participate in staking without owning any ADA initially, similar to how one could start mining Bitcoin or Ethereum with the necessary hardware resources?
Any guidance or resources on these topics would be greatly appreciated.

Offer a service which people with ADA are willing to pay for.

Cardano is a Proof-of-Stake system. The only way to get staking rewards is to own ADA and to stake it.

Given the lack of traditional mining in the Cardano ecosystem, is there an alternative way to earn ADA without an initial capital investment?

No.

Is it possible to participate in staking without owning any ADA initially, similar to how one could start mining Bitcoin or Ethereum with the necessary hardware resources?

No.


text:
I am getting error while using "cabal build all" cmd
I am new to plutus. I am trying to learn plutus for which I am using "plutus-starter" code to begin. while using "cabal build" i am getting following error:
Resolving dependencies...
cabal: Could not resolve dependencies:
[__0] trying: Win32-network-0.1.0.0 (user goal)
[__1] trying: base-4.16.4.0/installed-4.16.4.0 (dependency of Win32-network)
[__2] next goal: byron-spec-chain (user goal)
[__2] rejecting: byron-spec-chain-0.1.0.0 (conflict:
base==4.16.4.0/installed-4.16.4.0, byron-spec-chain => base>=4.12 && <4.15)
[__2] fail (backjumping, conflict set: base, byron-spec-chain)
After searching the rest of the dependency tree exhaustively, these were the
goals I've had most trouble fulfilling: base, byron-spec-chain, Win32-network

How can I solve this.

You are using the wrong version of GHC which supplies the base library.
According to https://www.snoyman.com/base/ base version 4.16.* is supplied by ghc-9.2.* .
From the bounds required on base (base>=4.12 && <4.15) I would suspect you should be using ghc-8.10.7.

I think it solved my problem. Thank you very much.


text:
Validating ecdsa signature in aiken
Im trying to let my validator validate my ecdsa signature yet I get a weird JSON error:
Uncaught (in promise) SyntaxError: Unexpected non-whitespace character after JSON at position 4
My Validator for the example is simple and goes as follows:
type ReedemerDatum {
  oracle: VerificationKey,
  signature: Signature,
  msg: ByteArray,
}

validator {
  fn test_val(
    oracle: Void,
    redeemer: ReedemerDatum,
    context: ScriptContext,
  ) -> Bool {
    let ScriptContext { transaction, purpose } = context
    when purpose is {
      Spend(_) ->
        validate_signature(redeemer.oracle, redeemer.msg, redeemer.signature)
      _ -> False
    }
  }
}

fn validate_signature(
  key: VerificationKey,
  msg: ByteArray,
  signature: Signature,
) {
  builtin.verify_ecdsa_secp256k1_signature(key, msg, signature)
}

To interact with my validator I use Lucid with the following code for trying to Spend Utxos on the validator:
export const Redeemer = Data.Object({
  oracle: Data.Bytes(),
  signature: Data.Bytes(),
  msg: Data.Bytes()
});

export const Datum = Data.Object({
  oracle: Data.Bytes()
});

type Datum = Data.Static<typeof Datum>;
type Redeemer = Data.Static<typeof Redeemer>;

let redeemerDatum = Data.to<Redeemer>({
  oracle: "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",
  signature: "2c3ddb94fb0cc34a2d4a83d886450c6e97f1ccc769b6eb968c81a0a423bbb66a2efac027f6d62733faae43f9f7628dbfc34f004ca27af912919b00a08c18634f",
  msg: "9c478bf63e9500cb5db1e85ece82f18c8eb9e52e2f9135acd7f10972c8d563ba"
}, Redeemer);

const utxosDeposited = await queryUtxosOfAddress(
  lucid,
  validatorInformation.address,
);

let depositedUtxoRef: OutRef[] = utxosDeposited.map((x) => {
  return {
    txHash: x.txHash,
    outputIndex: x.outputIndex,
  };
});

const depositedUtxos = await lucid.utxosByOutRef(depositedUtxoRef);

const txSpend = await lucid
  .newTx()
  .collectFrom(depositedUtxos, redeemerDatum)
  .attachSpendingValidator(validatorInformation.validator)
  .complete();
const txSignedSpend = await txSpend.sign().complete();
const txHash = await txSignedSpend.submit();
await lucid.awaitTx(txHash);

The utxos Im trying to redeem is created as such:
const tx = await lucid.newTx()
.payToContract(validatorInformation.address,
   {inline: Data.void()},{ lovelace: 1000000n}).complete();

Lastly the way Im getting my SpendingValidator and Validator address is as follows:
  const updateValidator = blueprint.validators.find(
    (v) => v.title === "test_val.test_val",
  );
let spendingValidator = {
    type: "PlutusV2",
    script: toHex(cbor.encode(fromHex(validator.compiledCode))),
  };
let addressValidator = lucid.utils.validatorToAddress({
    type: "PlutusV2",
    script: validator.compiledCodessssssssssssssssssssssssssssssssssssssssss,
  });

I'm entirely in the wild why this occurs. Any got ideas?


text:
I am getting error when using nix build command
when using following command
nix --extra-experimental-features nix-command build -f default.nix plutus.haskell.pack ages.plutus-core.components.library
getting following error
error: could not set permissions on '/nix/var/nix/profiles/per-user' to 755: Operation not permitted
to solve this I used sudo
sudo nix --extra-experimental-features nix-command build -f default.nix plutus.haskell packages.plutus-core.components.library

but then getting another error
sudo: nix: command not found

I am following evernote.com for the installation process.


text:
Retire a stake pool and get the rewards and pledge before
I had once the knowledge on how to operate a stake pool, but I hadn't had time to care about it, and now I want to end it. Now I still have some ADA staked but also as the pool deposit thingy (forgot how it was called). Now my problem is: it doesn't run anymore because it was so old...
Is it possible to copy all files to my own computer and get the ada out of there, or do I need to update and run the pool again before I am able to retrieve my ADA which sits at the pool's address?
Please help, the docs when I google it are all with "Error 404 Page not found " which is horrible..
Cheers

You can create the retirement certificate with just the cold key and a single payment utxo using cardano-cli. This can be done completely off-line on a cold environment if you know the utxo your referencing as tx-in ahead of time using cardano-cli transaction build-raw. It can also be done on a live environment with a running mainnet node using cardano-cli transaction build


text:
StakeCredentialHash - Lucid
I'm having difficulties getting the StakeCredentialHash from a privatekey. Using lucid
At the moment i can get the paymentCredentialHash, but missing the stakeCredentialHash, i have to put it manualy.
  // Replace with the path to the bot's private key file
  const botPrivateKeyFilePath = "./wallets/wallet1.sk";
  // Read the bot's private key from the file
  const botPrivateKey = await Deno.readTextFile(botPrivateKeyFilePath);

  // Import the bot wallet using the private key
  const wallet = await lucid.selectWalletFromPrivateKey(botPrivateKey);

  // Get the paymentCredential hash from the wallet address
  const walletAddress = await lucid.wallet.address();
  const { paymentCredential } = lucid.utils.getAddressDetails(walletAddress);
  const paymentCredentialHash = paymentCredential?.hash;

How can i achieve this?