text:
mustMintValueWithRedeemer - Number of tokens minted
On the Offchain code I am trying to mint a token using the following snippet
Constraints.mustMintValueWithRedeemer r (assetClassValue cTk 1)

In the validation code of the minting script I am trying to verify if only one token was minted
tkMinted :: Value
tkMinted = txInfoMint info

But when I try to check the number of currencies minted using the following code
symbols tkMinted

I see there are more than one type of currency in the value list. Is this expected ?
Here is a detailed snippet
--------------
-- Policy
--------------

data UsrParams = UsrParams {
    tk :: !TokenName
  , c :: !CurrencySymbol
} deriving (Show, Generic, FromJSON, ToJSON, ToSchema)

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

{-# INLINABLE usrPolicy #-}
usrPolicy :: UsrParams -> BuiltinData -> Contexts.ScriptContext -> Bool
usrPolicy params r ctx = traceIfFalse  "Failed to mint!" ( tkMinted == (Value.singleton (c params) (tk params) 1) )
  where
    info :: V2LedgerApi.TxInfo
    info = Contexts.scriptContextTxInfo ctx

    currencySymbol :: CurrencySymbol
    currencySymbol = c params

    tkMinted :: Value
    tkMinted = V2LedgerApi.txInfoMint info

---------------------
-- Test Code
---------------------

asset :: AssetClass
asset = AssetClass (usrCurrencySymbol, TokenName "T1")

getCoins :: Integer -> Value
getCoins i = assetClassValue asset i

-------------
-- Endpoint
-------------

mintEP :: () -> Contract w TradeSchema Text ()
mintEP _ = do
    let
        val     = getCoins 1
        lookups = Constraints.plutusV2MintingPolicy (usrMintingPolicy $ PlutusTx.toBuiltinData usrParams )
        tx      = Constraints.mustMintValue val

    ledgerTx <- submitTxConstraintsWith @Void lookups tx
    void $ awaitTxConfirmed $ getCardanoTxId ledgerTx
    Contract.logInfo @String $ printf "forged %s" (show val)

I don't understand why you're using <> here, is there another asset involved?

James - I have edited my question. I also added more snippets. The minting still fails


text:
How to build the transaction needed to have a user pay to mint an NFT
I have integrated a Cardano wallet into my site and done some basic interactions.
I am hoping to get a sample, example and/or guidance on how to build the transaction I am interested in implementing:
Scenario:

User visits my site, connects their wallet.
User pays an amount of ADA or an amount of a native token to mint an NFT.
User has NFT in their wallet now, and site can verify it is there as a means of confirming paid membership.

So the transaction I need to build:
User pays an amount of ADA or a native token to mint an NFT.
=> ADA gets transferred from the users wallet to the wallet of the site, NFT gets minted and sent to users wallet.
Has anyone here done this?

This all can be done in a single transaction using lucid. Suggest you to see examples here. You can use payToContract to pay Ada / native token and simultaneously, mintAssets to mint them (in your minting script, check script context to see whether the required amount is getting transferred to required address). Can see a similar example I coded for my project here.

source: Stack Exchange

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

sort: votes


text:
Creating a connect wallet button like JPEG.store
I am creating a React app and I want to integrate a connect wallet button that can then return the users wallet address, similar to JPEG.store. What is the best way to approach this. I tried using Cardano connect with wallet https://github.com/cardano-foundation/cardano-connect-with-wallet but I cant figure out how to return the users address after they have signed in with their wallet. Any help is appreciated.

This could be solved by variety of tools:

Using Lucid, you can first enable (connect) with wallet as outlined in this simple example. Then get address via lucid.wallet.address() (it returns a Promise, so you might need to use async / await). This address is basically obtained from CIP-30's, getUsedAddresses()'s first element.
Like what you have shared in question, Mesh has a prebuilt component for it, which can be seen here. Once connected, you can get address as mentioned in this page.
Regarding library in question, can use decodeHexAddress on browser wallet api's, getUsedAddresses()'s first element.

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


text:
Is it possible to create a flutter app that would create and sign cardano transaction
I would like to create a simple mobile application using flutter that would create and sign a transaction and submit it through an API like Blockfrost to the network for which it will   interact with a smart contract address.
Is there any supporting library or any approach that can achieve this?

If you are willing to use a javascript library (see https://stackoverflow.com/questions/66145501/how-to-use-a-js-library-and-a-js-function-in-a-flutter-mobile-app) then you can try the helios library: https://github.com/Hyperion-BT/Helios
Helios should be callable from within flutter as it doesn't have any dependencies and uses pure javascript (no wasm).
With helios.js you can build transactions (https://www.hyperion-bt.org/Helios-Book/api/building/index.html). Signing however is usually done by a wallet, and for submitting to blockfrost you would have the call the blockfrost endpoint directly.
helios.js also allows compiling smart contracts written in the Helios language, but you probably won't be needing that.


text:
BlockFrost IPFS error
I can't upload an image to IPFS through
ipfs.blockfrost.io/api/v0/ipfs/add
from browser. I am trying to upload image dircetly from frontend of my application (browser extension). I get this response:
{
"statusCode": 500,
"error": "Internal Server Error",
"message": "Converting circular structure to JSON\n    --> starting at object with constructor 'Socket'\n    |     property 'parser' -> object with constructor 'HTTPParser'\n    --- property 'socket' closes the circle"
}

When I try to do the same request from node.js server everything is fine. I use the same fetch call on both front and back:
let add = await fetch('https://ipfs.blockfrost.io/api/v0/ipfs/add', {
method: 'POST',
headers: {
'project_id': 'ipfsP0t7F3zOIIl6Op5fpM3c2q3CBYyYa7em'
},
body: form
});

It seems like there is a problem on blockfrost's server side with parsing additional headers that browser adds.
Or is this behaviour intentional and I shouldn't be able to send requests from frontend? Then the error seems uninformative.
Has anybody faced a similar problem?

What is your Content-Type header?


text:
How to specify a description using cardano-cli
In cardano-cli, when I create a transaction file (.body and also .signed) the contents of the file appear to be in JSON format with 3 fields, as follows
{
    "type": "Tx AlonzoEra",
    "description": "",
    "cborHex": "84a4008282582066188ffe......

I have searched the full cardano-cli help and done multiple Internet searches, but I cannot see how I can or should use that "description" field. I'm envisioning simple plain text such as "for new account jwb". Of course that can be put into metadata, which may be best anyway. Perhaps the description field is meant to be manually or programmatically changed, if desired, before or after submission, like a post-it note memo?

There is no way to currently specify the description via cardano-cli. Some things are generated with a default description and others are not. You can modify the description as it has no bearing on serialization.


text:
Daedalus for testnets and why not use Mainnet as test environment
Last year I set up a Cardano testnet as part of the Plutus Pioneers program. I'm now using my Daedalus installation to experiment with the cardano-cli, which I am finding much easier, with the added benefit of knowing that my transactions actually work in the real world. The transaction cost so far is trivial. Is there any reason not to use the mainnet for R&D, learning, and experimentation? I can't imagine I'm stressing the network, and I'm putting only my own ADA at risk (little 2-5 ADA transactions). I can imagine I could clutter up the blockchain with pointless metadata.
Closely related, is there a way to use Daedalus to talk to the testnet?

You can download the Testnet version (all Testnets) of Daedalus from here.
You can request testing funds from the faucet, this way you never risk any of your Mainnet ADA, even if it is a small amount.
At the end testnet are created for that reason.
If you want to make your test environment the most similar to Mainnet, use Preprod environment.

I just found a very good answer for why not to use the mainnet for learning and experimentation. Fortunately I did not learn this thru experience but by reading about other's difficulties.
If ADA is sent to a script, and no datum/hash is sent, or if the order of parameters is incorrect, the ADA will be locked forever in the script (assuming the script does not also have a fail-safe endpoint built in to return funds after a time if no other endpoint is triggered).
Perhaps this problem has already been fixed as it was discussed a year ago, but I'm sure the risk remains. Fortunately I am not at the point yet of experimenting with scripts.

You can create a small local testnet yourself using the cardano-private-testnet-setup
When the network starts up it starts ~3 Nodes and creates a few wallets which then can be used for your tests.


text:
How to redelegate with JS Nami/Eternl wallets?
Could you please point how can I unstake/undelegate OR redelegate with web cardano (window.cardano) api?
I need to let users delegate to my pool even if they already delegated anywhere else, so I need to track if the user already delegated - if the user did -> unstake and delegate to my pool.
I succeed doing that will Typhon (i was just creating a new transaction for delegate), but the Nami/Eternl doesn't seem to work
Nami (doesn't work): opens the wallet popup and wants to get the full pool price and if I agree - it will fail signing the transaction
Typhon (works perfectly): opens the wallet popup and wants to get the difference between pool price + fee - the transaction signing works


text:
“USDA” is All Set to launch in Early 2023 | What services will it provide?
According to Emurgo, USDA will go live on the Anzens platform in Q1 2023, allowing users to tokenize their USD into USDA using credit/debit cards, wire transfers, or the conversion of ADA.
USDA is a component of Emurgo’s Anzens program, a larger scheme that would provide customers with a range of financial services and products based on Cardano.
Can some one detail the application/services these programs support?

Based on this EMURGO's blog post, the services and use cases that the Anzens program will have are:

Managing Web3 balance sheets
Making card payments directly with crypto
Regulated lending and borrowing of assets
Conversion to other stablecoins (not only USDA)
Conversion and swaps of other cryptocurrencies
Setting up stake pools that pay out rewards in USDA

For more information, you can check their website.

Thank you for the detailed information.

No worries! If it was helpful, you can mark the answer as accepted using the grey tick. Cheers.


text:
Clocks on Air-gapped, Offline Computers
What risks (security-related or otherwise) may potentially inaccurate clocks--that is, clocks that do not synchronize with an Internet time server--on air-gapped, offline computers used to sign transactions create for Cardano mainnet?

Time plays no role in Cardano transactions, so the computer that signs transactions doesn't need a notion of time.
You can however specify a range of slots in which your transaction is valid. (But transaction building, which is distinct from signing, is something you would usually do on an online computer, so you can also easily determine the UTxO IDs to use as inputs.)


text:
Need client side browser Javascript example on how to make ADA payments via the Eternl wallet?
I want to initiate an ADA payment via the Eternl wallet via a Javascript code in my browser based dApp.    I'm hoping I can do this in a manner in the same way Eth devs do it on Ethereum via the Metamask browser.
Can someone point me to the most current client side Javascript example for connecting to a user's Eternl wallet and triggering an ADA payment?  Also, any tutorials or general docs on the subject are greatly appreciated as long as they are not outdated.
Also, if anyone knows of an NFT marketplace or contract that would allow me to query, buy, and sell NFTs from my live auction platform I'm building, please let me know.  I am aware of The JPG Store and NFTify but so far I have been unable to determine if they an API a developer can consume to perform those operations.
Note, if this is not the right forum for Cardano developer questions, please point me to the right forum for that.  I have not had much luck with these questions on the Catalyst and Cardano Discord forums.

https://github.com/Hyperion-BT/PicoSwap could be the demo you are looking for.
Hosted here: https://www.hyperion-bt.org/PicoSwap/ (chrome only)
The demo contains example code for creating transactions (with or without smart contracts), signing, and submitting through blockfrost. All using javascript only (with the helios library).
PicoSwap is also a minimal marketplace for NFTs, so might be useable for the second part of your question (preview testnet only)

will that code also work with the Eternl wallet?

that's the only wallet I've been testing it with :P

Thanks.  If you know of a link for a TestNet ADA faucet please let me know.

You've probably found the faucet link by now, but I'll put it here for reference: https://docs.cardano.org/cardano-testnet/tools/faucet

Hi Christian.  I'm having trouble getting PicoSwap started.  Can you give me some tips?  I posted an issue on the PicoSwap GitHub repo just now with the details.


text:
Cardano mempool
I have looked at this thread: Is there any platform to read the Mempool? asking if there is a way to read the (historic) cardano mempool. Back then, there was none so I was wondering if anything has changed since then. Anyone familiar with a method/ webpage that reports historic cardano mempool transactions?

There is no "historic" mempool. The mempool is ephemeral. It is updated every time a new block arrives.
It is however possibly to reconstruct the mempool for any point in time using something like cardano-db-sync or by replaying all blocks up to a certain point in time and applying them to the ledger.


text:
Docker - Cant access cardano-cli from other container than cardano-node
I have the following problem:
I am running several containers via docker-compose consisting of a cardano-node-container, cardano-db-sync-container (including a postgres-container) AND another container which wants to access the cardano-cli in order to submit transactions. I can't get the cardano-cli command working in the container I want to submit transactions from: "cardano-cli: command not found”. I am out of ideas and not very familiar with unix-sockets.
This is my docker-compose-file (irrelevant information replaced with (...)):
version: "3.4"
services:

  homeassistant:
    image: homeassistant/home-assistant:2022.9
    (...)

  CONTAINER-TRYING-TO-ACCESS-CARDANO-CLI:
    image: (...)
    restart: always
    environment:
      - CARDANO_NODE_SOCKET_PATH=/ipc/node.socket
    volumes:
      - "node-ipc:/ipc"
    logging: (...)

  cardano-node:
    image: inputoutput/cardano-node:1.35.4
    restart: always
    environment:
      - NETWORK=mainnet
      - CARDANO_NODE_SOCKET_PATH=/ipc/node.socket
    volumes:
      - "/volume1/docker/cardano/ada-node:/data"
      - "node-ipc:/ipc"
    healthcheck (...)
    logging (...)

  cardano-db-sync:
    image: inputoutput/cardano-db-sync:13.0.5-extra-args
    restart: always
    environment:
      - NETWORK=mainnet
      - POSTGRES_HOST=cardano-postgres-db
      - POSTGRES_PORT=5432
      - RESTORE_RECREATE_DB=N
    depends_on:
      cardano-node:
        condition: service_healthy
      cardano-postgres-db:
        condition: service_healthy
    secrets:
      - postgres_password
      - postgres_user
      - postgres_db
    volumes:
      - "/volume1/docker/cardano/db-sync-data:/var/lib/cexplorer"
      - "node-ipc:/node-ipc"
    logging: (...)

  cardano-postgres-db:
    image: postgres:11.5-alpine
    restart: on-failure
    environment:
      - POSTGRES_LOGGING=true
      - POSTGRES_DB_FILE=/run/secrets/postgres_db
      - POSTGRES_PASSWORD_FILE=/run/secrets/postgres_password
      - POSTGRES_USER_FILE=/run/secrets/postgres_user
    secrets:
      - postgres_password
      - postgres_user
      - postgres_db
    volumes:
      - "/volume1/docker/cardano/db-sync-postgres-db:/var/lib/postgresql/data"
    healthcheck: (...)
    logging: (...)

secrets:
  postgres_db:
    file: ./config/secrets/postgres_db
  postgres_password:
    file: ./config/secrets/postgres_password
  postgres_user:
    file: ./config/secrets/postgres_user

volumes:
  node-ipc:

When I get into the containers bash that wants to access cardano-cli (CONTAINER-TRYING-TO-ACCESS-CARDANO-CLI) I can see, that there is the node.socket file at the defined /ipc/ folder.
Now I do not know what else to do :-/ I tried playing around with socat but couldn't figure out how to use the node-socket in order to use the cardano-cli via bash. The cardano-node is fully synced and cardano-db-sync is also working as expected. I can use cardano-cli inside the cardano-node container, but not from others.
The dirties version I can think of to accomplish this, would be installing ssh inside the cardano-node container and access the cli from the other container via sshing into the node. But this would be my last resort if you do not have any ideas for using the cli via the socket :confused:
Edit:
Okay found a solution :) The base of my "CONTAINER-TRYING-TO-ACCESS-CARDANO-CLI"-container is node:17-alpine.
I am now pulling the hydra-binaries from https://github.com/input-output-hk/cardano-node/releases, unpacking and placing them inside my /usr/local/bin folder.
Now I am able to use the cli from bash :D
This is my edited Dockerfile:
FROM node:17-alpine as node

RUN apk add curl
RUN apk add tar

# dl cardano cli-binary 1.35.4
WORKDIR /dl-bin
RUN curl https://hydra.iohk.io/build/21343721/download/1/cardano-node-1.35.4-linux.tar.gz -o cardano-node.tar.gz
RUN tar -xzf cardano-node.tar.gz && rm cardano-node.tar.gz
RUN cp -r /dl-bin/. /usr/local/bin
WORKDIR /
RUN rm -rf /dl-bin
# end dl cardano cli-binary 1.35.4

(...)

That means that container CONTAINER-TRYING-TO-ACCESS-CARDANO-CLI do not have binary cardano-cli inside(basically there are no such file) or cardano-cli is there but it is in location what is not inside path of that container, but I would guess it is a first. So this is nothing to do with /ipc/node.socket.
If that container is in docker hub, please let me know which I will try to troubleshoot further.

Hey, thanks for the response! Indeed, the binaries are not installed, because I thought I can access them through the node.socket.
Its a custom image, so I guess I need to install the cli there inside? I'll check some tutorials on how to install the ci without bloating the image too much :) After that I guess I can point cardano-cli to the node.socket (as I already do via the env-var) and it all will work?

yes, should work. Seems you made it work! Glad I was able to help. Cheers!

Yep, I got it to work :) I updated my post with my solution. Thanks again!


text:
Submit transaction with cardano-cli which got built and signed with nodejs-cardano-wasm - formatting error
I am trying to submit a transaction via cardano-cli which got built and signed by a nodejs app using cardano-wasm. I tried the following approach:

The result I get from the cardano-cli execution:

error: Command failed: cardano-cli transaction submit --tx-file /tx-files/tx.signed --mainnet
Command failed: transaction submit Error: Failed to decode neither the cli's serialisation format nor the ledger's CDDL serialisation format. TextEnvelope error: /tx-files/tx.signed: TextEnvelope aeson decode error: Error in $: Failed reading: not a valid json value
TextEnvelopeCddl error: /tx-files/tx.signed: Could not JSON decode TextEnvelopeCddl file at: /tx-files/tx.signed Error: Error in $: Failed reading: not a valid json value

Besides txToSubmit.to_bytes() I have also tried to write the tx-file with content of txToSubmit.to_json() and txToSubmit.to_hex()
But I get the same result.
Does anyone know in which format the tx-file has to be and how to get it there? Submitting via Blockfrost "txSubmit(txToSubmit.to_bytes())" works flawlessly, but I want to switch to cardano-cli :)
EDIT:
I figured out, that the tx.signed file has to be in a similar format like this:

{
    "type":"Witnessed Tx ShelleyEra",
    "description":"",
    "cborHex":"xxx(cbor-built-by-cardano-wasm)"
}

(Is the type "Witnessed Tx ShelleyEra" even correct for submitting signed transactions on mainnet?)
Could someone provide me a sample tx.signed file?
When submitting the transaction via cardano-cli (cardano-cli transaction submit --mainnet --tx-file /tx-files/tx.signed) I receive the following error:

Command failed: transaction submit  Error: Failed to decode neither the cli's serialisation format nor the ledger's CDDL serialisation format. TextEnvelope error: /tx-files/tx.signed: TextEnvelope type error:  Expected one of: TxSignedByron, TxSignedShelley, Tx AllegraEra, Tx MaryEra, Tx AlonzoEra, Tx BabbageEra Actual: Witnessed Tx ShelleyEra
TextEnvelopeCddl error: /tx-files/tx.signed: TextEnvelopeCDDL CBOR decoding error: DecoderErrorDeserialiseFailure "Shelley Tx" (DeserialiseFailure 1 "Size mismatch when decoding \nRecord RecD.\nExpected 4, but found 3.")

EDIT2:
Okay its working now :)
I played around with cli and created a new address, supplied it with ada, built and signed a transaction and thats what I got:
{
  "type": "Witnessed Tx BabbageEra",
  "description": "Ledger Cddl Format",
  "cborHex": "xxx (cbor)"
}

I was able to submit a transaction with this code:
const txToSubmit = CardanoWasm.Transaction.new(signedTransaction.body(), keyWitness, undefined);
const tempTxName = '/tx-files/tx' + Math.round(Math.random() * 99999) + '.signed';
fs.writeFileSync(tempTxName, JSON.stringify({
            type: 'Witnessed Tx BabbageEra',
            description: 'Ledger Cddl Format',
            cborHex: txToSubmit.to_hex()
        }));
exec('cardano-cli transaction submit --tx-file ' + tempTxName + ' --mainnet', (error, stdout, stderr) => {
  if (error) {
    console.log(`error: ${error.message}`);
    return;
  }
  if (stderr) {
    console.log(`stderr: ${stderr}`);
    return;
  }
  console.log(`stdout: ${stdout}`);
});


text:
Plutus: multiple-utxo withdraw fails, single-utxo withdraw succeeds
A beneficiary tries to withdraw the maximum amount from 2 utxo's of a smart contract in one transaction but that fails. If the beneficiary does it in two steps it succeeds.
Why does the first one fail?
Detail :
-------------------------------------------------------------------------
ben         | addr_test1v⋯qarpt4  | = 1101556208 |
            | - 714d2e⋯dea7cb#0   | +    1021470 | [ "ben"×1 ] Token
            | - 714d2e⋯dea7cb#1   | + 1100534738 |
-------------------------------------------------------------------------
tokencheck  | addr_test1w⋯hyha8n  | =   34000000 |
            | - 347def⋯58e2c7#0   | +   21000000 | {14e594⋯4816fa} Datum
            | - dca3bc⋯b80ae8#0   | +   13000000 | {14e594⋯4816fa} Datum

The beneficiary 'ben' tries to withdraw the maximum amount from smart contract 'tokencheck',
and in that transaction also includes his token 'ben' (62656e),  to fulfill a condition in the contract.
Ben tries to withdraw from both the utxo's of the contract (both have the same, correct datum) :
# total amount = 21000000 (contract) + 13000000 (contract) + 1021470 (ben token) - 966660 (fee) = 34054810

cardano-cli transaction build-raw
  --babbage-era
  --protocol-params-file protocol-parameters.json
  --tx-in "714d2e⋯dea7cb#0"                    # utxo with ben's token
  --tx-in "347def⋯58e2c7#0"                    # first utxo of contract
  --tx-in "dca3bc⋯b80ae8#0"                    # second utxo of contract
  --tx-in-datum-file datum.json
  --tx-in-redeemer-file redeemer.json
  --tx-in-script-file tokencheck.json
  --tx-in-collateral "714d2e⋯dea7cb#1"
  --required-signer ben.skey
  --tx-out "addr_test1v⋯qarpt4 + 34054810 + 1 2d99fb⋯63d3a1.62656e"
  --fee 966660
  --tx-in-execution-units '(3000000000,7000000)'
  --out-file tx_raw.json

This fails when submitting, with error message:
Command failed: transaction submit  Error: Error while submitting tx: ShelleyTxValidationError
ShelleyBasedEraBabbage (ApplyTxError
[UtxowFailure(
  FromAlonzoUtxowFail
    (MissingRedeemers [(Spending (TxIn (TxId {_unTxId = SafeHash "347def⋯58e2c7"}) (
        TxIx 0)),ScriptHash "5c2d3c⋯7d947b")])),
UtxowFailure (
  UtxoFailure (FromAlonzoUtxoFail (UtxosFailure (CollectErrors
    [NoRedeemer (Spending (TxIn (TxId {_unTxId = SafeHash "347def⋯58e2c7"}) (TxIx 0)))])))
    )
])

If Ben just withdraws using only ONE of the contract's utxo's, the transaction succeeds:
# total amount = 21000000 + 1021470 - 953284 = 21068186

cardano-cli transaction build-raw
  --babbage-era
  --protocol-params-file protocol-parameters.json
  --tx-in "714d2e⋯dea7cb#0"                    # utxo with ben's token
  --tx-in "347def⋯58e2c7#0"                    # one utxo of contract
  --tx-in-datum-file datum.json
  --tx-in-redeemer-file redeemer.json
  --tx-in-script-file tokencheck.json
  --tx-in-collateral "714d2e⋯dea7cb#1"
  --required-signer ben.skey
  --tx-out "addr_test1v⋯qarpt4 + 21068186 + 1 2d99fb⋯63d3a1.62656e"
  --fee 953284
  --tx-in-execution-units '(3000000000,7000000)'
  --out-file tx_raw.json

Transaction successfully submitted.

Question: why does the first transaction fail while the second succeeds?
Update
Here's the contract, it's written in Helios:
struct Datum {
    donor:        PubKeyHash
    beneficiary:  PubKeyHash
    policy:       MintingPolicyHash
}

func main(datum: Datum, ctx: ScriptContext) -> Bool {
    tx: Tx = ctx.tx;
    if (tx.is_signed_by(datum.donor)) {
        true
    } else {
        if ( tx.value_sent_to(datum.beneficiary).get(AssetClass::new(datum.policy, #62656e)) == 1) {
            true
        } else {
            print("computer says no"); false
        }
    }
}

Does contract only allows one input utxo that requires script to be consumed per transaction? Can you check or share the contract code too.

Contract added to the text above.
I don't think the problem is with the contract's code, because it would give a different error.

Yeah i see. Could it be due to build-raw requiring tx-in-script-file, datum redeemer for each input. I think it can be repeated and order matters. You can try that but not sure if it automatically uses same script, datum, redeemer for two inputs.

The solution is, as Nabin suggested, to repeat after each contract-utxo the datum/redeemer/script and execution units arguments as shown here:
cardano-cli transaction build-raw
  --babbage-era
  --protocol-params-file protocol-parameters.json
  --tx-in "344b8c⋯a3325e#0"                     # utxo with ben's token
  --tx-in "9b7697⋯dbb2e4#0"                     # contract utxo #1
  --tx-in-datum-file datum.json
  --tx-in-redeemer-file redeemer.json
  --tx-in-script-file tokencheck.json
  --tx-in-execution-units '(3000000000,7000000)'
  --tx-in "f44eee⋯db6906#0"                     # contract utxo #2
  --tx-in-datum-file datum.json
  --tx-in-redeemer-file redeemer.json
  --tx-in-script-file tokencheck.json
  --tx-in-execution-units '(3000000000,7000000)'
  --tx-in-collateral "344b8c⋯a3325e#1"
  --required-signer ben.skey
  --tx-out "addr_test1v⋯qarpt4 + 33323655 + 1 2d99fb⋯63d3a1.62656e"
  --fee 1697815
  --out-file tx_raw.json

Transaction successfully submitted.

Indeed: datum/redeemer and script need to be specified for each utxo separately


text:
How to hide API keys when using Lucid-Cardano
Lucid-Cardano requires me to expose my api key on my client side of my app. How can I go around hiding this. I have tried to call my express backend to make a blockfrost request so that I can keep my api key on the backend. It works for connecting to the wallets but it doesn't work for signing transactions. How can I go around this. I am using express backend and react front end. How can I go about this?
//This is where I try to sign the transaction on my client side

import { Lucid, Blockfrost } from "https://unpkg.com/lucid-cardano@0.7.7/web/mod.js"
import axios from 'axios'

async function connect(){
  const data = await axios.get('http://localhost:4000/blockfrost').then((res) => {
  }).catch((err) => {
    console.log(err)
  })

  const lucid = await Lucid.new(data,
    "Testnet",
   );

    const api = await window.cardano.nami.enable();
    lucid.selectWallet(api);

    const tx = await lucid.newTx()
    .payToAddress("addr...", { lovelace: 5000000n })
    .complete();

    const signedTx = await tx.sign().complete();

    const txHash = await signedTx.submit();

    console.log(txHash);

}

//This is where i connect to blockfrost

const axios = require('axios')
require('dotenv').config()

axios.defaults.headers.common = {
    "project_id": process.env.BLOCKFROST_KEY,
  };

async function connect(){
    const data = await axios.get('https://cardano-testnet.blockfrost.io/api/v0')
    return data.data
}

module.exports = {connect}

export default connect

//This is the error I get
mod.js:2 Uncaught (in promise) Error: expected instance of u_
    at c (mod.js:2:535)
    at j_.new (mod.js:2:157455)
    at new cn (mod.js:4:35867)
    at ln.newTx (mod.js:4:52734)
    at connect (makeTransaction.js:20:1)

In the README.md file of lucid, their is a blockfrost proxy example, illustrating how you could implement a proxy api call.


text:
When is valid_contract column in tx table true and a contract?
In the schema descriptions for cardano-db-sync, the valid_contract column description is as follows (link below):
"False if the contract is invalid. True if the contract is valid or there is no contract."
If TRUE, how can we know the difference between a tx that is using a contract and one that is simply me moving an asset from one wallet to another?
https://github.com/input-output-hk/cardano-db-sync/blob/master/doc/schema.md

Pretty sure you can just look at the script_size field of the tx table. If that field it greater than zero there is a script.

Thank you! I will add that as a filter and see what I see.


text:
Call Martify Smart contract by cardano-cli
I call the martify smart contract by cardano-cli but I've seen the error Command failed: transaction build  Error: The following scripts have execution failures:
the script for transaction input 1 (in the order of the TxIds) failed with:
The redeemer pointer: RdmrPtr Spend 1 points to a Plutus script that does not exist.
The pointers that can be resolved are:
fromList [(RdmrPtr Spend 1,(Spending (TxIn (TxId {_unTxId = SafeHash "c502c6f0929e9eb7562097592a71d9e4aaae01033c7c5cb685c2103c9fee070c"}) (TxIx 1)),Nothing,ScriptHash "74d2a2a31173aad514c66551190f4ca4d6eedcdd71776a04ba263de5"))]

The command of building the transaction:
cardano-cli transaction build \
    --testnet-magic 1 \
    --tx-in c1ca2d6e65360e2acc78485ea93803e6119af1864872ff8cbdd6fcdf2044d7e5#0 \
    --tx-in-collateral c1ca2d6e65360e2acc78485ea93803e6119af1864872ff8cbdd6fcdf2044d7e5#0 \
    --tx-in c502c6f0929e9eb7562097592a71d9e4aaae01033c7c5cb685c2103c9fee070c#1 \
    --tx-in-script-file marketplace.plutus \
    --tx-in-datum-file datum.json \
    --tx-in-redeemer-file buy.json \
    --required-signer ./../../common/payment3.skey \
    --tx-out "$(cat ./../../common/payment3.addr) + 9982422778 + 1 d8375cb8ece93f752c57981c7978a6b3f9e06cee44c464dd3b7b7d2b.53706f7265734e46545f33" \
    --tx-out "$(cat script.addr) + 2000000" \
    --tx-out "$(cat ./../../common/payment4.addr) + 6000000" \
    --change-address $(cat ./../../common/payment3.addr) \
    --protocol-params-file testnet-protocol-parameters.json \
    --out-file buy.draft

Which: the payment3.addr is the buyer, the payment4.addr is the seller, and script.addr is the marketplace.

Two questions:

What's the datum-hash of datum.json ?
(output of cardano-cli transaction hash-script-data --script-data-file datum.json )

I assume this is the address on which your contract is: addr_test1wp6d9g4rz9e644g5cej4zxg0fjjddmkum4chw6syhgnrmegk8l8yj
(correct me if wrong)

The PT5 error exhibit the validator func return the error code in Onchain.hs file. So I put wrong pkh code in datum. By set correct value on datum, and its work.
Here is the code I used for making transaction via cardano-cli:
# Hash the datum

cardano-cli transaction hash-script-data --script-data-file datum.json >> dhash

# PUT ON SALE

cardano-cli transaction build \
    --alonzo-era \
    --testnet-magic 1 \
    --tx-in 8b076a7b96a24af1aec65213a45636b1e45c6acfe62e368f29e6e5119e368091#1 \
    --tx-out "$(cat script.addr) + 1800000 lovelace + 1 33700cf3c3d4aa6c84d9fd8a506c6c5482e4249abe78e37829913caa.53706f7265734e46545f33" \
    --tx-out-datum-hash $(cat dhash) \
    --change-address addr_test1vqquurd5cglaqfnnusnsfy3w0u6r20hpa4hf9x75evnmhxgwcrdas \
    --protocol-params-file testnet-protocol-parameters.json \
    --out-file tx.02

cardano-cli transaction sign \
    --tx-body-file tx.02 \
    --signing-key-file ./../../common/payment4.skey \
    --testnet-magic 1 \
    --out-file tx-2.02

cardano-cli transaction submit --tx-file tx-2.02 --testnet-magic 1

# BUY NFT

cardano-cli transaction build \
    --babbage-era \
    --testnet-magic 1 \
    --tx-in c1ca2d6e65360e2acc78485ea93803e6119af1864872ff8cbdd6fcdf2044d7e5#0 \
    --tx-in-collateral c1ca2d6e65360e2acc78485ea93803e6119af1864872ff8cbdd6fcdf2044d7e5#0 \
    --tx-in f2134f93278707a37a1ef03abac76e7fc38dd9796c1143f25953448efbd3fdca#1 \
    --tx-in-script-file marketplace.plutus \
    --tx-in-datum-file datum.json \
    --tx-in-redeemer-file buy.json \
    --tx-out "$(cat ./../../common/payment3.addr) + 9982422778 + 1 33700cf3c3d4aa6c84d9fd8a506c6c5482e4249abe78e37829913caa.53706f7265734e46545f33" \
    --tx-out "$(cat ./../../common/payment4.addr) + 6000000" \
    --required-signer ./../../common/payment3.skey \
    --change-address $(cat ./../../common/payment3.addr) \
    --protocol-params-file testnet-protocol-parameters.json \
    --out-file tx.04

cardano-cli transaction sign \
    --tx-body-file tx.04 \
    --signing-key-file ./../../common/payment3.skey \
    --testnet-magic 1 \
    --out-file tx-2.04

cardano-cli transaction submit --tx-file tx-2.04 --testnet-magic 1

Link to check on preprod cardanoscan: https://preprod.cardanoscan.io/address/6001ce0db4c23fd02673e42704922e7f34353ee1ed6e929bd4cb27bb99


text:
getDirectoryContents:openDirStream: does not exist
Running cabal update within nixos in my app fails with the following:
$HOME/my-app/dist-newstyle/src/plutus-ap_-cbcc5c6ab544aad6/web-ghc: getDirectoryContents:openDirStream: does not exist (No such file or directory)

Any help would be appreciated.

Same here. Trying to run cabal

I've been able to figure out the cause

It turns out that the problem is caused by the cabal.project file in plutus-starter template.
In the following section:
-- Plutus apps revision from 2022-04-06
source-repository-package
  type: git
  location: https://github.com/input-output-hk/plutus-apps.git
  tag: v0.1.0
  subdir:
    doc
    freer-extras
    playground-common
    plutus-chain-index
    plutus-chain-index-core
    plutus-contract
    plutus-example
    plutus-contract-certification
    plutus-ledger
    plutus-ledger-constraints
    plutus-pab
    plutus-pab-executables
    plutus-playground-server
    plutus-script-utils
    plutus-streaming
    plutus-tx-constraints
    plutus-use-cases
    web-ghc

An obsolete plutus-apps tag is still being used and it is expected that web-ghc folder is still present.
To fix the issue, I repaced the above subdir section with the following (found in the packages section in cabal.project file of the latest version of plutus-apps):
cardano-streaming
doc
freer-extras
marconi
marconi-mamba
playground-common
pab-blockfrost
plutus-chain-index
plutus-chain-index-core
plutus-contract
plutus-contract-certification
plutus-example
plutus-ledger
plutus-ledger-constraints
plutus-pab
plutus-pab-executables
plutus-script-utils
plutus-tx-constraints
plutus-use-cases
rewindable-index

And then replacing the tag with the latest tag found here

I am getting the same but for cardano-b_-c0de99f0ccd585cd/strict-containers: cardano-b_-c0de99f0ccd585cd/strict-containers: getDirectoryContents:openDirStream: does not exist (No such file or directory). Do you know what I can do? Thanks

what plutus-apps tag are you using? there seem to be an obsolete reference to strict-containers in cardano-binary. Perhaps, the version of cardano-binary is what's obsolete. You might want to give it a look


text:
tx_metadata: How to interpret a CBOR string
In the document:
https://github.com/input-output-hk/cardano-node/blob/master/doc/reference/tx-metadata.md
We are told: "JSON strings are represented as CBOR strings"
How can I interpret these?
The source of th eformat of those appears to be here:
https://www.rfc-editor.org/rfc/rfc7049
Here is an example of one from a transaction in the tx_metadata table of cardano-db-sync

d8799f581c25fa506339b24dc4e1a643637325e700ae498e646746a5426739f2

...there is this:
https://github.com/CardanoSharp/CBOR
...and this:
https://github.com/input-output-hk/cardano-node/blob/master/doc/reference/tx-metadata.md
...and this:
https://input-output-hk.github.io/cardano-wallet/user-guide/common-use-cases/TxMetadata

A good tool for manually analyzing CBOR is https://cbor.nemo157.com/
What they probably meant by "JSON strings are represented as CBOR strings" is that typical JSON objects can be represented in tx-metadata using CBOR

I am trying to figure out how a value like this one, in the object, is a value that decodes to a wallet address:
BAED3AE13D7EEB93BB4B4F44E10AFF9F1FC052869F4A1CD1501BE928

I don't think there are any easy-to-use online tools for converting the hex of, I'm assuming, a pubkeyhash into a bech32 encoded address. You would have to use a library. Eg. with Javascript and Helios: let isTestnet=true;helios.Address.fromPubKeyHash(isTestnet, helios.PubKeyHash.fromHex(" BAED3AE13D7EEB93BB4B4F44E10AFF9F1FC052869F4A1CD1501BE928")).toBech32() which results in addr_test1vzaw6whp84lwhyamfd85fcg2l703lszjs60558x32qd7j2qnwhmq3


text:
How to import Plutus.Contracts.Currency
I am trying to build an application that will make use of function mintContract under Plutus.Contracts.Currency, but i have difficulty importing this module. What can i do?

You can import it as follows as then use it with Cur.mintContract.
import Plutus.Contracts.Currency qualified as Cur

Thanks for your reply. But maybe i should have been more explicit on what i've tried before. I did try "import Plutus.Contracts.Currency qualified as XXX", but it said "Could not find module `Plutus.Contracts.Currency'". I tried this on my local playground and https://playground.plutus.iohkdev.io/, it shows the same error message.
I am not sure if it is due to the playground not being up-to-date.

Hey, it seems at the end i can get around with mintContract with singleton and mustMintValue and achieve the same purpose.


text:
How to load test Nami with Vesting example?
I'm working through week3 of PPP#4:
https://www.youtube.com/watch?v=C8TuGSzhqXU&list=PLNEK_Ejlx3x2zXSjHRKLSc5Jn9vJFA3_O&index=5]
Here, the Vesting example using Lucid is demo and while I'm able to load the dApp on my browser with npm start and I have a Nami wallet connected to the Preview network, its info/ PubKeyHash is failing to populate dApp like in the video. I'm not sure how to get the dApp to link with the browser wallet to create example transactions locally

I was using the instructor's old API key instead of creating one for myself through blockfrost. I just had to modify the section:
async function loadCardano() {
    const nami = window.cardano.nami;
    if (!nami) {
        setTimeout(loadCardano);
    } else {
        const api = await nami.enable();
        console.log('nami enabled');
        const lucid = await L.Lucid.new(
            new L.Blockfrost("https://cardano-preview.blockfrost.io/api/v0", "XXXX"),
            "Preview",
        );
        console.log('lucid active');
        lucid.selectWallet(api);
        return lucid;
    }
}


text:
How to get ALL used addresses of a Daedalus wallet (byron era) with cardano-cli
i'm looking for a way to get ALL used addresses of a Daedalus wallet (byron era) with the cardano-cli.
Background:
Daedalus is not showing up the used addresses combined under a "Recieve" tab, like it does for Shelly wallets. One can only click through all transactions an guess what addresses belong to the wallet. This is pretty time consuming and error prone, especially when there are transactions with multiple out-/inputs.
My hope is, to utilize the cardano-cli for that purpose. I already managed to install the cli and set it up to use the Daedalus socket. But further i didn't come. Can someone please hive me a hint where to start.
Thanks for any tips!

This is not possible directly using the cardano-cli. You can use a third party tool to do this, like blockfrost.
A simple curl command using your free project id would look like this.
curl -H "project_id: REPLACE WITH YOUR PROJECT ID" https://cardano-mainnet.blockfrost.io/api/v0/accounts/REPLACE WITH YOUR STAKE ADDRESS/addresses

thanks for your answer, but byron era wallets don't have a staking address.


text:
Catalyst App still showing Fund9 instead of Fund10 and connection in progress as of 26/6/2023
The Catalyst App has not been updated since 2022 and gives only information about Fund9 as of June. When will the Fund10 voting round be available in the app and my wallet registration completed?

Same question asked here (but with an answer):
https://forum.cardano.org/t/fund-10-registration/117712/5


text:
Can we Make a Multi-witness transactions using cardano Serialization Lib?
My Goal is to Transfer NFTs from one Wallet to another and use second wallet to cover my transaction fee.
According to this article https://developers.cardano.org/docs/integrate-cardano/multi-witness-transactions-cli/ this is possible can any one Point out where is my mistake.
Here is my code for Creating the TX
  try {
 // Policy For FiNFTS
    const policyId = Buffer.from(
      Wallet.nativeScript.hash(0).to_bytes()
    ).toString("hex");
    // Asset Utxo We Want to Transfer
    const SenderUtxos = await getLockedUtxosByAsset(
      Sender.paymentAddr,
      policyId + Asset
    );
    console.log(SenderUtxos);
    //Creating TX
    let { txBuilder, utxos } = await getTxBuilderAndUtxos(Wallet);
    //Adding Asset Output To the Receiver
    const MultiAsset = lib.MultiAsset.new();
    const Assets = lib.Assets.new();

    const assetName = lib.AssetName.new(Buffer.from(Asset, "hex"));
    const assetNumber = lib.BigNum.from_str("1");
    Assets.insert(assetName, assetNumber);

    MultiAsset.insert(Wallet.nativeScript.hash(0), Assets);

    txBuilder.add_output(
      lib.TransactionOutputBuilder.new()
        .with_address(lib.Address.from_bech32(Receiver.paymentAddr))
        .next()
        .with_asset_and_min_required_coin(
          MultiAsset,
          lib.BigNum.from_str("38890")
        )
        .build()
    );

    // Add Asset Utxo To Our Input Utxo List
    let converted = await Promise.all(
      SenderUtxos.map(async (utxo) => {
        console.log(utxo);
        return await utxoFromJson(
          utxo,
          lib.Address.from_bech32(Sender.paymentAddr).to_bytes()
        );
      })
    );
    converted.map((Utxo) => {
      utxos.add(Utxo);
    });
    // Add Input In Our TX
    txBuilder.add_inputs_from(utxos, 2);
    // Add Change Address to Return the Remaining Amount
    txBuilder.add_change_if_needed(lib.Address.from_bech32(Wallet.paymentAddr));
    const tx = txBuilder.build_tx();

    const user = await User.find({ email: "dawar33011@gmail.com" });
    const entropy = await Decrypt(user[0].entropy);
    console.log(entropy);
    const SenderKeys = getPaymentKeyFromEntropy(entropy);
    console.log(SenderKeys);
    const txVkeyWitness = signTxWithTwoWallets(SenderKeys, Wallet, tx);

    const transactionWitnessSet = tx.witness_set();
    transactionWitnessSet.set_vkeys(txVkeyWitness.vkeys());
    console.log(txVkeyWitness.vkeys().len());
    const signedTx = lib.Transaction.new(
      tx.body(),
      transactionWitnessSet,
      tx.auxiliary_data()
    );
    let txhash = await submitTx(Buffer.from(signedTx.to_bytes(), "hex"));
    console.log(txhash);
  } catch (error) {
    console.log(error);
  }

};

Here is The Code for Signing the Tx With my two different Wallet
export const signTxWithTwoWallets = (wallet1, wallet2, tx) => {
  const rawTx = tx;
  const txWitnessSet = lib.TransactionWitnessSet.new();
  const vkeyWitnesses = lib.Vkeywitnesses.new();
  const txHash = lib.hash_transaction(rawTx.body());
  const vkey = lib.make_vkey_witness(txHash, wallet1.paymentKey);
  vkeyWitnesses.add(vkey);
  const vkey2 = lib.make_vkey_witness(txHash, wallet1.stakeKey);
  vkeyWitnesses.add(vkey2);
  const vkey3 = lib.make_vkey_witness(txHash, wallet2.paymentKey);
  vkeyWitnesses.add(vkey3);
  const vkey4 = lib.make_vkey_witness(txHash, wallet2.stakeKey);
  vkeyWitnesses.add(vkey4);
  txWitnessSet.set_vkeys(vkeyWitnesses);
  return txWitnessSet;
};


text:
Lucid vesting demo
I'm running into the follow Lucid error from Week4 of Plutus pioneer program:
/workspace/code/Week04/lecture# deno run -A lucid-vesting.ts
error: Uncaught (in promise) TypeError: Cannot convert undefined to a BigInt
      keyDeposit: BigInt(result.key_deposit),
                  ^
    at BigInt (<anonymous>)
    at Blockfrost.getProtocolParameters (https://deno.land/x/lucid@0.10.6/src/provider/blockfrost.ts:39:19)
    at async Function.new (https://deno.land/x/lucid@0.10.6/src/lucid/lucid.ts:56:34)
    at async file:///workspace/code/Week04/lecture/lucid-vesting.ts:19:15

I tried updating the import to use the latest Lucid version, but it didn't help:
from "https://deno.land/x/lucid@0.10.6/mod.ts"
I'm not sure what these type errors mean

The result.key_deposit is undefined, which means it is not set to a value (and not null either). BigInt() expects you to provide a valid integer number either as a number or a string. Therefore BigInt() throws an error when you provide undefined instead.
Check what happens in your code before this line to figure out why result.key_deposit doesn't contain a number.
See BigInt coercion for more info on BigInt  errors.
One likely pitfall I can see is that you might not have replaced the Blockfrost API key:
// set blockfrost endpoint
const lucid = await Lucid.new(
  new Blockfrost(
    "https://cardano-preprod.blockfrost.io/api/v0",
    "insert you own api key here" // <-- REPLACE THIS WITH A REAL API KEY
  ),
  "Preprod"
);


text:
How to obtain the public key hash in on chain plutus validator?
It seems public key hash is generated from blake2b_224 but in on-chain validator we only have blake2b_256. Is there any way to obtain public key hash from public key in cardano plutus?


text:
PubKeyHash datatype vs BuiltinByteString for serialising scripts
In one of the utility function for serialising validator functions, we have
validator :: PubKeyHash -> Validator

and
saveVal :: PubKeyHash -> IO ()

I was able to compute the PubKeyHash for my test wallet, but within the cabal repl, I'm getting different script addresses when I serialise the contract with:
:set -XOverloadedStrings
import PlutusTx
import PlutusTx.Builtins
import Plutus.V1.Ledger.Crypto

saveVal (PubKeyHash ("f8493..." :: BuiltinByteString))

vs with
saveVal "f8493..."

I'm not sure why this is the case. How am I suppose to "give" the pubkeyhash to the function?

You're right, that won't store the PubkeyHash as the literal ByteString you want. We can see that by trying:
ghci> PubKeyHash "f778997b5e0fcaec19b7580bc23d010d24de9eea16f0275b5e766046"
6637373839393762356530666361656331396237353830626332336430313064323464653965656131366630323735623565373636303436

One way round is to use fromHex. For example, define a function using it to convert its output to BuiltinByteString:
import PlutusLedgerApi.V1.Bytes qualified as P
import PlutusTx.Builtins qualified as BI

bytesFromHex :: BS.ByteString -> BI.BuiltinByteString
bytesFromHex = BI.toBuiltin . P.bytes . fromEither . P.fromHex
  where
    fromEither (Left e)  = error $ show e
    fromEither (Right b) = b

(note that Plutus.V1.Ledger.Bytes changed to PlutusLedgerApi.V1.Bytes)
Then use to produce PubKeyHash:
PubKeyHash (bytesFromHex "f778997b5e0fcaec19b7580bc23d010d24de9eea16f0275b5e766046")
f778997b5e0fcaec19b7580bc23d010d24de9eea16f0275b5e766046


text:
Is it possible to generate secp256k1 addresses?
CIP-0049 introduces the secp256k1 elliptic curve to Cardano in order to provide the corresponding ECDSA/Schnorr signatures as primitives. What I don't understand about this is whether those primitives are restricted to be used in smart contract or if I can have a simple address generated from a secp256k1 public key.
Note: I'm new to the cardano ecosystem, so I apologize if I misused some concepts or terms.

SECP256k1 is currently just the verify functions for ECDSA/Schnorr signatures in a plutus script (smart contracts). Cardano uses ed25519 for its payment key pairs that addresses are derived.


text:
Lucid Vesting demo, signing from two different accounts but same seed
I'm working through the beneficiary vesting example where we have two beneficiaries: beneficiary 2 (giver who can reclaim funds after deadline), and beneficiary 1 (must claim gift before deadline).
In the demo lucid claim function, i tried to parametrize the signer function like so
async function claimVestedFunds(beneficiary: string): Promise<TxHash> {...

But I set up the wallet from the point of view of beneficiary 2 (wallet address):
lucid.selectWalletFromSeed(secretSeed);
const addr: Address = await lucid.wallet.address();
const details: AddressDetails = getAddressDetails(addr);
const beneficiary2: string = details.paymentCredential.hash

Then I hard-coded beneficiary 1 PKH into the Vesting datum, but I'm not sure how to get 1 to do the signing in claimVestedFunds
      const tx = await lucid
            .newTx()
            .collectFrom(ourUTxO, Data.void())
            .addSignerKey(beneficiary)
            .attachSpendingValidator(mistery1)
            .validFrom(Date.now()-100000)
            .complete();

I thought this would work because these two beneficiaries are actually derived from the same seed phrase (i control both accounts).
My code appears to allow beneficiary 2 to vest and reclaim, but i'm not sure how to allow beneficiary 1 to sign

The process for beneficiary 1 to reclaim the vested funds would be the same as for beneficiary 2. The only difference is that instead of passing in the seed phrase to generate the wallet, you would pass in the public key hash (PKH) of beneficiary 1.
You can create the wallet by passing in the PKH of beneficiary 1 to the selectWalletFromHash() function:
lucid.selectWalletFromHash(beneficiary1PKH);
You can then construct the transaction and use the same logic used for creating the transaction for beneficiary 2, but instead of passing in the seed phrase to add the signer key, you'll pass in the PKH of beneficiary 1.
const tx = await lucid
.newTx()
.collectFrom(ourUTxO, Data.void())
.addSignerKey(beneficiary1PKH)
.attachSpendingValidator(mistery1)
.validFrom(Date.now()-100000)
.complete();
Once you have created the transaction, you can send the transaction using the send() function.
Hope this helps!

unfortunately I am getting the error that "lucid.selectWalletFromHash" is not a function.  do you know where it might be defined?

Were you able to work this out?  I believe the command you had to use is "lucid.selectWalletFromPrivateKey(beneficiary1PKH)" .


text:
parse signed transaction error
I am using the cardano-serialization-lib to derive addresses and create a transaction unsigned.. See below
const signed_transaction = await cardanolib.Transaction.new(
newTx.body(),
witnesses,
undefined //metadata
);
Then I submit the signed transaction to the blockchain using the rosetta-api's /construction/submit endpoint， return failed：
{
"code": 5003,
"message": "Parse signed transaction error",
"retriable": false
}
What kind of encoding is required to submit a transaction signed with serialization lib with rosetta-api?


text:
Why does api.getRewardAddresses() return an array and does it matter?
The Cardano dApp-Wallet Web Bridge exposes an api.getRewardAddresses() function. This resolves to an array of stake keys, but I have only seen it contain one stake key in practice.
I'm developing a web app and want to store information about users' owned NFTs in a database. Can I use the first element in the stake keys/reward addresses array to identify the user, or should I show a dialogue window that allows the user to choose one? I am not aware of how most sites typically handle this.

The reason for the return type to be an array is CIP-18 (while it is not implemented yet, it is already taken into account in the web wallet bridge specification CIP-30).
So currently there should not be more than one stake key returned by api.getRewardAddresses().
However: Have a look at the mangled-addresses tag to find some more info about possible issues with looking at the stake key to identify ownership of NFTs. In short: Just because a wallet controls an address doesn't mean that it is the owner of the stake key part of the address.

Thanks for the help!


text:
VSCode setup for Typescript with Lucid and Deno
Although all my code have been compiling successfully, in VSCode linting for .ts files, I get a warning message for "Could not find name Deno" and "Could not find module '"https://deno.land/x/lucid@0.8.3/mod.ts' or its corresponding type declarations"
I do have the VScode extensions installed for both Deno and typescript, but I'm not sure what else to do. Also, these typescript files are within an Aiken project directory.


text:
Could someone explain mangled addresses to me?
I am developing a dApp where a user can send a few ada (3) to an address that I am listening to on my backend server, and I send a few tokens back depending on what NFTs they have in the wallet. When the transaction is received, I get the stake key from the sender's address using the Blockfrost API and read all assets they control. I then calculate how many tokens they are owed and send those to them.
I have seen mangled addresses mentioned a few times when developing, but I'm still struggling to wrap my head around them or understand if they would affect my app. Any insight would be much appreciated.

A Cardano/ADA address consists of two components; a spending credential and a staking credential.
By default, the spending and staking credential are derived from the same private key. However it is also possible to create an address from spending and staking credentials from different private keys. This is a mangled address.
For these mangled addresses, the ADA attached to the spending credential is what determines how much staking rewards are earned, but any rewards accruing due to this ADA can only be spent by the holder of the private key that generated the staking credential.

And specifically to your question (and continuing from Erik's answer), yes this can potentially affect your app.  The issue is that since the address may be one of these mangled (or "frankenstein") addresses, if you naively send the rewards to this address they may not be going to the intended person.
One method some people use is to check for the first registration of the staking address, which should normally be by the "real" owner.

What do you mean by the "first registration" and are there any common methods of checking that?

In provider's like blockfrost, when you want to receive list of addresses having a particular staking part, it allows giving this list, sorted with time it first appeared on chain. See https://docs.blockfrost.io/#tag/Cardano-Accounts/paths/~1accounts~1%7Bstake_address%7D~1addresses/get.

Ok, so if I use the "accounts/{stake_address}/addresses" endpoint and send rewards to the oldest address in the list, I will be safer. Is there any risk that when I use the "accounts/{stake_address}/addresses/assets" endpoint it will return assets that the account doesn't own?

yes but only the real owner of the tokens could spoof them to another staking address, which makes no sense for him


text:
Transfer funds to "heir" - Possible?
Is it possible to write a smart contract in cardano - without off-chain solutions - that would hold funds until a specified date (or block height), and if I didn't interact with that smart contract until that date/block it would send the funds to other wallets, that would be hard-coded into the SC?
If so, how? And is it possible to stake funds that are locked in a smart contract?
My guess is that it's not possible to make the smart contract know the tip of the chain, so a SC like that wouldn't be doable without an off-chain companion. Am I right? And is it also true for other chains and languages?

No, because there is no mechanism to build and submit transactions on-chain.
The closest option to what you want would be to create a simple timelocking script and send funds to the script's address. However, to unlock the funds, a transaction will need to be constructed off-chain and submitted once the slot boundary has passed.

Thanks. Do you know if this would be feasible in other networks? Is it a Cardano limitation, or something common to every blockchain?


text:
Different types of Datums
I have a good understanding of the role of Datums in Cardano's Extended UTXO model, including their use in representing the state of a smart contract. However, I'm seeking further clarification on the different types of Datums that can be used, such as inline and hashed Datums. Could someone elaborate on the various types, their specific uses, and the considerations for choosing between them in the development of smart contracts?

The Inline Datum was introduced with the Vasil Hard Fork (https://cips.cardano.org/cips/cip32/). Before this, only using a Datum Hash was possible. Using a Datum Hash is more difficult for a decentralized application, because the Datum has to be shared off-chain between all parties who are doing transactions.With Inline Datums, it becomes a lot easier, because the Datum is visible on-chain.

There is another point here as well, in addition to George's. The addition of "reference inputs" (https://cips.cardano.org/cips/cip31/) also means that it is possible to use datum without spending the corresponding UTxO, as was necessary before.  This also expands the use-cases and makes dealing with (for example) concurrency and shared state easier.

This is also how the Oracles in Cardano are working, they publish their information in a Datum, which can be used (as a reference input) multiple times by different DApps.


text:
How to handle sensitive data in smart contracts?
I'm interested in creating an escrow smart contract using Plutus, where a seller stores an encryption key in the Datum and sells it for a price. The key should only be accessible to a buyer who pays the required price. Considering that data in the Datum is publicly visible on the blockchain, what strategies or methodologies could I use to securely store and transfer sensitive information like this within the constraints of Cardano's smart contract model?

Storing secrets on the blockchain is not possible. Also, transferring secrets is not advisable because doing it via blockchain means publishing it to everybody.
For any real world scenario, I can think of, this makes the blockchain unsuitable for this type of transactions.
Now, if you are fine with the blockchain only playing the role of witness, i.e. a ledger showing that a secret has changed owner, than you can implement a protocol that treats the hash of the secret as the value to be transferred. The actual secret would need to be transferred off-chain. Any dispute could use the blockchain as proof-of-transaction though.
You can take it one step further and implement the messaging channel for the transfer of the secret on-chain. You could have the buyer publish single-use public encryption keys that the seller uses to encrypt the secret. The encrypted secret would then be pushed to the blockchain in a transaction. With this solution, you can of course not prove on-chain that the actual secret that corresponds to the hash was published in the transaction. But in case of dispute, both parties could have the transfer of the secret verified by an arbiter to whom the buyer would disclose the private key corresponding to the used public key.


text:
What alternatives to Eternl mobile wallet with dApp connectors do exist for Cardano?
I'm currently using Eternl on my mobile phone to connect to and use dApps. However, they only allow a select few dApps to be used within the wallet and on top of that charge a fee for using dApps like Minswap.
Are there any other Cardano mobile-wallets that support dApps, preferably without restrictions, so I can connect to any website I want? And if not, are there any other mobile-wallets that support dApp connection?

The mobile version of Flint Wallet is said to support arbitrary CIP30 dapps. For example, I've successfully run Marlowe transactions on Mobile using Flint.


text:
After transaction, how to display Transaction ID?
After signing a transaction (using Lucid), how can i display the transaction id?

Nevermind, I figured it out.
// Display success message with transaction ID as a link
const transactionLink = 'https://cardanoscan.io/transaction/' + txHash;
successMessageDiv.innerHTML = 'Success! Transaction ID: ' + txHash + '';


text:
Are all node-to-node and node-to-client mini-protocols available both over a network socket and a local socket?
There doesn't seem to be any cli flags available for cardano-node to run a subset of them.
Also, can the "locations" at where the mini-protocols are run be configured with the --socket-path and --host-addr/--port flags? I.e, when not specifying any of them, the mini-protocols won't be served over that method?


text:
Allowing users to select wallet to connect to website
I am looking for guidance on how I integrate the opportunity for users to select their wallet from a list which is then connected to my page. I have Nami working but when I try call for other wallets they do not seem to function.  the code I am working from is;
<button id="button" style="width: 200px; height: 30px;">
 connect wallet
</button>
<script>
    var button = document.getElementById("button");
    var status = document.getElementById("Status");

    async function connectWallet() {
      try {
        await cardano.enable();
        if (typeof window.cardano === "undefined" || typeof window.cardano.nami === "undefined") {
          throw new Error("Please install Nami Wallet");
        } else {
          const api = await window.cardano.nami.enable();
          const addresses = await api.getUsedAddresses();
          console.log(addresses);
        }
      } catch (error) {
        status.innerHTML = error.message;
      }
    }

    button.addEventListener("click", connectWallet);
</script>

Thanks in advance

If the wallet follows CIP-0030 the cardano object should be injected into global namespace and you can iterate through all objects that have an apiVersion, icon and name .
I tested this out with Nami, Eternl and Lace. All three were detected.
const isBrowser = () => typeof window !== 'undefined';
var cardano = window.cardano;
if (isBrowser() && window.cardano && window.cardano.enable) {
  for (const i in cardano) {
    const wallet = cardano[i];
    if (wallet.apiVersion !== null && wallet.icon != null && wallet.name !== null)   {
        // Do something with the 'name' variable here
        console.log(wallet.name);
    }
  }
}


text:
Incorrect formulation of valid state in "Small Step Semantics for Cardano" document?
The "Small Step Semantics for Cardano" document, specifies the following for valid state:

Regarding the second condition above, is it implicitly assumed that t is the consequent of rule r?


text:
Critical dependency: the request of a dependency is an expression
I keep receiving this:
Is it normal or i missed something?
- ready started server on 0.0.0.0:3000, url: http://localhost:3000
- event compiled client and server successfully in 1247 ms (18 modules)
- wait compiling...
- event compiled client and server successfully in 254 ms (18 modules)
- wait compiling /_error (client and server)...
- warn ./node_modules/@emurgo/cardano-serialization-lib-browser/cardano_serialization_lib_bg.js
Critical dependency: the request of a dependency is an expression

Import trace for requested module:
./node_modules/@emurgo/cardano-serialization-lib-browser/cardano_serialization_lib_bg.js
./node_modules/@emurgo/cardano-serialization-lib-browser/cardano_serialization_lib.js
./node_modules/@meshsdk/core/dist/core.js
./node_modules/@meshsdk/react/dist/react.js
- warn Fast Refresh had to perform a full reload. Read more: https://nextjs.org/docs/messages/fast-refresh-reload
- warn ./node_modules/@emurgo/cardano-serialization-lib-browser/cardano_serialization_lib_bg.js
Critical dependency: the request of a dependency is an expression

node versions LTS 18 and 16
Win/Ubuntu 20/22
url: https://meshjs.dev/guides/nextjs
It seems to be working fine, but how can I get rid off?
It installs @meshsdk/core 1.5.2 but can't upgrade to 1.5.4 due to @meshsdk/react@1.1.7
Thanks in advance!


text:
division amount to multi cardano address
There is a way to split a Cardano address among several addresses, for example, deposit an amount to one address and divide it equally among the holders of 100 NFTs.
thanks


text:
How to stake NFT without locking?
I am developing NFT staking platform.
And I want not to lock the NFT while it is staked.
(Users can move their NFTs at anytime)
But to do so, I have some problems.
How to calculate the rewards for this NFT?
(I was planning to distribute my token: Native Token not ADA, to users for staking their NFTs.)
But what if the user once puts their NFTs on staking pool and then get it back to their wallet, and put it back again (to receive rewards)?
Can you help me to decide how to calculate the rewards fairly?
Thank you.

An easy way to do this would be to take a snapshot of the staked NFTs at the end of every epoch (or any other pre-defined timeframe). This would mean that the NFTs are not locked, but would have to stay staked for at least 1 epoch go generate rewards.
Or you could track every single NFT to see from when to when it was in the staking pool and only count that time for the rewards. This would require you to process all future transactions for all NFTs that enter your stake pool.

Thank you, very much.
This is really helping.
But I'd love to know more about it.
Can I discuss with you further?

Well, I have thousands of NFTs, and to track them is really heavy work.
Can you suggest me the way to take the snapshot easily?

Without knowing the implementation details of your app, it's hard to give detailed advice. But have a look at APIs like https://api.koios.rest/ or https://blockfrost.io/, those can give you a lot of blockchain data in a simple REST call.

Eddex, can we discuss further in DM? (Discord, Telegram?)

If you have specific questions, I'm happy to help you here on StackExchange.

Okay, Thank you. @eddex.
Here is my question.
I am now trying to distribute the rewards in my own Native Token (not ADA) to delegators to my pool with ADA AND my custom NFT.

To do so, I am going to take the snapshot of delegators and each delegator owns how many NFT.
But there are total thousands of NFTs, and I don't know how to do it efficiently.
Can you help me?

I don't think there is much you can do to improve the performance of this. Checking the amount of NFTs each delegator holds should not be too expensive. And even if it takes a while to execute this, it should not be a problem since it is not a time/performance critical task.


text:
Maximum transaction fees possible & maximum ada needed for collateral as per current protocol parameters
As per my understanding, the formula to calculate for the transaction fees is a * tx' + b where tx' is the size of the transaction (in bytes).
Now the current value of a & b is 44 & 155381 respectively and bounding tx' by 16384, I get that fees is always <= 0.876277 ada. And therefore the ada only balance needed as collateral should always be <= ⌈1.5 * 0.876277⌉ = 1.314416 ada (collateral percentage is set to 150 inside current protocol parameters).
Is the above formulation correct?

Your formula is correct if no Plutus script is executed in the transaction. If a Plutus script validates the transaction, then one needs to add the cost of the most costly possible Plutus script. Here is a recipe: Language.Marlowe.Runtime.Transaction.Constraints.maximumFee.
The collateralPercentage procotol parameter will tell you how much greater than the fee the collateral requirement is. Currently it is 150%..


text:
How to take the snapshot of staking NFTs?
Last time I asked how to stake NFT without locking, and @Eddex gave me answer.
How to stake NFT without locking?
His answer is about to take the snapshot every epoch and track the NFTs so we can calculate the rewards according to the time, they are staked.
But if I have thousands of NFTs, this is really heavy work.
Can anybody suggest me the easy way to take the snapshot?
Or any other way to stake NFTs without locking and calculate the rewards.
Thank you.

How does your stake- and unstake-mechanism work? Where do you keep track of what NFTs are staked?

You can use an API such as blockfrost.io to fetch the data about the state of your NFTs at given time.


text:
Programmatically write and submit a smart contract
Title. Any ways to accomplish this? Preferrably in react/javascript
Edit: downvote me to oblivion!!

To avoid being downvoted, try to add more detail to your question instead of just writing "Title". If you post a vague question, you'll most likely only get a vague answer.

You can use plu-ts to create a smart contract in Typescript, and then use Mesh (Web3 SDK) in your React project to interact with the Smart Contract.


text:
Issue with Lucid and sending tokens
Any ideas of why this isn't working? I obviously removed the Blockfrost ID and address, and I have enough tokens to send. For some reason it keeps saying Inputs Exhausted. Any help appreciated.
import { Blockfrost, Lucid } from "/mod.js";

const lucid = await Lucid.new(
  new Blockfrost("https://cardano-mainnet.blockfrost.io/api/v0", "mainnet...")
);

// Assumes you are in a browser environment
const api = await window.cardano.nami.enable();
lucid.selectWallet(api);

const policyId = "2b28c81dbba6d67e4b5a997c6be1212cba9d60d33f82444ab8b1f218";

const tx = await lucid.newTx()
  .payToAddress("addr1...", { [policyId]: 100n })
  .complete();

const signedTx = await tx.sign().complete();

const txHash = await signedTx.submit();

console.log(txHash);

A token has two components, it's name & corresponding policy-id. Thus, instead of .payToAddress("addr1...", { [policyId]: 100n }) you need to do .payToAddress("addr1...", { [token]: 100n }) where token is defined as concatenation of policy-id & name, like const token = policyId + tokenName.

I'm sorry, I am not following.
Can you write out the full script so I can try and understand what you are trying to correct?

Let's say that the name of the token you wish to send is "BTC" (const tokenName = "BTC"). So  as mentioned in this answer, you need to update payToAddress like payToAddress("addr1...", { [policyId + fromText(tokenName)]: 100n }). You can import "fromText" from "/mod.js" itself.


text:
How to create wallets without a full node (cardano light client)
The only useful resource I could find is the .NET package cardanosharp-wallet which is not ideal since I don't know .NET.
Are there alternatives in other languages, for local wallet generation (also supporting sub-accounts)?
I found multiple REST APIs that I can use to interact with the chain without having a full node locally (for faster developing & testing), but what I miss is the starting point: being able to create wallets!
As for the official docs, both cardanocli-js and cardano-wallet-js depend on cardano-node, either directly or through cardano-wallet
I don't understand the full node requirement since I can prompt txs from my (off-chain) app-created accounts to the browser wallets using the common API. Is it needed to generate the CBOR even for simple send/stake transactions?
What would be the minimal tools needed that are part of cardano-wallet package?
Thank you

I guess you are familiar with JS/TS so I suggest you use https://github.com/input-output-hk/cardano-js-sdk with a blockchain query provider such as Blockfrost. This is the sdk used by Lace wallet so you should have everything you need.


text:
cardano_node_metrics_connectedPeers_int empty since node upgrade 1.35.7 -> 8.1.2
Since i upgraded my nodes from 1.35.7 to 8.1.2 the cardano_node_metrics_connectedPeers_int variable is empty.
All others are set as expected.
I already loaded the newest config, because ConwayGenesisFile was missing and set TraceBlockFetchDecisions again to true.
Are there any changes regarding cardano_node_metrics_connectedPeers_int in the new versions?

Yes, it is been changed from cardano_node_metrics_connectedPeers_int to cardano_node_metrics_peers_connectedPeers_int
If I recall correctly changes was brought since 8.0.0 version.


text:
Exodus and Eternl extensions in chrome and brave are incompatible?
Im developing some dApp with a wallet connector using the extensions in chrome and brave.
Everything was working fine until I installed Exodus extension.
Something in creating a conflict here.
Look pictures attached:
1- This is my wallet connector before enabling Exodus extension:

2- Now, look the icons when I enable Exodus:

The Eternl icon disappears and also the functionality of Eternl wallet.
If I press that button it will open the Exodus wallet.
I checked in the windows.cardano object and I also found the problem there:
3- This is before enabling Exodus:

4- This is with Exodus wallet extension enabled:

You can see that the Eternl object is overwriting with the same content that the exodus object and only the name eternal is left.
Any idea? It is a bug? From who? Eternl? Exodus?

This is definitely a bug. I would lean toward it being firmly rooted on Exodus, but could be the fault of both Eternl and Exodus. The problem seems to be with variable scope. They both seem to obfuscate their front end code, which ends up making variables like A = N('icon'). If those variables are not scoped properly, other things will override them. For example, if both extension make use of A, one of them could have their functionality changed by the other. Theoretically, Exodus could simply grab window.cardano.eternl.icon and set it, but that would seem malicious and really offer no benefit. I would report the bug to both, as I can confirm that what you're seeing is happening to me as well.


text:
Do we have any documents that help to understand Ouroboros Praos?
I'm trying to understand how the Cardano election process work by reading the paper https://eprint.iacr.org/2017/573.pdf. Nevertheless, there are many mathematic formulas in the paper, I really find them difficult to understand them.
Does anyone know a summary document around Ouroboros Praos that could help to understand how it works easier?
Thank you!


text:
Handling multi-address wallets in web apps
Regarding the topic of single and multi-address wallets:

What are the most commonly used single and multi-address based Cardano wallets? Are there any other single-address based wallets besides Nami or Lace that are live or currently being developed?
What are some strategies to manage multi-address wallet users in a web app? In my database I want to tie each user to their data by their wallet address, and for single-address based wallets there is no issue, however from my understanding some wallets like Yoroi and Eternl create a seemingly endless amount of wallet addresses because apparently in Cardano land you can make as many addresses derived from your private key as you want

Regarding number 1.
Single Address Wallets aside from Nami and Lace, which you mentioned, are Eternl which have single address mode, and Typhon which allows you to convert the wallet to a single address. These two have my personal recommendation.
At the end of this page, you'll see a list of "other wallets" which has quite a few.
Regarding number 2.
There are many options to accomplish this. Something like CardanoPress or Cardano Connect do this for you. But if you are building your own tool, you can "getUsedAddresses" from the cardano wallet dapp bridge here.


text:
TooMuchSpace error when running uplc profiling tool on simple minting policy
I have the following minting policy:
{-# OPTIONS_GHC -fplugin-opt PlutusTx.Plugin:profile-all #-}

{-# INLINABLE verify_mint #-}
verify_mint :: () -> V2.ScriptContext  -> Bool
verify_mint () _ = (3::Integer) == 2+1

policy :: V2.MintingPolicy
policy = V2.mkMintingPolicyScript
    $$(PlutusTx.compile [|| Typed.mkUntypedMintingPolicy verify_mint ||])

which I compiled into the cbor file with
writeMintingPolicy :: "test.plutus" policy

writeMintingPolicy :: Haskell.FilePath -> V2.MintingPolicy -> IO (Haskell.Either (FileError ()) ())
writeMintingPolicy file
    = writeFileTextEnvelope @(PlutusScript PlutusScriptV2) file Haskell.Nothing
    . PlutusScriptSerialised
    . SBS.toShort
    . LBS.toStrict
    . serialise
    . V2.getMintingPolicy

However, when I tried to use uplc to profile it I obtained the following error:
uplc evaluate -i test.plutus --if flat --trace-mode LogsWithBudgets -o logs

uplc: Flat deserialisation failure: TooMuchSpace (0x00000042005e893d,S {currPtr = 0x00000042005e6015, usedBits = 3})
CallStack (from HasCallStack):
  error, called at executables/src/PlutusCore/Executable/AstIO.hs:145:17 in plutus-core-1.5.0.0-inplace-plutus-core-execlib:PlutusCore.Executable.AstIO

Can anyone help?


text:
What is the Daedalus Pool Ranking Equation and where is it defined in the code?
What is the Daedalus Pool Ranking Equation? Where is it defined in open source code?
A seemingly simple question, but hard to find, where the Daedalus pool ranking equation lives. Can anyone tell me exactly where in the code this is defined? I want to trust but verify, and understand.
I've been reading thru here in the github input-output-hk/daedalus, but coming up empty handed. Specifically in ../source/renderer/app/components/staking/stake-pools. I just can't seem to find where the equation exists in the code, although there's many references, such as filtering here.
Theoretically, it is defined as cited in the cardano-ledger, README, Stake pool ranking specification. It also could be the same reference, but here as well ../tree/master/docs/pool-ranking
I just can't seem to close the gap from the theoretical to Daedalus code.

This data comes from stakePool.nonMyopicMemberRewards, which comes from stakePools, which comes from staking, which comes from the store. This is in the delegation center page code around line 81. So effectively this all happens at the API endpoint where the data that Daedalus uses comes from. The calculation doesn't happen in the Daedalus wallet code.
Here is the call to get the stake pools https://github.com/input-output-hk/daedalus/blob/0c4944dbd650f51d18d4f15add0001bac9f2445c/source/renderer/app/api/staking/requests/getStakePools.ts
The actual ranking appears to be here: https://github.com/input-output-hk/cardano-wallet/blob/4a3aff30f8a6f755115e8492ed0a6909f7bf8b65/lib/wallet/src/Cardano/Pool/Rank.hs#L299
This also might be helpful: https://gist.github.com/ilap/ad088d31e542f73685a3a245b3ad6c50

Thanks for the thorough answer! For future readers, after some digging, it looks like the pool score and equation is assigned in the /Rank.hs line 313: https://github.com/input-output-hk/cardano-wallet/blob/4a3aff30f8a6f755115e8492ed0a6909f7bf8b65/lib/wallet/src/Cardano/Pool/Rank.hs#L313 . Looks like the pool scores and other data is added to a data struct in /Pools.hs

@TheStophe Happy to help. The code can definitely be a bit spread out. I updated my answer to include the link you found.


text:
EDIT | Is it possible to send (transfer, request) ADA using just Javascript?
Using just HTML / PHP / Javascript and cardano-serialization, I have the connect wallet working. It shows the balance and stake address. So I have gotten that far.
My question is, how can I request the connected wallet for a chosen amount of ADA?
I do not want to use Mesh or any of those, just using Javascript.
Any and all input greatly appreciated!
EDIT: I am getting a lot of errors, can anyone tell me what else I can do to make this work correctly?
<script type="module">

import { Blockfrost, Lucid } from "https://unpkg.com/lucid-cardano@0.10.2/web/mod.js"; // NPM

const lucid = await Lucid.new(
  new Blockfrost("https://cardano-preview.blockfrost.io/api/v0",
"mainnet..."),
"Preview",
);

// Assumes you are in a browser environment
const api = await window.cardano.nami.enable();
lucid.selectWallet(api);

const tx = await lucid.newTx()

 .payToAddress("addr...", { lovelace: 5000000n })
  .complete();

const signedTx = await tx.sign().complete();

const txHash = await signedTx.submit();

console.log(txHash);

</script>

I recommend using Lucid for this:
import { Blockfrost, Lucid } from "lucid-cardano"; // NPM

const lucid = await Lucid.new(
  new Blockfrost("https://cardano-preview.blockfrost.io/api/v0", "<projectId>"),
  "Preview",
);

// Assumes you are in a browser environment
const api = await window.cardano.nami.enable();
lucid.selectWallet(api);

const tx = await lucid.newTx()
  .payToAddress("addr...", { lovelace: 5000000n })
  .complete();

const signedTx = await tx.sign().complete();

const txHash = await signedTx.submit();

console.log(txHash);

This piece of code (from the lucid github page) selects a wallet injected in the browser (in this case Nami) and creates a transaction using Lucid. It is quite easy to use and well documented!

I tried using this, can you look at the code i submitted and let me know what to change/add? Thanks.

I think you may be looking for this. https://cardano.stackexchange.com/a/7657/7159
Here is the official documentation.
https://developers.cardano.org/docs/get-started/cardano-serialization-lib/generating-transactions/


text:
Mutable NFT state by minting and burning in same transaction
The problem
Please consider the following case: a token (NFT) needs to holds some state, ie {a: 234, b: "someState"}, which needs to be mutable and it needs to abide to specific rules.
The solution
I found this to be possible by storing this state in the mint transaction redeemer, which works as follows:

The token is initially minted with said state
We now want to mutate the state, the token is burned and minted at the same time, where once again the minted token holds the mutated state in the redeemer of the mint transaction.
At any time we can look up the state by issuing the most recent mint transaction redeemer.

The state can be enforced into a specific format using the minting policy; the mint is rejected if the redeemer is in a wrong format. We can also check using the contract (minting policy) that the same token was both minted and burned in the same transaction. This solution would also allow for mutating the token metadata since in each new mint we can alter the metadata.
This was inspired by CIP-25 which states that metadata can be updated by minting the token with new data.
The error
I implemented a simple example of this in Aiken and Lucid for the on-chain and off-chain code respectively. The implementation, however, fails in step 2 when trying to mint and burn in the same transaction:
.mintAssets({
    [assetName] : -1n,
}, BurnRedeemer) // Just to tell the script we are burning the token
.mintAssets({
    [assetName] : 1n,
}, MintRedeemer) // Holds the new state

The following error code is returned:
Error: "transaction submit error ShelleyTxValidationError ShelleyBasedEraBabbage (ApplyTxError [UtxowFailure (FromAlonzoUtxowFail (WrappedShelleyEraFailure (ExtraneousScriptWitnessesUTXOW (fromList [ScriptHash \"6edbbd728fa1a6488c18994ece35cc5cc6d4e472a00b7e2e621218f0\"])))),UtxowFailure (FromAlonzoUtxowFail (ExtraRedeemers [RdmrPtr Mint 0])),UtxowFailure (FromAlonzoUtxowFail (PPViewHashesDontMatch (SJust (SafeHash \"98eab4d1a6dd11919b5b8ea820b1b867ca261c4f85e50ec4afa99f392950e81a\")) (SJust (SafeHash \"c06babada7564b7629ddadc5ef3689ad7fcc64b2d3bc3c85a489dde1eaccc29a\"))))])"
My question now is, is it possible to mint and burn a token in the same transaction and is this implementation possible? If not, what other options are there for doing this? Please note that CIP-68 is not an option (minUtxo value is too expensive for my use case).

The "mint" field in a transaction is a single "Value", defined as:
newtype Value = Value {
getValue :: Map CurrencySymbol (Map TokenName Integer)
}
newtype CurrencySymbol = CurrencySymbol {
unCurrencySymbol :: BuiltinByteString
}
newtype TokenName = TokenName {
unTokenName :: BuiltinByteString
}

not a list of values, so you can't mint and burn the same asset within a single transaction.
Not sure how lucid handles you code exactly, it's possible that the first call is just overwritten and therefore the signature for the utxo to burn is extraneous, resulting in the "ExtraneousScriptWitnessesUTXOW" error.

It is useful to know Cardano doesn't allow a mint and burn in the same transaction!
Is the code you provided plutus code?

It's from the official Plutus documentation, but it's a general ledger property.

ExtraneousScriptWitnessesUTXOW indicates that the same script is provided multiple times within a single transaction. It is only necessary and valid to provide the script once, either by including it in the transaction body as a witness or by referencing a UTxO containing the reference script.
This implies that there can only be one redeemer, making it impossible to execute the same policy more than once in a single transaction, irrespective of the values being minted or burned


text:
How to get data based on Block-Height?
in EVM we can call any read-only function and pass it a block_height we would want the data to be returned on.
for example if I wanted a pool's liquidity at block height 999999, i would call that liquidity function and pass it the blockheight .
contract.liquidity({ blockTag: 999999 })
is there something equivalent on cardano?


text:
Preferred Library For Working With Zero Knowledge Proofs
I have been thinking about a voting mechanism as seen at the following link.
The same text is also posted on the Cardano forum under governance.
https://johnshearing.github.io/bee_democracy/index.html#voting
Implementation will require working with zero knowledge proofs.
Does the Cardano community have a preferred tech stack or library for working with ZKPs?
Much thanks.

To my knowledge this does not exist in the Cardano suite of things. This is probably why Cardano is giving up to $2 million in prizes with a focus on ZKPs.
https://emurgo.io/hackathon-101-an-introduction-to-zero-knowledge-proofs/
I found this https://github.com/matter-labs/awesome-zero-knowledge-proofs
Which points to Haskel implementations here: https://github.com/sdiehl/bulletproofs

Amazing resources @PREEB. Much thanks!


text:
Force include wallet optional message?
Is there any way to force a message along with the payment using Lucid, or any other js payment? I am trying to tie an order number along with the transaction.
thanx.

You can include the order number as metadata.
https://lucid.spacebudz.io/docs/getting-started/make-payments/#send-ada-with-metadata


text:
How to differentiate NFTs of the same policy id?
For Example:
You have an NFT collection that has 5 different tiers all under the same policy ID (cip-25 metadata standard). You want to be able to provide on-chain benefits to holders of the NFT dependent on the tier they hold.
Because each tier shares the same policy ID what is the easiest way to categorize and reward the different tiers?
The solution that comes to my mind is having 1 piece of the NFTs metadata mention its tier, then using blockfrost to take a policy ID snapshot that sorts by tier name.

You can add custom metadata to your NFT. The most used standard is CIP-721.
The metadata could look like this:
{
  "721": {
    "<policy_id>": {
      "<asset_name>": {
        "name": <string>,
        "image": <uri | array>,
        "tier": 1
      }
    }
  }
}

As you mentioned you could then use an API like blockfrost or Koios to get the metadata, check the tier property and do whatever you want with that information.

Brilliant! This seems like the perfect solution to go with.
I will take a look at the blockfrost docs and see the best way to do so. If you happen to know any open source code or a good pre-built tool for this that would be fantastic!
Thank you for the help!

You could build a Merkle tree of asset names for each tier and encode the root hash in the smart contract.
In the redeemer you give the correct intermediate hashes (public), compute the root hash and verify with the tier root hash.

Ok fantastic! I appreciate this advice.
I think we are staying away from smart contracts on this one and just using NMKR for the minting side of things.
Where the more code intensive side of things come into play will be around differentiating asset types and then rewarding.

Definitely easier to start without smart contracts and do this with a backend / multi-sig instead. Something like a merkle tree based solution could still be added later.


text:
Failed to build cardano-crypto-wrapper
When I run "cabal build all" I get the error message "Failed to build cardano-crypto-wrapper-1.5.1.0". See below for log file. Any assistance would be appreciated. I was so close to the end!
Failed to build cardano-crypto-wrapper-1.5.1.0.
Build log (
/Users/larry/.cabal/logs/ghc-8.10.7/crdn-crypt-wrppr-1.5.1.0-ac1a8b90.log
):
Warning: cardano-crypto-wrapper.cabal:129:31: colon specifier is experimental
feature (issue #5660)
Configuring library for cardano-crypto-wrapper-1.5.1.0..
Preprocessing library for cardano-crypto-wrapper-1.5.1.0..
Building library for cardano-crypto-wrapper-1.5.1.0..
[ 1 of 22] Compiling Cardano.Crypto.Orphans ( src/Cardano/Crypto/Orphans.hs, dist/build/Cardano/Crypto/Orphans.o, dist/build/Cardano/Crypto/Orphans.dyn_o )
[ 2 of 22] Compiling Cardano.Crypto.ProtocolMagic ( src/Cardano/Crypto/ProtocolMagic.hs, dist/build/Cardano/Crypto/ProtocolMagic.o, dist/build/Cardano/Crypto/ProtocolMagic.dyn_o )
[ 3 of 22] Compiling Cardano.Crypto.Random ( src/Cardano/Crypto/Random.hs, dist/build/Cardano/Crypto/Random.o, dist/build/Cardano/Crypto/Random.dyn_o )
[ 4 of 22] Compiling Cardano.Crypto.Raw ( src/Cardano/Crypto/Raw.hs, dist/build/Cardano/Crypto/Raw.o, dist/build/Cardano/Crypto/Raw.dyn_o )
[ 5 of 22] Compiling Cardano.Crypto.Hashing ( src/Cardano/Crypto/Hashing.hs, dist/build/Cardano/Crypto/Hashing.o, dist/build/Cardano/Crypto/Hashing.dyn_o )
[ 6 of 22] Compiling Cardano.Crypto.Signing.Redeem.VerificationKey ( src/Cardano/Crypto/Signing/Redeem/VerificationKey.hs, dist/build/Cardano/Crypto/Signing/Redeem/VerificationKey.o, dist/build/Cardano/Crypto/Signing/Redeem/VerificationKey.dyn_o )
<command line>: dlopen(/Users/larry/.cabal/store/ghc-8.10.7/lib/libHScrdn-crypt-prs-2.1.2.0-5a34eb6e-ghc8.10.7.dylib, 0x0005): symbol not found in flat namespace (_crypto_vrf_ietfdraft03_bytes)
cabal: Failed to build cardano-crypto-wrapper-1.5.1.0 (which is required by
test:tx-generator-test from tx-generator-2.5, test:tx-generator-apitest from
tx-generator-2.5 and others). See the build log above for details.

What are the contents of /Users/larry/.cabal/logs/ghc-8.10.7/crdn-crypt-wrppr-1.5.1.0-ac1a8b90.log.
Also what versions of ghc and cabal are you using?

The contents of that file are in my post. cabal-install version 3.6.2.0 and The Glorious Glasgow Haskell Compilation System, version 8.10.7

This is due to use of old forked libsodium dependency. Follow the updated install guide to ensure yourLD_LIBRARY_PATH env var points to the correct build.
If you're using nix, then unset LD_LIBRARY_PATH because it can override the shared object used by nix for the correct libsodium.

I updated the shell profile and get the same error. small-steps-test-1.0.0.0 also fails to build for the same reason.  export PATH=$PATH:/Users/larry/Library/Python/3.9/bin
export LD_LIBRARY_PATH="/usr/local/lib:$LD_LIBRARY_PATH"
export PKG_CONFIG_PATH="/usr/local/lib/pkgconfig:$PKG_CONFIG_PATH"
[ -f "/Users/larry/.ghcup/env" ] && source "/Users/larry/.ghcup/env" # ghcup-env

Can somebody please elaborate and provide more details on James' answer. I am completely new to Cardano but learning. And although I am computer engineer I'm not a full time developer but I can understand and problem solve with a few more details. Thanks.


text:
How add many metadata
I want mint nft with many metadata?
https://meshjs.dev/apis/transaction/minting

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

Below is the example from the page you referenced, but with additional metadata fields attached. You can create your own custom metadata fields on the asset this way.
const assetMetadata: AssetMetadata = {
  "name": "Mesh Token",
  "image": "ipfs://QmRzicpReutwCkM6aotuKjErFCUD213DpwPq6ByuzMJaua",
  "mediaType": "image/jpg",
  "description": "This NFT is minted by Mesh (https://meshjs.dev/).",
  "custom1": "Your custom value 1",
  "custom2": "Your custom value 2"
};
const asset: Mint = {
  assetName: 'MeshToken',
  assetQuantity: '1',
  metadata: assetMetadata,
  label: '721',
  recipient: 'addr_test1vpvx0sacufuypa2k4sngk7q40zc5c4npl337uusdh64kv0c7e4cxr'
};
tx.mintAsset(
  forgingScript,
  asset,
);


text:
Decoding transaction redeemers to JSON
I need to decode a redeemer hash (such as c4f0f65e1a03560608800ab884a2ed37377361e64462d14645610ac88b4aebd3) to the readable JSON format, just like cexplorer does, preferably using Javascript/Typescript. Tools such as cardano-cli are not an option.
How is the redeemer encoded anyway? I was unable to find a clear definition of what this hash exactly is, which makes it difficult to find information on decoding...

A hash is the product of a one way function. It is not possible to decode the redeemer hash.
The redeemer itself is stored onchain inside the witness set of the transaction, see cddl spec (rfc8610). This also shows you how plutus_data is encoded.
Explorers such as cexplore obtain this information using a chain-index service which stores transaction data for efficient querying such as db-sync, kupo or marconi.

That is really helpful to know! I was unaware that the redeemer hash not what contains the data but I guess it's in the name (hash is data one way encoded).


text:
How mint nft from policy_id
import { Transaction, ForgeScript } from '@meshsdk/core';
import type { Mint, AssetMetadata } from '@meshsdk/core';

// prepare forgingScript
const usedAddress = await wallet.getUsedAddresses();
const address = usedAddress[0];
const forgingScript = ForgeScript.withOneSignature(address);

const tx = new Transaction({ initiator: wallet });

// define asset#1 metadata
const assetMetadata1: AssetMetadata = {
  "name": "Mesh Token",
  "image": "ipfs://QmRzicpReutwCkM6aotuKjErFCUD213DpwPq6ByuzMJaua",
  "mediaType": "image/jpg",
  "description": "This NFT is minted by Mesh (https://meshjs.dev/)."
};
const asset1: Mint = {
  assetName: 'MeshToken',
  assetQuantity: '1',
  metadata: assetMetadata1,
  label: '721',
  recipient: 'addr_test1vpvx0sacufuypa2k4sngk7q40zc5c4npl337uusdh64kv0c7e4cxr',
};
tx.mintAsset(
  forgingScript,
  asset1,
);

const unsignedTx = await tx.build();
const signedTx = await wallet.signTx(unsignedTx);
const txHash = await wallet.submitTx(signedTx);

After mint nft. I have policy id, How mint new nft with policy_id


text:
What are some best practices to launch a token in a DEX?
How can I incentivise users to provide liquidity to a pool so the pool is backed by a fair amount of ADA? Does anybody know of some good resources on strategies and best practices to achieve this?


text:
Using cardano-wallet with Plutip local cluster
I have to test integration Cardano with out services (written in c#, so I am totally noob in Haskel).
So I have built Plutip local cluster insing Nix and now  I can run Plutip local cluster in such a way:
/home/docker/plutip/result/bin/local-cluster \
  --wallets 3 \
  --wallet-dir /home/docker/cardano-data/wallets \
  --working-dir /home/docker/cardano-data/plutip \
  --ada 100000 \
  --utxos 5 \
  --dump-info-json /home/docker/cardano-data/local-cluster-info.json

Then try running cardano-wallet:
cardano-wallet serve \
  --node-socket /home/docker/cardano-data/plutip/pool-1/node.socket \
  --mainnet \
  --tls-ca-cert cert2/ca-cert.pem \
  --tls-sv-cert cert2/server.crt \
  --tls-sv-key cert2/server.key \
  --listen-address 0.0.0.0 \
  --port 8090 \
  --database /home/docker/wallet-db

And here is the problem: when I use --mainnet because Plutip generates funds for the mainnet network, then wallet tries to synchronise for an extremely long time.
When I run wallet with the --testnet /home/docker/cardano-data/plutip/genesis.byron.json option, the sync is very fast, but wallet gives me an address in testnetwork, so I have no idea how to transfer funds between plutus addresses and wallet ones.
Any ideas how to get them to work together, either in mainnet, or in testnet address pool?


text:
What's the benefit of headers-first sync in Cardano?
Looking at the source code, it seems that Cardano used to not have headers-first sync, but later, it started doing headers-first sync. In bitcoin, there's a benefit in headers-first sync because block headers are very small (80 bytes) and the cost to mining is extremely high that headers are almost always valid when proof of work is valid.
In proof of stake, it seems to be a bigger cost, having to include tons of proofs with lots of data. The data is easily 500 to 1000 bytes. It also adds a security risks because headers-first sync is, by its nature, more trusting and requires more checks.
Why did Cardano decide to go that route? What's the benefit, which overcomes all these challenges? Why not sync blocks directly?