text:
Inconsistent script addresses built with cardano-cli vs. PyCardano
Given the CBOR representation of a plutus validator, its script address can be easily generated with a variety of tools, e.g. cardano-cli and PyCardano.  However, both tools generate different script addresses for the same CBOR.  How is this possible?  Am I finding a bug in PyCardano?
In what follows I describe the building of the script address with both tools, using an example.  We are going to work with the following CBOR:
$ cat script.plutus
{
    "type": "PlutusScriptV2",
    "description": "",
    "cborHex": "581a581801000022232632498cd5ce2481064255524e542100120011"
}

Generate script address with cardano-cli:
$ cardano-cli address build \
>   --payment-script-file script.plutus \
>   --testnet-magic 2 \
>   --out-file scriptA.addr

which resulted in
$ cat scriptA.addr ; echo
addr_test1wrmz3pjz4dmfxj0fc0a0eyw69tp6h7mpndzf9g3kttq9cqqqw47ym

Generate script address with PyCardano:
>>> from pycardano import (
...     BlockFrostChainContext,
...     Network,
...     Address,
...     plutus_script_hash,
...     PlutusV2Script
... )
>>> from blockfrost import ApiUrls
>>> context = BlockFrostChainContext("your-preview-project-id", base_url=ApiUrls.preview.value)
>>> network = Network.TESTNET
>>> script_plutus = PlutusV2Script(bytes.fromhex("581a581801000022232632498cd5ce2481064255524e542100120011"))
>>> script_hash = plutus_script_hash(script_plutus)
>>> scriptB_addr = Address(script_hash, network=network)
>>> scriptB_addr
addr_test1wqql5y0gsa3ul0vcmdzmp9zaxz8ak0d3j8yfd4yd73pfh4c6ew25x

As claimed, we have obtained two completely different script-addresses, which is very strange.
Edit: correct procedure with PyCardano:
Following Michele's solution and insight, an efficient way of using PyCardano to deal with the same file script.plutus that we used with cardano-cli could be as follows:
>>> import json
>>> from pycardano import (
...     BlockFrostChainContext,
...     Network,
...     Address,
...     plutus_script_hash,
...     PlutusV2Script
... )
>>> from blockfrost import ApiUrls
>>> context = BlockFrostChainContext("your-preview-project-id", base_url=ApiUrls.preview.value)
>>> network = Network.TESTNET
>>> with open("script.plutus", "r") as f:
...     script_cborHex = json.load(f)["cborHex"][4:]
...
>>> script_plutus = PlutusV2Script(bytes.fromhex(script_cborHex))
>>> script_hash = plutus_script_hash(script_plutus)
>>> scriptB_addr = Address(script_hash, network=network)
>>> scriptB_addr
addr_test1wrmz3pjz4dmfxj0fc0a0eyw69tp6h7mpndzf9g3kttq9cqqqw47ym

and, as Michele pointed out, we have recovered the same address produced by cardano-cli.

The script address is the hash of a larger binary data struct. Even a single byte being different between the two will cause the hash to be vastly different. My first guess is that Network.TESTNET is not the same as 2. Even if these two are the same there is something else different.

network magic is irrelevant; all the address cares about is if it is testnet (any of them) or mainnet

After a quick look at the PyCardano implementation of script_hash
the problem is in the input of the function.
The hash of a Plutus script is calculated using the compiled contract wrapped only once in CBOR.
cardano-cli wraps the contract bytes twice in CBOR for historical reasons.
for that reason it is a valid input for cardano-cli but a bad input for PyCardano
in your case your script looks like this
581a581801000022232632498cd5ce2481064255524e542100120011

581a
5818
01000022232632498cd5ce2481064255524e542100120011

CBOR #1
CBOR #2
the actual contract

so ultimately you want to pass CBOR #2 + the actual contract
your snippet should then look like this
>>> from pycardano import (
...     BlockFrostChainContext,
...     Network,
...     Address,
...     plutus_script_hash,
...     PlutusV2Script
... )
>>> from blockfrost import ApiUrls
>>> network = Network.TESTNET
>>> script_plutus = PlutusV2Script(bytes.fromhex("581801000022232632498cd5ce2481064255524e542100120011"))
>>> script_hash = plutus_script_hash(script_plutus)
>>> scriptB_addr = Address(script_hash, network=network)
>>> scriptB_addr
addr_test1wrmz3pjz4dmfxj0fc0a0eyw69tp6h7mpndzf9g3kttq9cqqqw47ym


text:
NFT Minting with cip68 standard
I want to write the code for minting NFTs with CIP68 update. Like i need such NFTs whose metadata could be updated instead of minting the new NFT everytime. I searched about it and get to know that cardano has now allowed such functionality according to cip68
I have initially tried minting the NFTs with mesh library and also with cardano serialization library but i dont know about how do i implement according to cip68 standard in mesh.
Is there any resources or implementation available to mint the NFTs according to this CIP68 standard? I got one in CIP68 repo but its in Plutus (Haskell) and i am finding it difficult to implement with offchain. Here's the link for that.
Kindly guide me through this, it will be very helpful.
Thanks in Advance

In order to use Mesh for Cip 68 you will need to concat the (hexed)assetname with the correct prefix in order to avoid Mesh's hex conversion on submission.
Here are the correct prexfixes to add to the asset names:
const refprefix = '000643b0';
const usrprefix = '000de140';
const hexassetName = Buffer.from(`${assetName}`).toString("hex");
const hexrefName = Buffer.from(`${refName}`).toString("hex");

Here is an example of defining metadata with the cip 68 compliant names

const asset: any = {
            assetName: `${usrprefix}${hexassetName}`,
            assetQuantity: '1',
            metadata: assetMetadata1,
            label: '0', //721 if you also want cip25(cip 68 will overide)
            recipient: recipientAddress,
        };
The last bit is an example of how to create a recipient with inline datum load for transaction.
const inlineDatumFields = new Map();
              inlineDatumFields.set('name', `${assetName}`);
              inlineDatumFields.set('image', inlineDatumPair2);
              inlineDatumFields.set('description', misc);

              const inlineDatum: any = {
                alternative: 0,
                fields: [inlineDatumFields, 1, plutus_data],
              };

          const refercenceRecipient: Recipient = {
            address: 'addr',
            datum: {
              value: inlineDatum,
              inline: true,
            },
          };
    I'm sure Mesh will update the process, but this method I have tested to allow metadata retrieval using blockfrost and 'cardano-mode' UTXO view using cardano cli.

So how we will handle the thing of that one NFT have to be reference nft which will point towards the nft present in script? And also how metadata will get updated in reference nft according to other nft?

Mint the Reference NFT with the const '000643b0' prefix, and create the User asset with the prefix const '000de140'. When The nft is queried for metadata...the prefix tells the requester to look for the reference nft and read the metadata for the User nft there.
const inlineDatumFields = new Map();
inlineDatumFields.set('name', ${assetName});
inlineDatumFields.set('image', inlineDatumPair2);
Ref. contains the Metadata..user is the pointer to said metadata, lItems are linked by having user and ref prefix + same asset name. @duaaazhar

source: Stack Exchange

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

sort: votes


text:
Can a smart contract execute itself automatically?
I was wondering wether a smart contract can execute automatically or not. For example, let's say I have a vesting contract that, when a certain deadline passes, automatically executes and send some funds to the beneficiary. Is this possible? Or this can only happen if there is a transaction that triggers the sending of funds? Do smart contracts on other blockchain have automatic execution?

On Cardano the answer is simple: smart contracts cannot execute themselves automatically. Rather, a smart contract is nothing but a set of rules associated with an address. In a first transaction, Ada and other tokens are  transferred to the address - the so called script address. This script address is like a normal wallet address, the difference is that wallet addresses are associated to cryptographic keys and script addresses are associated with scripts (actually, the hash of the script as the script itself is not even stored on the blockchain), i.e. the smart contract. Then subsequently to this first transaction, any other transaction that wants to spend the funds sitting at the script address needs to satisfy the conditions set in the smart contract. Put simply, the smart contract is nothing else than a validator. In fact, there is nothing that gets "executed" in the narrow meaning of the word.

To complement Jey's answer and respond to your last question, I don't think that smart contracts can execute automatically as they are just code that is sitting at an address and they need an actual transaction to happen in order for them to be triggered. I would say this is the expected behaviour throughout the blockchain space.

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


text:
Cabal build all fail on M1
I want to add Cardano to Express project and followed the steps in documentation: https://developers.cardano.org/docs/get-started/installing-cardano-node/#macos. Unfortunately, “cabal build all” step failed after three hours of running.
I found a similar question on GitHub, it was advised to uninstall Libsodium, but I get an error for that as well(No such keg: /opt/homebrew/Cellar/libsodium).
Here is my terminal with the previous commands ran successfully:

Please see the failing final message:

Have you seen this:
https://github.com/input-output-hk/cardano-node/issues/3506#issuecomment-1089974749

Yes, I saw that post, but libsodium uninstall failed.
I posted a similar question on StackOverflow and provided the screenshot there.
https://stackoverflow.com/questions/76282227/cabal-installation-fails-on-m1

So I would think then that libsodium is not installed correctly

Welcome to the Cardano stack exchange! Please try to post your terminal output as text instead of images. Text can be found using the search or even search-engines like Google. With images this is not possible.


text:
When Mithril is used to bootstrap a cardano node, does it decrease its size?
I'm trying to understand the capabilities of Mithril. I noticed that you can bootstrap a cardano node using it as shown here: https://mithril.network/doc/manual/getting-started/bootstrap-cardano-node. But what does it mean to "bootstrap" the node? Does it only speed up the verification process or does it make the size of the node smaller?

"Bootstrap" means starting the node from scratch, and Mithril enables a fast bootstrapping of the Cardano node.
However, the size of the node database does not change: under the hood, the database of the Cardano node is restored from a Mithril certified snapshot. This accelerates significantly the synchronization of the database that is otherwise achieved by downloading data sequentially from other nodes.

I see, I was hoping it would allow cardano node to run on low spec devices e.g. smartphones. But it's certainly not the case. Thanks!

Actually, the fast bootstrap of the Cardano node is the first implemented use case for Mithril. In the long run, other use cases will be implemented, one of which will probably enable trustless light wallets that could run on devices such as smartphones.

Gotcha, I look forward to these use cases. But would this trustless light wallet still rely on services such as Blockfrost to query data or would it be able to sync on its own? Is that too soon for me to ask?

AFAIK, Mithril has a "currently" and an "in the future".
Currently:

the entire cardano-node's database (~136GB) is signed by nodes running Mithril and downloaded by the new node
thus, "fast bootstrapping" by downloading 136GB isn't all that light weight (do they also compress it?)

In the future:

since Mithril as a signature-scheme-and-a-process-architecture can sign any data, not just "the entire database", then it can be used to sign data much smaller
e.g, for a light wallet, it can receive a signed set of utxos, so you'll know both that (1) that's how much assets you have without needing to trust the node where you received the data from, and (2) construct a valid transaction to spend them.

Thus, looks promising!
(Somebody correct me if anything is wrong in the above.)


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

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

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


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

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


text:
Is it possible to integrate Cardano with Unity?
Is there a plugin that lets me integrate Cardano's network with Unity?


text:
Can there be duplicately named tokens?
I just want to clarify about this statement 'An asset is uniquely identified by an asset ID, which is a pair of both the policy ID and asset name.'
I'm guessing there can be duplicately named tokens where the asset name is the same, as long as the policy ID is different?

A token is uniquely identified as ploicyId + tokenName
the policy id is the hash of the rules imposed on minting and burning of the token.
the token name is the arbitrary name of the token ( there could be multiple tokens with the same rules ).
so it can very well happen that there are two tokens with the same name but different rules for minting/burning.
A token is NOT uniquely identified by the asset fingerprint
this is explained in the CIP itself
TLDR: even if extremly unlikely, it is possible for two different tokens to have the same asset fingerprint. The scope of the fingerprint is to have a quick way to distinguish between tokens but the final check should always be policyId + tokenName.

Yes, there can be more than one token with the same name, but there cannot be more than one token with the same token fingerprint. Pretty sure the fingerprint is just the bech32 encoding of (name, tokenId).

Yes it is technically possible. If you do this you will end up with a fungible token (FT) as opposed to a non-fungible token (NFT).
As the most obvious example, all the Lovelace (Ada) in your wallet have the same policy id and token name.
The uniqueness of a token name within a policy id is the responsibility of whoever controls the minting process.


text:
Having trouble getting a transaction to validate with my Plutus contract
validator :: BuiltinData -> BuiltinData -> BuiltinData -> ()
validator _ _ ctx =
  if paidTo seller then () else traceError "NFT locked until seller is paid."
    where
      paidTo x = valuePaidTo txInfo (PubKeyHash x) `gt` minAmount
      txInfo = scriptContextTxInfo $ unsafeFromBuiltinData ctx
      minAmount = assetClassValue (assetClass adaSymbol adaToken) 50
      seller1 = <public key hash of seller1_addr>

This is the basic validator. It compiles to PLC code and I can lock the NFT to the script address, however when I try to build a transaction to spend it:
cardano-cli transaction build \
--babbage-era \
--testnet-magic 2 \
--tx-in $script_utxo \
--tx-in-script-file $script_file \
--tx-in-inline-datum-present \
--tx-in-redeemer-value $redeemer \
--tx-in-collateral $buyer_utxo \
--tx-out "$(cat $seller1_addr) + 100000000 lovelace" \
--tx-out "$(cat $buyer_addr) + 1 $NFT" \
--change-address $(cat $buyer_addr) \
--protocol-params-file proto_params \
--out-file buyer_unsigned.tx

It fails with the following:
the script for transaction input 0 (in the order of the TxIds) failed with:
The Plutus script evaluation failed: An error has occurred:  User error:
The machine terminated because of an error, either from a built-in function or from an explicit use of 'error'.
Script debugging logs: NFT locked until seller1 paid.

Is there something incorrect here? What am I missing?


text:
Need to add signatures to plutus-simple-model-transaction
Any idea how to sign a transaction with multiple keys in plutus-simple-model ?

Seeing that source code just adds signature to the txSignatures map, you can call your signTx method multiple times for your different keys followed by sendTx to submit this transaction.


text:
Nami Wallet access
Cpu crashed,got new cpu, not able to send or receive in Nami wallet, no customer service email. How can I get customer service to Nami Wallet developers with no email available?

I'm assuming that you are referring to your computer with "cpu".
There is no customer support for Nami. You need your 24 words recovery phrase (that you wrote down when creating the wallet) to restore it. After doing this, you should see your funds and can use them as before.
You can find instructions on how to restore a wallet here: https://metaroids.com/learn/how-to-use-nami-wallet-full-guide/#How_to_Restore_Nami_Wallet


text:
A Simple stack language
I'm working through IOHK Haskell course from 2020, and I'm stuck on problem assignment W3.1, full description linked here:
https://github.com/iohkedu/w03
I do not understand how the instructions type is supposed to be ordered and evaluated. My code attempt introduces an extra parameter for initial stack, because otherwise I can't conceptualize how IfZero would be able to "look at the stack". Then my code attempt is

run :: Instructions -> [Int] -> Maybe [Int]
run (Push n code) xs    = run code (n:xs)
run (Pop code) (x:xs)   = run code xs
run (Add code) xs       = case xs of
                            (x:y:ys) -> run code (x+y:ys)
                            otherwise -> Nothing
run (Mul code) xs       = case xs of
                            (x:y:ys) -> run code (x*y:ys)
                            otherwise -> Nothing
run (Dup code) xs       = case xs of
                            (x:ys) -> run code (x:x:ys)
                            otherwise -> Nothing
run (Swap code) xs      = case xs of
                            (x:y:ys) -> run code (y:x:ys)
                            otherwise -> Nothing
run (Over code) xs      = case xs of
                            (x:y:ys) -> run code (y:x:y:ys)
                            otherwise -> Nothing
run (Neg code) xs       = case xs of
                            (x:ys) -> run code (-x:ys)
                            otherwise -> Nothing
run (IfZero c1 c2) xs   = case xs of
                            (0:ys) -> run c1 xs
                            (_:ys) -> run c2 xs
                            otherwise -> Nothing
run (Loop f) xs         = run (f (Loop f)) xs
run Halt xs             = Just xs

But when run on their example fact5 instructions, my run fact5 [] gives me the wrong output of Just [0,0,1,4,9,16,25,1]. I'm unable to even trace out on pen and paper what their fact5 is supposed to be doing ...
fact5 :: Instructions
fact5 =
  Push 5 $
  Push 1 $
  Swap $
  Loop $ \ loop ->
  Dup $
  IfZero (Pop $ Halt) $
  Swap $
  Over $
  Mul $
  Swap $
  Push 1 $
  Neg $
  Add $
  loop

appreciate any help

I was able to figure this out. My IfElse case was incorrect. It should be:
run (IfZero c1 c2) xs   = case xs of
                            (0:ys) -> run c1 ys
                            (_:ys) -> run c2 ys
                            otherwise -> Nothing


text:
How does the Mithril network sustain itself?
I’ve been reading about Parity Fether, an Ethereum wallet powered by a light client and noticed that it’s discontinued in 2022. I couldn’t find why it was abandoned but after doing a bit digging I found some comments that criticized Parity’s lack of incentives to run light client servers. This made me wonder about Mithril and how Cardano might run into the same problem.
How will Cardano incentivize people to run the Mithril network? Will Mithril light clients charge a fee?
p.s I can’t tag “Mithril” since my score is too low to create one
update: thanks for adding the tag


text:
How to get Daily Volume for an Cardano token by using Cardano-Db-Syncs database
Is there an way to query directly Cardano Db Syncs database to get withhold of the daily volume of an certain token ( For example via using multi_asset.fingerprint )
WITH ma_tx_ids AS (
    SELECT ma_tx_out.tx_out_id AS tx_id
    FROM multi_asset
    INNER JOIN ma_tx_out ON multi_asset.id = ma_tx_out.ident
    WHERE multi_asset.fingerprint = 'asset1wwyy88f8u937hz7kunlkss7gu446p6ed5gdfp6')
SELECT *, encode(tx.hash::bytea, 'hex') AS encoded_hash FROM block
    INNER JOIN tx ON block.id = tx.block_id
    INNER JOIN tx_out ON tx.id = tx_out.tx_id
    INNER JOIN collateral_tx_out ON tx.id = collateral_tx_out.tx_id
        WHERE block.time > '2023-06-06 00:00:00' AND tx_out.id IN (
        (SELECT tx_id FROM ma_tx_ids));

With this query it should return all transaction what have been done today with AGIX token, the multi_asset_descr contains for an single result
fromList [(PolicyID {policyID = ScriptHash "32cc9c6c3456bc048d14a4a8e4ee3592e9664e8daac921a8ef52d92a"},fromList [(4752415353,40020000)]),(PolicyID {policyID = ScriptHash "4f1440d7813020d5f359eeeb355902edf1ab9598de9c7c783224795d"},fromList [(536e656b4149,235237509)]),(PolicyID {policyID = ScriptHash "5d16cc1a177b5d9ba9cfa9793b07e60f1fb70fea1f8aef064415d114"},fromList [(494147,4786312)]),(PolicyID {policyID = ScriptHash "75fcc276057db5fc48eae0e11453c773c8a54604c3086bf9d95ac1b7"},fromList [(43485259,3137346983)]),(PolicyID {policyID = ScriptHash "83117b5acb702fd086db386d26e83b7de3b19fbfe24c9e96f8f101a3"},fromList [(433343757469657330383137,1),(433343757469657330393030,1),(433343757469657331303832,1),(433343757469657332303930,1)]),(PolicyID {policyID = ScriptHash "8db269c3ec630e06ae29f74bc39edd1f87c819f1056206e879a1cd61"},fromList [(446a65644d6963726f555344,251584)]),(PolicyID {policyID = ScriptHash "9a9693a9a37912a5097918f97918d15240c92ab729a0b7c4aa144d77"},fromList [(53554e444145,78915974)]),(PolicyID {policyID = ScriptHash "a2936e00439913f1ac105c29883c013322360247c409343028b831be"},fromList [(4d564f5543484552,386180)]),(PolicyID {policyID = ScriptHash "b6a7467ea1deb012808ef4e87b5ff371e85f7142d7b356a40d9b42a0"},fromList [(436f726e75636f70696173205b76696120436861696e506f72742e696f5d,470750000)]),(PolicyID {policyID = ScriptHash "d15c36d6dec655677acb3318294f116ce01d8d9def3cc54cdd78909b"},fromList [(,87452787799)]),(PolicyID {policyID = ScriptHash "dda5fdb1002f7389b33e036b6afee82a8189becb6cba852e8b79b4fb"},fromList [(0014df1047454e53,850843)]),(PolicyID {policyID = ScriptHash "f0ff48bbb7bbe9d59a40f1ce90e9e9d0ff5002ec48f232b49ca0fb9a"},fromList [(7061792e746869732e77616c6c6574,1)]),(PolicyID {policyID = ScriptHash "f43a62fdc3965df486de8a0d32fe800963589c41b38946602a0dc535"},fromList [(41474958,36959748122)])]

From the response we could read out
,fromList [(41474958,36959748122)]
Should all the values from the "fromlist containing AGIX (41474958) asset name" summed up?


text:
Best light wallets on Cardano?
In terms of efficiency/speed for dapp usage, what light wallets are the best for dapp usage? Is there any notable difference between them? For example, what's the difference in speed/efficiency of Lace versus Nami?

wallet speed and efficiency depend by how fast they can submit your transaction to the network.
For wallets like lace, eternl, nami this is done by a service they rely on.
as an example nami relies on blockfrost servers to submit transactions.
eternl instead has their own servers so that they can better balance the load of requests.
In general the less people use the same server, the faster their transaction will be submitted.
The most efficient way to have a transaction submitted is by sending them to a (trusted) stake pool node, since those are the nodes that ultimately will execute the transactions.
the above doesn't necessarily have to be a full wallet (like daedalus to be clear); you can just have a full node somewhere in the world and then submit your transaction there using the cardano-submit-api.
some stake pools are exposing an endpoint where they accept transactions for you to send.
So if you want your transactions to be submitted efficiently you might want to consider setting up a node on your own and then use any light wallet by specifying that you want to use your node (instead of their default servers) in order to submit transactions.


text:
Get from, to, amount information from a tx hash?
How to fet from, to, and amount information from a tx hash in cardano usin javascript?
Thank you


text:
Failed 400. Error code on Eternl
Trying to figure out why I can’t cancel a limit order I put on Eternl wallet app. For some reason when I try to cancel it tells me Failed 400. I’ve tried everything I can think of with no success.

Please provide more information, otherwise it's hard to help you. On which exchange/DEX are you trying to cancel the trade? Do you have sufficient funds on your wallet? Do you have a collateral UTxO set up? Are you using single address mode? Is the error from the DEX or from Eternl itself? A screenshot of the error would help too.


text:
Fetch rich cardano addresses?
I am building some dapps on Cardano network.
What I want to do is to

fetch cardano addresses whose balances are more than 1M ada.

Can anybody help me with this?
Thanks.

I see the tag blockfrost so I assume that is your tool of preference.
I believe the only solution using blockfrost would be performing a series of requests for every stake address to the "specific account" endpointand access the controlled_amount field.
you could get a list of all the addresses from a tool like koios: https://api.koios.rest/#get-/account_list
However, tools like blockfrost and koios are not meant for such queries;
What you are asking for is a snapshot of all possible addresses currently present on the blockchain; so what you likely want is to have your own cardano node and your own cardano-db-sync instance to perform these queries.


text:
How to monitor Cardano Minswap transactions using Blockfrost?
I was trying to monitor the swap actions
like who swapped which A to B Token, as real-time from Minswap platform.
I was using Blockfrost webhook for this, but I fetched lots of transactions including those (main swap transaction which are what I want).
The problem is that I couldn't filter them out of all transactions.
Can anybody help me with this issue?
Thank you.

Have you able to resolved your issues?

Oh, @Hebrew, I solved this issue.

I used a blockfrost api for this issue.
To be exact, blockfrost supports webhooks features which can be used as a hook to catch up certain cardano transactions.
So you can monitor Minswap Transactions (You know Minswap Order, Pool contract address).

Try to look at the blockfrost-adapter from MinSwap.


text:
Error: encoding/hex: invalid byte: s When using Lucid calling payToContract
I am getting an issue when creating a Lucid transaction and calling payToContract
I have created the datum and it is erroring on the line that converts this datum toHex
With the following error: Error: encoding/hex: invalid byte: s
This happens every time I run the logic,
Code to build the datum
onst deadline = Date.now() + 6 * 60 * 60 * 1000; // in 6 hours
const datum = new RequestDatum(
  new RequestMetadaDatum(
    ownerAddress,
    ownerAddress.payment_cred()!, // the owner whe can reclaim the request
    bigint.from_str(deadline.toFixed(0)), // deadline in posix time
    assetClassFromUnit('lovelace'), // the LP assets need to be ordered
    assetClassFromUnit(assetSubject)
  ),
  new SwapAction(SwapDirection.BTOA, bigint.from_str(minimumAmountTokenOut.toString()))
).to_plutus_data();

Transaction code
// Create a transaction that creates a swap request
const unsignedTx = await this._lucid
  .newTx()
  .payToContract(this._lucid.utils.credentialToAddress(this._lucid.utils.scriptHashToCredential(REQUEST_SCRIPT_HASH)), toHex(datum.to_bytes()), {
    lovelace: BigInt(lockedCoins.to_str()),
    assetSubject: quantityOfToken,
  })
  .complete();

This is an implementation using the Wingriders Blockfrost Adapter found here: https://github.com/WingRiders/dex-blockfrost-adapter/blob/main/examples/swap-fe-vanilla-js/src/swap.ts
Would appreciate any guidance here, thanks!

it's a bit hard to tell from where your error might come from, but your error simply means that you tried to use something that wasn't properly encoded in hex.
Therefore, the error message arises that the character s was read, but it's indeed not a valid character of a hex-encoding.
This problem often occurs for me, when I have forgotten to convert the name of a token from UTF-8 to hex.
This could also be the issue for you, i.e., you have a token starting with s in its name, and now you want to use the string encoded with utf-8 in, e.g., your datum. Instead, the token name should be converted to hex before using it as part of your datum.


text:
Javascript SDK for working with Plutus smart contracts
Are there any javascript SDKs which enable you to do the following:

programmatically create and submit a Plutus smart contract to mainnet
check what assets are currently locked at a given script address
create and send a transaction inlcuding some ada and native tokens to a given script address

You have many options for that:

programmatically create a Plutus smart contract to mainnet

Here the only option is plu-ts; it allows you to write and compile a smart contract directly in typescript (or javascript if you prefer)
you can even store pieces of contracts inside typescript functions and then build your contracts programmatically.
the compilation happens in the js runtime so you can compile them in your application.
Alternatively, you could use Helios, which can also be compiled in the js runtime; but is not javascript, is a newly created language.

check what assets are currently locked at a given script address

This can be done even without any library, what you need is something to query the blockchain.
many use blockfrost; I would also suggest you to have a look at koios

create and send a transaction

here you have many options too.
plu-ts also has an offchain component that allows you to build transactions.
Lucid is also an option but is based on a customized version of the cardano-multiplatform-library; so you would have to allow for web assembly; which can be tricky.
Mesh SDK is also currently based on web assembly (though are switching the backend to plu-ts in a future version) and it also provides you all the tools to build a user interface (UI) for you applicaiton

Yes, there are multiple:

Lucid
Mesh
plu-ts
Helios
Slightly less on abstraction is Cardano Multiplatform Library & Cardano Serialization Library.


text:
`set` generic meaning in CDDL specification
I see the set generic in babbage.cddl file but couldn't find it's definition. It seems to be defined as set<T> = [ * T]

yes it is an array of T
the only difference is that it is meant to have unique elements; which is a constraint that you can't express in the CDDL.
You will see ofthen used as
set<transaction_input>

where transaction_input is an utxo reference; it is obvious then that it needs to be an array with unique elements (eg you CAN NOT have the same UTxO spent twice)

Thanks, is this set inbuilt in CDDL specification (RFC 8610), o/w it should be defined somewhere right?

no set is not part of the CDDL spec, that's why it is defined so

My question was, if it's not part of CDDL spec, then it should be defined somewhere right? Now I know where it is defined, which is here. I got earlier misled by the comment at top, These are definitions ... thinking these definitions are for testing purposes but rather, the ones here are for testing.

yeah, you should assume all CDDL files for a single era to be a single file; if they are referring to a set then the definition you found is correct


text:
Dandelion graphQl endpoints not working?
I'am was trying to use these endpoints to use playground of cardano graphQL ( https://graphql-api.mainnet.dandelion.link/ ) and (https://graphql-api.testnet.dandelion.link/) but none is working, they are giving 503 and 403 errors
Are they shut down permanently ?

probably related: https://twitter.com/DandelionLink/status/1667281153764515841?t=d2O7q8eowxyFfVUJ4kF-cQ&s=19
It is likely just internal maintainance


text:
ogmios standalone running in a different computer that is running cardano-node
is it possible to run Ogmios standalone in a different computer that is running cardano-node. it happens that i already have cardano-node running in a computer but i dont want to overload that with Ogmios and want to run it in another equipment. Is it possible? Thank you

It should be possible.
You need to connect to the Cardano node socket on the Node PC from your Ogmios PC over the network. To do this, you can use the socat command (assuming you're running on Linux.
See here for instructions: https://unix.stackexchange.com/a/714010
Make sure your firewall is configured correctly.
Then you can simply follow the Ogmios Standalone instructions to connect to the socket on the Ogmios PC.


text:
Adding stake credential to script address
I compiled my plutus script and generated a payment credential only address. The logic all working fine- no issues.
However when I add a stake credential to my plutus script address, the logic starts to fail. I have tried with PKH and Script hash staking credentials. Even tried using a stake credential created with an always succeeds withdrawal validator.
Anyone know whats going on?

some actual code of the contract would help understand the issue better.
The error you describe suggests you are doing some checks for the script address (which is formed by payment credentials + optional staking credentials)
if you are checking for equality with an address built at contract runtime
(something like PCredential.PScriptCredential({ valHash: ownHash }) in plu-ts)
then you are checking for the address to be strictly equal to the one without any stake credentials.

A simple way to generate such an address is by using Eternl.

Go to https://eternl.io/
Open Settings (gear icon in the bottom left)
Open "Franken Address Generator"
Enter your script and stake address parts and generate

Hope this helps. Otherwise please add an example of what you already tried and provide more details on the error you get.


text:
Unable to connect wallet to node on mainnet
I have been following the instructions here:
https://developers.cardano.org/docs/integrate-cardano/creating-wallet-faucet
I have the node up and running and get the following output from cardano-cli query tip --mainnet:
{
    "block": 8929511,
    "epoch": 419,
    "era": "Babbage",
    "hash": "57ed1fb41f5bf65b1f2641e098cb540d9c8480988fcf3109de5c0e35564169a4",
    "slot": 95722889,
    "slotInEpoch": 78089,
    "slotsToEpochEnd": 353911,
    "syncProgress": "100.00"
}

When I enter:
cardano-wallet serve \
--port 1337 \
--mainnet \
--database $HOME/cardano/wallets/db \
--node-socket $CARDANO_NODE_SOCKET_PATH

I get the following error:
[cardano-wallet.main:Info:4] [2023-06-20 19:24:45.59 UTC] Running as v2023-04-14 (git revision: 0000000000000000000000000000000000000000) on x86_64-darwin
[cardano-wallet.main:Info:4] [2023-06-20 19:24:45.59 UTC] Command line: /Users/X/.cabal/store/ghc-9.2.7/crdn-wllt-2023.4.14-878a4af6/bin/cardano-wallet serve --port 1337 --mainnet --database /Users/liam_dolittle/cardano/mainnet/db/ --node-socket /Users/X/cardano/mainnet/db/node.socket --token-metadata-server https://tokens.cardano.org
[cardano-wallet.main:Debug:4] [2023-06-20 19:24:45.59 UTC] ServeArgs {_hostPreference = Host "127.0.0.1", _mode = Normal (CardanoNodeConn "/Users/liam_dolittle/cardano/mainnet/db/node.socket") (SyncTolerance 300s), _listen = ListenOnPort 1337, _tlsConfig = Nothing, _networkConfiguration = MainnetConfig, _database = Just "/Users/X/cardano/mainnet/db/", _enableShutdownHandler = False, _poolMetadataSourceOpt = Nothing, _tokenMetadataSourceOpt = Just (TokenMetadataServer {unTokenMetadataServer = https://tokens.cardano.org}), _logging = LoggingOptions {loggingMinSeverity = Debug, loggingTracers = Tracers {applicationTracer = Const (Just Info), apiServerTracer = Const (Just Info), tokenMetadataTracer = Const (Just Info), walletEngineTracer = Const (Just Info), walletDbTracer = Const (Just Info), poolsEngineTracer = Const (Just Info), poolsDbTracer = Const (Just Info), ntpClientTracer = Const (Just Info), networkTracer = Const (Just Info)}, loggingTracersDoc = Nothing}}
[cardano-wallet.main:Info:4] [2023-06-20 19:24:45.59 UTC] Wallet databases: Using directory: /Users/X/cardano/mainnet/db/
[cardano-wallet.application:Info:4] [2023-06-20 19:24:45.59 UTC] Wallet backend server starting. Using /Users/X/cardano/mainnet/db/node.socket.
[cardano-wallet.application:Info:4] [2023-06-20 19:24:45.59 UTC] Node is Haskell Node on mainnet.
[cardano-wallet.pools-db:Info:4] [2023-06-20 19:24:45.60 UTC] Starting connection pool for /Users/X/cardano/mainnet/db/stake-pools.sqlite
[cardano-wallet.pools-engine:Info:37] [2023-06-20 19:24:45.63 UTC] Chain following starting.
[cardano-wallet.main:Info:4] [2023-06-20 19:24:45.63 UTC] Wallet backend server listening on http://127.0.0.1:1337/
[cardano-wallet.pools-db:Info:4] [2023-06-20 19:24:45.67 UTC] Stopping database connection pool /Users/X/cardano/mainnet/db/stake-pools.sqlite
[cardano-wallet.pools-db:Info:4] [2023-06-20 19:24:45.67 UTC] Closing single database connection (/Users/X/cardano/mainnet/db/stake-pools.sqlite)
[cardano-wallet.main:Debug:4] [2023-06-20 19:24:45.67 UTC] Logging shutdown.
cardano-wallet: ExceptionInLinkedThread (ThreadId 13) DecoderFailure (LocalStateQuery HardForkBlock (': * ByronBlock (': * (ShelleyBlock (TPraos StandardCrypto) (ShelleyEra StandardCrypto)) (': * (ShelleyBlock (TPraos StandardCrypto) (ShelleyMAEra 'Allegra StandardCrypto)) (': * (ShelleyBlock (TPraos StandardCrypto) (ShelleyMAEra 'Mary StandardCrypto)) (': * (ShelleyBlock (TPraos StandardCrypto) (AlonzoEra StandardCrypto)) (': * (ShelleyBlock (Praos StandardCrypto) (BabbageEra StandardCrypto)) (': * (ShelleyBlock (Praos StandardCrypto) (ConwayEra StandardCrypto)) ('[] *)))))))) Query (BlockQuery (HardForkBlock (': * ByronBlock (': * (ShelleyBlock (TPraos StandardCrypto) (ShelleyEra StandardCrypto)) (': * (ShelleyBlock (TPraos StandardCrypto) (ShelleyMAEra 'Allegra StandardCrypto)) (': * (ShelleyBlock (TPraos StandardCrypto) (ShelleyMAEra 'Mary StandardCrypto)) (': * (ShelleyBlock (TPraos StandardCrypto) (AlonzoEra StandardCrypto)) (': * (ShelleyBlock (Praos StandardCrypto) (BabbageEra StandardCrypto)) (': * (ShelleyBlock (Praos StandardCrypto) (ConwayEra StandardCrypto)) ('[] *))))))))))) ServerAgency TokQuerying BlockQuery (QueryIfCurrent (QS (QS (QS (QS (QS (QZ GetCurrentPParams)))))))) (DeserialiseFailure 53 "expected integer")

and the following on the node output:
[x:cardano.node.LocalErrorPolicy:Error:67] [2023-06-20 19:24:46.65 UTC] IP LocalAddress "/Users/x/cardano/mainnet/db/node.socket@4" ErrorPolicyUnhandledApplicationException (MuxError MuxBearerClosed "<socket: 30> closed when reading data, waiting on next header True")
[x:cardano.node.LocalErrorPolicy:Error:67] [2023-06-20 19:24:46.69 UTC] IP LocalAddress "/Users/x/cardano/mainnet/db/node.socket@5" ErrorPolicyUnhandledApplicationException (MuxError MuxBearerClosed "<socket: 32> closed when reading data, waiting on next header True")
[x:cardano.node.LocalErrorPolicy:Error:67] [2023-06-20 19:24:46.69 UTC] IP LocalAddress "/Users/x/cardano/mainnet/db/node.socket@6" ErrorPolicyUnhandledApplicationException (MuxError MuxBearerClosed "<socket: 33> closed when reading data, waiting on next header True")

Great to know if you have any suggestions. Thanks!

This may not be a problem but your --database path and your CARDANO_NODE_SOCKET_PATH are pointing at different directories.


text:
Why does an cardano token have multiple policys
I stumbled upon Society token, in multi_assets table via cardano-db-sync it has 2 entries with same name but the meta data difference is minimal, as well they're fingerprints are different

policy = 25f0fc240e91bd95dcdaebd2ba7713fc5168ac77234a3d79449fc20c
name = 534f4349455459
fingerprint = asset1tpsewdtydk223j2tkx2wh09qptuyge638246u4

https://tokens.cardano.org/metadata/25f0fc240e91bd95dcdaebd2ba7713fc5168ac77234a3d79449fc20c534f4349455459

policy = 24ecd375f858e31b20ec8c16a19b2c4efededf66f1f994325c41dcc1
name = 534f4349455459
fingerprint = asset12sq05wm7ujttuzz5v7a3rulgw0zfy2j8e4uez6

https://tokens.cardano.org/metadata/24ecd375f858e31b20ec8c16a19b2c4efededf66f1f994325c41dcc1534f4349455459

How to acknowledge which of the entry is the correct one ?
Are we dealing with an copycat actually, that somebody has made the exact meta data entry?

When looking from https://cardanoassets.com/ we could see, it might be just an copycat

Probably they launched it with the wrong supply in the first place and then they launched the second one with 700M.


text:
which programming language is predominantly used for writing smart contracts in Cardano now?
I am a newbie to blockchain in the Cardano ecosystem. I have been exploring the Cardano documentation, which mentions various programming languages for writing smart contracts on the platform.
How do I determine the appropriate programming language for my Dapp?
Currently, which programming language is predominantly used for writing smart contracts and has been widely adopted in production on Cardano now?

The main programming language used to date is still Haskell.
Whether based on the GHC plugin "PlutusTX" by IOG (the first "smart contract language" released for cardano) or based on "Plutarch" (the second one, which is an eDSL in Haskell)
Despite that, new languages such as Aiken, plu-ts, OpShin are gaining momentum.
To determine which one is the one for your dApp it strictly depends on what you are more comfortable with
(eg. if you prefer typescript you'll go with plu-ts; if you prefer python you'll go with OpShin, and so on).
Keep also in mind that most of your dApp will likely be offchain code (transaction creation), and the smart contracts will only be needed to validate those transactions.

If you are interested in learning about Cardano I can highly recommend the course at plutuspbl.io it's a project based learning environment and covers PlutusTX, Aiken etc (and it's free)


text:
Multiple NFT meta in the tx_metadata.json of a single asset?
In some, not all cases, when I retrieve the tx_metadata.json of a given fingerprint (of an NFT), the json contains the meta of several NFT's, redundantly.
I cannot seem to see any sensible way of being certain which of them belongs to the asset who's metadata I am querying if the asset name is not itself in the meta data, as is the case, for example, in adahandles.
It is not this way for all assets, many, if not most, have a single meta data object, as one might expect.
If there are multiples though, firstly...why? Secondly, how do I know which meta data object to extract from the multiple objects in the tx_metadata.json field of a single asset?


text:
Why is "Current Time" (slot) validating script logic when its interval is not contained within the deadline interval (as defined in script logic)?
I have locked my "deadline" (which is set into the future) in "POSIXTime" to the On-Chain Datum of my contract.
To unlock it, I am using the "current time" (aka current slot) obtained via [cardano-cli query tip --testnet-magic 2] when drafting the unlocking transaction.
The slot is entered into transaction as "Invalid-before xxxxxxxx" command. Note: the xxxxxxxx is the current time slot at that moment of inquiry.
My script/contract logic mandates: deadlineReached = from deadline contains (txInfoValidRange info)
My understanding is that it should not be unlocking because the "current time (or slot)" interval is not contained within the future "deadline" interval locked in my datum.
Example:
deadline = 5
CurrentTime = 3
Since my deadline Interval (locked in datum) is in the future (as POSIXTime), why am I able to unlock the above said UTxO using the current slot (as queried at the time of transaction submission)?


text:
Is there any way to check reward address value?
Smart contract should allow the reward withdrawal only if all rewards are withdrawn. In other words only if the reward address will have exactly 0 lovelaces after the reward withdrawal. Is there any way/idea how to check this?

The ledger already enforces this rule. See "Reward accounts are set to zero for each corresponding withdrawal." in the Shelley ledger spec.

Thanks for your answer james! Yeah, I know about this. But the question is how can Plutus validator script get this info? As far as I know, all withdrawal data Plutus validator has is txInfoWdrl :: Map StakingCredential Integer. So, there is no any flags like 'Rewards are set to zero' or something like that. At the moment I use a stakeDeregistrationCert trick (it fails in case withdrawal amount < reward amount since stake address can be deregister only if reward amount = 0). However it's a bit expensive (tx fee) and complicated, and I'm trying to find a cheaper and easier way.


text:
How to continue syncing the newest data after importing snapshot data completed
I'm trying to sync the newest data from Cardano-db-sync, but after importing snapshot data successfully. I don't know how to continue to sync new data in realtime.
There is an example here https://github.com/IntersectMBO/cardano-db-sync/blob/master/doc/docker.md#restore-from-snapshot. However, it's not specified how the *.lstate file is used as a parameter to insert new data only.
Once I run the below command, old data is also being inserted.
RESTORE_SNAPSHOT=https://update-cardano-mainnet.iohk.io/cardano-db-sync/db-sync-snapshot-schema-10-block-6014140-x86_64.tgz \
docker-compose up && docker-compose logs -f

Anyone could help, please?
Thank you

After importing a snapshot, db-sync should just start following the chain.


text:
Could we remove old data in cardano-db-sync table (PostgreSQL)?
I'm trying to improve the performance of cardano-db-sync's database by removing unused tables (truncate block table) and deleting old data from the tx_out table.
However after re-start the cardano-db-sync instance, seems that it is trying to re-fill old data even when I specified ledger-state from the snapshot state https://github.com/IntersectMBO/cardano-db-sync/blob/master/doc/syncing-and-rollbacks.md#ledger-state
2024-02-08 00:46:15 [db-sync-node:Info:165] [2024-02-07 17:46:15.39 UTC] Setting ConsistencyLevel to Unchecked
2024-02-08 00:46:15 [db-sync-node:Info:165] [2024-02-07 17:46:15.39 UTC] Starting chainSyncClient
2024-02-08 00:46:15 [db-sync-node:Info:165] [2024-02-07 17:46:15.39 UTC] Suggesting intersection points from memory: [] and from disk: []
2024-02-08 00:46:15 [db-sync-node:Info:165] [2024-02-07 17:46:15.40 UTC] Cardano.Db tip is at slot 16311, block 16312
2024-02-08 00:46:15 [db-sync-node:Info:172] [2024-02-07 17:46:15.40 UTC] Running Offline fetch thread
2024-02-08 00:46:15 [db-sync-node:Info:171] [2024-02-07 17:46:15.40 UTC] Running DB thread
2024-02-08 00:46:15 [db-sync-node:Info:171] [2024-02-07 17:46:15.96 UTC] Delaying delete of 16312 while rolling back to genesis. Applying blocks until a new block is found. The node is currently at Tip (SlotNo 54073215) 3888541878ad6584df95be05ca8816c32ba9976011c4cd5f0703a773cf61eaf8 (BlockNo 6918590)
2024-02-08 00:46:16 [db-sync-node:Info:171] [2024-02-07 17:46:16.74 UTC] Found snapshot file for genesis
2024-02-08 00:46:16 [db-sync-node:Info:171] [2024-02-07 17:46:16.74 UTC] Setting ConsistencyLevel to DBAheadOfLedger
2024-02-08 00:47:03 [db-sync-node:Info:171] [2024-02-07 17:47:03.07 UTC] Received block which is not in the db with HeaderFields {headerFieldSlot = SlotNo 16312, headerFieldBlockNo = BlockNo 16313, headerFieldHash = a0bce776e49a0998e7acde647e7cb3a1794395abdb162d45c9c6f8ca16bdd049}. Time to restore consistency.
2024-02-08 00:47:03 [db-sync-node:Info:171] [2024-02-07 17:47:03.08 UTC] Starting at epoch 0
2024-02-08 00:47:03 [db-sync-node:Info:171] [2024-02-07 17:47:03.14 UTC] insertByronBlock: epoch 0, slot 16312, block 16313, hash a0bce776e49a0998e7acde647e7cb3a1794395abdb162d45c9c6f8ca16bdd049
2024-02-08 00:47:03 [db-sync-node:Info:171] [2024-02-07 17:47:03.14 UTC] Setting ConsistencyLevel to Consistent
2024-02-08 00:48:00 [db-sync-node:Info:171] [2024-02-07 17:48:00.26 UTC] insertByronBlock: epoch 0, slot 16999, block 17000, hash be219f7f8e2d4116ea718f34a7741eaf404c835ca0365b8f94426618b1a576a8
2024-02-08 00:48:04 [db-sync-node:Info:171] [2024-02-07 17:48:04.48 UTC] insertByronBlock: epoch 0, slot 17999, block 18000, hash e711abf703ebb7aa7c1ad235dafacdb6880fbc4a5ff27f368046ee6a2975724d
2024-02-08 00:48:07 [db-sync-node:Info:171] [2024-02-07 17:48:07.75 UTC] insertByronBlock: epoch 0, slot 18999, block 19000, hash 5c469c0c52cc8ad9b0d21d029c9aae75a8e0d82e686eb98e026c2ca71ee4fb21
2024-02-08 00:50:22 [db-sync-node:Info:171] [2024-02-07 17:50:22.59 UTC] insertByronBlock: epoch 0, slot 19999, block 20000, hash 683be7324c47df71e2a234639a26d7747f1501addbba778636e66f3a18a46db7
2024-02-08 00:50:25 [db-sync-node:Info:171] [2024-02-07 17:50:25.57 UTC] insertByronBlock: epoch 0, slot 20999, block 21000, hash e744980befb7bfbc2251efcce3897842545a766575bbfc931d42c875a9573dbf
2024-02-08 00:52:22 [db-sync-node:Info:171] [2024-02-07 17:52:22.76 UTC] Took a ledger snapshot at /var/lib/cexplorer/21599-3bd04916b6-0.lstate. It took 0.034869166s.
2024-02-08 00:52:22 [db-sync-node:Info:171] [2024-02-07 17:52:22.79 UTC] Persistant SQL Statement Cache size is 14
2024-02-08 00:52:22 [db-sync-node:Info:171] [2024-02-07 17:52:22.79 UTC]
2024-02-08 00:52:22 Cache Statistics:
2024-02-08 00:52:22   Stake Addresses: cache size: 0, hits: 0, misses: 0
2024-02-08 00:52:22   Pools: cache size: 0, hits: 0, misses: 0
2024-02-08 00:52:22   Datums: cache capacity: 50000, cache size: 0, hits: 0, misses: 0
2024-02-08 00:52:22   Multi Assets: cache capacity: 250000, cache size: 0, hits: 0, misses: 0
2024-02-08 00:52:22   Previous Block: hit rate: 49%, hits: 5273, misses: 5275
2024-02-08 00:52:22 [db-sync-node:Info:171] [2024-02-07 17:52:22.79 UTC] Starting epoch 1
2024-02-08 00:52:22 [db-sync-node:Info:171] [2024-02-07 17:52:22.80 UTC] insertABOBBoundary: epoch 1, hash 1941d944df546dea699791c318aeb9cc63b94e4cdb133d79856cda35bf7ecbb1
2024-02-08 00:59:32 [db-sync-node:Info:171] [2024-02-07 17:59:32.52 UTC] insertByronBlock: epoch 1, slot 22013, block 22000, hash aad3ea4b6f582418364b4396e52d13742a20251c0c24bd00b87a166c89721da5
2024-02-08 01:02:33 [db-sync-node:Info:171] [2024-02-07 18:02:33.09 UTC] insertByronBlock: epoch 1, slot 23013, block 23000, hash 66c167990b622ce28943a2bf518dbe810de7bb3356a8c8975ae0a1f9d621698f
2024-02-08 05:41:11 [db-sync-node:Info:171] [2024-02-07 22:41:11.79 UTC] insertByronBlock: epoch 1, slot 24013, block 24000, hash 1a8ef01c1a92288b269638552c051a64d0a9b741abd37d78d7762070f9333810
2024-02-08 09:40:14 [db-sync-node:Info:171] [2024-02-08 02:40:14.70 UTC] insertByronBlock: epoch 1, slot 25013, block 25000, hash 37e44110466a04ee127106043c7b20fe7ccc19de01e7cf5da99a4d001865ed2c

So could we remove old data in cardano-db-sync's tables (PostgreSQL) safely?
Could anyone help, please?
Thank you.

If I understand the problem correctly, there is this command line flag --prune-tx-out which will do the pruning for you.
There are also other performance flags available that may be able to help you further, though some are experimental at the moment.


text:
What does "Exception: unpaired digit" digit mean when trying to use the "assetClassValue" function?
Attempting to use function : assetClassValue (assetClass "67890" "PussToken") 100
Value (Map [(678900,Map [("PussToken",100)])])
Getting error -> Value (Map [(*** Exception: unpaired digit
CallStack (from HasCallStack): error, called at src/Data/Either/Extras.hs:6:34 in plutus-ledger-api-1.0.0.1 a5376ffff9bcd7feae2f904cd9bf193d5371c9e71ecc491aed0dbf5d6852f891:Data.Either.Extras

The input for "assetClass" excepts a paired hex value. I simply turned "67890" into an even number of digits -> 678900.
Then it works-


text:
Does Cardano has flash loans DeFi?
Does Cardano has flash loans implemented? Are they available in production?
If not: are there potential problems with eUTxO model, preventing their usage?

The only information I could find is https://www.essentialcardano.io/glossary/flash-loan .


text:
To create a dead-end "burning mechanism" contract for a specific native token
I am not sure how this should, or could, be done on Cardano...
I would like an address/script which, if a specific native token were submitted there, that token would become permanently irretrievable.
The goal is to effectively "burn" specific tokens so they are no longer considered as a part of the circulating supply of that token.  The policy used to create them is closed, so truly using the mint/burn mechanism is no longer possible.
I am seeking advice/guidance/examples of a way to transparently, and verifiably remove some of these tokens from circulation.

It should be irreversible.
It should only be for a specific token.
It should be possible for anyone to verify for themselves on-chain, that the tokens are truly locked irreversibly.

How can this be done?
Also, if there are more ways than one, what are the pros & cons of doing it one way vs another?
Thank you for helping me get this question answered!


text:
mesh starter template cant find wallet
Ok so when running this live demo https://starter-template.meshjs.dev/
the "Connect wallet" button does not show any wallets. Even if I have installed Yoroi (and others) wallet extension in my chrome browser. What wallets are this demo supposed to find if not those in the browser extensions?? I may very well have misunderstood something fundamental as Im new to this.
Nils Christian


text:
Where can I find Cardano implementation repository?
For Bitcoin and Ethereum I can easily find repositories with their implementations.
Where is an equivalent for that for Cardano?
I have found this repository but I am confused by the name of the owner of this repository (I heard about Emurgo, IOHK and Foundation but not about IntersectMBO) so I am not sure if that's what I am looking for(?)...

The Cardano node is composed of numerous components including:

https://github.com/IntersectMBO/cardano-base
https://github.com/IntersectMBO/cardano-ledger/
https://github.com/IntersectMBO/ouroboros-network/
https://github.com/IntersectMBO/ouroboros-consensus/
https://github.com/IntersectMBO/cardano-api/
https://github.com/IntersectMBO/cardano-cli/
https://github.com/IntersectMBO/cardano-node/

Ok, so I assume that if I am looking for the "core" Cardano functionality then I should go with cardano-node most likely.

If you are looking for the core functionality you should probably look at ledger and/or consensus.

Intersect is the cardano members based organization launched last year. Think of it like the Linux foundation equivalent for supporting Cardano development.

Ok, so my confusion about IntersectMBO was unnecessary :) There are a lot of organizations around Cardano...


text:
Eternl not able to send ADA to Kucoin (Error 400)
I'm not sure where the problem is. I'm trying to send some tokens from my eternl wallet to my kucoin address. I've copied the address using the copy button from kucoin so I don't think it's because it's the wrong address.
I enter my password to sign the transaction, and it always fails.
Some transactions failed to submit (400)
failed:
723ae8bdfde988437f80f9ca4fxxxxxxxxxxxxxxxxx533e18f84ac3dc8c2bb4
Bad Request
[object Object]
The hash changes, the error always the same.
I'm from Canada, and I know Kucoin has some legal issues here and new Canadian's can't get verified. But my account shows fully verified and I was able to send other tokens 2-3 months ago.
Thoughts?


text:
Minting and spending from the same script in a single transaction
I have a state NFT token locked in an hybrid script written in Aiken. I want to :

spend this NFT state to the script itself ( with a new datum which stores the new issuance state )
mint tokens I want to distribute. ( the state NFT is designed to
store the minting issuance numbers ).

Is it possible ? I have coded my offchain code with lucid, but I can't do both minting and
spending... But I can't figure why it wouldn't be possible to do both in the same transaction.


text:
Plutus-tx on XEON v2
I am trying to compile plutus script on 'Intel(R) Xeon(R) CPU E5-2680 v2' machine.  I initialized nix flake from input-output-hk/iogx haskell template (tried with ghc96 and ghc92), entered development environment with nix develop and tried to compile simple code like
integerOne :: CompiledCode Integer
integerOne = $$(compile [|| (1 :: Integer) ||])

Compilation fails with
Error: cabal: Failed to build hello-1.0.0.2. The build process terminated with exit code -4

And when I try to load the code to ghci, it reports
Illegal instruction (core dumped)

On my laptop it compiles successfully.
Looking at the coredump I discovered that the instruction was mulx from adx cpu feature.  /proc/cpuinfo says that my laptop has that feature, but the server does not.
Except for compiling with PlutusTx.compile anything other from ghc seems to work on the server well.
The question is, is there any way to run this on my server?  Any flag or fix to plutus-tx or ghc?  Can anyone point me to the part of plutus-tx package (or the proper ghc?) that generates that instruction?

I created the ticket: https://github.com/IntersectMBO/plutus/issues/5842

try this flake.nix, it uses the iogx as well with plutus-tx >= 1.21.  The corresponding code builds on my lenovo p1 laptop with Xeon CPU. Although, I am not sure if it is the exact CPU as your specs.

Thank you for the reply.  I tried your flake.  I cloned the repo and tried to enter development environment.  When nix built it, it dumped core while compiling plutus-script-utils so I believe the repo also has the same problem.


text:
Querying db-sync for ADA Balance
I want to write the ADA balance of my wallet to a console window using sql queries against the db-sync database.
How can I use sql statements to obtain the ADA balance of a given address by querying db-sync via postgresql? I tried querying the sum of the [value] of the utxo's of my wallet but seem to get inaccurate results acording to what my Eternl wallet says my balance is. Somehow I am misunderstanding what I should be summing etc.
There is no straightforward query for "wallet balance" in the interesting queries in the db-sync git repo.

The tx_out table contains both spent and unspent tx outputs. In order to calculate your balance, you need to sum only the unspent outputs.
We can check which outputs are unspent by joining on the tx_in table. If there is no associated entry for a particular tx_out row in the tx_in table, this output has not been spent.
Here are the associated queries for calculating both address and stake address balances:
-- address balance
select sum(tx_out.value)
from tx_out
left join tx_in on tx_in.tx_out_id = tx_out.tx_id and tx_in.tx_out_index = tx_out.index
where address = '<your-address-here>'
  and tx_in.id is null

-- stake address balance
select sum(tx_out.value)
from stake_address
inner join tx_out on tx_out.stake_address_id = stake_address.id
left join tx_in on tx_in.tx_out_id = tx_out.tx_id and tx_in.tx_out_index = tx_out.index
where stake_address.view = '<your-stake-address-here>'
  and tx_in.id is null

Note that these balances will not include your staking reward balance.

This is a concise and correct answer.
I ran the queries and they work just as expected.
Much appreciated, thank you!


text:
What number of confirmations is considered secure in Cardano?
There is k finalization param in Ouroboros, but it is absolutely non-practical. It takes around 36 hours AFAIU.

Related questions: https://cardano.stackexchange.com/questions/8760/what-is-your-comfort-level-for-number-of-confirmations-and-why

It depends on the amount of ADA at risk.
Personally I would be happy with 3 block confirmations for a value of US $10, but would want more than that for US $10,000.
Rollbacks of more than 3 blocks are roughly once a year events.

Agree, DbSync waits two blocks before inserting in database, just for reference

Rollbacks of more than 3 blocks are roughly once a year events.

Are there any stats available on rollbacks?


text:
How to query latest transaction for a policy where an asset of that policy changed address/ownership
How can I return the latest transaction where any asset of a given policy changed address/ownership?
Here is a query which returns me the most recent transaction which included an asset of a given policy in it's utxo's:
select encode(tx.hash::bytea, 'hex') as hash
from ma_tx_out as matxo
join multi_asset as ma on matxo.ident = ma.id
join tx_out as txo on matxo.tx_out_id = txo.id
join tx as tx on txo.tx_id = tx.id
left join tx_in on tx_in.tx_out_id = txo.tx_id and tx_in.tx_out_index = txo.index
where tx_in.id is null and ma.policy = '\x{policy_id}'
order by txo.id desc limit 1;

What I would like is similar but also very much not the same, and every way I try to do it turns into a VERY long running query, so I am reaching out here for help.
I want only transactions where any asset of the given policy changed address - i.e. changed ownership, moved to another wallet, was sent to a script address, etc.
So I am trying by differentiating on address of asset in an input utxo being on a different address in an output utxo but I think I may be misunderstanding how things are represented in the schema.

Here is a query that will detect whether a spacebudz nft has changed ownership. It uses a stake address if one exists and otherwise uses the address.
It runs in ~2 min for me when the time is set to 10 days ago.
with
tx_id_limit as (
  select tx.id as tx_id
  from block
    join tx on tx.block_id = block.id
  where time > '2024-03-10 00:00:00+00'
  order by tx_id asc
  limit 1
)

, stxo as (
  select  stxo.tx_out_id
     ,    stxo.tx_in_id
     ,    case
            when stake_address.view is not null then stake_address.view
            else stxo.address
          end as address
     ,    stxo.fingerprint
  from (
    select  tx_out.tx_id as tx_out_id
        ,   tx_in.tx_in_id as tx_in_id
        ,   tx_out.address
        ,   tx_out.stake_address_id
        ,   multi_asset.fingerprint
    from tx_out
    join tx_in on tx_in.tx_out_id = tx_out.tx_id and tx_in.tx_out_index = tx_out.index
    join ma_tx_out on ma_tx_out.tx_out_id = tx_out.id
    join multi_asset on multi_asset.id = ma_tx_out.ident
    where tx_out.tx_id > (select tx_id from tx_id_limit)
      and multi_asset.policy = '\x4523c5e21d409b81c95b45b0aea275b8ea1406e6cafea5583b9f8a5f'
      and tx_in.id is not null
  ) as stxo
  left join stake_address on stake_address.id = stake_address_id
)

select  stxo_1.fingerprint
    ,   stxo_1.address as from_address
    ,   stxo_2.address as to_address
    ,   encode(tx.hash, 'hex') as tx_hash
from stxo as stxo_1
join stxo as stxo_2 on stxo_2.tx_out_id = stxo_1.tx_in_id
join tx on tx.id = stxo_1.tx_in_id
where stxo_1.fingerprint = stxo_2.fingerprint
  and stxo_1.address <> stxo_2.address

This will probably not work as intended for fungible assets. For that you have to treat the input and output addresses as sets (since there can be multiple addresses for a single asset) and then check that the input set and output set are different.

Very cool - I am going to try it out now! Thank you.
First question: I keep the last tx.id processed, and use that as my constraint, but you have used time. Is there a specific reason you chose to use time from the block table?

Nah I just use time so I have a better sense of how far back in the chain I'm going. tx_id would be more efficient here but is less ergonomic imo

This is a non-trivial task. You can't quickly fetch the latest tx that meets this criteria. Postgres will first need to compute whether the criteria has been met across all txs for that asset. Then it will order them and return the latest one.
You have a few options:

You can improve performance by selecting a timeframe (subset of latest txs). You then have to balance the risk returning of no results with the speed of the query ie the longer the timeframe the slower the query.
You can write a postgres function that will iterate a day at time in reverse order until it finds a matching tx. This may still be quite slow especially if you are trying to load results for a web page.
You can create a materialized view that maps assets to txs if they meet this criteria ie a table with columns asset_id, tx_id, time. This is probably your only option if you are doing this for a user-facing app. You then backfill the table with your relevant data and need a way to update the table with the new data coming in.

Agreed, and in fact I do have a tx id I use for limiting the scope in time:
and tx_id > {X}
this does reduce the amount of work required, agreed!
The thing I need help with most though is what is it in the schema/data that would definitively identify a given transaction as one where any asset of the given policy has changed ownership.

Thanks btw @adjuric.
For your #1:
I do constrain by time, typically only querying for records of the last hour, constrained by using: and tx.id > X
It is not for a web UI per-se, it is for extracting the transactions I am interested in, and then storing/updating data in a separate DB.
The part I need help on is determining for certain how to identify that a tx is one where an asset of the given policy changed ownership.
There is the asset being on an input UTXO on one address, and then on another as an output ...


text:
How to identify that a tx is one where an asset of a given policy changed ownership
By querying db-sync using postgresql queries, how can I identify that a tx is one where an asset of the given policy changed ownership?
Is checking if any asset of the policy is on one address as an input utxo, but on a different address as an output utxo a valid way? If so, is it the only way?


text:
Blockfrost API 403 Error in React Node JS app
I'm trying to get info about the latest block in my React Node JS app using Blockfrost and I'm running into an error:
GET https://cors-anywhere.herokuapp.com/https://cardano-mainnet.blockfrost.io/api/blocks/latest 403 (Forbidden)

Why is this happening? Any potential solutions are much appreciated!
Here's my code:
useEffect(() => {
fetch(
  'https://cors-anywhere.herokuapp.com/https://cardano-mainnet.blockfrost.io/api/blocks/latest',
  {
    contentType: "application/json",
    headers: {
      project_id: PROJECT_ID
    },
    method: 'GET'
  }
)
  .then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    return response.json()
  })
  .then(data => {
    console.log(data)
  })
  .catch(error => {
    console.error(error)
  })

}, [])

Your URL appears to be incorrect:
https://cors-anywhere.herokuapp.com/https://cardano-mainnet.blockfrost.io/api/blocks/latest


text:
"Transaction submit error" while trying to unlock funds from script address using Mesh
This is my setup code.
const wallet = await BrowserWallet.enable('Nami');

// this script always succeeds regardless of the datum or redeemer
const script: PlutusScript = {
  code: '59079559079201...0122212200201',
  version: 'V2',
};

const scriptAddress = resolvePlutusScriptAddress(script, 0);

const myAddress = await wallet.getChangeAddress();

const myDatum: Data = {
  alternative: 0,
  fields: [42]
}

const myRedeemer = {
  data: {
    alternative: 0,
    fields: [21]
  }
}

I lock the funds in the script address using the function below and it works.
async function lock(ada: string) {

  const tx = new Transaction({ initiator: wallet })
    .sendLovelace(
      {
        address: scriptAddress,
        datum: {
          value: myDatum,
        }
      },
      ada + '000000'
    )

  try {
    const unsignedTx = await tx.build();
    const signedTx = await wallet.signTx(unsignedTx);
    const txHash = await wallet.submitTx(signedTx);
  } catch (err) {
    console.log(err.message);
  }
}

I have a helper function for getting asset utxos from the blockchain.
sync function _getAssetUtxo({ scriptAddress, datum, amount }) {

  try {

    //const koios = new KoiosProvider('preprod');
    //const utxos = await koios.fetchAddressUTxOs(scriptAddress);

    const blockfrostProvider = new BlockfrostProvider('preprod...Rkbm');
    const utxos = await blockfrostProvider.fetchAddressUTxOs(scriptAddress);

    const dataHash = resolveDataHash(datum);

    let utxo = utxos.find((utxo: UTxO) => {
      return utxo.output.dataHash == dataHash && utxo.output.amount[0].quantity == amount;
    });

    return utxo;

  } catch (err) {
    console.log(err);
  }

This is my function for unlocking the funds from the script address.
async function unlock(ada: string) {

  const assetUtxo = await _getAssetUtxo({
    scriptAddress: scriptAddress,
    datum: myDatum,
    amount: ada + '000000'
  });

  const tx = new Transaction({ initiator: wallet })
    .redeemValue({
      value: assetUtxo,
      script: script,
      datum: myDatum,
      redeemer: myRedeemer
    })
    .setRequiredSigners([myAddress])
    .sendValue(myAddress, assetUtxo)

  try {
    const unsignedTx = await tx.build();
    const signedTx = await wallet.signTx(unsignedTx, true);
    const txHash = await wallet.submitTx(signedTx);
  } catch (err) {
    console.log(err.message);
  }
}

But when I run the function above, I get the error bellow:
transaction submit error ShelleyTxValidationError ShelleyBasedEraBabbage
(ApplyTxError [UtxowFailure (FromAlonzoUtxowFail
(PPViewHashesDontMatch (SJust (SafeHash
\"6ea33d2943315bf6179393f97af792376fd0c29851831b183c96a395db712337\"))
(SJust (SafeHash
\"ed2dc348e2070315e474c83981b40015d1dec8eaee9704735776e4d6147f7c41\"))))])

What am I doing wrong?

Mesh version 1.5.1 just got deployed to npm with the updated cost models for Plutus V2. Have a nice day and happy coding!!

The preprod env was upgraded this weekend and there were cost model updates for the upcoming release.  Blockfrost wasn't in synch for with the latest cost model so you would get that error.  This issue has been fixed and should be working now in preprod.

I waited a few days, updated Mesh to 1.5.0, tested with sending native assets and ADA only, tested with Blockfrost and Koios, tested with Nami and Eternl, and still getting the same error.

Well, there is still (most likely) a mismatch between the network protocol parameter file used during transaction construction and what is then submitted to blockfrost.   I am not too familiar with Mesh, but you need to find out what network parameter file is being used when you build the transaction.  Are you using Demeter Run for your dev env.  They should have everything setup and ready to go.

Hi @lley154, the problem was due to the changes in the cost model, this changes was not broadcasted to the community. Or is it? If it is, how can I get subscribe to such update?

I started noticing a simliar issue on the Helios discord and I suspected it was a protocol parmeter mismtach (eg the cost mode), and then Gavin posted this to IOG techincal discord and one of the SPOs confirmed the change was done on preprod and Gavin confirmed the cost model had changed.  Perhaps IOG can post something in IOG technical discord when a hard fork on preprod occurs, but I suspect there is a SPO discord channel that would broadcast this info as well.  https://discord.com/channels/826816523368005654/826829805387120690/1074254823261745242


text:
Need to Retrieve Info from (NFT)Assets in Policy ID to see if they are in a Plutus Contract (smart contract) or Not using Blockfrost API
I have a python script that retrieves the NFT asset name, and addresses of a specific policy ID using blockfrost API. Now I need to amend the script to add to the csv whether or not the specific asset is in a smart contract (plutus contract) or not. any ideas?
current script:
import requests,csv

blockfrost_api_key=input('blockfrost api key')
project_policy_id=input('project policy id')

base_api="https://cardano-mainnet.blockfrost.io/api/v0"

headers={'project_id':f'{blockfrost_api_key}'}

allAsset=[]

page=1

while True:
    response=requests.get(f'{base_api}/assets/policy/{project_policy_id}?page={page}',headers=headers)

    if len(response.json())==0:
        break

    for asset in response.json():
        temp={}
        asset_hex_name=asset["asset"][len(project_policy_id):]
        temp['name']=bytearray.decode(bytearray.fromhex(asset_hex_name))
        temp['asset']=asset['asset']

        allAsset.append(temp)

    page+=1

data=[]

for asset in allAsset:
    response=requests.get(f'{base_api}/assets/{asset["asset"]}/addresses',headers=headers)
    address=response.json()[0]['address']

    data.append([asset['name'],address])

    print(asset['name'])

file=open('snapshot.csv','w')
csvWriter=csv.writer(file,delimiter=',')
csvWriter.writerows(data)
file.close()

I'm a complete noob and followed a tutorial to get this far. Thanks for any help! greatly appreciated

You are also there, all you need to do is to fetch the address using the /addresses endpoint and check if the address has a script flag.

@mmahut how do i do this exactly in my current script? I'm so new to scripting. thanks for any help

i figured it out with some help from a buddy. thanks


text:
Overuse of resources when comparing for equality of VALUES (==)
I found an strange consumption of mem and CPU when comparting VALUES on-chain.
If I do the same comparison with my own writing functions I found is more efficient. How could it be?
Everything is detailed here:
https://github.com/input-output-hk/plutus/issues/5135
Basically, I run some test evaluations over two different minting policies. One using the (==) operator between VALUES and other using my own function called valueEqualsValue. The results where overwhelming.
With zero tokens my own functions use 12% less of resources and with 19 different tokens they use 32% less than the officials one.
It could be I'm missing some functionality in the comparison, that is implemented in the official one with the (==) operator. I found also benefits like this writing my own version of flattenValue.
How do you compare VALUES online?
Did you notice this unexpected inefficiency in some of other core functionalities of Plutus On Chain Code?
Considering the limited amount of memory that we have to write our smart contracts its very strange for me to realize that even the most basic functionalities they look very inefficient.
Thank you

Copying my answer from the Github issue here as well:
We have hit the same issue lately. It is due to how the == function in the Eq Value instance is implemented.
A value is logically a Map CurrencySymbol (Map TokenName Quantity), but on-chain there are no maps. Instead associative lists are used instead. As a Haskell type, a Value would be something like [(CurrencySymbol, [(TokenName, Quantity)]].
This means that given two values with the same contents, they may not be exactly the same if you compare them element by element. (I assume) the implementation of Eq Value was intended to mitigate this by implementing a Map-like equality. While correct, it turns out, this is quite an expensive implementation.
What we have opted for is an "exact equality" check for Value in the Hydra code base: https://github.com/input-output-hk/hydra/pull/709 (We investigated and indeed serializing to bytes and comparing the results was most efficient for us with complexity of about O(2n) or so)
I think we should discuss the need for such an exact equality function and maybe guide users more towards that if just want to ensure values are exactly the same / unchanged? From my experience this is often good enough and could be implemented cheaper.

Can you tell me about the limits of your idea on comparing values with the serialized data, the "exact equality"? When it will work and when it wont?
Im in process of comparing results of your idea with the idea I proposed for check equality.
This is my idea, could be wrong or not enough good, but its better than the actual one. Can you spot any inconvenient using my proposal?
https://github.com/input-output-hk/plutus/issues/5135#issuecomment-1436071599

Using serialiseData it will only be equal if the all the contents are exactly the same. That is, same elements, in the same order and no duplicates (or same duplicates).

In maps, can we have two elements with the same key? in the case of VALUES, can we have two equals currency symbols or two equals token name in the maps inside each currency symbol?

There are no maps on chain, they are association lists as I described in my answer above. So yes, multiple pairs with same key can be in there.

thank you for all the answers! Lets see how this evolves!

Sebastian, I have still a question about this. Would you give me a concrete example of a transaction where it can fail the exactly equality?
Given a transaction with one input and one output, I need to compare the VALUES of them. In witch cases it can fail?


text:
Convert between address types?
Is there any way to convert between Byron-era addresses (ie "Ae2tdPwUPEZ5faoeL9oL2wHadcQo3mJLi68M4eep8wo45BFnk46sMkvCmM9" or "DdzFFzCqrhswh7xiYG8RE1TtcvWamhbExTXfsCYaF9PrGWHRLCwCsBH5JkeApUagvo4FZE3DJD3rn5hw8vaMBib2StKMJ77rJHt51jPt" and the Shelley type (ie "addr1vx7vlgvuupzvvls99penvatpm2c4j9ljscevzsnn3awk8ys6xynxk")?
Failing that, is there a way to use Cardanosharp to generate the Byron type from mnemonic (I know you can use PurposeType.Byron, but it produces "addr1"-prefixed addresses, and I want the old Daedalus/Yoroi version)?  Can I do it in cardano-address?

Yes, you can use cardano-address to generate Byron addresses, starting from a mnemonic phrase.
You can use this script for that:
https://gist.githubusercontent.com/cardano-apexpool/f37f333eea7f8aac9a76687a94a9cf51/raw/5a5e613e1e352074993682fba3031cc6a4c3806e/byron_wallet_from_mnemonic.sh

Please add an example, otherwise this answer isn't very helpful.

I added the script. You can use an existing 12 words recovery seed or generate a new one, just edit in the script that part.


text:
Whats the python script to check if an cardano address has a script flag?
I have a script to fetch asset name, address from a policy id with blockfrost API, now I need to see if the asset is in a smart contract script. I have no coding skills but followed a tutorial to get this far. Thanks!

PyCardano can help you to find the address type.
For example, addr1wyzynye0nksztrfzpsulsq7whr3vgh7uvp0gm4p0x42ckkqqq6kxq is the script address of Spacebudz. You can decode it into an Address object using pycardano, and the address_type field will tell you the information about this address.
>>> from pycardano import Address
>>> addr = Address.from_primitive("addr1wyzynye0nksztrfzpsulsq7whr3vgh7uvp0gm4p0x42ckkqqq6kxq")
>>> addr.address_type
<AddressType.SCRIPT_NONE: 7>

The output SCRIPT_NONE tells us that this address's payment part is a script (first half is SCRIPT), and the address doesn't have staking part (second half is NONE). All possible address types could be found in this doc.


text:
Different addresses from same mnemonic?
I want to generate an old Byron address.  However, depending on which software I use (cardano-address or cardano-serialization-lib), I get a different result for the same mnemonic phrase.  Here is my code for cardano-serialization-lib, run online with https://npm.runkit.com/:
var bip39 = require('bip39');
var CardanoWasm = require('@emurgo/cardano-serialization-lib-nodejs');
var b58 = require('base58-js');

var digits = '0123456789abcdef'.split('')
var encodeLookup = []
var decodeLookup = {}

for (var i = 0; i < 256; i++) {
  var ones = i & 0xf
  var sixteens = i >> 4 & 0xf
  var string = digits[sixteens] + digits[ones]
  encodeLookup[i] = string
  decodeLookup[string] = i
  //console.log(decodeLookup)
}

encode = function (array) {
  var length = array.length
  var string = ''
  var i = 0
  while (i < length) {
    string += encodeLookup[array[i++]]
  }
  return string
}

function harden(num){
  return 0x80000000 + num;
}

const entropy = bip39.mnemonicToEntropy(
  [ "test", "walk", "nut", "penalty", "hip", "pave", "soap", "entry", "language", "right", "filter", "choice" ].join(' ')
);

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

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

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

const byronAddr = CardanoWasm.ByronAddress.icarus_from_key(
  utxoPubKey, // Ae2* style icarus address
  CardanoWasm.NetworkInfo.mainnet().protocol_magic()
);

const address = byronAddr.to_address();

console.log(b58.binary_to_base58(address.to_bytes()));

I get Ae2tdPwUPEZ7sZ29n6td4jkbnK31Q2BdQQ2rrMGYAXeEjVznrixjc5PZ2rj as the address.
Here is my command-line for cardano-address (yes, I'm on Windows):
ECHO test walk nut penalty hip pave soap entry language right filter choice | "%CD%\cardano-address.exe" key from-recovery-phrase Byron | "%CD%\cardano-address.exe" key child 44H/1815H/0H/0/0 | "%CD%\cardano-address.exe" key public --with-chain-code | "%CD%\cardano-address.exe" address bootstrap --network-tag mainnet & ECHO.

Here I get Ae2tdPwUPEZ9xFkLoCFGvtgrHc5K5jr3n1wMuVLRXSZZ32iGGyfQpZQcK6f.
Which one is correct?

cardano-addresses is official IOHK software, but the cardano-serialization-lib is listed on cardano.org's developers site, so it must be approved somehow, yet they don't agree on address generation.  This seems like a huge problem.  If I can't get an answer here, does anyone know a better place to raise this issue?

you can try to ask on https://forum.cardano.org

You should get an answer in here as the majority of the Cardano devs and main contributors are part of this community. If you don't get an answer here, then I guess we have a problem...


text:
Unable to deploy Plutus NFT Minting Policy parametrized by TxOutRef using cardano-cli
UPDATE:
I'm making progress.  It is apparent the TxOutRef stored on-chain has some extra-structure.  For evidence I "printed" the TxOutRef's of the 'utxo' hard-wired in my minting policy and the one stored onchain.  For the former/latter I uncommented the first/second comment in
hasUTxO :: Bool
hasUTxO = case txInfoInputs info of
--  [i] -> traceError . decodeUtf8 . getTxId . txOutRefId $ oref
--  [i] -> traceError . decodeUtf8 . getTxId . txOutRefId . txInInfoOutRef $ i
  _   -> traceError "many inputs"

The "printouts", given by the transaction errors returned by cardano-cli were, respectively:
1.
Command failed: transaction build  Error: The following scripts have execution failures:
<ommited stuff>
The machine terminated because of an error, either from a built-in function or from an explicit use of 'error'.
Script debugging logs: Redeemer decoded successfully
Script context decoded successfully
9c087132a325f6483aca8398bab1a56eda1390e762984ba054c25cafd738486c

Command failed: transaction build  Error: The following scripts have execution failures:
<ommited stuff>
The machine terminated because of an error, either from a built-in function or from an explicit use of 'error'.
Caused by: [
  (builtin decodeUtf8)
  (con
    bytestring #9c087132a325f6483aca8398bab1a56eda1390e762984ba054c25cafd738486c
  )
]
Script debugging logs: Redeemer decoded successfully
Script context decoded successfully

It is apparent that in 2. the relevant txOutRefId is buried inside some extra structure.  The question now is, how can I extract the txOutRefId from all this structure?
ORIGINAL POST:
This simple minting policy should serve to mint an NFT by consuming a UTxO parametrized by TxOutRef:
{-# INLINABLE mkPolicy #-}
mkPolicy :: TxOutRef -> () -> ScriptContext -> Bool
mkPolicy utxo () ctx = traceIfFalse "UTxO not consumed" hasUTxO
  where
    info :: TxInfo
    info = scriptContextTxInfo ctx

    hasUTxO :: Bool
    hasUTxO = any (\i -> txInInfoOutRef i == utxo) $ txInfoInputs info

(To simplify, we don’t even check that the number of minted tokens is one, since that is a non-issue here.)
I have been unable to deploy a concrete instance of this minting policy using cardano-cli.  I now describe my procedure.  Hopefully somebody can point out where the mistake is!
The UPLC policy and corresponding currency symbol are obtained with:
policy :: TxOutRef -> MintingPolicy
policy oref = mkMintingPolicyScript $
  $$(PlutusTx.compile [|| mkUntypedMintingPolicy . mkPolicy ||])
  `PlutusTx.applyCode`
  PlutusTx.liftCode oref

curSymbol :: TxOutRef -> CurrencySymbol
curSymbol = Scripts.scriptCurrencySymbol . policy

Meanwhile I have a wallet on Testnet PreProd with one UTxO:
[bash]$ cardano-cli query utxo --address $(cat wallet1.addr) --testnet-magic 1
                           TxHash                                 TxIx        Amount
--------------------------------------------------------------------------------------
9c087132a325f6483aca8398bab1a56eda1390e762984ba054c25cafd738486c     1        9784666930 lovelace + TxOutDatumNone

so I define an instance of my minting policy with:
oref_1 :: TxOutRef
oref_1 = TxOutRef
  { txOutRefId = TxId "9c087132a325f6483aca8398bab1a56eda1390e762984ba054c25cafd738486c"
  , txOutRefIdx = 1
  }

policy_1 :: MintingPolicy
policy_1 = policy oref_1

curSymbol_1 :: CurrencySymbol
curSymbol_1 = curSymbol oref_1

(Note that I have enabled the language extension OverloadedStrings.)
Now I serialize the minting policy and currency symbol, as well as the unit redeemer, with:
Prelude Deploy SimpleMinting> writePolicy "ledger/mint_1.plutus" policy_1
Right ()
Prelude Deploy SimpleMinting> writeCS "ledger/mint_1.hex" curSymbol_1
Prelude Deploy SimpleMinting> writeUnit "ledger/unit.json"

where the commands writePolicy, writeCS and writeUnit are defined in this Deploy.hs.
Now, also inside directory 'ledger', I wrote the shell script 'mint.sh':
cardano-cli transaction build \
        --babbage-era \
        --testnet-magic 1 \
        --tx-in $(cat oref1.tmp) \
        --tx-in-collateral $(cat oref1.tmp) \
        --tx-out $(cat wallet1.addr)+"2000000 lovelace"+"1 $(cat mint_1.hex).$(cat tokenName.hex)" \
        --change-address $(cat wallet1.addr) \
        --mint "1 $(cat mint_1.hex).$(cat tokenName.hex)" \
        --mint-script-file mint_1.plutus \
        --mint-redeemer-file unit.json \
        --protocol-params-file protocol-params.json \
        --out-file tx.body

('tokenName.hex' was generated with echo -n "FUNKYTOKEN" | xxd -ps > tokenName.hex.)
Let us verify that 'oref1.tmp' stores the correct TxOutRef as queried above with cardano-cli:
[bash]$ cat oref1.tmp ; echo
9c087132a325f6483aca8398bab1a56eda1390e762984ba054c25cafd738486c#1

which is indeed correct.  So we try to build the transaction by executing:
[bash]$ ./mint.sh
Command failed: transaction build  Error: The following scripts have execution failures:
the script for policyId 0 (in the order of the PolicyIds) failed with:
The Plutus script evaluation failed: An error has occurred:  User error:
The machine terminated because of an error, either from a built-in function or from an explicit use of 'error'.
Script debugging logs: Redeemer decoded successfully
Script context decoded successfully
UTxO not consumed
PT5

The "UTxO not consumed" error message implies that my Minting Policy fails to recognize the TxOutRef.  I am really puzzled about what am I doing wrong.
For reference, here is the complete haskell code for the plutus minting policy: SimpleMinting.hs.

Ok, I think I have it...
oref_1 = TxOutRef
  { txOutRefId = TxId "9c087132a325f6483aca8398bab1a56eda1390e762984ba054c25cafd738486c"
  , txOutRefIdx = 1
  }

This is not doing what you expect... you must do some conversions, if not its converting your hex string into something else.
You can do like this:
import qualified Data.Maybe as DataMaybe(fromJust)
import qualified Data.Text as DataText
import qualified PlutusTx.Builtins.Class as TxBuiltinsClass
import qualified Prelude as P
import qualified Text.Hex as TextHex

stringToStrictText :: P.String -> DataText.Text
stringToStrictText = DataText.pack

txOutRef = TextHex.decodeHex P.$ stringToStrictText "9c087132a325f6483aca8398bab1a56eda1390e762984ba054c25cafd738486c"
txOutRef' = TxBuiltinsClass.toBuiltin P.$ DataMaybe.fromJust txOutRef

oref_1 = TxOutRef { txOutRefId = TxId txOutRef', txOutRefIdx = 1 }

For using TextHex you must add this in your cabal file:
  build-depends:
  hex-text

This works indeed.  Awesome!  As a side note, it is frustrating that it was so hard to deploy this simple example (taken from PPP week 5) to the blockchain.

Yes, I known, to put all the parts in move in the beginning take some time, but the good part is that after that most of the rest is reuse them in different ways. Good Luck!

You can also do it without DataText.Text, but using function from Plutus.V1.Ledger.Bytes instead. See https://github.com/input-output-hk/plutus-apps/blob/b220a4e4c861c7e09d9528839e81fbff85ebb2aa/plutus-e2e-tests/test/PlutusScripts/Helpers.hs#L19-L24

Did you try to have at least two utxos and use one for the mint and one different for collateral?
--tx-in $(cat oref1.tmp)
--tx-in-collateral $(cat oref2.tmp)

Yes.  It didn't help.  The problem seems to be that the TxOutRef stored onchain has some extra structure.

Mhhh don't believe that, the TxOutRef is just a hash and an Index.
https://playground.plutus.iohkdev.io/doc/haddock/plutus-ledger/html/Ledger.html#t:TxOutRef