text:
Get Value of Datum from a UTXO
I currently have a utxo that i am getting like this.
initalMatchPool <- Map.filter (findInitalAmount fundAddress) <$> utxosAt scrAddress

How do i get the value of the datum attached to this specific utxo ?

The ChainIndexTxOut type has a data field called _ciTxOutValue :: Value and another that is _ciTxOutDatum :: Either DatumHash Datum I'll show you how to get the value. Getting the datum is the same process with the extra step of having to extract it from the Either binding.
utxos <- utxosAt ...
list = Map.toList utxos
firstUtxo = head list
ci = snd firstUtxo
val = _ciTxOutVale ci

utxos is type Map(TxOutRef ChainIndexTxOut)
list is type [(TxOutRef, ChainIndexTxOut)]
firstUtxo is type (TxOutRef, ChainIndexTxOut)
ci is type ChainIndexTxOut
val is type Value
All those lines can be combined to vals = _ciTxOutValue (snd (head (Map.toList utxos))) or if you want the sum of all the of the values instead of just the value in the first utxo at the address, you can do vals = _ciTxOutValue <$> (snd <$> Map.toList utxos)

I am getting type errors from using this.

@szhang9921 Can you share your code?

it works now , the type error was because i was parsing the final value wrong. Thanks

The upshot is that you might not find a datum, but instead get a hash of the datum (it depends).
When submitting a transaction, the full "unhashed" datum is not automatically attached to the output. This to save space and add use cased where the sender wants to keep the datum a secret. If it is not attached, you will not find it onchain, only the hash of the datum used. Reversing this is (computational) impossible by construction.
In the other case, where there is one attached, you can retrieve it. As stated by Kyle Murphy the constructor ChainIndexTxOut(1) that resulted from the filter "findInitalAmount fundAddress" over all UTxO's sitting at the script address scrAddress contains all info known of these outputs fitting the condition you specified.
The function utxosAt returns a map of two fields, Map TxOutRef ChainIndexTxOut (2). Each TxOutRef contains the hash of the transaction that made this utxo and an associated id relative to the other outputs of that transaction (TxOutRef TxId Integer). Now the other field in the Map is the ChainIndexTxOut which can contain one of two things depending on the query. If you queried a script address, this will be

Note That the _ciTxOutDatum constructor holds a Either DatumHash Datum. So if the UTxO contains a datum you can retrieve, you can extract it with Right like below.
getDatum :: ChainIndexTxOut -> Maybe Datum
getDatum o = case _ciTxOutDatum o of
            Right  i               -> Just i
            Left   j               -> Nothing

I hope this helps.

Great explanation. However, I believe your last sentence is inaccurate and in order to read the datum from the call to _ciTxOutDatum we match it using Right and not Left.

OffChain:
It's a datum hash - so there is no reverse lookup if you don't know how to construct datums for a given contract.
Datum values are usually provided by the consumer of a script UTxO.
OnChain:
If this is onchain code (which it does not look like), you can use a function called findDatum to lookup datums provided by the consumer of a script UTxO.


text:
start-cluster - Command failed: genesis create - */genesis.alonzo.spec.json: openBinaryFile: does not exist (No such file or directory)
After cloning latest cardano-node and running nix-shell successfully I get an error running start-cluster and different error if I run with sudo:
Do I need to download the latest genesis jason file? or set WORKBENCH_BACKEND?

[nix-shell:~/plutus/cardano-node]$ start-cluster
workbench:  cabal-inside-nix-shell mode enabled, calling cardano-* via cabal run (instead of using Nix store)
 10 days ago 65422ff37 HEAD -> master, origin/nightly, origin/master, origin/HEAD Merge #3816
workbench:  prebuilding executables (because of useCabalRun)
workbench:    prebuilding cardano-node
/nix/store/m2ckif2l1xf3x9y91wgczlah2snvbicw-cabal-install-exe-cabal-3.6.2.0/bin/cabal --project-file=/Users/deano/plutus/cardano-node/.nix-shell-cabal.project -v0 build -- exe:cardano-node
workbench:    prebuilding cardano-cli
/nix/store/m2ckif2l1xf3x9y91wgczlah2snvbicw-cabal-install-exe-cabal-3.6.2.0/bin/cabal --project-file=/Users/deano/plutus/cardano-node/.nix-shell-cabal.project -v0 build -- exe:cardano-cli
workbench:    prebuilding cardano-topology
/nix/store/m2ckif2l1xf3x9y91wgczlah2snvbicw-cabal-install-exe-cabal-3.6.2.0/bin/cabal --project-file=/Users/deano/plutus/cardano-node/.nix-shell-cabal.project -v0 build -- exe:cardano-topology

workbench:  run | allocate | profile:  pre-supplied
workbench:  run | allocate | topology:  computed
/nix/store/m2ckif2l1xf3x9y91wgczlah2snvbicw-cabal-install-exe-cabal-3.6.2.0/bin/cabal --project-file=/Users/deano/plutus/cardano-node/.nix-shell-cabal.project -v0 run exe:cardano-topology -- --topology-output /Users/deano/plutus/cardano-node/run/2022-05-02-17.18.plain.default-alzo/topology/topology-nixops.json --dot-output /Users/deano/plutus/cardano-node/run/2022-05-02-17.18.plain.default-alzo/topology/topology.dot uni-circle --size 6 --loc LO
workbench:  run | allocate | genesis:  computed
realpath: /Users/deano/.cache/cardano-workbench/genesis/k6-d1-0.006kD-0kU-e74709a: No such file or directory
workbench:  genesis:  cache entry at /Users/deano/.cache/cardano-workbench/genesis/k6-d1-0.006kD-0kU-e74709a is incompatible:  layout version 'unknown' does not match current: March-14-2022
workbench:  genesis: preparing cache entry k6-d1-0.006kD-0kU-e74709a:  miss (/Users/deano/.cache/cardano-workbench/genesis/k6-d1-0.006kD-0kU-e74709a)
workbench:  genesis: generating due to cache-miss:  k6-d1-0.006kD-0kU-e74709a @/Users/deano/.cache/cardano-workbench/genesis/k6-d1-0.006kD-0kU-e74709a
/nix/store/m2ckif2l1xf3x9y91wgczlah2snvbicw-cabal-install-exe-cabal-3.6.2.0/bin/cabal --project-file=/Users/deano/plutus/cardano-node/.nix-shell-cabal.project -v0 run exe:cardano-cli -- genesis create --genesis-dir /Users/deano/.cache/cardano-workbench/genesis/k6-d1-0.006kD-0kU-e74709a/ --supply 6010000000000000 --testnet-magic 42 --gen-genesis-keys 0 --gen-utxo-keys 1
Command failed: genesis create  Error: /Users/deano/.cache/cardano-workbench/genesis/k6-d1-0.006kD-0kU-e74709a/genesis.alonzo.spec.json: /Users/deano/.cache/cardano-workbench/genesis/k6-d1-0.006kD-0kU-e74709a/genesis.alonzo.spec.json: openBinaryFile: does not exist (No such file or directory)

[nix-shell:~/plutus/cardano-node]$ sudo start-cluster
Password:
/nix/store/c6jc5fbkvr45p6wpdj5k7d3ldim1lymw-workbench-0.1/bin/backend.sh: line 58: WORKBENCH_BACKEND: unbound variable
/nix/store/c6jc5fbkvr45p6wpdj5k7d3ldim1lymw-workbench-0.1/bin/backend.sh: line 60: WORKBENCH_BACKEND: unbound variable
'''

and here is result of cardano-node install:

```
exprType TYPE: Text
exprType TYPE: Text
exprType TYPE: Text
exprType TYPE: Text
exprType TYPE: Text
workbench:    prebuilding cardano-cli
/nix/store/m2ckif2l1xf3x9y91wgczlah2snvbicw-cabal-install-exe-cabal-3.6.2.0/bin/cabal --project-file=/Users/deano/plutus/cardano-node/.nix-shell-cabal.project -v0 build -- exe:cardano-cli
exprType TYPE: AssetName
exprType TYPE: AssetName
workbench:    prebuilding cardano-topology
/nix/store/m2ckif2l1xf3x9y91wgczlah2snvbicw-cabal-install-exe-cabal-3.6.2.0/bin/cabal --project-file=/Users/deano/plutus/cardano-node/.nix-shell-cabal.project -v0 build -- exe:cardano-topology

  Commands:
    * nix flake lock --update-input <iohkNix|haskellNix> - update nix build input
    * cardano-cli - used for key generation and other operations tasks
    * wb - cluster workbench
    * start-cluster - start a local development cluster
    * stop-cluster - stop a local development cluster
    * restart-cluster - restart the last cluster run (in 'run/current')
                        (WARNING: logs & node DB will be wiped clean)
'''

cardano-cli etc are working

I have used the local cluster from cardano-node many times and on several different installs (1.34.1 & 1.33.1) and did not encouter the issue you are having.   No need to run start-cluster from sudo, so you can rule this out.
It sounds like there may be an issue with an invalid nix cache somewhere, so maybe you should try to clear/delete your nix store and start fresh?
https://nixos.wiki/wiki/Cleaning_the_nix_store

source: Stack Exchange

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

sort: votes


text:
Send Given Amount of Tokens From Script to Wallet
Which TxConstraints i o method should I use to create a transaction where the script pays a specified amount to the wallet? The mustSpendScriptOutput is the only one I can find that sends tokens from the script to the wallet, but it sends all the tokens at a utxo. I am looking to send a specified amount, and the change is returned to the script.

UTxOs can only be consumed completely which means you will have to create a new output at the script address that receives the change that shall stay with the script which can be done via mustPayToTheScript <datum> <value>.

When I added that to the constraints the transaction failed. Is there a way I can post my code in multiple lines in a comment?

https://meta.stackexchange.com/questions/207842/how-to-easily-indent-multi-line-code

I'm getting a ConstraintResolutionError TxOutRefNotFound during the ledgerTx line of code
utxos <- utxosAt $ scriptAddress payValidator
let orefs = fst <$> Map.toList utxos
     change = _ciTxOutValue (snd (L.head (Map.toList utxos))) - (Ada.lovelaceValueOf bet)
     lookups = Constraints.typedValidatorLookups typedPayToScriptValidator
     tx = Constraints.mustSpendScriptOutput (last orefs) unitRedeemer <> Constraints.mustPayToTheScript bet change
ledgerTx <- submitTxConstraintsWith lookups tx
void $ awaitTxConfirmed $ getCardanoTxId ledgerTx

Looks like your TxOutRef is invalid and does not exist. Check your orefs

I needed to add Constraints.unspentOutputs utxos and Constraints.typedValidatorLookups myValidator to my lookups variable. Thanks for the help, I appreciate it.

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


text:
Can you include a minting policy in a transaction without minting or burning any tokens?
I want to use the minting policy to abstract the script logic away from the validator and only validate what's necessary for a specific transaction. Right now, I'm able to do this by minting a token I call ticket and creating the validator in such a way that it makes sure this tokens is being minted.
Since my purpose is not to mint a token, this ends up increasing the transaction size without any added value so I wonder if it's possible to include the minting policy in the transaction, verify that somehow in the validator, but not mint or burn any tokens.

I had a similar issue where I needed to break up the validator logic to keep under the maxTx size limits.  I was able to do this by testing for the presence of threadtokens so that each of validators could "communicate" with each other.   I also implemented some performance improvements that reduce the overhead as well.
The project is called The Open Source Cardano Lottery and you can checkout the source code here:
https://github.com/lley154/cardano-lottery

I know I'm not answering your exact question, but I think I can help you achieve your goal of "abstracting the script logic from the validator and only validate what's necessary for a specific transaction." Plutus pioneer program cohort #3 week 1's code is a good example of this
https://github.com/input-output-hk/plutus-pioneer-program/blob/main/code/week01/src/Week01/EnglishAuction.hs
You'll see that Lars used a custom data type for his redeemer, that allowed him to have different logic for whether the validator script was called with the intention of bidding or closing the auction.

Thanks for your answer. I see value on what Lars did, but my purpose was to reduce the script size. If I put all the possible conditions into one script, it could reach the transaction limit, so I prefer to have multiple minting policies that are only called when one of the conditions is met.


text:
How can I allow users to update a public array of data based on whether they own a token or not?
I want to construct public lists that can be altered by people who own a specific token.
Is there a way I can group data together into an array like structure and allow users to append to it?
I understand metadata will play a fundamental role here, and I guess it will have something to do with the wallet updating the arrays digital signature.

How large is this array going to be and what shall it contain ?

It will contain IPFS hashes of files, the size could vary but possibly up to 500 entries

What function does the array serve? Does it only serve information or do you want to use it with some logic?

purely as an immutable information log that can be queried using blockfrost for example

Do you want it to be an append only list?

The transaction size is limited. So your list cannot grow too large. But assuming you stay within these constraints, you can achieve what you want by (i) parametrising your validator with a type that contains the currency symbol of the needed token and then (ii) checking in your validator if the token with this currency symbol is in the inputs. Additionally you would check that the list of hashes (which you would store in the datum) is only appended and not altered.
With the Vasil hard fork in June, you can have another approach to (ii). You could add the UTxO that contains the token as a reference input and check in the validator that (a) the reference input contains the token and (b) that the transaction is signed by the holder of this reference UTxO.
Edit:
If you want a solution without smart contracts you could indeed use the metadata but it would also mean that the list update is controlled by a central party (which would be you). A possible design would be the following one:

The location of the list is the metadata of the most recent transaction containing a specific token that you own. Let's call this token the list-NFT.
The users that want to append the list make a transaction to your wallet address. This transaction contains in its metadata the entry to be appended. The transaction would also contain a specific token that proves that the user has the right to append the list.
You have a service running that regularly filters the payments to your wallet address, verifies the presence of the token, and makes a transaction containing the list-NFT and the appended list.

thank you for information on this, i appreciate it. I was thinking users could all add entries to the same metadata key and true entries could be found by querying the blockchain with some off chain logic to confirm the person owned the nft at that time. Smart contracts seem like a better option though.

Ok, I understand. I edited the answer.

I think there are two kinds of solutions. The first is the most cost efficient and is focused on offchain indexing of the database, anybody can do it but there is no logic onchain. The second one is where you use plutus (and especially version 2, hard fork will be 29 of june and plutus will be fully available 1 epoch later).
For the former you can just let holders of a token create metadata transaction that contain atleast x tokens y. Then with a DB-sync instance anyone can index the latest state of the database. You even can introduce some overriding rules.
The second solution could be to use the reference capabilities of plutus V2. With the upcoming hard fork referencing outputs will be possible. With this you could make a database sitting on an script address where each UTxO is an entry. You could use this database in the future if needed. To prevent false entries you could create a minting policy which created some validity token if x amount of token are present. The cool thing about this solution is that the data is pretty localized and the present state is well defined and easy to obtain.
Hope this helps and I would love to see you make one of these!


text:
symbol lookup error: cardano-node: undefined symbol: crypto_vrf_publickeybytes
I am trying to run a cardano node in my local and the command which i am running goes like this.
cardano-node run \
   --topology mainnet-topology.json \
   --database-path db \
   --socket-path db/node.socket \
   --host-addr 127.0.0.1 \
   --port 3001 \
   --config mainnet-config.json

But it is showing me this error.
cardano-node: symbol lookup error: cardano-node: undefined symbol: crypto_vrf_publickeybytes

In at this post it is getting solved but the links on that post is broken.
Does anyone knows how to resolve the same.
https://forum.cardano.org/t/cardano-node-symbol-lookup-error-cardano-node-undefined-symbol-crypto-vrf-publickeybytes/36359
The cardano installation progress is here.
{
    "era": "Byron",
    "syncProgress": "61.71",
    "hash": "21e4ea98fafcb565733debefca7fecf2d2ab901b7ce6587f1ad4f5ca327e93d1",
    "epoch": 207,
    "slot": 4490076,
    "block": 4487787 }

Once solution is to add the following to cabal.project.local:
package cardano-crypto-praos
  flags: -external-libsodium-vrf

and then rebuild the node executable.
If the file does not already exist, just add at the top level directory of the git checkout, with just the two lines above.

How do i do this? do i need to execute this command in terminal?

where is this cabal.project.local i am fairly new to haskel

The cabal.project.local file should be in the top level directory of the Gut checkout. There should already be a cabal.project file in the same location.


text:
How can I convert from cborHex to VRFKeyHash type from the Cardano Serialization Lib?
I need to generate a VRF Key Hash in this format: vrf_vk13hg4gg5fg67399nuz2ldk89kqw9h379cfgtkpvd83ra89f908kcqv2cw3j
When I generate it using cardano-cli, I get this file:
{
    "type": "VrfVerificationKey_PraosVRF",
    "description": "VRF Verification Key",
    "cborHex": "5820d3e6e69edf63e50ce0d12bc8fd891d6d00a09cb484a55f99caf0767bd9d75488"
}

What I'm trying to do is to convert this to VRFKeyHash. I'm using this function (I'm reading the value directly from the file, that's why I'm parsing it):
const fromHex=(hex)=>Buffer.from(hex,"hex");
const vrfKeyHash = CardanoWasm.VRFKeyHash.from_bytes(fromHex(JSON.parse(vrfKeyFile).cborHex));

But when I do this, I get the following error:
Deserialization failed in VRFKeyHash because: Invalid cbor: expected tuple 'hash length' of length 32 but got length Len(34).

What is it that I'm doing wrong?

To convert from cborHex to VRFKeyHash I did the following, assuming there's a file with this format...
{
    "type": "VrfVerificationKey_PraosVRF",
    "description": "VRF Verification Key",
    "cborHex": "5820d3e6e69edf63e50ce0d12bc8fd891d6d00a09cb484a55f99caf0767bd9d75488"
}

...which can be generated using cardano-cli or cardanocli-js:
const vrfKeyFile = readFileSync(vrfKeyAccount.vkey, 'utf-8');
CardanoWasm.VRFKeyHash.from_bytes(Buffer.from(JSON.parse(vrfKeyFile).cborHex.substring(4), "hex"));

You need to get rid of the first 2 bytes ("5820" prefix) in order for it to work.

Verification keys can be represented in different ways. The one that you want is a representation where the key hash is converted with a prefix vrf_ to the bech32 format. This can be done via the following repo (1).
Given your specific given vrf verification key file you first have to convert it to a vrf key hash. This can be done via the cardano-cli with
cardano-cli node key-hash-VRF --verification-key-file fileName.vkey

Which returns 80bdf88001bcfb0723f93aff337b299d1502f1d1884afe65342b7b8dfd18c2e6 for your vkey file. Then one can convert this hash to bech32 format with prefix vrf_ as follows
cabal run exe:bech32 -- vrf_ <<< 80bdf88001bcfb0723f93aff337b299d1502f1d1884afe65342b7b8dfd18c2e6

which returns vrf_1sz7l3qqphnaswgle8tlnx7efn52s9uw33p90uef59dacmlgcctnqut3ndw.
To reverse the bech32 transformation you can run the following
cabal run exe:bech32 -- <<< vrf_vk13hg4gg5fg67399nuz2ldk89kqw9h379cfgtkpvd83ra89f908kcqv2cw3j

which return 8dd154228946bd12967c12bedb1cb6038b78f8b84a1760b1a788fa72a4af3db0, the vrf key hash of the example bech32 address you gave.

Do you know what conversion should I apply to cborHex in order to work with Cardano Serialization Lib?
const vrfKeyHash = CardanoWasm.VRFKeyHash.from_bytes(X)
Imagine that X is the cborHex. If I provide it directly that way, I get the following:
"JsValue("Deserialization failed in VRFKeyHash because: Invalid cbor: expected tuple 'hash length' of length 32 but got length Len(34).")"
I have also tried converting it to bytes, but same error.

Note that in the bech32 is something similar to JSON, to indicate if something is a bytestring or a list etc some bytes indicate those objects. If you have a look at cbor.me and put in the full you will see the key is D3E6E69EDF63E50CE0D12BC8FD891D6D00A09CB484A55F99CAF0767BD9D75488. Which has length 32 not 34. I am no expert on the serialization lib so I cannot help with that unfortunately.

Also see https://www.npmjs.com/package/@dcspark/cip5-js, this might help.

Thank you very much!


text:
Where to locate the path to node.socket in order to set CARDANO_NODE_SOCKET_PATH env variable?
I would like to check the sync progress of the cardano node from within a cardano-node-ogmios docker container that I installed. When I open the docker CLI and I run the command cardano-cli query tip --mainnet I get that $CARDANO_NODE_SOCKET_PATH environment variable is not defined. I've tried locating /db/node.socket path, but I cannot seem to find it. Any clue as to where it may be located?

Just a side note, you can run cardano-tip outside of container, no need to login to container. I use it something like that from the host: docker exec -ti test-producer /usr/local/bin/cardano-cli query tip --testnet-magic 1097911063

A note for other people, when starting your node the --socket-path option will contain the path to the socket.
CARDANO_NODE_SOCKET_PATH should match this value.
cardano-node run \
   --topology path/to/mainnet-topology.json \
   --database-path path/to/db \
   --socket-path path/to/db/node.socket \
   --host-addr x.x.x.x \
   --port 3001 \
   --config path/to/mainnet-config.json

After checking the Ogmios documentation again I finally found it in /ipc/node.socket. (Post can be deleted or remain in case for future reference)

Including the snippet of the documentation would improve your answer and remember you can mark your own answer as accepted.

Just create db folder inside your cardano-node, and pointing your script to that folder, the node.socket will be created once after you node is sync 100%


text:
How does the Fμω lambda calculus use C?
While poking around in the repositories I wondered how the sha2_256 algorithm was implemented in the PlutusTx module. I followed all the imports and got the following path

The sha2_256 function in PlutusTx.Builtins is defined at (1). In this module it is imported from a internal module with import name BI.

{-# INLINABLE sha2_256 #-}
-- | The SHA2-256 hash of a 'ByteString'
sha2_256 :: BuiltinByteString -> BuiltinByteString
sha2_256 = BI.sha2_256

This BI.sha2_256 function in the PlutusTx.Builtins.Internal is defined at (2). Here the function is wrapped in the BuiltinByteString type. A function is imported from the the Hash module.

{-# NOINLINE sha2_256 #-}
sha2_256 :: BuiltinByteString -> BuiltinByteString
sha2_256 (BuiltinByteString b) = BuiltinByteString $ Hash.sha2 b

This Hash.sha2 function in the Data.ByteString.Hash is defined at (3). Here it gets a bit more complicated. A cryptographic hash function takes an arbitrary block of data and calculates a fixed-size bit string (the digest). Since there may be other hash function (like the SHA3_256 version in PlutusTx) the function is abstracted to a general hash function where the type inferred by the type application @SHA256). This data type and its instance of a hash algorithm is imported from Cardano.Crypto.Hash.SHA256.

-- | Hash a [[BSL.ByteString]] using the SHA-256 hash function.
sha2 :: BS.ByteString -> BS.ByteString
sha2 = digest (Proxy @SHA256)

In this cardano-base package the module Cardano.Crypto.Hash.SHA256 defines the data type SHA256 and its instance of a hash algorithm at (4). The function sha256_libsodium is also defined there. This function uses another function called c_crypto_hash_sha256, this is where it gets interesting imported from the module Libsodium.C.

data SHA256

instance HashAlgorithm SHA256 where
  type SizeHash SHA256 = 32
  hashAlgorithmName _ = "sha256"
  digest _ = sha256_libsodium

The function c_crypto_hash_sha256 in Cardano.Crypto.Libsodium.C (like many other cryothographic derivatives used in cardano) is defined in (5). Here this function is actually import from the package Libsodium which is a library for encryption, decryption, signatures, password hashing and more written in C.

Now my question is, how is this lower level C function get used in the lower level Fμω lambda calculus onchain? Does each node just invoke/inject the C function once the lambda calculus references it?


text:
ConstraintResolutionError
I'm getting the following error during the ledgerTx line of code
"ConstraintResolutionError (TxOutRefNotFound (TxOutRef {txOutRefId = 70d473b55eaac244c821a001fe153813249c22395cb55631f34eb149937d340a, txOutRefIdx = 1}))"
utxos <- utxosAt $ scriptAddress payValidator
let orefs = fst <$> Map.toList utxos
     change = _ciTxOutValue (snd (L.head (Map.toList utxos))) - (Ada.lovelaceValueOf bet)
     lookups = Constraints.typedValidatorLookups typedPayToScriptValidator
     tx = Constraints.mustSpendScriptOutput (last orefs) unitRedeemer <> Constraints.mustPayToTheScript bet change
ledgerTx <- submitTxConstraintsWith lookups tx
void $ awaitTxConfirmed $ getCardanoTxId ledgerTx

The issue was caused by the lookups. The combination of Constraints that resolved the issue is let lookups = Constraints.unspentOutputs utxos <> Constraints.typedValidatorLookups typedPayToScriptValidator <> Constraints.otherScript (Scripts.validatorScript typedPayToScriptValidator) I'm not sure exactly what these lookup constraints do and why they are necessary, but they fixed the ConstraintResolutionError

smacks self on forehead - I've been stuck on the exact same error. I couldn't figure out why it couldn't find a TxOutRef that I had just found a few lines earlier using utxosTxOutTxAt, but it's the lookups!
thanks!


text:
How can I make QR codes that work with wallets like nami?
Im making payment gateways for crypto on non-web3 infrastucher. One of the ways I'm doing this is by making qr codes that after being scanned with a wallet fill in the transaction i.e. the amount of ADA the platform user sends to the platform and the receiving address.
I want to do this in a language that is compatible with my website i.e. python, javascript, CSS,HTML,PHP so I think only PHP/JS/Python are viable options.
How do I start with this? What should I do to make sure that the qr code is compatible with the wallets?

The content of the QR code data will need to match what each wallet is expecting eg receiving address.
Each wallet will handle the data differently and could expect different things. Some might expect address and amount, others might only expect address.
In this last case the wallet will use a second prompt for the amount, which can probably also be scanned if the wallet allows for it. So you could provide a second QR code containing only the amount data for the user to scan.
You will need to check the documentation on each wallet to see what they expect and how they handle it.
You could also install each wallet and test it out - there aren't that many wallets yet.
Usually the user will need to open their wallet and go into the payment area to then scan your QR code(s). Or are you wanting the user to scan your QR code and the wallet application start up and populate the address/amount details? This is more tricky.


text:
Check status of past transaction using cli
How can you check the status of a past transaction given the TxHash (i.e. pending, failed, or successful) and also the assurance level / number of confirmations and block number? (like on Cardanoscan here for example https://cardanoscan.io/transaction/df8c580d50c1b8f97bd0831edb622be2737bc2a7e46971a8b369ab12e51cb214#:~:text=7214272-,Assurance,-Low?
Is this possible using the cli or @emurgo/cardano-serialization-lib-asmjs library?

The main option you have with cardano-cli is to keep running
cardano-cli query utxo --tx-in df8c580d50c1b8f97bd0831edb622be2737bc2a7e46971a8b369ab12e51cb214#0 --mainnet

Where df8c580d50c1b8f97bd0831edb622be2737bc2a7e46971a8b369ab12e51cb214 is the TxHash and #0 indicates the first output of that transaction, noting that all transactions must have at least one output.
It will give an output like the following
 TxHash                                 TxIx        Amount
--------------------------------------------------------------------------------------
df8c580d50c1b8f97bd0831edb622be2737bc2a7e46971a8b369ab12e51cb214     0        49517208 lovelace + 1 7482551a1dab4a992e579718a81e6cd14401bf4d02856c0c738a2587.5061706572536f63696574793032303132 + 1 7482551a1dab4a992e579718a81e6cd14401bf4d02856c0c738a2587.5061706572536f63696574793036333930 + TxOutDatumNone

Note it will only highlight the moment the transaction makes it to a block accepted by your local node with no additional details such as the block number or assurance level.
As it currently stands there are limited options to query the status of a transaction using the cardano-cli. cardano-serialization-lib-asmjs on the other hand has no querying capability but allows you to build and serialise the transaction itself.
For more information you will have to consume the following resources from HTTP-based APIs

Blockfrost
Koios

These will give you the block number but you will have to calculate the assurance level yourself by subtracting it from the current tip.


text:
How precise is the time inside a plutus script?
It is a known fact that you can calculate time inside a plutus validator script by looking at the txInfoValidRange attribute. Now, since this value is a range and not an exact time, it makes me wonder how large can this range be and who determines it?
This is important for me, because I might want to add a deadline of 5 days, or a deadline of 5 hours and I don't know how reliable this attribute can be.

The range is determined by the party that builds the transaction. So anybody can specify it.
A range [t1, t2] —where t1 and t2 are integers, or infinite, standing for the slot number— can include any t2 that satisfies t2 >= t1. The only additional restriction is that transactions will be dropped if t1 lies too much in the future - I think the maximum is 2 days in the future. More explanations can be found in chapter 3.3.1 here: https://plutus-pioneer-program.readthedocs.io/en/latest/pioneer/week3.html
For the smart contract validator this means that the current slot is always in the range [t1, t2] (the blockchain will make sure that the transaction will not be processed outside this range) and that this range is potentially unbounded. If your smart contract needs a smaller range, this is however no problem, it just needs to be known and followed by the one building the transaction. Your off-chain code for instance would implement this and choose a proper range needed by your validator.

What about t2? Can it be any value?

I edited the response. Yes, t2 can basically be any slot after t1 including the infinite value.


text:
How to retrieve staking credential hash
How to retrieve staking credential hash using cardano serialization library and what is it? How does it differ from public key hash?

Needs some more details.  Try searching for "staking credential" here and seeing how others have asked.

Try referring https://github.com/StricaHQ/typhonjs, it's a pure js library. It has many util functions which might be useful for you.

I Can't find much info about it. I think it is address stake credential converted into key hash.

You should add more details in your question, provide more context.

You require an instance of type BaseAddress which you can get using a bech32 formatted address (addr_... or addr_test...). Here an example:
const bech32Addr = "addr_test1qpgljxnfw696g0zslw0p6y4z5qt3vdlxws3e5d2ghftrvgtt0t2lsj2wyyal9d5s5ga3204hzkzrsah9ndu2d7zvqezsl7shc6";
const addr = BaseAddress.from_address(Address.from_bech32(bech32Addr));

console.log(addr.stake_cred().to_keyhash()); // Ed25519KeyHash | undefined
console.log(addr.stake_cred().to_scripthash()); // ScriptHash | undefined

In regards to how they differ from PubKeyHashes:
I recommend taking a look at the possible constructors for staking credentials which can be found here:
https://playground.plutus.iohkdev.io/doc/haddock/plutus-ledger-api/html/Plutus-V1-Ledger-Credential.html#t:StakingCredential
Generally, if a staking credential was created using the Credential constructor which itself can be constructed using either PubKeyCredentials or ScriptCredentials you already see that staking credentials are not just pub key hashes. They could be validator hashes if a script manages staking actions for that address or even a staking pointer.

Thank you very much! That's what I needed. :)

I'd appreciate if you can mark my response as answer :)

Very helpful. Thank you!


text:
Get transaction unspent output value
I have payment signing key and staking signing key of my wallet. How can I get transaction unspent outputs with cardano-cli/cardano-serialization-lib/pycardano.
I expect to get string like this 82825820eef507b798abbb8a1360efbd113f51eda22e2fbaae3cc32c78724c8644c164a40082583900756e62ff9667b187209b6fe1b577061491cf6f93a81e1f91741e2e3accb864ae67087f69bbd9ab74f71781d13ae40aab86e1de30ca7e21171a1dcd6500.
Thank you.

You don't need your payment signing key nor your staking signing key to get the list of UTxOs of any address, as this is public information. Though, you will need your spending private key to use a UTxO as input for a transaction.
With that said, you can get the list of UTxOs using function utxos from pycardano. Check the code here: https://github.com/cffls/pycardano/blob/22ab109fcfd75f4ba23d0aea620c09d92e1201c1/pycardano/backend/blockfrost.py#L111
What this function will do is to get the list of UTxOs using this Blockfrost API under the hood.

Thank you for reply, but this method returns this {'index': 1,  'transaction_id': TransactionId(hex='2a4c7fb343a525d6bd044dce725882eed41a1f20cad9fdc21855dbb250eec761')},  'output': {'address': addr1q8r32a0d8a6lp6ycrd02g9j5xljnzqvx2mkntpg4lzd6zkcyvp55w2vasj3favjz3uqcccef4vhet3z29596j2lf6shscxdf4y,  'amount': 20099765,  'datum_hash': None}, and I expect exactly another value like in my topic.

I am trying to automate the nft purchase process on jpeg.store. Purchase trx build request contains this value "collateral":["82825820733717b579bfdace...8eafb97d2e60b0951a004c4b40"]. But I have no idea how to get it.

If I deserialize it from CBOR I will recive follow data [[h'0E5569B3E2A645A849E5DB422A86F4705E947A294DFB0E7D04D88A5162482428', 1], [h'01709C2F10828D291925C6887375E90289B001C1521DEB3D3AA2F779E6C0E49B65E74CDDEAADA2C3A37CDC01416A6269ADAF84D82F49DA3BD9', 14320544]]

I don't know what is that value you are expecting really. Can you explain a little more where did you get that value from?

I want to automate the purchase process on jpg.store and to build the transaction I need to send this data to the server. https://imgur.com/a/E5Nbr4R


text:
How to Make Sure A Contract Is Signed By a Certain Party?
I'm thinking about making a parameterised contract between two users. User A can be anyone i.e. any customer, But User B should always be the company. I want to make it so that the validator only validates if the Company signs the contract. How do I do this?
Also, How would both signatures be sent to the contract, without making it easy for somebody to fake the signature of the company?

So, at a high level, you can't make any restrictions on who can create a script, or submit datums to a script address. You can only put restrictions on who can "spend" datum utxos at the script address.
So, one solution is you specify a token that needs to be attached to the datum for it to be spent. That token's minting policy requires the minter to be User B.
User B can create an active instance of the script by submitting a datum attached to the token only she can create. This would essentially be the same as signing the contract, as User B would need to sign the tx that created that token.
The script will only allow User A and User B to spend that datum and make state changes if the "signing" token exists on the UTxO.

Note: You'd probably want to take care that the "signing" token can never be sent to a wallet, only to the script address. Otherwise it's essentially a blank check.

Your suggesting to have a locked policy and ensuring that a UTXO is present to sign the contract in the validator. This makes me want to ask what do you do if you want to update the SC how do you remove the token from it?

I don't think there is one correct answer. But you can't modify scripts ever. Script addresses are the hash of the code the validates it. So, if you modify the script, it will change the address.
That doesn't mean you can't make your SC upgradable. The upgrades will just cause it to use new scripts. Well designed SCs could be backwards compatible if participants want to interact with old scripts.
A script isn't the same thing as a SC. Multiple SCs can use the same script, and SCs can use many scripts and minting policies.

How do I attach the token UTXO to the Datdum?

All datums are attached to a UTxO. And UTxOs have a Value field that can include multiple native tokens.

Can you please send me a link on how to attach those tokens or let me know what I should be using to do it. Thanks This is the most helpful question I posted on here. Kinda sad I cant give you more upvotes,

Haha. Thanks. Don't worry about it. I can't tell you how to build your app, but here's an example of off-chain code combining multiple tokens into a single value:
https://github.com/input-output-hk/plutus-apps/blob/ea10bbfa3df3164f87c3687b6c4d99fc0310cf57/plutus-use-cases/src/Plutus/Contracts/Uniswap/OffChain.hs#L230

Thanks man that's perfect.


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:
Referencing (U)TxO's
When Vasil HF is here with the new plutus version, can we only reference unspent transaction outputs or even spent ones? Is there some documentation on these newly added functions? Preferably haddock documentation.

The referencing of UTxO is decribed in the CIP 31 (1). There it is stated that

Referencing an output still requires the output to be presented as
part of the transaction and be unspent, so determinism is preserved.

So no, referencing already spend outputs is not possible to preserve determinism.
On the topic on how these referenced utxo's will be used see the source (2).


text:
cardano-cli is marked as depricated. Is there a replacement or is that what we are supposed to use?
I see that the cardano-cli is marked as deprecated.
Can someone tell me what is being used in it's place?
If there is no replacement right now then I would like to know that please.
Just trying to direct my time and attention most productively as I try and get oriented to developing on Cardano.
Much thanks

You are looking at the wrong cardano-cli. It you go to the cardano-node repo, one of the components is the real, current and maintained cardano-cli.

Thank you @erik-de-castro-lopo, I wonder how it is possible to request that a notice of redirection can be placed in the README.md of the old deprecated repository?

I will look into it.


text:
Decrypt data with wallet private key
If data is encrypted using the public key from a wallet is there a way to decrypt that data using the private key of the wallet? I am essentially looking for the inverse of signData from CIP-0030. I'd like to encrypt a payload using the public key and then allow the user to decrypt it with their private key.

Please have a look at https://crypto.stackexchange.com/questions/83266/why-are-ed25519-keys-not-recommended-for-encryption

@Fermat thank you for the link as it was very helpful. What I had in mind was https://en.wikipedia.org/wiki/ElGamal_encryption where the key generation had already occurred when the wallet was created. From the answer in the link you posted, it looks like that should work fine or am I misreading that?

I am familiar with El-Gamal (look at https://github.com/fermatspace/el-gamal-onchain for a small experiment onchain). The problem with key generation in the wallet is that it uses Ed25519 keys (El-gamal uses big integers). Now of course you could convert the Ed25519 binary representation of a key to an integer to fix this, but you will have to build the tools.

@Fermat thank you again. It is very cool that you already put together a little proof-of-concept for El-Gamal encryption on chain. Converting the binary representation of the Ed25519 key to an integer makes sense and I have no problem building the tools to do all this. Thank you for your help!

No problem! Looking forward to your implementation :) Hope you open source it!

There is a difference in encryption and signing.

Signing is the act of providing a piece of evidence alongside data that prove that the information is processed with a particular signing key. Given a public corresponding to the singing private key you can check if the data is aproved by that public key.

Encryption is the act of obscuring data to make it not readable. Depending on what type of encryption you use, symmetric vs asymmetric, one can encrypt the data with a private key or public key. Decrypting can only be done with the private key.

Cardano's wallets use an elliptic curve signature scheme (1). Note that this can not encrypt data! It can only create signatures, you can verify signatures onchain with, for example (2). If you want to encrypt some data, you have to use another scheme (like the mentioned El-Gamal encryption scheme).


text:
How to Send A Token to an Smart Contract Alongside a Datum?
I asked another question (How to Make Sure A Contract Is Signed By a Certain Party?) and got the answer I expected.
It raised the secondary Question of how to send a token with a datum to a smart contract to enable custom permissions via the validator.


text:
Cardano Wallet Server Invalid Argument
I'm trying to run cardano wallet server but it keeps me giving an error and have no idea what's wrong with it.
This is the command I run:
    cardano-wallet serve \
      --port 1919 \
      --node-socket /home/ubuntu/cardano-src/cardano-node/data/node.socket \
      --mainnet /home/ubuntu/cardano-src/cardano-node/mainnet-byron-genesis.json \
      --database /home/ubuntu/cardano-src/cardano-node/data \

This is the error:
Invalid argument `/home/ubuntu/cardano-src/cardano-node/mainnet-byron-genesis.json'

Any help is appreciated, thank you all in advance!

Problem solved after deleting the path to the file. --mainnet doesn't need any parameter to pass.
cardano-wallet serve \
      --port 1919 \
      --node-socket /home/ubuntu/cardano-src/cardano-node/data/node.socket \
      --mainnet \
      --database /home/ubuntu/cardano-src/cardano-node/data \

It does not seem you need a genesis file for the mainnet. Check here https://input-output-hk.github.io/cardano-wallet/user-guide/common-use-cases/how-to-start-wallet-server

I did download the file again from here: https://hydra.iohk.io/build/14528927/download/1/mainnet-byron-genesis.json but I still got the same error :/


text:
What are the options for Bitcoin integration on Cardano?
What are the options for Bitcoin integration on Cardano?
Is there a way to allow users to deposit BTC, have smart contract rules that adjust balances (based on signed app specific transactions), whilst also allowing users to withdraw their balance? Does a simple example exist anywhere?

There's a great read here on one possible approach to such an integration: https://medium.com/@anetaBTC/anetabtc-litepaper-v1-0-171f29b3276a
Basically there is a piece of software - the bridge - that acts as an intermediary between both chains, ie locking and releasing btc to / from a bitcoin vault and minting / burning native assets on Cardano (or Ergo).
This way you can freely use your native assets on Cardano and then trade them back in to redeem your BTC later.

If I am understanding this correctly you wish for:

users to be able to move assets (Having BTC deposited on Cardano Smart Contracts Would mean doing this)

Have a smart contract that enables arbitrary deposits and withdrawals by an authorised party.

Have balances of a party automatically updated in the smart contract.

I will now attempt to help with each in turn:

Assets on the bitcoin blockchain are completely different from assets on the Cardano blockchain and currently, smart contracts can only interact with their own blockchain and assets on it (this may change in the future but I doubt it).

The way projects get around this currently is to first wrap assets into a representation of that assets on a different blockchain through a bridge. You can wrap BTC and to Cardano and have that work with Cardano smart contracts. For more details, I would suggest reading up on Nomad and Milkomeda and AnnetaBTC.

I have not heard of anything like this but it is conceivably possible, also this is a bad project design. After the Vasil hardfork reference scripts will enable you to have two lightweight contracts to implement and decrement the balances. Currently, you will have to resubmit the contracts to the chain every transaction.

I don't think you should attempt to use smart contracts to store states that is the job of the ledger. I am not sure if this is even possible at the moment.

Thankyou, btw is there a type on your new suggested tag - should be "wrapped"?

Yes sorry about that the UI for editing does not let me select tags in the same way that you can do for submitting questions and I knew the tag would be called warp or wrapped and just guest at that point.


text:
How to Validate A Smart Contract Twice?
I have a smart contract I want to validate at a certain date. Exacute its logic and then revalidate on a second date. The trick is I only want it to be signed once. How do I do this?
can I just add and or statement in the validator?


text:
Error on Cabal Build: Failed to build plutus-core-0.1.0.0
Following the instructions from https://github.com/input-output-hk/marlowe-pioneer-program, yet on a Mac M1, running cabal build from within /marlowe-pioneer-program/code main generates 2 errors:

Failed to build byron-spec-ledger-0.1.0.0. (According to the build profile, this is the first item to be built.) The log for this error reads:

Configuring library for byron-spec-ledger-0.1.0.0..
Preprocessing library for byron-spec-ledger-0.1.0.0..
Building library for byron-spec-ledger-0.1.0.0..
[ 1 of 16] Compiling Byron.Spec.Ledger.Core ( src/Byron/Spec/Ledger/Core.hs,     dist/build/Byron/Spec/Ledger/Core.o, dist/build/Byron/Spec/Ledger/Core.dyn_    o )
<command line>: dlopen(/Users/dlindberg/.cabal/store/ghc-8.10.7/lib/libHScrd    n-crypt-clss-2.0.0-3518c5de-ghc8.10.7.dylib, 0x0005): symbol not found in fl    at namespace '_crypto_generichash_blake2b'

Failed to build plutus-core-0.1.0.0. (Third item to be built). Log for this error:

Warning: plutus-core.cabal:312:23: visibility is experimental feature (issue
#5660)
Configuring library for plutus-core-0.1.0.0..
Preprocessing library for plutus-core-0.1.0.0..
Building library for plutus-core-0.1.0.0..
[  1 of 191] Compiling Crypto           ( plutus-core/src/Crypto.hs, dist/bu    ild/Crypto.o, dist/build/Crypto.dyn_o )
[  2 of 191] Compiling Data.Aeson.Flatten ( plutus-core/src/Data/Aeson/Flatt    en.hs, dist/build/Data/Aeson/Flatten.o, dist/build/Data/Aeson/Flatten.dyn_o     )
[  3 of 191] Compiling Data.Aeson.THReader ( plutus-core/src/Data/Aeson/THRe    ader.hs, dist/build/Data/Aeson/THReader.o, dist/build/Data/Aeson/THReader.dy    n_o )
[  4 of 191] Compiling Data.ByteString.Hash ( plutus-core/src/Data/ByteStrin    g/Hash.hs, dist/build/Data/ByteString/Hash.o, dist/build/Data/ByteString/Has    h.dyn_o )
[  5 of 191] Compiling Data.SatInt      ( plutus-core/src/Data/SatInt.hs, di    st/build/Data/SatInt.o, dist/build/Data/SatInt.dyn_o )
[  6 of 191] Compiling ErrorCode        ( common/ErrorCode.hs, dist/build/Er    rorCode.o, dist/build/ErrorCode.dyn_o )
[  7 of 191] Compiling PlutusCore.Builtin.Emitter ( plutus-core/src/PlutusCo    re/Builtin/Emitter.hs, dist/build/PlutusCore/Builtin/Emitter.o, dist/build/P    lutusCore/Builtin/Emitter.dyn_o )

Any advice is greatly appreciated!

try following this guide, it's specific for Mac M1


text:
How to Get the Script Address of A Smart Contract?
Once I have written up the smart contract how to I get the script address value to be able to interact with the script whilst its on chain?

There's multiple ways to do it. For example using cardano-addresses or Pycardano library
Pycardano:
script_cbor_hex = '...'
script = cbor2.loads(bytes.fromhex(script_cbor_hex))
script_hash = plutus_script_hash(script)
script_address = Address(script_hash)

for those looking to use ```cardano-cli``
cardano-cli address build --$testnet --payment-script-file path/to/serialized-smartContract.plutus.json


text:
ADA handle NFT royalty address
Is it possible to use an ADA handle as the address for NFT royalties? I’d like a way of changing the address that royalties get sent to if I decide to sell my project in the future. Maybe it would be possible to do this through a smart contract instead?

This is possible. You can make a script address where royalties are send to with an Ada handle in the datum. The script only permits grabbing those funds if the corresponding ada handle is part of the transaction.
With the upcoming HF (cip 31) you can even make it so that the script can allow grabbing by anyone as long as the destination of the funds are the same as the referenced utxo that contains the ada handle. Hope this helps.

AdaHandles are used to query the blockchain with either Block Frost or DB-Sync to find the wallet containing the NFT, in this case it would depend on how the marketplace uses the metadata in the CIP-27 royalty token.


text:
How to Look Up a Token Policy ID from The Smart Contract Validator
I have attached a token to the datum and sent it to the smart contract, now I need the validator to check that the token has a certain policy ID before it allows the contract to proceed.
How do I do that?

How did you attach the token to the datum? did you do something like <policy id>.<token name> as a BuiltinByteString ? I'm asking since the Datum is supposed to only have data

Please check the answer to my previous question. Someone told me to send along the token with the datum maybe attached isn't the right word but I don't know what would be.

You can use the following
info :: TxInfo
info = scriptContextTxInfo ctx

inputValue :: [Value]
inputValue = map (txOutValue . txInInfoResolved) (txInfoInputs info)

checkValueHasToken :: Value -> Bool
checkValueHasToken val = case flattenValue val of
        (pol, tn, amt) -> pol == knownPolicyID

checkInputHasToken :: Bool
checkInputHasToken = any checkValueHashToken inputValue


text:
Error creating a transaction with Cardano Serialization Library
I am trying to create a transaction using the Cardano Serialization Library but I cannot figure out what is going wrong.
The code is
const BlockFrost = require('@blockfrost/blockfrost-js');
const {
PrivateKey, Vkey, Ed25519Signature, PublicKey, Vkeywitnesses , TransactionHash
  TransactionBuilderConfigBuilder,
  LinearFee,
  BigNum,
  TransactionBuilder,
  Transaction,
  TransactionWitnessSet,
  hash_transaction,
  make_vkey_witness,
  Address,
  Value,
  TransactionOutput,
  TransactionInput,
} = require('@emurgo/cardano-serialization-lib-nodejs');

const BLOCKFROST_API_KEY = 'xxxxx';
const PRIVATE_KEY =
  PrivateKey.from_bech32('ed25519e_sk14p2a82zpk7y27pme7sy8yxaw0ad93j47k7dvgnc55e50lfm66a88rmz0zh0ezfqd7x30mclsjaqtkzmazy2l6crfxxd0j9ynmzxn6ac6vryrz');

const RECEIVER_ADDRESS = Address.from_bech32(
  'addr_test1qpzqmyejxwvwal9vx6w0wgezvpmjlp3cqwfg2vkjt0y9fns0d5cyvvu88y78wtfl8xyey3gr3ygpxpphevvmz7ulaf2qrhxz34',
);

const SEND_AMOUNT = '5000000';

const API = new BlockFrost.BlockFrostAPI({
  projectId: BLOCKFROST_API_KEY,
  isTestnet: true,
});

const _transactionConfig = async () => {
  const epoch = (await API.epochsLatest()).epoch;
  return await API.epochsParameters(epoch);
};

const _configureTransactionBuilder = async () => {
  // const protocolParams = await _transactionConfig();
  try {
    return (
      TransactionBuilderConfigBuilder.new()
        .fee_algo(
          LinearFee.new(BigNum.from_str('44'), BigNum.from_str('155381')),
        )
        .pool_deposit(BigNum.from_str('500000000'))
        .key_deposit(BigNum.from_str('2000000'))
        .max_tx_size(16384)
        .max_value_size(5000)
        .coins_per_utxo_word(BigNum.from_str('34482'))
        .prefer_pure_change(true)
        .build()
    );
  } catch (error) {
    console.log(`Error in tx config: ${error}`);
  }
};

const buildTransaction = async () => {
  try {
    const txBuilderConfiguration = await _configureTransactionBuilder();
    const txBuilder = TransactionBuilder.new(txBuilderConfiguration);

    //add key hash input
    txBuilder.add_key_input(
      PRIVATE_KEY.to_public().hash(),
      TransactionInput.new(
        TransactionHash.from_bytes(
          Buffer.from('d56839c08b51e159a3931b36c65b1305aa82e8625a0b2d6969f200b3ddf806cf', 'hex'), //tx hash on ada received from faucet
          0, //index
        ),
      ),
      Value.new(BigNum.from_str(SEND_AMOUNT))
    )

    //tx outputs
    const txOutputs = TransactionOutput.new(
      RECEIVER_ADDRESS,
      Value.new(BigNum.from_str(SEND_AMOUNT)),
    );
    txBuilder.add_output(txOutputs);

    //latest block
    const latestBlock = await API.blocksLatest();
    const currentSlot = latestBlock.slot;
    txBuilder.set_ttl(currentSlot + 7200); //+2h from current slot

    //metadata
    // txBuilder.add_json_metadatum(BigNum.from_str('0'), 'today is a great day');

    txBuilder.set_fee(BigNum.from_str("190000"));
    // txBuilder.add_change_if_needed(SENDER_ADDRESS);
    //build tx
    const txBody = txBuilder.build();

    //make witness
    const txHash = hash_transaction(txBody);

    const witnesses= TransactionWitnessSet.new();
    const vKeyWitness = Vkeywitnesses.new();

    vKeyWitness.add(make_vkey_witness(txHash, PRIVATE_KEY));
    witnesses.set_vkeys(vKeyWitness);

    const signedTx = Transaction.new(txBody, witnesses);

    const response = API.txSubmit(signedTx.to_bytes());

    return response;
  } catch (error) {
    console.log(`Tx compose error: ${error}\n`);
    console.error(error.stack);
  }
};

module.exports = {
  buildTransaction,
};

I am getting the error below. From my research it apparently means I am not using the correct keys for the witness. But I can't find a way to fix it. Any ideas on what could be wrong?
BlockfrostServerError: "transaction submit error ShelleyTxValidationError ShelleyBasedEraAlonzo (ApplyTxError [UtxowFailure (WrappedShelleyEraFailure (MissingVKeyWitnessesUTXOW (WitHashes (fromList [KeyHash \"0c7a0e8dc785e893f8fca246646ba10df9d5bdd5ebed92e72b163e75\"])))),UtxowFailure (WrappedShelleyEraFailure (UtxoFailure (ValueNotConservedUTxO (Value 1000000000 (fromList [])) (Value 5190000 (fromList [])))))])"

ValueNotConservedUTxO (Value 1000000000 (fromList [])) (Value 5190000 (fromList []))
This suggests that your sum of inputs (1000000000) do not match the sum of outputs (5190000), you'd want to send the delta (i.e. input - (output + fees) ), i.e. change back to your original address.


text:
Do I need to verify data signed with Nami wallet or will the cryptography algorithms automatically detect if it was tempered with?
Based on this answer which seems to have some bugs in the verification methods I created this piece of code:
const {
  Address,
  Ed25519Signature,
  PublicKey,
  BaseAddress,
  StakeCredential,
  RewardAddress,
} = require("@emurgo/cardano-serialization-lib-nodejs");
const { Buffer } = require("buffer");
const { COSESign1, Label } = require("@emurgo/cardano-message-signing-nodejs");

class SignedData {
  constructor(signedDataInHex) {
    let message = COSESign1.from_bytes(
      Buffer.from(Buffer.from(signedDataInHex, "hex"), "hex")
    );
    let headermap = message.headers().protected().deserialized_headers();
    this.headers = {
      algorithmId: headermap.algorithm_id().as_int().as_i32(),
      address: Address.from_bytes(
        headermap.header(Label.new_text("address")).as_bytes()
      ),
      publicKey: PublicKey.from_bytes(headermap.key_id()),
    };
    this.payload = message.payload();

    this.signature = Ed25519Signature.from_bytes(message.signature());
    this.data = message.signed_data().to_bytes();
  }

  extractData() {
    const decoder = new TextDecoder();
    const payloadString = decoder.decode(this.payload);
    const payloadObj = JSON.parse(payloadString);
    const signerAddress = this.headers.address.to_bech32();
    return { payloadObj, signerAddress };
  }
}

let signedDataBytes =
  "845869a30127045820b0999904bd50dfd74835576573d684a1377879278264b55cf83e6201e7975e9c6761646472657373583901655e5688424b3d2f69a9628af9b60be62376cdcd0d10ad9a618999ac4d04421e9d573a5a33a0ac52ea00213c5634e0ca1f1e62a065905356a166686173686564f4581a7b227369676e65644174223a313635353036313038313830397d5840af4a4bb4c7c7ac23c86d6527f797fdd2f058f71d434a1b34ae91abd6fecb504d82e519ace7c171e1238c4aa5bcd252166a58f2ba855770ce98a9123917ded60b";
let signedData = new SignedData(signedDataBytes);

console.log(signedData.extractData());

Can I safely rely on the data extracted with extractData() function? If I managed to extract signer address and payload form the signed data, is it enough to be sure that the signed data was actually signed by the extracted address and that the payload was not tempered with or should I mare some further steps?


text:
How to release an NFT collection on Cardano?
I come form EVM background and now I'm looking at Cardano ecosystem. From what I can see, the approach is fundamentally different when releasing NFTs. On EVM you deploy a smart contract on which users can call a mint function to obtain an NFT. On Cardano the contract is already there and you just register your NFTs into it.
I've seen a few tutorials on how to release NFTs on Cardano, but there's still one thing I don't get. How do I make NFTs available for users on the primary market? On EVM, like I mentioned above, users just mint the tokens themselves right form my contract. On Cardano, at least form what I saw in the tutorials, NFTs are minted up front by the owner.
What's the default approach to make it possible for the users to buy the NFTs for ADA. Is there a simple solution to let the users mint NFTs themselves for ADA? Or should I mint the NFT collection myself and put them in one of the stores? Please bare in mind that the collection will be pretty numerous.
I'd be grateful for pointing me to any useful resources.

NFTs (and tokens) are native assets on Cardano and do not need separate contracts to manage them. They can be sent/received just as ADA can be (and need to be sent along with some ADA).
More info here: https://developers.cardano.org/docs/native-tokens/ - This also discusses how to mint an NFT and has example code.
Not all wallets can handle native assets, so maybe start with Nami wallet as it makes things easy - https://namiwallet.io/
In terms of minting a stack of new NFTs there are services like https://www.nft-maker.io/ which offer APIs and will mint on demand for you (for a small fee).
Also look at NFT market places like https://www.jpg.store/ and https://cnft.io/ for more information.

Is it possible to orchestrate mint NFTs on demand without nft-maker and without creating a dedicated smart contract?

One way to do that would be 1) Website sells/reserves NFT with a unique decimal price eg ADA12.341202 (NFT reserved for 20 mins, 341202 is the unique ID/ref). 2) User sends ADA 3) Your back-end notices the received ADA, mints the NFT and sends it back to the sending address along with 2ADA. Step 1 should log details into your DB for reference and matching. You'll notice that most of this is off-chain, only minting and sending are on-chain, so less fees and on-chain congestion.


text:
How Can You Prevent A Burn Address From Polluting The Cardano Ledger?
Making a Burn Address on the blockchain is currently done by using a script address with a validator that always returns False and so never validates.
This ties up ADA and causes the size of the blockchain to increase (become bloated with addresses full of useless assets) causing the full node requirements to increase.
How can you do the following two things:

Prevent ADA from Accumulating in these scripts?
Minimnse the effect they have on the size of the ledger (prevent bloating)?

Not sure if there is a generic way to tell whether a script is a "burn" script or something that succeeds really rarely. Also, I don't think accumulating ADA to these script addresses should be prevented (it's the spender's choice): they might also send their ADA to an address where the private key has been (deliberately) forgotten.

You must correctly specify what is allowed in the monetary policy to allow burning. If when minting a token you use a minting policy that does not allow the burning of the token, the ledger rule will not allow the burning of the token. Then the only way of burning the token is to lock it indefinitely.
You can also make minting policies that allow for burning the token, this will remove it from the output.

Burning isn't a problem as it essentially means the remaining Ada/tokens become more valuable.
Once many UTxOs start accumulating at burn script addresses, cardano-db-sync can be upgraded to start filtering those addresses out.
The actual ledger contains each individual transaction, not the most recent UTxO snapshot, so accumulation of UTxOs at burn addresses will have no impact on ledger size.

This will likely be resolved by keeping UTxOs in RAM depending on when these were created: keep recent ones in RAM while relaying older ones to disk (much like a filesystem cache).


text:
PPViewHashesDon'tMatch Exception on submit transaction for Cardano serialization-lib version 10.0.x
On emurgo/cardano serialization versions 10.0.X receiving error on submit transaction that:
https://drive.google.com/file/d/1SNpM1LtEDPnZPMQXdz1X_Ujiy_FW9BJW/view?usp=sharing
Also, in emurgo/cardano-serialization version 10.2.0 there is a function in TransactionBulderConfigBuilder.ex_unit_prices() that takes ExUnitPrices Instance, what is the numerator and denominator in ExUnitPrices.new() function, how can one calculates them?

Hello, beacuse this is your first question I have been asked by the site to review it. It seems there are two questions here and they are not tightly related. In addition if the first question requires a lot to answer the second one might be drowned by the first. It might be better to separate the two into 2 questions.


text:
What's the difference between these two TxOut?
Applying the functions (1) findOwnInput and (2) getContinuingOutputs in a context both return TxOut. What is the difference between these two TxOut?

getContinuingOutputs makes use of findOwnInput to find all outputs at the script address.
findOwnInputs only returns Maybe TxInInfo.
See here fore implementation details:
getContinuingOutputs

findOwnInput get the actual utxo being consumed and validated for that validator in that moment.
same validator could run more than one time if you are consuming more than one utxo at the smart contract address. Every time findOwnInput will give you different result.
getContinuingOutputs will give you all the utxo at the outputs that are going to be locked and saved in the contract address after the transaction.

Example:
I create a transaction using Utxo1 and Utxo2 as inputs and with two expected outputs, one utxo3 going again to the contract and another going to some wallet, utxo4
The transaction will execute the contract two times for validate the consume of utxo1 and utxo2.
In the first run of the validator, findOwnInput  will give you Utxo1
In the second run will give you Utxo2
In all the runs  getContinuingOutputs  will give you the output going to the contract, in this case Utxo3


text:
Why does forgeContract receives a PubKeyHash?
The forgeContract is responsible for minting NFT's and in the arguments we have a token name and amount, why do we have a public hash key for minting NFT?

Hello, I have been asked to review this question and have found that most people would not know which contract your on about. So can I ask you to link to the contract in the question. Thank you

The reason you have to provide a public key hash to mint an NFT is to verify that any future NFTs minted under the same policy are originating from the same private key.  The public key is a cryptographic identifier that only the developer/creator with access to the private key is able to reliably generate.  See Wikipedia's entry on Public/Asymmetric Key Cryptography for a good primer.
Deeper dive: "NFTs" are created using Cardano Native Scripts that declare: "this was minted by a specific secret key, [optionally before a specific expiration time], belonging to the NFT creator".  When you generate your policy ID for a Cardano NFT, that policy ID is actually hashed based off of the public key you are seeing in that minting script.  So long as the Cardano nodes agree that "this is the way we mint NFTs", no one will be able to create a new NFT under the creator's specific policy ID without the private key corresponding to that public key hash you are seeing.


text:
How to convert some of the db-sync data types/columns to C# data types?
Specifically, I am using the Npgsql lib in a C# console app, and am reading data just fine so far for the obvious types like bigint, uinteger, boolean, etc. - but for a few different types/columns in some tables I am unsure:

hash32type
lovelace
word64type

Can anyone point me to a resource that would provide me the required knowledge for converting these types into C# types?
Thank you.

SQL domain types like lovelace etc are created in the stage one migration scripts (schema/migration-1* of the repo). Eg lovelace is:
CREATE DOMAIN lovelace AS numeric (20, 0) CHECK (VALUE >= 0 AND VALUE <= 18446744073709551615);

From these domain types you should be able to figure out the appropriate language type for your language.

yes! In the repo - of course it is, thank you!
https://github.com/input-output-hk/cardano-db-sync/blob/acf795fdcb23be0038ffa19554f3c8b0c8c43ed9/schema/migration-1-0001-20190730.sql#L19


text:
Whats Your Mental Model For Monads?
I was asked by a friend trying to learn plutus what a monad was, so I began talking about category theory. It seems that this confused him further how would you explain monads to a noob?
Whats your mental model for dealing with them?

Great question!, maybe also post in the regular stackoverflow?

You mean the haskell one?

Don't think there is one, but stackoverflow may help...

okay thanks ill do that

If you have some python experience, this might be helpful: https://github.com/cffls/py2hs#monad. It implements a monad in Python, explains the motivation, and then shows how to do the same thing in Haskell.

Thanks, man. I don't really need help with monads but I love python and really surprised to find this existed. gonna check it out thanks a bunch.

Just read one definition:
A monad is just the minimal amount of structure needed to overload a function composition in a way that performs an extra computation on the intermediate value.
My Explanation:
In a single program, you will licky have many functions such as those dealing with IO and others dealing with Computation. Function composition then enables us to chain functions together (basically piping the output of one function into another).
This works well when the later functions expect the type of data given to them, but will fail if the data type is not what's expected. To get around this we normally refactor functions using factories or decorates in languages such as python.
Now in functional programming, we have an alternative way of doing this and that is the monad. It basically can be thought of as a tuple of operations attached to a data type (or container of data). This tuple of operations is a wrapping and an unwrapping function that allow polymorphic (arbitrary) data types to work with arbitrary functions.
TLDR:
basically, a  monad allows the output of one function to be compatible with another.

I have done a couple of videos trying to explain monads, one explaining the formal implementation and one implementing a new monad from scratch
the second in particular shows you how monads do allow side effects by considering the container (your Monad instance) as a context
this way the side effect is not "outside" the function, since the monad is part of the function
this explanation is very raw but in the second video you can see how the bind operator (>>=) handles all the "side effects"


text:
How do I set Up a Cabal file?
Whats a basic template I should use for cabal files that is easily customisable?

It you run cabal init it will generate a template. You can also run it with the --interactive flag so that it asks you questions on what should go in the file.


text:
Is there a place where we can find the Haskell library for Marlowe?
I investigated some Code examples, in haskell for Marlowe smart-contract, and used the "cabal repl" with the " :i " command, like this:
*Main> :i ValueEQ
type Observation :: *
data Observation = ... | ValueEQ Value Value | ...
-- Defined in ‘Language.Marlowe.Extended’
But I could not find the target library ‘Language.Marlowe.Extended’.
Is there a place where we can find the Haskell libraries for Marlowe?
There's perhaps also a haddock, like in Plutus, for Marlowe?

Here are instructions for accessing Marlowe types and functions from ghci.

Thank you very much, Brian, It will be very very helpful. By the way, your lecture on the Cli was really great too!

With some research, the Haskell libraries for Marlowe seems to be here precisely.

What you are looking for is the repo where the Marlowe lang is implemented, more specifically the data constructor that you show is defined in the Observation data type:
data Observation = AndObs Observation Observation
                 | OrObs Observation Observation
                 | NotObs Observation
                 | ChoseSomething S.ChoiceId
                 | ValueGE Value Value
                 | ValueGT Value Value
                 | ValueLT Value Value
                 | ValueLE Value Value
                 | ValueEQ Value Value
                 | TrueObs
                 | FalseObs
  deriving stock (Show,Generic)
  deriving anyclass (Pretty)

Which is found in Language.Marlowe.Extended. So you can directly refer to the repo where the Haskell libraries are defined.

Yes, with your links and some research, the Marlowe libraries seems to be here. Thanks Igodlab. I don't know if it's the same version as in the Marlowe Playground, yet.

You can look at the git rev in your cabal.project file to know what commit snapshot the Marlowe Playground uses.
Glad it helped! If you upvote and mark my answer as solved it will help other people find it ;)

You need at least 15 reputations to cast a vote, So I can't.

I have upvote your answer, which helped me in part, and put one with a bit more of precision, now that my reputation has grown, Igodlab.


text:
Whats a Good Example of Interconnected Smart Contracts?
In the Contract Monad we have the use of w s e a. Now w is used to connect contracts is there a good example of how this is done, in particular how to validate a contract using the w of another contract?


text:
Can the price of a Dex pair be tracked using the data in cexplorer / db-sync?
Is there a way to query the price of a pair that's on a dex independent of the dex? For example: MIN/ADA or others? I am trying to see how the data in the cexplorer database could be used to do this.

cardano-db-sync does not track native asset prices.

I do understand cardano-db-sync does not track prices of anything per-se, but I was asking if there is a method for extracting that information given the data available in cexplorer - i.e. a way of doing it yourself, not a way cardano-db-sync does it for you :|

I would be surprised if all of the data you need is even in db-sync.

This can be done. I used to do it via the client. One can index the current price by looking at the script address of the dex and filtering the native asset to get the utxo that represents the liquidity pool. From that you can deduce the price by just dividing, price = native asset amount in pool / ada amount in pool. I used a bash script to watch this price together with awk, something like
watch -n 1 'cardano cli query address $(cat addresOfDex) | awk \'*filter for line that contains native asset or pool id*\' | awk \'*devide the correct things*\'

Note that I ommitted the filters as I do not remember them. Db-sync can do something similar of course.

Thank you for the guidance to a possible solution!

This is a useful answer except the equation should be: price in ada = ada amount / native asset amount


text:
I wanted to know how can i deploy my smart contract made on marlowe playground using blocky on cardano testnet and mainnet?
Please, it would be so helpful if somebody steps up and tell me the way to do it.

If you press the "Send to Simulator" button in the Marlowe Playground, there is a "Download JSON" button for downloading your contract in Core Marlowe JSON format. That JSON-format contract can be run using the marlowe-cli tool.
In order to run your contract, you'll also need to create a JSON file specifying the initial state of the contract: here are instructions for creating that file. Here is a step-by-step example for actually running a contract on a Cardanon network. Before running your own contract on the network, you might want to run one of the examples first.
Although it is technically possible to run Marlowe contracts on mainnet, the Marlowe validator script has not completed an audit yet, so it is safest to just use a testnet.


text:
Providing a list of mappings from datum hashes to values while creating a transaction
I noticed that TxInfo datatype has a txInfoData field which carries a list of mappings from datum hashes to datum values. This seems very useful for validating transactions with multiple input UTxO's.
Where and how is this list provided while creating a transaction?

There are at least two reasons for that field to be a list:

A transaction may spend UTxO's from multiple script addresses,
The datum value for a transaction output can optionally be provided.

Using cardano-cli transaction build, we can provide a datum value for each input UTxO with --tx-in-datum-file (or --tx-in-datum-value). And also, for each output UTxO we can provide a datum value with --tx-out-datum-embed-file (or --tx-out-datum-embed-value).

With the upcoming Babbage era the flag --tx-out-inline-datum-file and --tx-out-inline-datum-value will also be available.

TxInfoData can be obtained via the ScriptContext that is included as part of every transaction.  The list of datum and datum hashes is created when the transaction is submitted and made available to the plutus script.   Here are the relevant plutus docs https://playground.plutus.iohkdev.io/doc/haddock/plutus-ledger-api/html/Plutus-V1-Ledger-Contexts.html
Hope this helps.


text:
How To Get Transaction Royalityies on Fungable Tokens
I want to make a fungible token (FT) that has a royalty attached (N%). The problem is UTxOs are purely passive so how can I get my N% of the transaction value on P2P transactions using code is law.
To clarify how do I ensure (using code) that every time my token is moved between people I get a cut.

This is not possible. Native Tokens are first class citizens on Cardano. They are not part of a smart contract that could enforce behavior like this but are assets in your wallet like ADA.
It's the same for NFTs, no one prevents you from sending a Cardano NFT directly to another wallet without paying the royalties that would apply on a marketplace.

To add to that, key witnessed address determines how the native assets located at that address are spend. So to enforce this you need to create "shared" pensioned address with a plutus script. Now the problem with this is that a wallet does not index this. This is something that we as a community have to solve with standards. An ECR20 contract does something similar, you have to import it into a wallet to keep track of funds. So it is possible but you have to invent the wheel.


text:
How do I test my smart-contract on Cardano
I'm from EVM background and I've started learning about Cardano lately. I was just wondering how do I write unit tests for my smart-contract written in Haskell? Since i've been doing unit testing in javascript for solidity, using mocha/chai. Can I use javascript here aswell for uint tests?
TIA!

I find that using the plutus PAB simulator is the best way to first test out your smart contract.   Once you confirm the smart contract logic is correct, you then move on to a local dev environment using cardano-cli to deploy your smart contract and run transactions against it.   Finally, once that is working, then you are ready for testnet testing which can be done either via the cardano-cli or through javascript wallet integration via Cardano serialization library.  This has been my experience to date and it will most likely be improved and be streamlined over time.
You can checkout my repo for some code examples and tips and trick I used for the PAB simulator, devnet and testnet testing.
https://github.com/lley154/cardano-lottery


text:
Using carano-cli How Do I send All of the ADA from a wallet?
I am trying to build a transaction with a wallet that has 6 ADA. The transaction fee is 165721 lovelaces. So 6000000 - 165721 = 5827019 lovelaces. But when i try to send 5827019 lovelaces I get an error saying I can't build the transaction because the Minimum UTxO threshold: Lovelace 999978. Is it possible to send all my ADA or do I have have to leave a balance of at least 1 ADA?
Here is my build command
cardano-cli transaction build --alonzo-era --testnet-magic 1097911063 --change-address <change_addr> --tx-in <tx_in> --tx-out <recpt_addr>+5827019 --out-file <build_file>

Note: cardano-cli transaction build does have some issues, I find cardano-cli transaction build-raw is more reliable but need some extra work. You will need to calculate fees manually and add another --tx-out for the change.

Additiionally, if you use the cardano-cli transaction build-raw command, you can specify exactly the fee amount you wish to pay, and as long as it is above the minimum (which itself is estimated by the calculate-min-fee subcommand), the tx will be valid. Use this if you wish to create a transaction without change.

If you are trying to send all to one address, just put that address in the --change-address and remove the --tx-out line.

The problem is that your fee is probably not exactly 165721.

You have 6000000 lovelace
You want to send 5827019 lovelace to recpt_addr
The fee is something like 165721 but not exactly (probably less)
Some lovelace are left and the command tries to send them to change_addr

You can inspect the transaction using cardano-cli transaction view --tx-body-file <build_file> to see the problem, then you can adjust your command params accordingly.
Maybe it would also work if you simply set the change address to the same address as the recipient:

--change-address <recpt_addr>

Cli commands to send all ada from an address to another :
cardano-cli transaction build-raw \
--tx-in a61c02<...>8848#0 \
--tx-out DdzFF<...>v2mEoo+2061351 \
--invalid-hereafter 000000 \
--fee 172233 \
--out-file tx.raw

cardano-cli transaction calculate-min-fee \
--tx-body-file tx.raw \
--tx-in-count 1 \
--tx-out-count 1 \
--witness-count 1 \
--byron-witness-count 0 \
--mainnet \
--protocol-params-file ../../protocol.json

cardano-cli transaction sign \
--tx-body-file tx.raw \
--signing-key-file payment.skey \
--mainnet \
--out-file tx.signed

cardano-cli transaction submit \
--tx-file tx.signed \
--mainnet

As George and eddex mentioned, you should use the change field as your sole output. Since you are using the build endpoint rather than build-raw, and your input doesn't carry any tokens/NFTs, you don't need to worry about the fee either. Your build command should look like this:
cardano-cli transaction build $MAGIC \
  --tx-in <tx_in>                    \
  --change-address <recpt_addr>      \
  --out-file <build_file>

Sign and submit, and that's it!

I simply used build-raw command to send all ADA from first wallet to second.
Here --tx-out-count will be 1 only. As there will be only one recipient
cardano-cli transaction calculate-min-fee \
 --tx-body-file tx.raw \
 --tx-in-count 1 \
 --tx-out-count 1 \
 --witness-count 1 \
 --byron-witness-count 0 \
 --mainnet \
 --protocol-params-file params.json

Command to build raw transaction
cardano-cli transaction build-raw \
 --tx-in <txn hash>#0 \
 --tx-out $(cat recipient.addr)+<all ada balance> \
 --invalid-hereafter 0 \
 --fee 0 \
 --out-file tx.raw

calculate min fee and manually calculate remaining ADA balance.
Transaction with Fees
 cardano-cli transaction build-raw \
 --tx-in <txn hash>#0 \
 --tx-out $(cat recipient.addr)+<remaining ada balance>  \
 --invalid-hereafter $(( ${currentSlot} + 10000)) \
 --fee <Fee> \
 --out-file tx.raw


text:
Can Nami connect to custom testnet?
I made custom testnet with magic 42. Cardano-cli work absolutly correct but Nami always connect to testnet with magic 1097911063 (main testnet).
So my question: can Nami connect to my testnet?
P.S. Yeah, I set custom node into Nami settings

Nami uses Blockfrost to submit transactions. If you're using a private testnet you cannot simply use Blockfrost to submit txs anymore. You'll probably have to setup cardano-submit-api in your custom testnet and tinker with Nami's local node setting (Network tab)

Not at the moment.
But you can run your own instance of Blockfrost and point your Nami wallet to it.


text:
How to get prices, volume and latest transactions of a liquidity pool
I am working on a app to view charts and more. For the charts I need open, close, high, low prices for any intervals like 1min, 5min, 1h etc for a specific token/pool. So far there seems a lack of APIs providing that data. I only found the API of muesliswap, which is ok but not perfect as it does not provide all the data I need and I would like to integrate multiple exchanges (minswap, sundaeswap etc) not just one. This week I found this project: https://taptools.io/charts, which comes very close to what I want to do with the charts. They say they have the data directly from blockchain, so this made me thinking if I could do this too.
I have to say, I am fairly new to coding but I am fast learner. But I feel a bit lost where to start. I would appreciate if anyone could lead me in the right direction to pull this off. What are my options, do I need a cardano node for this. Or is it maybe possible with something like bitfrost or koios?
Thanks.