text:
HELP NEEDED Block producer blocked by DigitalOcean - recover ADA?
can someone please help me? I had just started setting up my stake pool, using DigitalOcean droplets to host the block producer & relay nodes. All was going really well. Then, for some crazy reason that has still not been explained to me, DigitalOcean blocked my account and refuses to give me access. So now I can no longer access the block producer. Fortunately, I copied all keys, certificates etc, payment address, but I cannot find how to recover the ADA that I had pledged to my stake pool. I would also like to know if anyone could also explain how to retire the stake pool after I recover my funds. Any help would be much appreciated and please, if you’re using DigitalOcean, please be careful they don’t do this to you. Thanks in advance, Simon

If you had copied your keys there will be no loss of funds. Please edit your question to include the methods followed by you to install the node and the keys you have in your possession. Do not give out the content of key files to anyone.

if you have all your keys, you can start locally a node. When the node is synced, deregister your pool with cardano-cli by submitting a transaction with a deregistration-certificate created by the command cardano-cli stake-pool deregistration-certificate [...]
You don't have to recover the funds you pledged because you never lost control of your funds : you still have the signing key of the pledge owner address, do you ?
If you want to transfer your funds, you can create a wallet on Daedalus or Yoroi, and submit locally a payment transaction to transfer your pledged ADAs to this wallet. Be careful : sign the transactions offline.
Edited : gave more informations on the way to de-register a pool

Thank you so much for your help. When you mention the "signing key of the pledge owner address" you mean the payment.skey, is that correct? Thanks once again

yes, the payment.skey file

Hi, just to let you know, I followed your suggestions but actually spun up a new service using linode, copied all the files, synchronized, and now everything is up and running fine. Thanks again and thanks so much for your help, greatly appreciated


text:
Missed slot leader checks
The “missed slot leader checks” on my stakepool are at 0.98% or 14,527. Is this cause for concern? I have tried applying the solutions found in the following links, but nothing seems to make a difference, links →

https://forum.cardano.org/t/too-many-missed-slots-happens-help-me/75942/44
http://www.htgsd.com/cryptocurrency/ada-cardano-stakepool/missed-slot-leader-checks-missed-blocks-with-stakepool-cardano-node-ada/
https://forum.cardano.org/t/solving-the-cardano-node-huge-memory-usage-done/67032/37
https://forum.cardano.org/t/no-more-missed-slots-during-epoch-after-changing-one-setting/67924/20

My BP is running on a Contabo VM (VPS M), 6 cores, 16GB RAM, 400GB SSD hard drive and 400 Mbit/s, hosted in Germany. My 2 nodes are running on two VMs, with specifications
4 vCPU cores, 8GB RAM with a 10GB swap setup, 200GB SSD hard drive and 200 Mbit/s. My stake pool was prepared following the CoinCashew tutorial.
Does anyone know what I am doing wrong? Thanks so much, Simon

What does your current mainnet config file look like? Specifically wondering about the tracemempool settings for relays and BP.

I have read all those links too and tried many different things.  I still get some missed slots.
The things I have found:
-I0 (Default garbage collector with idle garbage collection off):
With this set I don't get missed slots at all for many hours and then eventually the garbage collector has to run and copy a lot of memory and then I get many missed slots all at once.
-I0.3 -Iw600 (Default garbage collector with regular collector sweeps with minimum 10mins between sweeps when processor idle > 0.3 secs)
This results in few missed slots which occur when the garbage collector runs.  However, because it is done more regularly the amount of memory copying is less and it takes less time so there are less missed slots each time.  But for my setup there were still a couple of missed slots every 10 mins when the GC ran.
--nonmoving-gc
I still get occasional missed slots.
Memory use seems to gradually increase over time and the node eventually uses all available RAM 16G and starts using swap.  After running 20hrs rts_gc_peak_megabytes_allocated is 24G which seems excessive.  Node appears to be running OK with almost no missed slots (4 in 20hrs).
If you run a small pool with limited processor power/speed then one option is to do the following:
Work out when your allocated slots are by running cncli-leaderlog ahead of time.  Then plan to restart your block producer cardano-node service 20 minutes before you are due to produce your block.  This way you can be sure your memory is fresh and garbage collection won't be necessary for a while just at the time when you are due to produce your block.
Overall, throwing faster hardware at the problem is an easy fix.  Faster processor means memory copying is quicker and garbage collection takes less time so missed slots are eliminated.
Update 2021-12-21:
After lots of testing I have concluded that the only RTS option which stops my node from missing slot leader checks is --nonmoving-gc.  However the problem with this setting is that memory is never released back to the OS with GHC version 8.10.7.  Unfortunately we need to wait until the cardano-node is able to be compiled using GHC version later than 9.2.x
What I currently use is:
+RTS -N --nonmoving-gc -RTS

As I understand things, the other settings compiled in (set by IOG in the source code) are also enabled.  These include: "-I0 -A16m".  You can check what your binary has with:
cardano-node +RTS --info

The output for my version currently is:

("Flag -with-rtsopts", "-T -I0 -A16m -N2 --disable-delayed-os-memory-return")

Then I restart cardano-node every few days at a convenient time between block production.
Or check your memory usage periodically with:
free

And restart cardano-node when you get close to exhausting your RAM, or after this but before too much swap is used.
If you just let cardano-node keep running using the nonmoving-gc then eventually all the RAM and swap is used and the OS kills the process using its out of memory reaper.  I believe this is because GHC version 8.10.7 doesn't return the collected memory to the OS.
Addition 2021-12-21:
OK now I am not sure about the last bit.  Memory is eventually returned to the OS when using nonmoving-gc.  Here are some outputs of 'free' while running continuously with:
'+RTS -C0 -N -I0 --nonmoving-gc -RTS'
Tue 21 Dec 2021 10:04:57
               total        used        free      shared  buff/cache   available
Mem:        16393504    15851756      161420          20      380328      262232
Swap:       17039352    13271360     3767992

Tue 21 Dec 2021 22:02:44
               total        used        free      shared  buff/cache   available
Mem:        16393504    15325260      648972          20      419272      786832
Swap:       17039352    11186532     5852820

Note that 12hrs has elapsed and RAM and Swap usage has reduced a little.

Thanks so much for your reply and for all the research

Indeed, adding cardano-node +RTS -N -H3G -qg -qb --nonmoving-gc -RTS run ..... to the startBlockProducingNode.sh file seems to have solved the issue. I've now been running for close to 24 hours with zero missed slot leader checks. Thanks once again, Simon

The concern I have is that memory usage seems to progressively increase.  After running 24hrs with "-N -H3G -qg -qb --nonmoving-gc" I have no missed slot leader checks but command "free" shows RAM used 15G, swap used 5G and metric rts_gc_peak_megabytes_allocated is 20G.  So I am concerned about the garbage collection / memory allocation.  I don't think it should be this high.

Yes, I'm seeing similar stats on my BP

Your relays are under the recommended memory specifications that is current 12GB of RAM for cardano-node. This might or might not be the root cause.

Thanks so much for your reply

I am sorry to tell you this, but from what I saw (other people complaining about the same thing), the Block Producers hosted at Contabo have a lot of missed slot leader checks. This is most likely because of the over-provisioned cpu cores. Missed slot leader checks are happening when the CPU is busy doing other tasks and does not have enough time to check each slot (each second) if it should mint a block or not.
Also from my experience on my own block producer on mainnet (because on testnet I do not have any missed slots, even on epochs transitions), using any other RTS option than -N will not improve this metric. Using all the CPU cores is the only option that really helps here.
Most of the missed slot leader checks happen when the cardano-node service is doing a snapshot of the ledger on the disk. This happens once every hour (if I'm not mistaking) by default. You can change this behavior by adding the "SnapshotInterval" setting in your mainnet-config.json file and setting a larger value. for example:
  "SnapshotInterval": 86400,

for one snapshot every 24 hours. This will reduce a lot the missed slot leader checks. The downside is probably a longer start time of the service, but from my observation and calculations, it is a matter of a few extra seconds, probably under 10 seconds, so it is negligible. I am using this in my config, exactly as above, and I only have 2 missed slot leader checks every 24 hours. Before adding it, I had 2 every hour, so it is obvious what made the difference. But my BP has 8 CPU Cores and 24 GB RAM, on Contabo you will still probably have some missed slot leader checks, but this should decrease. If it does not decrease a lot, you might want to find a new hosting for your Block Producer, if you thing it might cause you missed blocks.

I am running on bare metal.  With "+RTS -N -RTS" I get a few missed slots.  These seem to be caused when the haskell garbage collector runs and maybe also, as you say, when snapshots happen.  However, with "+RTS -N --nonmoving-gc -RTS" I get no missed slots except at epoch transition.  Though using the nonmoving-gc increases memory usage and I need to restart the node occasionally.

Yes, running on a bare metal is different than running on a VM, especially at the above hosting company.
Correct, --nonmoving-gc should increase memory usage and should help on a machine with lots of RAM.
You should restart the node ocasionally anyway, from my experience on testnet, after a few weeks of running the nodes without restart, the blocks are ghosted. I am now restarting all the nodes after 2 weeks or sooner.

Interested about the ghosted blocks you see on testnet:  What causes the ghosted blocks?  Do you think your node is not keeping up with mempool transactions thereby creating a block with transactions already executed so other nodes reject the block???

No, the node was keeping up with the blocks and transactions in mempool (I assume), but the blocks were not being propagated quickly to the network (I assume). Some of them were being propagated, but most of them not. I did not investigate further.
Restarting the relay fixed the issue, and since then I am always restarting the nodes from time to time, as I wrote, and it never happened again.

You miss slot leader check when CPU is busy with something else. Remember slot is 1 sec so each sec (slot) the BP needs to check if its leader. Now you always know when you forge the block before epoch but that is not the case for the node. It has to check because there could be slot battles.
So is your Contabo VM having dedicated CPU? the check has to finish within that sec else the slot is missed.
Is this a problem? if you are not forging block then not that much. But in general its always best to not have too many missed slot except during the epoch end which is a known problem.
Also note that if you are using GHC options which trigger garbage collection etc then sometimes and more regularly you will miss slots. restart and Watch for 24 hours and see when the first slots are missed and how regular they are.
There is no good number for missed slots but main thing is you should not miss the slot when you are forging block

Thanks so much for your reply

RAM 16GB may not be sufficient when the network is busy. If +RTS ... -RTS doesn't help, you can try setting "TraceMempool": false in the mainnet-config.json file. This will give you some extra free space in RAM.

source: Stack Exchange

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

sort: votes


text:
Deploy smart contract to testnet using cardano-cli
I am trying to run a few examples of deploying a smart contract to testnet using the cardano-cli. I am running version 1.33.0 for both the cardano-cli and cardano-node. The example I am using is from https://github.com/input-output-hk/cardano-node/tree/master/plutus-example (plutus-example).
I can successfully transfer tADA to the script addresses. However, I cannot unlock the funds that are locked at the script addresses. The error message is below - from the little that I find on internet, it looks like an issue with the redeemer, but I can't figure out how to correct. Can anybody help? My understanding is that both datum and redeemer must both equal a specific value for validation to work (I changed 42 to 1970).
Error message (for cardano-node/plutus-example) ->
Command failed: transaction build  Error: The following scripts have execution failures: the script for transaction input 0 (in the order of the TxIds) failed with:  The Plutus script evaluation failed: An error has occurred:  User error: The provided Plutus code called 'error'. Caused by: [ (builtin unConstrData) (con data #1907b2) ] Script debugging logs:
Code for plutus-example.hs and CustomDatumRedeemerGuess.hs are only slightly modified compared to the repo (no change in logic, only in some file naming).
The cardano-cli commands I use are as follows ->
cardano-cli address build
--payment-script-file custom.plutus
--$testnet
--out-file custom-script.addr
cardano-cli transaction hash-script-data --script-data-value 1970
export scriptdatumhash=7619130e301e1b52e1c333c96d8489fba07ea98eeec3327f719a03d2c713302f
cardano-cli query protocol-parameters --$testnet --out-file protocol.json
cardano-cli transaction build
--alonzo-era
--$testnet
--change-address $address1
--tx-in 4c7c3e12d3ed18241520a8c95a7f68855a1e17af933e207918f65a66bd02c49e#0
--tx-out $(cat custom-script.addr)+10000000
--tx-out-datum-hash $scriptdatumhash
--protocol-params-file protocol.json
--out-file tx-script.build
cardano-cli transaction sign
--tx-body-file tx-script.build
--signing-key-file ../nft/payment.skey
--$testnet
--out-file tx-script.signed
cardano-cli transaction submit --$testnet --tx-file tx-script.signed
Up until here, everything works great and I can transfer funds to the script address.
However, running the following transaction build command fails with the error message above ->
cardano-cli transaction build
--alonzo-era
--$testnet
--tx-in 29f0adfb6ff1ba9b4cb9117b3678cf84532314a1b82a29a6991dfcc38e37d4c6#1
--tx-in-script-file custom.plutus
--tx-in-datum-value 1970
--tx-in-redeemer-value 1970
--tx-in-collateral 29f0adfb6ff1ba9b4cb9117b3678cf84532314a1b82a29a6991dfcc38e37d4c6#0
--change-address $address3
--protocol-params-file protocol.json
--out-file test-alonzo.tx
Can anyone help me? Thanks in advance, Simon

The error output points to error in the actual script. It seems the BuiltIn data is unreadable:
The Plutus script evaluation failed: An error has occurred:  User error:
The provided Plutus code called 'error'. Caused by: [ (builtin
unConstrData) (con data #1907b2)

Thanks, I'll try and investigate that

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


text:
Errror cardano-cli build-raw: AssetName deserisalisation failed expecting hexadecimal digit
I am trying to figure out what's wrong but I do not see it, is my command really wrong? do I need to encode the token name with something? Get a different cardano-cli executable?
transaction build-raw --tx-in c4d3606f4f9a3688d13aa1afbd114cd0e78cc04dc2c0952557db0fb4260d2560#0 --tx-out addr_test1qqrsm4vj985epelhc8qpv8jahaqpjll7ed67647dk47ku4x5x8xk48yntkwhc2s20manmqartkchrp2qxgfwdaezsq5qu9urvd+2000000+"1 b75d4e90a96db2468d4c3d45d65b1f846307b1fc25acdb5489851481.CSCT" --tx-out addr_test1vpl22c6vml7p7n5vv4n2mjf6sfw9kcse5c7jjk3uxc9dllcvvvj8q+2830000 --mint="1 b75d4e90a96db2468d4c3d45d65b1f846307b1fc25acdb5489851481.CSCT" --mint-script-file newtesttokenpolicy.script --invalid-hereafter 42970622 --fee 170000 --out-file c4d3606f4f9a3688d13aa1afbd114cd0e78cc04dc2c0952557db0fb4260d2560.mint.raw
This builds tx with cli from mainnet Daedalus on Windows, but fails on my Ubuntu testnet with the latest cardano-node build. I have this error:
option --tx-out:  unexpected "S" expecting hexadecimal digit AssetName deserisalisation failed

That's because since cardano-node v1.31, you should pass the asset name as base16-encoded.
You can use this command:
echo -n "myassetname" | xxd -ps


text:
What ensures that the supply of ADA is finite, so ADA can definitely be regarded as a store of value?
45 billion is the total eventual supply of ADA (up from from 32 billion or so in circulation now, of which over 71% is staked).
What elements of the code of the Cardano protocols and the structure of the ecosystem ensure that 45 billion is the maximum number of ADA that will ever be in circulation, and when will that maximum be available in circulation for all purposes such as staking etc?

As for the 45 billion ADA it's defined in the genesis JSON file, search for the field "maxLovelaceSupply"

You cannot guarantee that the supply is constantly 45 billion Ada for all eternity, however; you can say with certainty that this particular version of code doesn't support increasing the supply. At some point in the future, the majority of block producing nodes (SPOs) could fork the code base and increase the supply with a future hard fork, but that's the case with any decentralized blockchain.


text:
Best setup of your air-gapped offline machine (cold environment)?
What setup are you using for your air gap machine? Did you buy specific hardware, or some old pc laying around? If reusing some of your old hardware did you wipe it before using it again?
Im looking for a cheap solution. I also read that it is possible to use a hardware wallet to create your cold keys. Any experiences with this? And how would you technically do this?

I use a Chromebook with Arch for storing all kind of sensitive data, cheap and powerful enough to do the work gracefully

The way that I choose is to use a live USB with Tails OS and a persistent encrypted storage.
Once Tails OS is installed, you can decide to boot it without network connection or as they call it "Offline mode". Tails also supports OpenPGP, so if you want to be extra secure and encrypt your keys/recovery phrases with a YubiKey or something similar you can do it.
The only hardware that you need are 2 USBs with at least 8GB, one for main usage and one for backups.
If you need help on setting up this solution just let me know, I am here to help.
Edit:
If anyone is interested, I've created a guide on setting up this solution, you can find it here.
If you have any improvements just let me know, I will be happy to make it better over time :-)

That sounds like a very interesting solution! on the backup, you just store your key files, right? or do you also install tails there?

I wouldn't store my backups for private key/recovery phrases files in an unencrypted usb, so I have 2 solution for this, one to install Tails also on the secondary usb, the other one is to use an encrypted usb like this one. There are many of this usbs arround, but with the second solution costs go up. There is a really good video made by Charles Hoskinson where he explains how to store your private key/recovery phrases. I took inspiration from there.

Secure Airgapping
This topic deserves an in-depth guide, which I will begin working on and will link to it as soon as I complete it. For now, I hope the following gives a high level overview of what I use: an ultra-paranoid, pain-in-the-ass, peace-of-mind setup for key storage and transaction signing
Note: Physical access to the machine is kept under strictly authorized access only. If done correctly, the only way to compromise this setup's security is through unauthorized physical access. Any such access will therefore be considered catastrophic, so keep the machine hidden and secure!

The Setup
Step 1: Acquire an old/used laptop and REMOVE the wifi card. This will require unscrewing the back cover and performing a little surgery, but this way there can be no question about wireless attacks.
Step 2: Download the latest Ubuntu Server LTS and flash it onto a USB stick. I also recommend downloading and re-flashing the BIOS for the machine. This is to rid the machine of any (potential) rootkit/BIOS level malicious software. Be careful with this step; doing it improperly can brick the computer.
Note: ALWAYS verify your downloads through PGP and/or SHA checksums.
Step 3: During Ubuntu installation, choose the minimal installation and select full disk encryption. When selecting the password, I recommend a salted static yubikey OTP. You can then use the same salt as the sudo password for the OS.
Step 4: Establish a one-time network connection using an ethernet/USB port to download all necessary software. This will be the one and only time the machine will be exposed to the internet, prior to any key generation.
Step 5: Download all necessary software: ubuntu updates, git, cardano-cli, cardano-wallet (optional, but recommended if you want to generate mnemonic-style keys). qrencode is also highly recommended. If building from source, you'll also need all prerequisite software like git and such. Depending on the machine's specs you may want to install pre-compiled cardano binaries instead of building from source.
Step 6: Terminate the network connection and (for peace of mind) disable all networking interfaces in the OS and/or BIOS. Never connect to any network again.

Inputs and Outputs
You are now ready to generate keys with cardano-cli. Once this is done, there are two options for inputting transaction bodies for signing:

Use a hardware encrypted USB that has write-protection feature. I recommend the Apricorn Aegis NX. Draft transactions on a hot machine, transfer to the Aegis, turn on write protection, and plug into the airgapped machine. This way, even if a malicious payload finds its way into the airgapped machine, there would be no way to exfiltrate the data.
Manually enter the cborHex of the transaction body into the airgapped machine. Use a JSON template so all you have to do is manually type the cborHex. This is the biggest pain of the setup (if you choose to do this), but it makes the system truly airgapped.

For outputting signed transaction bodies, use qrencode to generate qr images in the command line, and use a phone camera to extract the image contents. If the signed tx body is too large to fit into a single qr image, use the split command to break up the file into multiple smaller files and QR each file sequentially.
Note: ALWAYS backup any keys generated on another secure USB drive and/or a paper wallet.

I will expand on this guide on github and will link to it as soon as I feel it is ready. Hope this helps for now!


text:
Starting a Node Startup Help
The team and i have decided to start a node in the Cardano ecosystem.
we have mac book pro with m1 chip that meets the requirement and ubuntu installed but having problems with rufus for some reason can anyone help me get this going.
any info will be appreciated im sure in some way or another

Please try to put some information regarding the specific error so we can help you out

If this is still a topic for you may look at the cnTools guide and framework to setup your Stakepool Relays and BlockProducer
https://cardano-community.github.io/guild-operators/


text:
Historic and Real-Time Data on Cardano Blockchain in csv or json format
I am conducting some research on Cardano and would like to know if there's any historic and real-time information (on daily basis or more granular) for the below area in json or csv format:
(1) Number of wallet addresses (total unique address and active address)
Note: Active address means addresses that made one or more on-chain transaction(s) on a given day.
(2) Daily transaction value (in ADA and USD value)
(3) Daily number of transaction
(4) Total value staked/locked (TVL)
(5) Number of Dapps built on the blockchain
(6) Transaction fees.
(7) Number of stake pool operators
(8) Average staking return (annualized %)
(9) Block time (s) and transaction per seconds (tps)
I figured it'll be nice to have all the above metrics listed on a website so we can track the status easily. Appreciate if you can share with me if you have the sources for anyone of the above metrics. Thank you in advance.
Cheers

Pull this data from the PostgreSQL database associated with DB-Sync, or GraphQL
Pull exchange data.
See 1.
See 1 & note that delegating stake does not lock ada.
Check back after the 12th of September.
Tx Fees currently depend on: https://docs.cardano.org/explore-cardano/fee-structure#gatsby-focus-wrapper
See 1
See 1
You can calculate the average values via the data in 1.
Please have a look at https://bi.stakepoolcentral.com/ and if you have different metrics than what they offer you could reach out to them to collaborate.


text:
Spare computer with Yoroi or Daedalus as pseudo cold wallet v. Ledger
Am running through my mind the pros and cons of storing Ada on a spare computer disconnected from the network, not happy with being connected to the Internet 24/7 despite being behind firewall.
Apart from the inconvenience (due to physical size) of storing on a spare wiped and reinstalled computer, what are the security implications versus something like the Ledger cold wallet? Seems to be a few grey areas in that regard.
The computer would be disconnected from the network when not doing transactions but obviously does not have the physical as well as logical separation which something like the Ledger provides. On the other hand, Yoroi sandboxing provides a good level of security, and that coupled with a clean install, a dedicated computer would possibly suffice. Would there be advantages in installing Daedalus in this situation?
Any thoughts on this much appreciated.

I've done something similar on a Virtual Machine. I have a Linux based operating system for additional security.
Doing as you propose is basically the same as using a Ledger/Trezor. The additional risk with your setup is that you have your wallet on a computer that can run additional code that a hardware wallet can not. Every time you connect it to the internet and run code on it, you are presenting a security risk.
One possible risk I face from running Linux is that when I update my OS I download an app that's been compromised and can somehow run code to steal my funds.
Over using Yoroi and Daedalus, Daedalus is considered the safer option. But in a practical sense, they're as safe as each other and it's only in theory or extreme situations that Daedalus is safer.
The risks between these setups I believe is rather minimal. One advantage of having a big clunky PC is that you can't lose it easily, so at least you always know where it is as a convenience.

The question is, is it worth the trouble instead of spending $70 for a warranted and battle tested hardware wallet?
My answer to your post is that is probably not, if you are not doing anything specific that a hardware wallet can't do (like minting NFTs).

I built a fully offline Raspberry Pi solution on another coin years ago using QR codes, and cameras as readers.
Cardano is similar in the fact that you 1. build a transaction, 2. sign a transaction and then 3. broadcast a transaction.  Only the signing part needs access to your keys.
As an early step just transferring the data from step 1 to the computer, and then back after step 2 on a small USB stick would allow you to keep your computer fully offline, you would need to learn to construct raw-transactions in a cardano-node CLI.
If this is really of interest look at the Zymbit HSM6 which is a way to encrypt a Raspberry Pi and it has access to common cryptocurrency key schemes, though I didnt check for compatibility with Cardano.
EDIT: Found my old code, it was never meant for production use, just a fun project, but it gives you a start: https://github.com/Scalextrix/coinofflinewallet

This is similar to what I do with an airgap system, the main difference is the airgap system I use is never connected to the network and only signs transactions. I have a live USB stick that only uses Internet when iso is built, can import a wallet mnemonic via https://github.com/input-output-hk/adawallet, and I build transactions on-line using rosetta to query utxos, then sign on the offline system sneaker netting a usb stick back and forth.


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

Edit

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

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

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

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

using cardano-cli

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

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

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

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

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


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

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

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

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


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

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

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

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

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


text:
What is the best (and most secure) way to store private keys in an Express server?
I'm working on a server that will have access to a specific wallet that hold funds and NFTs to submit transactions. Therefore, it will have to manage private keys.
I'm thinking of storing them encrypted as environment variables (.env file), using RSA encryption.
Is this a good practice or is there a better way to do this?

See this post, Best setup of your air-gapped offline machine (cold environment)?.
Also consider the following https://cosd.com/frankenwallet.


text:
How did SundaeSwap solve the scalability issue associated with consuming the same UTxO more than once in the same block?
I know that this was a very hot topic when SundaeSwap came out.
How did the team solve this?

A good thing to remember when developing on Cardano is that there exists no global state! The state and its history of the blockchain is captured in a graph, where the current state of the chain are the outer leafs of this graph.
This above structure allows the blockchain to process transactions that append to this graph to be highly concurrent. The only problem is, once a leaf has left the current state and has become history, then other transaction cannot use it anymore. This latter is the misnamed “concurrency problem”. I call this misnamed, since the whole ledge is as concurrent as it can be. With only local state, you thus have to design your protocols accordingly, an EVM style approach (which relies on a global state) is not possible.
In the most common dexes liquidity is provided via a liquidity pool. This is a centralized piece of data that stores the information about the state. When a transaction utilized this pool, it needs to know the entire state of that pool. On Cardano, this thus has to be represented in a single unspent transaction output, no way around that. But since every transaction consumes this output and pushes it to the history of the graph creating a new location for the state of the pool, other transaction that try to utilize it as well lose track of its location. This means that only one transaction per block can trade with the pool.
To overcome this, we introduce a waiting line of outputs that want to interact with this pool. Then each block, these waiting transactions are combined to create multiple trades with the same pool in one transaction. This solves the problem.
For more information see (1)
This picture helps visualize the graph, here the E, F, G, H, I are leafs (these are nodes without any children) representing the current state of the blockchain. The rest of the nodes are already consumed outputs in the past.


text:
Is there a way to start a Cardano node in Devnet?
I'd like to start a Cardano node in Devnet (not Testnet).
I looked for the configuration files in here, but it seems they are not available.
Is this even possible?

Is there even a devnet?

Yes, I know there is a Devnet because the Hydra POC should be run in Devnet using Docker (check this repo: https://github.com/input-output-hk/hydra-poc). What I don't know if it is possible to run cardano-node in Devnet without Docker.

Looks like devnet refers to your local/private environment.
The Hydra-POC docs refer to it as 'a single Cardano node producing blocks used as a local devnet'
More details about Hydra-POC set up here:
https://hydra.family/head-protocol/docs/getting-started/demo/with-docker/
There are 'With Docker' and 'Without Docker' instructions.
The 'With Docker' portion notes: 'From there, we can run the ./prepare-devnet.sh script to create an initial configuration for our development network'.


text:
How can I stop Cardano Node correctly without running it as a service?
Is there a way to correctly stop cardano-node different than making it run as a service?
I have noticed that, since version 1.34.1, I'm getting the message Validating chunk no. X out of Y. every time I restart it.
I assume this is happening because I'm not stopping it correctly.
I'm using tmux and I just use kill-session command to stop my node.

I'm using tmux and I just use kill-session command to stop my node.

That is probably not a safe shutdown.
For a safe shutdown you should go to the terminal where the node is running and send Control-C. You will then get a message like:
[mainnet:cardano.node.ChainDB:Info:5] [2022-05-30 05:32:03.82 UTC] Closed db with
 immutable tip at 1000a37390ad4590c317da8ec0b456b7d2a50b5a07ad6162cd3fb0b5f5862a7a
 at slot 62277555 and
 tip b1b90587bf4e55e88a0f59ebfd0e4010aabfcd4c5209921a77bb12f479f32df0
 at slot 62322410

Shutting down..

This indicts a correct and safe shutdown.

I think you should resume the session and press Control-C to stop cardano-node when you are running it in tmux.

I've seen people suggest kill -2 <PID> as it sends a SIGINT (similar to CTRL-C), but it never quite completes for me. There is always 1 external network connection active and the main node process is still running, which I then kill <PID> after 10-15 minutes.
Although doing it this way does start up more quickly and avoids most of the Validating chunk X of Y work.


text:
How can I issue an operational certificate using cardano-serialization-lib?
Cardano Serialization Lib has this class:
export class OperationalCert {
  free(): void;
/**
* @returns {Uint8Array}
*/
  to_bytes(): Uint8Array;
/**
* @param {Uint8Array} bytes
* @returns {OperationalCert}
*/
  static from_bytes(bytes: Uint8Array): OperationalCert;
/**
* @returns {KESVKey}
*/
  hot_vkey(): KESVKey;
/**
* @returns {number}
*/
  sequence_number(): number;
/**
* @returns {number}
*/
  kes_period(): number;
/**
* @returns {Ed25519Signature}
*/
  sigma(): Ed25519Signature;
/**
* @param {KESVKey} hot_vkey
* @param {number} sequence_number
* @param {number} kes_period
* @param {Ed25519Signature} sigma
* @returns {OperationalCert}
*/
  static new(hot_vkey: KESVKey, sequence_number: number, kes_period: number, sigma: Ed25519Signature): OperationalCert;
}

How can I generate the KESVKey and the Ed25519Signature required for issuing an OperationalCert using this library?

There's no way, at the moment, to issue a stake pool operational certificate using cardano-serialization-lib.
I suggest using using cardanocli-js instead.
Like this:
const CardanocliJs = require("cardanocli-js");

const shelleyGenesisPath = "/path/to/your/testnet-shelley-genesis.json";
const options = {
  shelleyGenesisPath,
  network: "testnet-magic 1097911063"
};

const cardanocliJs = new CardanocliJs(options);

const nodeOperationalCert = cardanocliJs.nodeIssueOpCert(stakePoolName);

I do not think that Cardano-Serialization-Lib has KES key generation functionality. However, to create an OpCert, you only need the byte string of the KES verification key. If you've already generated the key, then you have the byte string (probably either in bech32 or CBOR format).
The op cert signature is an Ed25519 signature of the KES VKey, the sequence number, and the kes period all concatenated together (in that order) as a string of bytes. The integers are packed as 8-byte BigEndian vectors. The Cardano-Serialization-Lib does have an Ed25519 capability so generating the signature programmatically should be possible.
Update: libcardano is a C++ library that implements this capability. It is possible to pull C++ code into a Rust project if that is needed. Disclaimer: I am the author of libcardano.


text:
Is there an OpenZeppelin like library for Cardano?
Developers on EVM compatible blockchains can make use of battle-tested libraries of smart contracts using https://github.com/OpenZeppelin/openzeppelin-contracts
I'm thinking about having a basic functionality, let's say a base auction contract and then the developer can add/modify whatever he/she needs for his/her specific use case.
Is there something similar on Cardano or a base repo with Plutus Smart Contracts on it for us to take a look?
Thanks

There's no official or adopted standard library in Cardano, yet, as it is on Ethereum.
Anyway, in my opinion the best tools and techniques for Plutus can be found in this repo: https://github.com/Plutonomicon
It belongs to MLabs, a Haskell, Rust, Blockchain and AI consultancy that has built more than 30 projects in Cardano.
There is also more information about their tools here: https://plutonomicon.github.io/plutonomicon/

You can find reference plutus implementations here on github that can be used as a starting point:
https://github.com/input-output-hk/plutus-apps/tree/main/plutus-use-cases/src/Plutus/Contracts
You can also look at the cardano essential list and hopefully there will be more open source projects that you can also reference in the future.
https://github.com/input-output-hk/essential-cardano/blob/main/essential-cardano-list.md


text:
What's the correct way of submitting a transaction using cardano-graphql?
I'm getting this error when trying to submit a transaction using graphql:
{
  "errors": [
    {
      "message": "Deserialization failed in Transaction.metadata because: Expected null, found other type",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "submitTransaction"
      ],
      "extensions": {
        "code": "INTERNAL_SERVER_ERROR",
        "exception": {
          "stacktrace": [
            "Error: Deserialization failed in Transaction.metadata because: Expected null, found other type",
            "    at Object.<anonymous> (/app/packages/api-cardano-db-hasura/dist/executableSchema.js:77:43)",
            "    at Generator.throw (<anonymous>)",
            "    at rejected (/app/packages/api-cardano-db-hasura/dist/executableSchema.js:6:65)",
            "    at processTicksAndRejections (internal/process/task_queues.js:95:5)"
          ]
        }
      }
    }
  ],
  "data": null
}

What is this trying to say?
The transaction has been built using cardano-serialization-lib.
I'm 100% sure the transaction is correct because it's been accepted using other methods.

I don't suggest using cardano-graphql to submit a transaction: every time the node gets behind the tip of the blockchain, it fails.
ogmios is much more reliable for this regard.
You can submit a transaction using the following code:
const WebSocket = require('ws');
const client = new WebSocket("wss://ogmios-api.testnet.dandelion.link");

function wsp(methodname, args) {
    client.send(JSON.stringify({
        type: "jsonwsp/request",
        version: "1.0",
        servicename: "ogmios",
        methodname,
        args
    }));
}

client.once('open', () => {
    const submit =
      "g6QAgYJYIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGCglg5AQEBAQEBAQEB"+
      "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBGgAehICC"+
      "WDkBAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIC"+
      "AgICAgIaAHgXXAIaAAH6pAMZHkahAIGCWCABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+
      "AAAAAFhA169grjPSrzUUEcFEXHlZBSaZC/pzy7NzK1TvMi2qFC5ohAI0EPi+PBbpvVIHbyuz"+
      "a/ON/gNKnwRljp9WGXq4D/Y=";

    wsp("SubmitTx", { submit });
});

client.on('message', function(msg) {
    const response = JSON.parse(msg);
    console.log(response);
    client.close();
});

Keep in mind that, in this example, the transaction is already in base64 format (submit variable). To convert from hex to base64, you need to use these helpers:
const arrayBufferToBase64=( buffer )=> {
  var binary = '';
  var bytes = new Uint8Array( buffer );
  var len = bytes.byteLength;
  for (var i = 0; i < len; i++) {
      binary += String.fromCharCode( bytes[ i ] );
  }
  return Buffer.from(binary, "binary").toString("base64");
}

const fromHex=(hex)=>Buffer.from(hex,"hex");

const bytes = arrayBufferToBase64(fromHex(txHex));

Then you can pass bytes to wsp function.


text:
How can I generate a KES Signature using cardano-serialization-lib?
Cardano Serialization Lib has this class:
export class KESSignature {
  free(): void;
/**
* @returns {Uint8Array}
*/
  to_bytes(): Uint8Array;
/**
* @param {Uint8Array} bytes
* @returns {KESSignature}
*/
  static from_bytes(bytes: Uint8Array): KESSignature;
}

What Uint8Array should I provide to the from_bytes method to obtain a valid KESSignature?

I suggest using cardanocli-js to generate the KES signature file.
You can do it like this:
const CardanocliJs = require("cardanocli-js");

const shelleyGenesisPath = "/path/to/your/testnet-shelley-genesis.json";
const options = {
  shelleyGenesisPath,
  network: "testnet-magic 1097911063"
};

const cardanocliJs = new CardanocliJs(options);

const nodeKeyGenKES = cardanocliJs.nodeKeyGenKES(stakePoolName);


text:
Is it possible to generate all stake pool files and keys using Cardano Serialization Lib?
To successfully create and register a stake pool, we are require to generate:

Payment keys and address
Stake keys and address
Stake pool cold key
Stake pool hot key
Stake pool VRF key
Stake pool operational certificate

We can do all this using cardano-cli.
Is it possible to do it using https://github.com/Emurgo/cardano-serialization-lib as well?

No, it's not possible at the moment.
I have found this commit of the cardano-multiplatform-lib that starts giving some support for these kind of tasks related to generating different types of certificates (stake pool ones included):
https://github.com/dcSpark/cardano-multiplatform-lib/commit/d9ec0ce32136deda2a497dd1c04e6dce8932ba5a
The PR is in progress yet. We will need to wait a little more for dcSpark team, in order to have full support for this feature.
In the meanwhile, I suggest using cardanocli-js to generate stake pool certificates.
Like this:
const CardanocliJs = require("cardanocli-js");

const shelleyGenesisPath = "/path/to/your/testnet-shelley-genesis.json";
const options = {
  shelleyGenesisPath,
  network: "testnet-magic 1097911063"
};

const cardanocliJs = new CardanocliJs(options);

const nodeKeyGenKES = cardanocliJs.nodeKeyGenKES(stakePoolName);
const nodeKeyGen = cardanocliJs.nodeKeyGen(stakePoolName);
const nodeOperationalCert = cardanocliJs.nodeIssueOpCert(stakePoolName);
const vrfKeyAccount = cardanocliJs.nodeKeyGenVRF(stakePoolName);

Check out this link about generating keys:
https://developers.cardano.org/docs/get-started/cardano-serialization-lib/generating-keys


text:
Plutus script execution at every end of epoch
I would like to develop a Plutus script that executes each time an epoch ends.
What's the best way to achieve this behaviour?

As mentioned by Jey earlier, blockchains and smart contracts remain latent until triggered by a user submitted transaction.
One way you could pull this off is that you could use the cardano-cli application to create, sign and submit a transaction which executed the plutus script at the end of every epoch. You can find out more about cardano-cli and plutus scripts here and a simple sample here
UPDATE: I realized that I missed out explaining how this could be done by creating an javascript bot which submits this kind of transaction near the end of the epoch automatically.
You can use the cardanocli-js javascript library to achieve this... here's a basic sample, but you can pretty much do any kind of action that the cardano-cli can do, in a programmatic submission.
Hope this helps!

This is exactly what I learned at the Plutus Pioneer Program but I just needed to be sure I was understanding it correctly. Thank you very much for your clarification!

Scripts are executed as part of a transaction validation. That means: no transaction -> no script execution. The blockchain has no mechanism of timed or automatic script execution. What you can do is to implement transaction submission at every new epoch in your off-chain code.


text:
Script Witness Not Validating for Multisig
I'm getting the following error when trying to consume a UTxO sitting in a multisig script address:
[
  {
    "scriptWitnessNotValidating": [
      "74947280b4d63d1051d319d700e21dac50ee858c089378ccc410b568"
    ]
  }
]

This is the script I created for requiring 4 of 6 signatures to consume the UTxO:
const jsonScript = {
    type: 'atLeast',
    require: 4,
    scripts: [
        {
          type: 'sig',
          keyHash: '6bccf3fc71642dbc8f34deb976784ca636665043ef1384b31cab2524'
        },
        {
          type: 'sig',
          keyHash: 'acfdc19b3081ef21301f76eee0e5e35411b9d2c2b5624e580f36bac4'
        },
        {
          type: 'sig',
          keyHash: 'f03009eb94e1d4a208ccc64bde7e91dc3f6a6c1d8660199fc2f120b8'
        },
        {
          type: 'sig',
          keyHash: '3c76bbfc8af2b0862c3aca122a1d5a4493ee8b2aa2cfb7aadcfdcbc5'
        },
        {
          type: 'sig',
          keyHash: '52a09a992dfbe55f9ec80bc73fecf1bf7f42434c73e8bb79067aaf30'
        },
        {
          type: 'sig',
          keyHash: 'dd31fc7bf8d266eb08f840361ff528108d6689eeb3af96cfa77d8547'
        }
    ]
};

I'm using this function to provide each of the signing keys to the transaction I want to execute:
tx.addKeyWitnesses(signingKeys[0]);
tx.addKeyWitnesses(signingKeys[1]);
tx.addKeyWitnesses(signingKeys[2]);
tx.addKeyWitnesses(signingKeys[3]);
tx.addKeyWitnesses(signingKeys[4]);
tx.addKeyWitnesses(signingKeys[5]);

Is there something I'm missing?
Thank you

Are you sure you are trying to consume the right UTxO? Check the index, maybe you are trying to consume the wrong output of that transaction.

I tried all over again and it worked. I'm not sure if it was that or not but at least I have it right now. Thanks for your reply.

Finally I was able to sort this out.
You can use this library to create the multisig: https://github.com/tango-crypto/cardano-wallet-js
The code I ran was the following:
multisig.js
const { WalletServer , Seed } = require('cardano-wallet-js');

const data = {
    "type":  "atLeast", //requires at least 4 keys to sign the tx
    "require": 4,
    "scripts":
    [
        {
            "type": "sig"
        },
        {
            "type": "sig"
        },
        {
            "type": "sig"
        },
        {
            "type": "sig"
        },
        {
            "type": "sig"
        },
        {
            "type": "sig"
        },
    ]
};
// generate the native script
const script = Seed.buildScript(data);

const jsonScript = Seed.scriptToJson(script);

console.log(jsonScript);

// get native script private keys (all them will be needed to sign the final tx)
const keys = Seed.getScriptKeys(script).map(k => k.to_bech32());
console.log("keys:", keys);

//Generate script address
const address = Seed.getScriptAddress(script, 'testnet').to_bech32();
console.log("address:", address);

The code to sign the transaction is this one (you need to replace every 'XXXX' on scriptKeys with your signing keys, and every 'YYYY' on jsonScript.scripts with the key hashes of each signature - all this is output of multisig.js):
tx-sign.js
const { WalletServer , Seed , Config, Bip32PrivateKey } = require('cardano-wallet-js');

const scriptKeys = [
    'XXXX',
    'XXXX',
    'XXXX',
    'XXXX',
    'XXXX',
    'XXXX'
];

const signingKeys = scriptKeys.map(key => Bip32PrivateKey.from_bech32(key).to_raw_key());

// get native script (this is the SAME SCRIPT, we're just "loading" it back)
const jsonScript = {
    type: 'atLeast',
    require: 4,
    scripts: [
      {
        type: 'sig',
        keyHash: 'YYYY'
      },
      {
        type: 'sig',
        keyHash: 'YYYY'
      },
      {
        type: 'sig',
        keyHash: 'YYYY'
      },
      {
        type: 'sig',
        keyHash: 'YYYY'
      },
      {
        type: 'sig',
        keyHash: 'YYYY'
      },
      {
        type: 'sig',
        keyHash: 'YYYY'
      }
    ]
};

// set network configuration
let buildOpts = {
    startSlot: 0,
    config: Config.Testnet,
};

const ttl = 52399446; // slot before the tx should be processed

const CoinSelectionWallet = {
    "withdrawals": [],
    "inputs": [
        {
            "amount": {
                "quantity": 10000000,
                "unit": "lovelace"
            },
            "address": "addr_test1xr20j5t970ssz0323tzqqvp3pp02s96yf64zmzj83kksyvx5l9gktulpqylz4zkyqqcrzzz74qt5gn429k9y0rddqgcq2yupvs", // script address
            "id": "d48f256aea384066756be0c11c6e6b8baef8f7ad25ba92b76d1ae3c294443400",
            "assets": [],
            "index": 0
        },
    ],
    "deposits": [],
    "change": [
        {
            "amount": {
                "quantity": 8800000, // fee of 200000 initially
                "unit": "lovelace"
            },
            "address": "addr_test1xr20j5t970ssz0323tzqqvp3pp02s96yf64zmzj83kksyvx5l9gktulpqylz4zkyqqcrzzz74qt5gn429k9y0rddqgcq2yupvs",
            "assets": []
        }
    ],
    "outputs": [
        {
            "amount": {
                "quantity": 1000000,
                "unit": "lovelace"
            },
            "address": "addr_test1qpypxf9jma2lkmzwn6nhypmynqpmus7x0ekwp2jfdrxqgm8vecdcssszlmywlyn7h0nkqp9jyk8p7dhjecglhu9m75xq4mwl9v",
            "assets": []
        }
    ]
};

const script = Seed.buildScript(jsonScript);
// for the script witnesses we only need to specify the native script root
const scripts = [script.root];

// build the tx (you can include scripts/signingkeys here, eg: let tx = Seed.buildTransactionMultisig(selection, ttl, scripts, null, sigingKeys, buildOpts);)
let tx = Seed.buildTransactionMultisig(CoinSelectionWallet, ttl, [], null, [], buildOpts);
// add script
tx.addScriptWitness(...scripts);
// add witness
tx.addKeyWitnesses(signingKeys[0]);
tx.addKeyWitnesses(signingKeys[1]);
tx.addKeyWitnesses(signingKeys[2]);
tx.addKeyWitnesses(signingKeys[3]);
tx.addKeyWitnesses(signingKeys[4]);
tx.addKeyWitnesses(signingKeys[5]);

const signed = tx.build();
console.log(signed)

When you do :
tx.addKeyWitnesses(signingKeys[0]);
tx.addKeyWitnesses(signingKeys[1]);
tx.addKeyWitnesses(signingKeys[2]);
tx.addKeyWitnesses(signingKeys[3]);
tx.addKeyWitnesses(signingKeys[4]);
tx.addKeyWitnesses(signingKeys[5]);

You are signing with all 6 signatures. You can sign with any 4 you want and the UTxO will be consumed as well. On the contrary, if you provide less than 4 signatures, then the validation will fail.


text:
How to convert a Stake Key Address from hash to BECH32?
I have this Stake Key:
https://testnet.cardanoscan.io/stakekey/7622b4611b15441e7e15cba128ff999ad72388aeb267adc6e70cc9bc?tab=stakehistory
I want to convert from 7622b4611b15441e7e15cba128ff999ad72388aeb267adc6e70cc9bc to stake_test1upmz9drprv25g8n7zh96z28lnxddwgug46ex0twxuuxvn0qp3cptz format.
How do I do it using this library https://github.com/Emurgo/cardano-serialization-lib?
Thanks

The beech32 representation is a bit tricky, but you can do it like this:
const stakeKey = StakeCredential.from_bytes(from_hex('7622b4611b15441e7e15cba128ff999ad72388aeb267adc6e70cc9bc'));
const networkId = 1; // testnet = 1, mainnet = 0
const beech32StakeKey = RewardAddress.new(networkId, stakeKey).to_address().to_bech32();
console.log(beech32StakeKey);

Hope this helps. The "from_hex" function is just a simple js function to convert the Hex string into an UInt8Array that is needed for the from_bytes function of StakeCredentials.


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

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


text:
How to convert from cborHex to VRFKeyHash using both cardanocli-js and cardano-serialization-lib?
I'm using cardanocli-js to create both VRF files for running a stake pool: vrf.vkey and vrf.skey:
const vrfKeyAccount = cardanocliJs.nodeKeyGenVRF("Totem");

Then I want to read the vrf.vkey file and convert the cborHex value to VRFKeyHash format, from the Cardano Serialization Lib. For that, I do:
CardanoWasm.VRFKeyHash.from_hex(JSON.parse(vrfKeyFile).cborHex);

But I'm getting the following error:
/cardano-multiplatform-lib/rust/pkg/package/cardano_multiplatform_lib.js:16780
    throw takeObject(arg0);
    ^
JsValue("Deserialization failed in VRFKeyHash because: Invalid cbor: expected tuple 'hash length' of length 32 but got length Len(34).")
(Use `node --trace-uncaught ...` to show where the exception was thrown)

I have checked that every cborHex on vrf.vkey files starts with the prefix "5820" and every cborHex on vrf.skey files starts with the prefix "5840". If I remove those prefixes from the conversion, then it works:
CardanoWasm.VRFKeyHash.from_hex(JSON.parse(vrfKeyFile).cborHex.substring(4)));

Maybe this could help,
as cborHex is in hex, and you can pass a Uint8Array (bytes) to initialize a VRFKeyHash like in many cardano-serialization-lib objects, in theory you can use Buffer.from(hexValue,"hex"), like this:
CardanoWasm.VRFKeyHash.from_bytes(Buffer.from((JSON.parse(vrfKeyFile).cborHex,"hex")));

not tested!


text:
What's the correct way of deserializing a UTxO?
I'm getting the following error when trying to deserialize a UTxO obtained using cardano-graphql:
Deserialization failed in TransactionUnspentOutput because: No variant matched

This is the code that it's failing:
for (const rawUtxo of rawUtxos) {
      const utxo = CardanoWasm.TransactionUnspentOutput.from_bytes(
        Buffer.from(rawUtxo.transaction.hash, "hex")
      )
      const input = utxo.input()
      const txid = input.transaction_id().to_bytes().toString();
      const txindx = input.index()
      const output = utxo.output()
      const amount = output.amount().coin().to_str() // amount in lovelace
      const multiasset = output.amount().multiasset()

What am I doing wrong?

This is the code to deserialize the UTxOs of an address:
for (const rawUtxo of rawUtxos) {
      const utxo = C.TransactionUnspentOutput.from_bytes(Buffer.from(rawUtxo, "hex"));
      const input = utxo.input();
      const txid = Buffer.from(input.transaction_id().to_bytes(), "utf8").toString("hex");
      const txindx = showPtrInHex(input.index());
      const output = utxo.output();
      const amount = output.amount().coin().to_str(); // ADA amount in lovelace
      const multiasset = output.amount().multiasset();
      let multiAssetStr = "";

      if (multiasset) {
        const keys = multiasset.keys() // policy Ids of thee multiasset
        const N = keys.len();

        for (let i = 0; i < N; i++) {
          const policyId = keys.get(i);
          const policyIdHex = Buffer.from(policyId.to_bytes(), "utf8").toString("hex");
          const assets = multiasset.get(policyId)
          const assetNames = assets.keys();
          const K = assetNames.len()

          for (let j = 0; j < K; j++) {
            const assetName = assetNames.get(j);
            const assetNameString = Buffer.from(assetName.name(), "utf8").toString();
            const assetNameHex = Buffer.from(assetName.name(), "utf8").toString("hex")
            const multiassetAmt = multiasset.get_asset(policyId, assetName)
            multiAssetStr += ` + ${multiassetAmt.to_str()} ${policyIdHex} . ${assetNameHex} (${assetNameString})`
          }
        }
      }

      const obj = {
        txid: txid,
        txindx: txindx,
        amount: amount,
        str: `${txid} # ${txindx} = ${amount}`,
        multiAssetStr: multiAssetStr,
        TransactionUnspentOutput: utxo
      }

      utxos.push(obj);


text:
Error when executing nix-shell in plutus-apps
I am getting...
error: experimental Nix feature 'flakes' is disabled; use '--extra-experimental-features flakes' to override

...when trying to run nix-shell from plutus-apps repo.
Does anybody know how I can enable flakes?
I am using the latest commit 7952b9d30d15779a7fd8103bdbc9612d5df18ec2.

There are two ways of fixing this issue:
Temporary
Add --experimental-features 'nix-command flakes' when calling the nix-shell command.
Permanent
Edit either ~/.config/nix/nix.conf or /etc/nix/nix.conf and add:
experimental-features = nix-command flakes

For more information you can refer to: https://github.com/input-output-hk/plutus-apps/#nix-1

This is in plutus-apps nix config https://github.com/input-output-hk/plutus-apps/#nix-1

Thank you. I have edited the answer to include that link instead of the one from Nix.


text:
How would you implement Soulbound Tokens in Cardano?
A lot is going on at the moment in the Ethereum dev community with Soulbound Tokens: https://ethereum-magicians.org/t/eip-5114-soulbound-badges/9417
What would be the best approach for implementing non-transferable tokens in Cardano?
A soulbound token is a token that is bound to a wallet when it is minted, and cannot be transferred/moved after that. In Cardano, I understand this means it should be locked to a specific UTxO that has to be part of the wallet.
Is it possible to implement this in Cardano without the need of smart contracts?

Def: "Soulbound tokens (SBT) are non-transferable, publicly-verifiable digital tokens that can act as a type of CV for web3 users, showing an individual’s memberships, credentials, and affiliations." This is a pretty good write up on SBTs: https://www.axi.com/au/blog/education/blockchain/soulbound-tokens

Just thinking out loud here, this would probably be best implemented at the protocol level eg an extra flag to indicate if an asset/NFT is transferable or not. Plus methods to query/verify and burn. So a CIP would be needed to get some consideration and deep discussion https://cips.cardano.org/ - mind you Atala Prism and Digital IDs might offer the same functionality.

Thanks for your comment, mate. Yes, I'm thinking of proposing a CIP myself, that's why I'm trying to get some ideas from the community first, on how this can be addressed.

Atala Prism looks to address this use case: "Atala PRISM is a self-sovereign identity (SSI) platform and service suite for verifiable data and digital identity. Built on Cardano, it offers core infrastructure for issuing DIDs (Decentralized identifiers) and verifiable credentials, alongside tools and frameworks to help expand your ecosystem." https://www.atalaprism.io/ - They also have a useful services walk through showing the different interactions https://www.atalaprism.io/app/credentials

Even though Prism exists, having competition/alternative services is always better for the eco-system, and having core services at the protocol level offers more certainty and robustness. Good luck with the CIP.

Any native asset on cardano can be transferred according to the ledger rules.
To make something non-transferrable you would need to make it unspendable.

For "pay to pubkey" outputs, this would mean to throw away the key - I don't think this is what you want in this case.
The only alternative "pay to script" outputs are governed by the script (currently either a simple or plutus script). Making these unspendable is easy, think const False for plutus.

As you ask "without the need for smart contracts" I would say: No, scripts will be required to implement something like this.
But isn't Ethereum using smart contracts for this as well?
If scripts are okay, one could draft up a specification what an SBT is. For example (based on my limited familiarity with SBTs) something like:

A cardano native token / asset with quantity 1, which
was minted by a policy that ensures single mint & pay to some public key (two parameters: TxOutRef and PubKeyHash) creating an output, that
is governed by an unspendable script (identified by script hash), which
also contains a datum (inline or hash) pointing to the owner (PubKeyHash above).

Note that "from the outside" this would not be resolvable who some SBT belongs to, you would need the parameters of the minting script and anything needed for the datum pre-image to verify. For example the "seed" TxOutRef and the PubKeyHash of the "soul"


text:
Is it possible to change the minimum ada value for an UTxO?
If I want to send a token or NFT in Cardano, I need to include some ada with it. This is known as minimum-ada-value.
Is it possible to change this value for a specific NFT and make it so big that it is almost impossible to send the NFT?
I'm thinking of this solution as a way of implementing non-transferable tokens in Cardano.

The minAda requirement is given by the protocol parameters and is a core parameter that cannot be changed for individual UTxOs.
If you want to create non-transferable tokens on Cardano, please check out this thread, this was just answered recently :).
Non-transferrable Tokens


text:
Is it MuesliSwap the only DEX with an API?
I'd like to build a backend that brings data from all Cardano DEXes.
I have been exploring this link: https://docs.muesliswap.com/cardano/api/api-v1
Is it the only DEX that provides an API? I didn't find any information on MinSwap, SundaeSwap or Wingriders.

Minswap uses a GraphQL endpoint that you can find here:

https://monorepo-mainnet-prod.minswap.org/graphql/

Example:
curl --request POST \
  --url https://monorepo-mainnet-prod.minswap.org/graphql/ \
  --header 'Content-Type: application/json' \
  --data '{"query":"query TVLSeries {  tvlSeries {    time    tvl  }}\n\n","operationName":"TVLSeries"}'

They also have an adapter to query their data using Blockfrost:

https://github.com/minswap/blockfrost-adapter

SundaeSwap has an API located at:

https://stats.sundaeswap.finance/api/

Example:
curl --request GET \
  --url https://stats.sundaeswap.finance/api/ticks/0029cb7c88c7567b63d1a512c0ed626aa169688ec980730c0473b913.70202d01/2022/09/02

Both of them don't seem to have public documentation, so you can either ask the team directly or try to find the endpoints you need.
Hope this helps!


text:
How can I create a token that shows 6 decimals places in Eternl?
I have created my own token and I have added a Cardano Token Registry specifying that the token has 6 decimals places. My entry looks exactly like the Minswap's token entry, but the difference is that, when I want to send a transaction, I don't have the possibility to add decimal places, like I do have on the Minswap token.
Is there anything else I should do so my token shows like this:

Not sure if Eternl has this implemented, but there is a proposal that adds this token information to the metadata of the minting transaction:
https://github.com/cardano-foundation/CIPs/blob/1d9fbd0e29f07b931bf1524c7aed6635d478cd75/CIP-0035/CIP-0035.md
Minswap doesn't follow it, but Sundae does. Here's an example under Label 20:
https://cardanoscan.io/transaction/d74798c4a1e453fbc6ba4fbb1d785e0534fb8531fd1bc054ceff5b086240d3b5?tab=metadata
Probably worth a try.
Also, if your token is not correctly displayed in Eternl, you can click the "update" button (marked in red below), to re-fetch the data of your token from the Cardano Token Registry:

I tried also with that but it doesn't work. The problem is only in Eternl, in Nami and in Cardanoscan I can visualise the right amount of decimal places.

in discord it is suggested to "press the little update icon button to fetch the new registry data". Couldn't try it myself though

Did you register your token at CFtoken registry ? You can specify decimals as part of JSON you register on that repo.

Yes, I did, my entry looks exactly like the Minswap entry.

Any other suggestion? Because I still have this issue. The problem appears to be only with Eternl, in Nami it works fine.


text:
Is it possible to swap tokens in Cardano using a SDK?
I am looking for a SDK from any potential protocol that let me swap tokens, as you would do in Ethereum using Uniswap or SushiSwap.
Is there such a thing in Cardano?

One option would be the SundaeSwap SDK: https://github.com/SundaeSwap-finance/sundae-sdk

Yes, at the moment that is the only DEX with a SDK. Minswap team has their own private, it will be released soon.


text:
Is it possible to integrate Cardano in Unreal Engine?
I want to build a game using Unreal and I want to use Cardano's wallets for authentication.
Is it possible to integrate Unreal Engine with Cardano's network via a plugin or something like that?

I did a Google search and found a couple of projects that may be of interest to you:
https://devpost.com/software/unreal-engine-cardano-plugin
"Unreal Engine 5 plugin that allows users to connect to the Cardano API via Blockfrost.io"
https://www.lidonation.com/en/proposals/cardanosharp-unrealengine-sdk
"a plugin that will give UnrealEngine developers the ability to mint Tokens and NFTs in a way that integrates with their game logic"


text:
Compile errors when importing Cardano Serialization Lib Browser in React
I'm getting several compile errors as soon as I import @emurgo/cardano-serialization-lib-browser in my project, all of them similar to these:
ERROR in ./node_modules/@emurgo/cardano-serialization-lib-browser/cardano_serialization_lib_bg.js 19251:82-105
Can't import the named export '__wbindgen_realloc' (imported as 'wasm') from default-exporting module (only default export is available)

ERROR in ./node_modules/@emurgo/cardano-serialization-lib-browser/cardano_serialization_lib_bg.js 19280:36-58
Can't import the named export '__wbindgen_malloc' (imported as 'wasm') from default-exporting module (only default export is available)

ERROR in ./node_modules/@emurgo/cardano-serialization-lib-browser/cardano_serialization_lib_bg.js 19280:60-83
Can't import the named export '__wbindgen_realloc' (imported as 'wasm') from default-exporting module (only default export is available)

ERROR in ./node_modules/@emurgo/cardano-serialization-lib-browser/cardano_serialization_lib_bg.js 19482:36-58
Can't import the named export '__wbindgen_malloc' (imported as 'wasm') from default-exporting module (only default export is available)

ERROR in ./node_modules/@emurgo/cardano-serialization-lib-browser/cardano_serialization_lib_bg.js 19482:60-83
Can't import the named export '__wbindgen_realloc' (imported as 'wasm') from default-exporting module (only default export is available)

ERROR in ./node_modules/@emurgo/cardano-serialization-lib-browser/cardano_serialization_lib_bg.js 19497:12-23
Can't import the named export 'memory' (imported as 'wasm') from default-exporting module (only default export is available)

Is there any other library I should use on a React project to handle wallet interaction?

I suggest using dcSpark's Cardano Multiplatform Lib: https://www.npmjs.com/package/@dcspark/cardano-multiplatform-lib-browser.


text:
Error when compiling cardano-node 1.35.5
I am getting the following error when trying to compile the new version of the cardano-node:
Resolving dependencies...
Error: cabal: Could not resolve dependencies:
[__0] trying: cardano-api-1.35.5 (user goal)
[__1] next goal: base (dependency of cardano-api)
[__1] rejecting: base-4.17.0.0/installed-4.17.0.0 (conflict: cardano-api =>
base>=4.14 && <4.15)
[__1] skipping: base-4.17.0.0, base-4.16.4.0, base-4.16.3.0, base-4.16.2.0,
base-4.16.1.0, base-4.16.0.0, base-4.15.1.0, base-4.15.0.0 (has the same
characteristics that caused the previous version to fail: excluded by
constraint '>=4.14 && <4.15' from 'cardano-api')
[__1] rejecting: base-4.14.3.0, base-4.14.2.0, base-4.14.1.0, base-4.14.0.0,
base-4.13.0.0, base-4.12.0.0, base-4.11.1.0, base-4.11.0.0, base-4.10.1.0,
base-4.10.0.0, base-4.9.1.0, base-4.9.0.0, base-4.8.2.0, base-4.8.1.0,
base-4.8.0.0, base-4.7.0.2, base-4.7.0.1, base-4.7.0.0, base-4.6.0.1,
base-4.6.0.0, base-4.5.1.0, base-4.5.0.0, base-4.4.1.0, base-4.4.0.0,
base-4.3.1.0, base-4.3.0.0, base-4.2.0.2, base-4.2.0.1, base-4.2.0.0,
base-4.1.0.0, base-4.0.0.0, base-3.0.3.2, base-3.0.3.1 (constraint from
non-upgradeable package requires installed instance)
[__1] fail (backjumping, conflict set: base, cardano-api)
After searching the rest of the dependency tree exhaustively, these were the
goals I've had most trouble fulfilling: base, cardano-api

I am using ghc 9.4.4 and cabal 3.8.1.0

The solution to this error is to downgrade ghc to version 8.10.7 by running the following commands:
ghcup install ghc 8.10.7
ghcup set ghc 8.10.7

Then, you have to prepare the compilation for that specific compiler version, like this:
cabal configure -O0 -w ghc-8.10.7

Then you can run:
cabal build cardano-node cardano-cli

Unfortunately, cardano-node is not yet compatible with the latests versions of ghc (9.4.4 and 9.2.5 at the time of this post).


text:
Error when trying to build my Plutus project
I am getting the following error after trying to execute cabal build:
cabal: Could not resolve dependencies:
[__0] next goal: cardano-crypto-class (user goal)
[__0] rejecting: cardano-crypto-class-2.0.0.0.1/installed-iw7NtuXmRKLDXiVT5sxh
(constraint from user target requires ==2.0.0)
[__0] rejecting: cardano-crypto-class-2.0.0 (conflict: pkg-config package
libsodium-any, not found in the pkg-config database)
[__0] fail (backjumping, conflict set: cardano-crypto-class)
After searching the rest of the dependency tree exhaustively, these were the
goals I've had most trouble fulfilling: cardano-crypto-class

I am using cabal 3.6.2.0 and ghc 8.10.7

You are missing libsodium :
[__0] rejecting: cardano-crypto-class-2.0.0 (conflict: pkg-config package
libsodium-any, not found in the pkg-config database)

The way I get around this is sudo apt install libsodium-dev and then create a top level file cabal.project.local containing:
package cardano-crypto-praos
  flags: -external-libsodium-vrf

Pretty sure this is documented somewhere in the cardano-node repository.

It is documented here: https://github.com/input-output-hk/cardano-node/blob/1.35.5/doc/getting-started/install.md#installing-libsodium

It is documented, but it no longer works. Builds are failing with the hack in place.

I just tried it and it works for me. What specifically is the problem you are seeing. Probably worth asking that as a new question. You need to specify what steps you are taking and what the error is.


text:
How can I build a transaction to send different assets (not just ada) using Cardano Serialization Lib?
I have followed this example on how to create a transaction to send ada and I had no issues so far.
What I would like to do next is to add different assets to this same transaction.
Is there an example on how to do that?

If you are open to use other packages, https://github.com/StricaHQ/typhonjs is a package which you can use to build transactions, It's easy to explore this as this is written in TS.

This is how you build a multi-token transaction using cardano-serialization-lib:
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());

}

https://github.com/ozgrakkurt/cardano-mint-nft/blob/master/index.js
The example above from Özgür Akkurt on GitHub demonstrates how to mint native tokens in JS, assuming you are looking for that language.
https://github.com/Emurgo/cardano-serialization-lib/blob/master/doc/getting-started/minting-nfts.md
This is the next example directly from the Emurgo library is the next example in sequence from the previous example you followed.
Is it Native tokens you are looking to send?

Referencing guidelines: https://cardano.stackexchange.com/help/referencing


text:
How to convert UTxOs from Graphql to Cardano Serialization lib format?
I want to use this function as coin selection for my transactions:
txBuilder.add_inputs_from(unspentOutputs, 3);

The problem I have is I'm using cardano-graphql to retrieve UTxOs:
{
  "data": {
    "utxos": [
      {
        "transaction": {
          "hash": "ae6a7f64b2ce09ac0f0ffd8f92dda8af15367e02801057b4be40ca1d199e74b0"
        },
        "index": 1,
        "value": "2592591",
        "address": "addr_test1qpypxf9jma2lkmzwn6nhypmynqpmus7x0ekwp2jfdrxqgm8vecdcssszlmywlyn7h0nkqp9jyk8p7dhjecglhu9m75xq4mwl9v",
        "tokens": [
          {
            "asset": {
              "policyId": "4223e84e15c5fc65bd4959ef84264ea53133b782fc176b2c538d8900",
              "assetId": "4223e84e15c5fc65bd4959ef84264ea53133b782fc176b2c538d890047616d654368616e676572303033",
              "assetName": "47616d654368616e676572303033"
            },
            "quantity": "10"
          },
          {
            "asset": {
              "policyId": "4223e84e15c5fc65bd4959ef84264ea53133b782fc176b2c538d8900",
              "assetId": "4223e84e15c5fc65bd4959ef84264ea53133b782fc176b2c538d890047616d654368616e676572303034",
              "assetName": "47616d654368616e676572303034"
            },
            "quantity": "10"
          }
        ]
      },
      {
        "transaction": {
          "hash": "ae6a7f64b2ce09ac0f0ffd8f92dda8af15367e02801057b4be40ca1d199e74b0"
        },
        "index": 2,
        "value": "2481480",
        "address": "addr_test1qpypxf9jma2lkmzwn6nhypmynqpmus7x0ekwp2jfdrxqgm8vecdcssszlmywlyn7h0nkqp9jyk8p7dhjecglhu9m75xq4mwl9v",
        "tokens": [
          {
            "asset": {
              "policyId": "4223e84e15c5fc65bd4959ef84264ea53133b782fc176b2c538d8900",
              "assetId": "4223e84e15c5fc65bd4959ef84264ea53133b782fc176b2c538d890047616d654368616e676572303035",
              "assetName": "47616d654368616e676572303035"
            },
            "quantity": "10"
          }
        ]
      }
   ]
}

How do I convert from this format to TransactionUnspentOutputs?
export class TransactionUnspentOutputs {
  free(): void;
/**
* @returns {TransactionUnspentOutputs}
*/
  static new(): TransactionUnspentOutputs;
/**
* @returns {number}
*/
  len(): number;
/**
* @param {number} index
* @returns {TransactionUnspentOutput}
*/
  get(index: number): TransactionUnspentOutput;
/**
* @param {TransactionUnspentOutput} elem
*/
  add(elem: TransactionUnspentOutput): void;
}

Is there a function or helper I could use?

This is the function I use to convert the UTxOs from graphql to TransactionUnspentOutputs:
async function getUTxOs(address: string) {

  const url = `https://d.graphql-api.${process.env.ENVIRONMENT}.dandelion.link`;

  const headers = {
    "content-type": "application/json"
  };

  const query = `
  {
    utxos(where: { address: { _in: "${address}" } }) {
      transaction {
        hash
      }
      index
      value
      address
      tokens {
        asset {
          policyId
          assetId
          assetName
        }
        quantity
      }
    }
  }
  `;

  const graphqlQuery = {
    "query": query
  };

  const response = await axios({
    url,
    method: 'post',
    headers: headers,
    data: graphqlQuery
  });

  const Utxos = []

  try {
    const rawUtxos = response.data.data.utxos
    for (const rawUtxo of rawUtxos) {
      var utxo: CardanoWasm.TransactionUnspentOutput;
      if(rawUtxo.tokens.length > 0) {
        const multiAsset = CardanoWasm.MultiAsset.new()
        const assets = CardanoWasm.Assets.new()
        for (const token of rawUtxo.tokens) {
          assets.insert(
            CardanoWasm.AssetName.new(Buffer.from(token.asset.assetName, "hex")),
            CardanoWasm.BigNum.from_str(token.quantity)
          )
          multiAsset.insert(CardanoWasm.ScriptHash.from_bytes(Buffer.from(token.asset.policyId, "hex")), assets)
        }
        utxo = CardanoWasm.TransactionUnspentOutput.new(
          CardanoWasm.TransactionInput.new(CardanoWasm.TransactionHash.from_bytes(Buffer.from(rawUtxo.transaction.hash, "hex")), rawUtxo.index),
          CardanoWasm.TransactionOutputBuilder.new()
            .with_address(CardanoWasm.Address.from_bech32(rawUtxo.address))
            .next()
            .with_coin_and_asset(CardanoWasm.BigNum.from_str(rawUtxo.value), multiAsset)
            .build()
        )
      } else {
        utxo = CardanoWasm.TransactionUnspentOutput.new(
          CardanoWasm.TransactionInput.new(CardanoWasm.TransactionHash.from_bytes(Buffer.from(rawUtxo.transaction.hash, "hex")), rawUtxo.index),
          CardanoWasm.TransactionOutputBuilder.new()
            .with_address(CardanoWasm.Address.from_bech32(rawUtxo.address))
            .next()
            .with_value(CardanoWasm.Value.new(CardanoWasm.BigNum.from_str(rawUtxo.value)))
            .build()
        )
      }

      const input = utxo.input()
      const txid = input.transaction_id().to_bytes().toString();
      const txindx = input.index()
      const output = utxo.output()
      const amount = output.amount().coin().to_str() // amount in lovelace
      const multiasset = output.amount().multiasset()
      let multiAssetStr = ''

      if (multiasset) {
        const keys = multiasset.keys() // policy Ids of the multiassets
        const N = keys.len()
        // console.log(`${N} Multiassets in the UTXO`)

        for (let i = 0; i < N; i++) {
          const policyId = keys.get(i)
          const policyIdHex = policyId.to_bytes().toString();
          const assets = multiasset.get(policyId)
          const assetNames = assets?.keys()
          const K = assetNames?.len() ?? 0

          for (let j = 0; j < K; j++) {
            const assetName = assetNames?.get(j)
            const assetNameString = assetName?.name().toString()
            const assetNameHex = assetName?.name().toString()
            const multiassetAmt = multiasset.get_asset(policyId, assetName!)
            multiAssetStr += `+ ${multiassetAmt.to_str()} + ${policyIdHex}.${assetNameHex} (${assetNameString})`
          }
        }
      }

      const utxoObj = {
        txid: txid,
        txindx: txindx,
        amount: amount,
        str: `${txid} #${txindx} = ${amount}`,
        multiAssetStr: multiAssetStr,
        TransactionUnspentOutput: utxo,
      }
      Utxos.push(utxoObj)
    }
    return Utxos
  } catch (error) {
    console.log(error)
  }
}


text:
How can I build a transaction to register a stake pool using Cardano Serialization Lib?
I have built the following transaction to register a stake pool:
{
  "txHash": "0f874a3cb0ba57ed68a79601781eb9e29666f7f2f0e72ab4ed1f3cc9fcea7dee",
  "ttl": 60310548,
  "txSize": 386,
  "inputs": [
    {
      "txHash": "ca0bca365de069364e4c74b818d8a1c4faebbb095e05635fbab5b1033ede3270",
      "index": 0
    }
  ],
  "outputs": [
    {
      "outputIndex": 0,
      "address": "addr_test1qpypxf9jma2lkmzwn6nhypmynqpmus7x0ekwp2jfdrxqgm8vecdcssszlmywlyn7h0nkqp9jyk8p7dhjecglhu9m75xq4mwl9v",
      "policyId": "ada",
      "assetName": "ada",
      "quantity": "499827547"
    }
  ],
  "metadata": {},
  "outputTotals": [
    {
      "policyId": "ada",
      "assetName": "ada",
      "quantity": "499827547"
    }
  ],
  "fee": "172453",
  "outputAda": "499827547",
  "inputTotalEstimation": "500000000"
}

The transaction has the stake pool certificate attached to it, that's why it consumes an additional 500 ADA for the deposit.
The problem I have is I'm getting the following error when trying to submit it to the blockchain:
The sum of inputs, outputs and fee is not zero. (ValueNotConservedError)

    [
      {
        "valueNotConserved": {
          "consumed": {
            "coins": 1000000000,
            "assets": {}
          },
          "produced": {
            "coins": 500000000,
            "assets": {}
          }
        }
      }
    ]

The input UTxO has a value of 1000 ADA, which is more than enough to cover the stake pool deposit fee. And, in addition to this, if I do...
output + fee + deposit = 499827547 + 172453 + 500000000 = 1000000000

...I get the value of the input of the transaction (so nothing's being lost in theory).
What am I doing wrong?

This is the code to build a transaction to register a Stake Pool using cardano-serialization-lib:
export const submitRegistrationTransaction = async (
  mnemonic,
  poolCertificate
) => {

  //const privateKey = await getPrivateKeyFromEntropy(entropy);
  const entropy = mnemonicToEntropy(mnemonic);

  const rootKey = CardanoWasm.Bip32PrivateKey.from_bip39_entropy(
    Buffer.from(entropy, 'hex'),
    Buffer.from(''),
  );

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

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

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

  const baseAddr = CardanoWasm.BaseAddress.new(
    CardanoWasm.NetworkInfo.testnet().network_id(),
    CardanoWasm.StakeCredential.from_keyhash(utxoPubKey.to_raw_key().hash()),
    CardanoWasm.StakeCredential.from_keyhash(stakeKey.to_raw_key().hash()),
  );

  const stakeAddr = CardanoWasm.RewardAddress.new(
    CardanoWasm.NetworkInfo.testnet().network_id(),
    CardanoWasm.StakeCredential.from_keyhash(stakeKey.to_raw_key().hash())
  )

  const privateKey = deriveSpendPrivateKey(accountKey, 0).to_raw_key();
  const stakingPrivateKey = deriveStakePrivateKey(accountKey, 0).to_raw_key();
  const fromAddress = baseAddr.to_address().to_bech32("addr_test");

  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);

  // 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);

  const certificates = CardanoWasm.Certificates.new();
  certificates.add(poolCertificate);
  txBuilder.set_certs(certificates);

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

  // 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);
  //const vkeyWitness2 = CardanoWasm.make_vkey_witness(txHash, stakingPrivateKey);

  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());

}

This is how you create the stake pool certificate:
export const createStakePoolCertificate = (
  mnemonic,
  stakePoolName,
  relayIP,
  relayPort,
  pledge,
  cost,
  poolMarginNumerator,
  poolMarginDenominator
) => {

  const entropy = mnemonicToEntropy(mnemonic);

  const rootKey = CardanoWasm.Bip32PrivateKey.from_bip39_entropy(
    Buffer.from(entropy, 'hex'),
    Buffer.from(''),
  );

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

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

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

  const baseAddr = CardanoWasm.BaseAddress.new(
    CardanoWasm.NetworkInfo.testnet().network_id(),
    CardanoWasm.StakeCredential.from_keyhash(utxoPubKey.to_raw_key().hash()),
    CardanoWasm.StakeCredential.from_keyhash(stakeKey.to_raw_key().hash()),
  );

  const stakeAddr = CardanoWasm.RewardAddress.new(
    CardanoWasm.NetworkInfo.testnet().network_id(),
    CardanoWasm.StakeCredential.from_keyhash(stakeKey.to_raw_key().hash())
  )

  const privateKey = deriveSpendPrivateKey(accountKey, 0).to_raw_key();

  // Declare variables for pool params
  const operatorKeyHash = utxoPubKey.to_raw_key().hash().to_bech32('ed25519_pk');

  const nodeKeyGenKES = cardanocliJs.nodeKeyGenKES(stakePoolName);
  const nodeKeyGen = cardanocliJs.nodeKeyGen(stakePoolName);
  const nodeOperationalCert = cardanocliJs.nodeIssueOpCert(stakePoolName);
  const vrfKeyAccount = cardanocliJs.nodeKeyGenVRF(stakePoolName);

  //const kesKeyFile = readFileSync(nodeKeyGenKES.vkey, 'utf-8');
  //console.log(CardanoWasm.KESSignature.from_bytes(Buffer.from(JSON.parse(kesKeyFile).cborHex), "hex"));
  const vrfKeyFile = readFileSync(vrfKeyAccount.vkey, 'utf-8');
  //const vrfKeyHash = CardanoWasm.VRFKeyHash.from_hex(JSON.parse(vrfKeyFile).cborHex.substring(4));
  const vrfKeyHash = CardanoWasm.VRFKeyHash.from_bytes(fromHex(JSON.parse(vrfKeyFile).cborHex.substring(4)));

  const poolMargin = CardanoWasm.UnitInterval.new(
    CardanoWasm.BigNum.from_str(poolMarginNumerator), // numerator
    CardanoWasm.BigNum.from_str(poolMarginDenominator)  // denominator
  );

  const poolOwner = CardanoWasm.Ed25519KeyHashes.new();
  poolOwner.add(CardanoWasm.Ed25519KeyHash.from_bech32(operatorKeyHash));

  const relays = CardanoWasm.Relays.new();
  const relay = CardanoWasm.Relay.new_single_host_addr(
    CardanoWasm.SingleHostAddr.new(
      relayPort,
      CardanoWasm.Ipv4.new(new Uint8Array(relayIP.split('.').map((segment) => Number.parseInt(segment, 10))))
    )
  );
  relays.add(relay);

  // Prepare pool params
  const poolParams = CardanoWasm.PoolParams.new(
    CardanoWasm.Ed25519KeyHash.from_bech32(operatorKeyHash),
    vrfKeyHash,
    CardanoWasm.BigNum.from_str(pledge),
    CardanoWasm.BigNum.from_str(cost),
    poolMargin,
    stakeAddr,
    poolOwner,
    relays
  );

  // Create Pool Registration
  const poolRegistration = CardanoWasm.PoolRegistration.new(poolParams);
  console.log(poolRegistration);
  // Generate Pool Certificate
  const poolCertificate = CardanoWasm.Certificate.new_pool_registration(poolRegistration)
  return poolCertificate;
}


text:
How do I change the -with-rtsopts flags when I execute cardano-node?
I want to specify some extra flags like --nonmoving-gc and -N (with the right amount of CPU cores that I want my cardano-node to execute in - my server has 16 CPU cores) in my +RTS configuration.
What would be the correct way of adding these flags to my cardano-node run command?
This is my current setup (which should be default):
[("GHC RTS", "YES")
 ,("GHC version", "8.10.7")
 ,("RTS way", "rts_thr")
 ,("Build platform", "x86_64-unknown-linux")
 ,("Build architecture", "x86_64")
 ,("Build OS", "linux")
 ,("Build vendor", "unknown")
 ,("Host platform", "x86_64-unknown-linux")
 ,("Host architecture", "x86_64")
 ,("Host OS", "linux")
 ,("Host vendor", "unknown")
 ,("Target platform", "x86_64-unknown-linux")
 ,("Target architecture", "x86_64")
 ,("Target OS", "linux")
 ,("Target vendor", "unknown")
 ,("Word size", "64")
 ,("Compiler unregisterised", "NO")
 ,("Tables next to code", "YES")
 ,("Flag -with-rtsopts", "-T -I0 -A16m -N2 --disable-delayed-os-memory-return")
 ]


text:
Where does the PAB run?
I understand that PAB is a backend that:

provides a standardized environment in which Plutus applications run
provides disciplined state management
presents discoverable interfaces to the external clients
tracks on-chain information for smart contract uses
allows developers to work in an emulated or non-emulated environment
deals with requests such as running contract instances, forwarding user input to these instances, and notifying these instances of ledger state change events

But is it just another piece of infrastructure we should consider in our solution or is it a service we can consume for example from a third party like Blockfrost?

You don't have to use it in your dApp stack. As a matter of fact, many existing dApps don't use it since it's not ready. It essentially is a module/ component that makes use of existing IO products (cardano-node, cardano-db-sync or its light version of it chain-indexer etc.)
Therefore, if you want to create a dApp you can choose to use Blockfrost to keep track of your smart contract state/ fetch datum hashes/ get UTxOs etc.
or you host your own instances of cardano-node/ submit-api and db-sync to do what blockfrost allows you to do and eventually PAB will as well.
PAB will offer more features than Blockfrost from what I understand.