text:
Can Nami wallet provide the TransactionWitnessSet for minting a native asset?
I'm trying to mint a native asset reusing the keys that Nami already uses. This is to make a minting service that is connected to a specific wallet, and that wallet is always able to mint more tokens if they want to.
However, it doesn't seem like Nami is providing all the signatures that I need. When submitting the transaction I get the following error:
transaction submit error ShelleyTxValidationError ShelleyBasedEraAlonzo (ApplyTxError [UtxowFailure (WrappedShelleyEraFailure (MissingScriptWitnessesUTXOW (fromList [ScriptHash \"9f84ae8b52e374a0cd09e7ec10854309f8dd7b1f5caf69dd658ed6c5\"]))),UtxowFailure (WrappedShelleyEraFailure (UtxoFailure (UtxosFailure (CollectErrors [NoRedeemer (Minting (PolicyID {policyID = ScriptHash \"9f84ae8b52e374a0cd09e7ec10854309f8dd7b1f5caf69dd658ed6c5\"})),NoWitness (ScriptHash \"9f84ae8b52e374a0cd09e7ec10854309f8dd7b1f5caf69dd658ed6c5\")]))))])

I seem to be missing the witness for the native asset script. Is there any way of making Nami sign this or is it impossible? Note that I'm already using the signTx(...) endpoint so it seems to be signing the entire transaction just not what is required by the minting script.
Code:
async function mint(mintData: MintData, wasm: any, walletConnector: WalletConnector){
  const userAddress: Address = wasm.Address.from_bytes(
    Buffer.from(mintData.address, "hex")
  )

  const p = await initTx()

  const txBuilder: TransactionBuilder = wasm.TransactionBuilder.new(
    wasm.TransactionBuilderConfigBuilder.new()
      .fee_algo(wasm.LinearFee.new(wasm.BigNum.from_str(p.linearFee.minFeeA),
                                  wasm.BigNum.from_str(p.linearFee.minFeeB)))
      .pool_deposit(wasm.BigNum.from_str(p.poolDeposit))
      .key_deposit(wasm.BigNum.from_str(p.keyDeposit))
      .coins_per_utxo_word(wasm.BigNum.from_str(p.coinsPerUtxoWord))
      .max_value_size(p.maxValSize)
      .max_tx_size(p.maxTxSize)
      .build()
  );

  const invalidHereafter=10

  if (p.slot === null){
    return
  }

  const ttl = p.slot+invalidHereafter
  const timelockExpiry = wasm.TimelockExpiry.new(ttl)
  const timeLockedPolicyScript = wasm.NativeScript.new_timelock_expiry(timelockExpiry)
  const policyScripts = wasm.NativeScripts.new()
  policyScripts.add(timeLockedPolicyScript)
  const scriptHash = wasm.ScriptHash.from_bytes(timeLockedPolicyScript.hash().to_bytes())
  const policyID = bytesToString(timeLockedPolicyScript.hash().to_bytes())

  //const assetName = Buffer.from(mintData.tokenName, 'hex')
  txBuilder.add_mint_asset_and_output_min_required_coin(
    timeLockedPolicyScript,
    wasm.AssetName.new(mintData.tokenName),
    wasm.Int.new_i32(mintData.amount),
    userAddress,
    );

  const valueFilter: Value = wasm.Value.new(wasm.BigNum.from_str("5000000"))
  //Add inputs
  const utxos: TransactionUnspentOutputs = wasm.TransactionUnspentOutputs.new();
  (await walletConnector.getUtxos(Buffer.from(valueFilter.to_bytes()).toString('hex')))
                .forEach(rawUTXO => {
                  const utxo: TransactionUnspentOutput = wasm.TransactionUnspentOutput.from_bytes(Buffer.from(rawUTXO, "hex"))
                  utxos.add(utxo)
                })

  txBuilder.add_inputs_from(utxos, 0)

  txBuilder.add_change_if_needed(userAddress)

  const toBeSignedTx: Transaction = txBuilder.build_tx();
  const rawToBeSignedTx: string = Buffer.from(toBeSignedTx.to_bytes()).toString('hex')

  const rawWitnesses: string = await walletConnector.signTx(rawToBeSignedTx)
  const witnessSet = wasm.TransactionWitnessSet.from_bytes(
    Buffer.from(rawWitnesses, "hex")
  )
  const witnessSets: TransactionWitnessSets = wasm.TransactionWitnessSets.new()
  witnessSets.add(witnessSet)

  const submitTx: Transaction =
    wasm.Transaction.new(
      toBeSignedTx.body(),
      witnessSet
    )
  const rawSubmitTx: string = Buffer.from(submitTx.to_bytes()).toString('hex')
  walletConnector.submitTx(rawSubmitTx) // <- Error occurs when submitting

}

lol I probably need to use signData(...) I'll update the post if that turns out to be the solution

Where are you running it? is it Ts ? what is this walletConnector objet?

Yes it is possible, i am doing it with out any problems. So the problem must be somewhere in your code. As far as i see you are signing correctly. And you are not adding addressKeyHash in the policy, so there might be a problem related to other utxo? how are you getting the utxos? ...  Can you send a simpler Tx, with out minting?

Instead of using a time-locked script, I required the user to include their wallet key as a witness.
Solution:

export async function mint(mintData: MintData, wasm: any, walletConnector: WalletConnector){
    const userAddress: Address = mintData.address.to_address()
    const netId: NetworkID = await walletConnector.getNetworkId()
    const p = initTxStatic(netId)

    const txBuilder: TransactionBuilder = wasm.TransactionBuilder.new(
      wasm.TransactionBuilderConfigBuilder.new()
        .fee_algo(wasm.LinearFee.new(wasm.BigNum.from_str(p.linearFee.minFeeA),
                                    wasm.BigNum.from_str(p.linearFee.minFeeB)))
        .pool_deposit(wasm.BigNum.from_str(p.poolDeposit))
        .key_deposit(wasm.BigNum.from_str(p.keyDeposit))
        .coins_per_utxo_word(wasm.BigNum.from_str(p.coinsPerUtxoWord))
        .max_value_size(p.maxValSize)
        .max_tx_size(p.maxTxSize)
        .build()
    );

    const baseAddress: BaseAddress = wasm.BaseAddress.from_address(userAddress)
    const scriptPubKey = wasm.ScriptPubkey.new(baseAddress.payment_cred().to_keyhash())
    const pubKeyScript = wasm.NativeScript.new_script_pubkey(scriptPubKey)
    const policyScripts = wasm.NativeScripts.new()
    policyScripts.add(pubKeyScript)

    const hexString = Util.hexEncode(mintData.assetName)
    const assetName: Uint8Array = Uint8Array.from(Buffer.from(hexString, 'hex'));
    txBuilder.add_mint_asset_and_output_min_required_coin(
      pubKeyScript,
      wasm.AssetName.new(assetName),
      wasm.Int.new_i32(mintData.amount),
      userAddress,
      );

    const valueFilter: Value = wasm.Value.new(wasm.BigNum.from_str("5000000"))
    //Add inputs
    const utxos: TransactionUnspentOutputs = wasm.TransactionUnspentOutputs.new();
    const outputs: TransactionUnspentOutput[]  = (await walletConnector.getUtxos(valueFilter))
    outputs.forEach(utxo => utxos.add(utxo))

    txBuilder.add_inputs_from(utxos, 0)

    txBuilder.add_change_if_needed(userAddress)

    const toBeSignedTx: Transaction = txBuilder.build_tx();

    const witnessSet: TransactionWitnessSet = await walletConnector.signTx(toBeSignedTx)

    witnessSet.set_native_scripts(policyScripts)

    const submitTx: Transaction =
      wasm.Transaction.new(
        toBeSignedTx.body(),
        witnessSet,
        undefined
      )
    await walletConnector.submitTx(submitTx)

  }

This error indicates you have all the witnesses you need for the transaction except the minting script and the policy key witness for minting.
You should be able to add a witnessSet to the transaction containing the missing policy script and policy key witness(es) before submitting.


text:
Does NFT name need to be base16 encoded in metadata.json file? How can I verify it was registered successfuly including the json?
The guide for NFT minting is quite outdate and not working at this moment - https://developers.cardano.org/docs/native-tokens/minting-nfts/ because since recent version of cardano-cli all token names must be base16 encoded (I wasn't able to use non-encoded names at least).
So I was following this guide completely and managed to register the NFT on testnet when I base16 encoded the token name in CLI, but I don't seem to be able to verify if it was actually correctly registered. Most of NFT browsers don't work with testnet and when using testnet cardanoscan I only see the name of token, but nothing else - no metadata, no IPFS picture, not even description, just the decrypted base16 name, which makes me feel like the metadata either didn't register, or they mismatch the token name?
How can I verify if testnet token was properly registered? How can I query metadata for a token in certain address? Do I need to base16 encode the token name in metadata.json?

Please note that the guide was updated with this pull request: https://github.com/cardano-foundation/developer-portal/pull/428/files

it would be useful if manual also contained the actual command echo -n $NAME | base16 explaining how you can get the encoded name

I agree, can you do a pull request?

How can I verify if testnet token was properly registered?

When you mint your NFT, you're able to check the Mint transactions tab in cardanoscan/testnet.cardanoscan. For example, the following tokens were minted in one transaction:

https://testnet.cardanoscan.io/token/62264a920c007b90d6b950f34245d42c66f6fd23c1547f1662bfa54743617264616e6f7263313636

Then you can go to the Transaction in the Mint transactions and you will find Metadata tab. There should be your Metadata for 721.
If nothing is displayed there, it's because your minting process has something wrong.

How can I query metadata for a token in certain address?

You can use blockfrost to query an specific asset and get the metadata. For example, to query this token: https://testnet.cardanoscan.io/token/62264a920c007b90d6b950f34245d42c66f6fd23c1547f1662bfa54743617264616e6f726331363239
You can use:
curl --location --request GET 'https://cardano-testnet.blockfrost.io/api/v0/assets/62264a920c007b90d6b950f34245d42c66f6fd23c1547f1662bfa54743617264616e6f726331363239' \
--header 'project_id: <your_project_id>'

And you will get this:
{
    "asset": "62264a920c007b90d6b950f34245d42c66f6fd23c1547f1662bfa54743617264616e6f726331363239",
    "policy_id": "62264a920c007b90d6b950f34245d42c66f6fd23c1547f1662bfa547",
    "asset_name": "43617264616e6f726331363239",
    "fingerprint": "asset1gljzhfsaqvep43gjez0t4hj3fj3jwv455cw0e4",
    "quantity": "1",
    "initial_mint_tx_hash": "9262943a49cc3dca038e907e0e0a9f3ac55ef60a2d3032cab45bfee1ff4d4e37",
    "mint_or_burn_count": 1,
    "onchain_metadata": {
        "name": "Cardanorc1629",
        "image": "ipfs://Qme3iiz4QWXo48xusytQ2u2E7RpnNJdLjGpUStcb6aYWtn",
        "id": 1629,
        "properties": {
            "Eye": "Agate",
            "Head": "No Head Accessory3",
            "Race": "Margog",
            "Mouth": "No Trait",
            "Earring": "No Earring 1",
            "Background": "Brown",
            "Special_Skin": "None",
            "Body_Accessory": "No Armor2",
            "Special_Mouth_Trait": "Gold Side Tooth"
        },
        "description": "Cardanorcs - The Beginning"
    },
    "metadata": null
}

Do I need to base16 encode the token name in metadata.json?

No, you don't need it.

Some additional points to consider:

Make sure you're using the right policyId in your metadata and your minting process
You can verify your metadata from here: https://pool.pm/test/metadata

what do I replace your_project_id with? that curl returns {"status_code":403,"error":"Forbidden"

ok seems account on blockfrost was needed, there is a free plan, now I can see that the NFT was probably registered properly, although using cardanoscan it's barely visible as it doesn't render IPFS image

Yes, you need a blockfrost account. Sure, cardanoscan only works to check the metadata , not to render IPFS. Anyway, you can use the blockfrost gateway to check that.

source: Stack Exchange

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

sort: votes


text:
How to calculate fees for Plutus Smart Contract?
How can someone calculate fee for executing Plutus smart contract given that they know CPU and Memory Units required for executing Plutus Script?

You can now use fee estimator at https://testnets.cardano.org/en/testnets/cardano/tools/plutus-fee-estimator/

Doesn't really answer the question.  OP or somebody who finds this might be looking for an explanation of the formula rather than a tool to do the calculation.

The formula is a simple multiplication. MemoryUnits X MemoryUnitCost + CPUsteps X CPUstepCost. As for the costs, I honestly don't know the numbers.

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


text:
Can I always imply that **if** a transaction was successful, all validators from all inputs were successful?
I have a transaction with many validators and I want to rule out a possible error.

If I got you right, you are asking if both of the following statements are true:

Transaction is successful -> all validators were successful,
and also
All validators were successful -> transaction is successful

Statement 1) is clearly true. Statement 2) is also true as all other conditions that need to be met are checked before the validators are run, which means that when the validators are run, only their failure can make the transaction invalid.
An article from Polina Vinogradova on www.iohk.io explains the validation process in a very good way. Quoting:

Transaction validation on Cardano is divided into two phases. The main reason for introducing two-phase validation is to limit the amount of uncompensated validation work by nodes. Each phase serves a purpose in achieving this goal. Roughly speaking, the first phase checks whether the transaction is constructed correctly and can pay its processing fee. The second phase runs the scripts included in the transaction. If the transaction is phase-1 valid, phase-2 scripts run. If phase-1 fails, no scripts run, and the transaction is immediately discarded.

(see: https://iohk.io/en/blog/posts/2021/09/07/no-surprises-transaction-validation-part-2/)

Yes. The transaction will be treated as atomic. If one of the inputs are unspendable, the tx will fail.


text:
How to export a transaction from Plutus for the wallet
I have a contract that returns an unbalanced transaction:
buyTokensTx :: forall w s. TokenPool -> BuyParams -> Contract w s Text (Either MkTxError UnbalancedTx)

From what I understand, I need to export this unbalanced transaction from the PAB and import it into the Nami wallet in a CBOR serialised format. In Plutus.Contract.Wallet, I found a function that does just this:
export :: C.ProtocolParameters -> C.NetworkId -> UnbalancedTx -> Either CardanoAPI.ToCardanoError ExportTx

This ExportTx seems to wrap the CBOR I need, as one can conclude from its toJSON:
-- IMPORTANT: The JSON produced here needs to match the schema expected by
-- https://input-output-hk.github.io/cardano-wallet/api/edge/#operation/balanceTransaction
instance ToJSON ExportTx where
    toJSON ExportTx{partialTx, lookups, redeemers} =
        object
            [ "transaction" .= JSON.encodeByteString (C.serialiseToCBOR partialTx)
            , "inputs"      .= lookups
            , "redeemers"   .= redeemers
            ]

(see: https://github.com/input-output-hk/plutus-apps/blob/main/plutus-contract/src/Plutus/Contract/Wallet.hs)
My problem is that export takes as its two first arguments ProtocolParameters and NetworkId. Where do I get these ? And also, where is the best place to call this export-function ?


text:
Is there an open source vending-machine script for NFT minting?
Many projects either use a vending-machine service like NFT-Maker PRO or buffybot or have built their own vending-machine scripts.
Is there any open-source vending machine script that can be connected to a cardano-node to mint NFTs when a UTxO arrives on a specific address?

Here is my version of a vending machine:

Upgraded with metadata creation
"Completed" counter backed up in a *.txt file so if the machine restarts the script does not start minting from the beginning
You should create your own Blockfrost project
Picture uploaded to Infura
Sorry for the Hungarian comments

#!/bin/bash

cd /opt/cardano/cnode/priv/wallet/cpostal
looping=1
log=log_file.txt
txs=txs.txt
numberCompleted=`cat numbercompleted.txt`

# ez lesz raymond címe, most a sajátom
donationAddr=`cat rajmond_yoroi_address`

# erre a címre várjuk a befizetéseket
paymentAddr=`cat payment.addr`

paymentSignKeyPath=./payment.skey
policySignKeyPath=./policy/policy.skey
scriptPath=./policy/policy.ada.2.120.script

POLICYID=$(cardano-cli transaction policyid --script-file $scriptPath) > policy/policyID

# ez az én yoroi-s stake címem
profitAddr=`cat yoroi_address`

echo "" >> $txs
echo "" >> $log
echo "Log File" >> $log
echo "-------------------" >> $log
echo "Process started at: $(date +%T)" >> $log
echo "-------------------" >> $log
echo "" >> $log

arcedula=50000000 # ennyit kérünk ezért az NFT-ért

trap 'looping=0;wait' INT TERM

while (( looping )); do
    echo ==================================================================================
    cardano-cli query utxo --address $paymentAddr --mainnet > fullUtxo.out
    tail -n +3 fullUtxo.out | sort -k3 -nr > balance.out
    cat balance.out
    while read -r utxo; do
        sleep 5s
    #echo "UTXO detected" >> $log
        tx_hash=$(awk '{ print $1 }' <<< "${utxo}")
    echo "TXHash: "$tx_hash
    idx=$(awk '{ print $2 }' <<< "${utxo}")
        utxo_balance=$(awk '{ print $3 }' <<< "${utxo}")
    tx_in="--tx-in ${tx_hash}#${idx}"
    if [ $( grep -q "${tx_hash}" "$txs" && echo $? ) ];
    then
       # echo "Previous tx" >> $log
        echo "nem trténr  utalás"
        break
    else
        echo ${tx_hash} >> $txs
        echo "utalás trtént"
        echo "A küldő cím: " >> $log
        echo $(curl -H 'project_id: *********' \
                https://cardano-mainnet.blockfrost.io/api/v0/txs/${tx_hash}/utxos \
                | jq '.inputs' | jq '.[0]' | jq '.address') >> $log
            in_addr=$(curl -H 'project_id: *********' \
                https://cardano-mainnet.blockfrost.io/api/v0/txs/${tx_hash}/utxos \
                | jq '.inputs' | jq '.[0]' | jq '.address' | sed 's/^.//;s/.$//')
            echo "Address: ${in_addr}"
        echo "utalás értéke: "$utxo_balance
            if [ ${utxo_balance} != $arcedula ] || [ $(ls "/opt/cardano/cnode/stamps/s1/" | wc -l) == 0 ];
            then
            echo ${utxo_balance} >> $log
            echo "Refund Initiated..." >> $log
        echo `date` >> $log
        echo "Pénzvisszafizetés"
            currentSlot=$(cardano-cli query tip --mainnet | jq -r '.slot')
                cardano-cli transaction build-raw \
                    --fee 0 \
                    ${tx_in} \
                    --tx-out ${in_addr}+${utxo_balance} \
                    --invalid-hereafter $(( ${currentSlot} + 1000)) \
                    --out-file tx.tmp >> $log
                fee=$(cardano-cli transaction calculate-min-fee \
                    --tx-body-file tx.tmp \
                    --tx-in-count 1 \
                    --tx-out-count 1 \
                    --mainnet \
                    --witness-count 1 \
                    --byron-witness-count 0 \
                    --protocol-params-file protocol.json | awk '{ print $1 }') >> $log
                echo "Fee:"$fee >> $log
        fee=${fee%" Lovelace"}
                amountToSendUser=$(( ${utxo_balance}-${fee} ))
            echo ${amountToSendUser} >> $log
                cardano-cli transaction build-raw \
                    --fee ${fee} \
                     ${tx_in} \
                    --tx-out ${in_addr}+${amountToSendUser} \
                    --invalid-hereafter $(( ${currentSlot} + 1000)) \
                    --out-file tx.raw >> $log
echo "Pénz visszküldés submit" >> $log
         cardano-cli transaction sign \
                    --signing-key-file $paymentSignKeyPath \
                    --tx-body-file tx.raw \
                    --out-file tx.signed \
                    --mainnet >> $log
echo "Pénz visszaküldés submit" >> $log
                cardano-cli transaction submit --tx-file tx.signed --mainnet >> $log

# *******************************************NFT MINT *************************************
            else
            echo ========================================================= >> $log
        echo ======================== ÚJ NFT ========================= >> $log
        echo ========================================================= >> $log
        echo "Sending NFT..." >> $log
        echo `date` >> $log
            numberCompleted=$(( numberCompleted+1 ))
        echo "Token száma: $numberCompleted" >> $log
        echo $numberCompleted > numbercompleted.txt
#           POLICYID=$(cardano-cli transaction policyid --script-file $scriptPath) ezt beépítetem az elejére, de ha minden nFT küln policit kapna akkor ide kell

#*********************** metadata gerebléyzés *****************

  tokenname=`cat /opt/cardano/cnode/stamps/s1/Stamp_Ada_$numberCompleted.png.ipfs.txt | awk -F'"' {'print $4 '} | awk -F'.' {'print $1'} | sed -e 's/_//g'`
tokennameID=`cat /opt/cardano/cnode/stamps/s1/Stamp_Ada_$numberCompleted.png.ipfs.txt | awk -F'"' {'print $4 '} | awk -F'_' {'print $3'} | awk -F'.' {'print $1'} | sed 's/^0*//'`
  ipfs_hash=`cat /opt/cardano/cnode/stamps/s1/Stamp_Ada_$numberCompleted.png.ipfs.txt | awk -F'"' {'print $8 '}`
echo "tokenname:" $tokenname >> $log
echo "tokennameID:" $tokennameID >> $log
echo "Poolpm név:"$POLICYID"."$tokenname >> $log

echo "{">> $tokenname"metadata.json"
echo "      \"721\": { ">> $tokenname"metadata.json"
echo "           \"$POLICYID\": { ">> $tokenname"metadata.json"
echo "              \"$tokenname\": { ">> $tokenname"metadata.json"
echo "                \"description\": \"CARDANO POSTAL SERVICE STAMP\"," >> $tokenname"metadata.json"
echo "                \"name\": \"Ada Lovelace stamp $tokennameID\"," >> $tokenname"metadata.json"
echo "                \"id\": $tokennameID, ">> $tokenname"metadata.json"
echo "                \"creator\": \"Ildiko Kovacs\"," >> $tokenname"metadata.json"
echo "                \"image\": \"ipfs://$ipfs_hash\"," >> $tokenname"metadata.json"
echo "                \"url\": \"https://cardanopostalservice.io\"" >> $tokenname"metadata.json"
echo "              }" >> $tokenname"metadata.json"
echo "            }">> $tokenname"metadata.json"
echo "        }" >> $tokenname"metadata.json"
echo "}">> $tokenname"metadata.json"
metadatajson="${tokenname}metadata.json"

echo ================
echo "mintelési adatok"
echo "tokenname:" $tokenname
echo "tokennameID:" $tokennameID
#cat $metadatajson

# **************** Bevétel szétdobása ********************

       amountToSendUser=1800000
((amountToDonate = arcedula * 5 / 100)) # ez magy rajmondnak

((amountToSendProfit = arcedula - amountToDonate - amountToSendUser))  # ez megy szabinak

echo 'vegleges szamok:'
echo 'arcedula:' $arcedula
echo 'amount to send profit:' $amountToSendProfit
echo 'amount to send user:' $amountToSendUser
echo 'amount to donate:' $amountToDonate

                currentSlot=$(cardano-cli query tip --mainnet | jq -r '.slot')
                cardano-cli transaction build-raw \
                    --fee 0 \
                    ${tx_in} \
                    --tx-out ${in_addr}+${amountToSendUser}+"1 $POLICYID.${tokenname}" \
                    --tx-out ${profitAddr}+${amountToSendProfit} \
            --tx-out ${donationAddr}+${amountToDonate} \
            --mint="1 $POLICYID.${tokenname}" \
            --minting-script-file $scriptPath \
            --metadata-json-file ${metadatajson} \
                    --invalid-hereafter $(( ${currentSlot} + 10000)) \
                    --out-file tx.tmp >> $log
                fee=$(cardano-cli transaction calculate-min-fee \
                    --tx-body-file tx.tmp \
                    --tx-in-count 1 \
                    --tx-out-count 3 \
                    --mainnet \
                    --witness-count 2 \
                    --byron-witness-count 0 \
                    --protocol-params-file protocol.json | awk '{ print $1 }') >> $log
            fee=${fee%" Lovelace"}
                amountToSendUser=$((${amountToSendUser}-${fee}))
                cardano-cli transaction build-raw \
                    --fee ${fee} \
                    ${tx_in} \
                    --tx-out ${in_addr}+${amountToSendUser}+"1 $POLICYID.${tokenname}" \
                    --tx-out ${profitAddr}+${amountToSendProfit} \
            --tx-out ${donationAddr}+${amountToDonate} \
            --mint="1 $POLICYID.${tokenname}" \
                    --minting-script-file $scriptPath \
            --metadata-json-file ${metadatajson} \
                    --invalid-hereafter $(( ${currentSlot} + 10000)) \
                    --out-file tx.raw >> $log

echo 'amount to send user minusz fee:' $amountToSendUser
echo "Fee:"$fee

echo "NFT küldés aláírás" >> $log
                cardano-cli transaction sign \
                  --signing-key-file $paymentSignKeyPath \
               --signing-key-file $policySignKeyPath \
                  --tx-body-file tx.raw \
                  --out-file tx.signed \
                  --mainnet >> $log
echo "NFT küldés submit" >> $log
              cardano-cli transaction submit --tx-file tx.signed --mainnet >> $log

echo "============= mintelés vége ============="
echo
            fi
            rm tx.*
        echo "====bejegyzés vége====" >> $log
        fi
     done < balance.out

  wait
done

I hope it help,
cheers!

You may be interested in this MIT licensed Cardano NFT vending machine bash script available on GitHub. It hasn't been updated in 6 months, but you can fork it from the ftpmorph repo and audit to see if it does what you need.

We open-sourced one of these on GitHub here: https://github.com/thaddeusdiamond/cardano-nft-vending-machine
It's written in Python but requires no cardano-node (only cardano-cli and a Blockfrost key).  There's also a sample script in main.py to show how to use it (or just invoke that script from CLI). Our PFP mint was done on my Macbook Pro.  Hopefully that helps!


text:
How do I read the datum of an output?
How do I get the datum of an output from cardano-graphql (or another service)? I have attached it using the --tx-out-datum-embed-file flag already when building the tx using cardano-cli.
Thanks!

If you are running a DbSync node you can retrieve the datum and redeemer:
redeemer
A table containing redeemers. A redeemer is provided for all items that are validated by a script.

Primary Id: id

Column name
Type
Description

id
integer (64)

tx_id
integer (64)
The Tx table index that contains this redeemer.

unit_mem
word63type
The budget in Memory to run a script.

unit_steps
word63type
The budget in Cpu steps to run a script.

fee
lovelace
The budget in fees to run a script. The fees depend on the ExUnits and the current prices.

purpose
scriptpurposetype
What kind pf validation this redeemer is used for. It can be one of 'spend', 'mint', 'cert', 'reward'.

index
uinteger
The index of the redeemer pointer in the transaction.

script_hash
hash28type
The script hash this redeemer is used for.

datum_id
integer (64)

datum
A table containing Plutus Data available in the blockchain, found in redeemers or witnesses

Primary Id: id

Column name
Type
Description

id
integer (64)

hash
hash32type
The Hash of the Plutus Data

tx_id
integer (64)
The Tx table index for the transaction where this script first became available.

value
jsonb
The actual data in json format

Taken from dbSync:
https://github.com/input-output-hk/cardano-db-sync
It is also possible by just inspecting the blockchain. Even tho only the Datum hash is attached to the eUTXO, the datum value should be in the witness set of the transaction that created such eUTXO, so we should be able to:
a) Get the datum hash from the eUTXO and then.
b) Get the transaction that created such eUTXO and use the hash to retrieve the actual datum data.
Otherwise, if the Datum were not present at all on the chain it would be impossible to re-validate the blockchain from scratch.

As per the comments on this PR the datum is included in the TX that spends the corresponding eUTXO rather than on the one that creates it. https://github.com/input-output-hk/cardano-db-sync/issues/1076

It is possible to just add the datum hash when creating a transaction, in which case the actual datum value won't be included in the witness set of the transaction that creates the output, however, it is also possible to add the datum value at creation of the transaction if you use the flag "tx-out-datum-embed-file" or "tx-out-datum-embed-value" on the CLI and add the datum value, in which case, the datum value will be available on chain from the creation of the eUTXO.

This solution somehow doesn't work for tx 034cd38f3f8387e6963c78175e459a2ffab0e36becb36510aaa81534f6ea6e54
I can't find the datum for this tx in cardano db sync.


text:
About slot battles and db sync
I wanted a way to check if a pool is having some sort of slot dispute with somebody else's pool for the right to mine a block.
I couldn't find a solution for that, maybe using dbsync I don't know exactly if its possible to check that information without be the owner of that pool in question.
I'm accepting suggestions or directions on how to query these block disputes for a pool analysis tool we are creating.
thank you

db-sync only records accepted blocks. Blocks that are rolled back are removed from the database before the roll forward.

You can also check the logs on your block producer or on a relay.
This is how a slot battle looks like in the logs (it happened less than half an hour ago):
Dec 22 07:16:53 relay4 bash[3623433]: #033[35m[relay4:cardano.node.ChainDB:Notice:365]#033[0m [2021-12-22 07:16:53.43 UTC] Chain extended, new tip: 701733ec51d44a307341e9fecb3ae7b921b3a8529fffcf1cda958aeaac813c9c at slot 48591122
Dec 22 07:16:53 relay4 bash[3623433]: #033[34m[relay4:cardano.node.ChainDB:Info:365]#033[0m [2021-12-22 07:16:53.60 UTC] Block fits onto some fork: 0cd72eebab15a4e66b3225694928938362c0aef931186ea5aaeffd9830753c63 at slot 48591122
Dec 22 07:16:53 relay4 bash[3623433]: #033[34m[relay4:cardano.node.ChainDB:Info:365]#033[0m [2021-12-22 07:16:53.66 UTC] Valid candidate 0cd72eebab15a4e66b3225694928938362c0aef931186ea5aaeffd9830753c63 at slot 48591122
Dec 22 07:16:53 relay4 bash[3623433]: #033[35m[relay4:cardano.node.ChainDB:Notice:365]#033[0m [2021-12-22 07:16:53.66 UTC] Switched to a fork, new tip: 0cd72eebab15a4e66b3225694928938362c0aef931186ea5aaeffd9830753c63 at slot 48591122

db-sync doesn't track forks so can't be analyzed to identify slot battles. There are some 3rd party tools, such as cncli that do track forks so you can analyze the data from the view of one of your nodes. Note that it can only be analyzed if it's running when it happens though. Here's a reference video that could help in understanding what they are, why they occur and how to analyze them using cncli and sqlite queries: https://www.youtube.com/watch?v=Cm5pBM7UYa0

On a relay node running cardano-node install cncli and get it fully sync'ed.
Query the cncli database using sqlite:
sqlite3 cncli.db

.schema chain

select id, block_number, slot_number, hash, pool_id, orphaned from chain where pool_id = 'the_poolid_you_want_to_check' and orphaned = 1;

That should give you some ideas.


text:
User interaction with smart contracts
I want my users to interact with my smart contracts. All transactions come from these users. There are no transactions - except for setting up - that come from my wallets. As entry point for this interaction, I have the PAB running. The PAB runs on local host and listens to the requests that my webpage forwards to it.
My understanding is that every interaction with the Cardano block chain happens within a contract instance. This instance needs to be activated and then listens to calls. So I start one long running contract instance on PAB startup.
Now, the PAB exposes (among others) two endpoints:

api/contract/< contract-instance-id >/endpoint/< json >
api/contract/< contract-instance-id >/status

Using curl, I can call endpoint 1.:
curl --header "Content-Type: application/json" -X POST http://127.0.0.1:9080/api/contract/instance/1c893716-913b-4fce-a28d-1d09f15f56d1/endpoint/buyTx --data '{"quantity":1}'

When I call endpoint 1., I can see the logs but there is no output in the console. It seems the http request does not return any value.
To get a value I need to call endpoint 2. (after having called endpoint 1.):
curl -X GET http://127.0.0.1:9080/api/contract/instance/1c893716-913b-4fce-a28d-1d09f15f56d1/status

And this returns a very big json containing the ExportTx that my contract function returns.
My questions are:

Is it possible to get the ExportTx as a return value of http request 1. ?
Is my use of the PAB and the contract instances correct for the use case described or am I doing something wrong ?
Shall I activate a contract instance for every user request or can I use one long running instance for all users ? The need to issue two http requests make me wonder if the latter is even possible without mixing up requests of different users.


text:
Similar source for Cardano
I want to generate public and private keys with an address. I found this repository but it doesn't support Cardano. Does anybody know any similar source?

Cardano uses Bip32-Ed25519 standard for deriving keys and uses bech32 for encoding keys/addresses. I'm not aware of any native python libraries for doing the key derivation, but you could wrap cardano-addresses as long as it's in the path as I do here in adawallet: https://github.com/input-output-hk/adawallet/blob/ae8ddbb164b9b95037cd2d7e795e9926dc0f5df6/adawallet/adawallet/lib.py#L326-L332.

This should help. You can use cardano-wallet and cardano-cli for wallet and addresses management.

The thing is I don't wanna run a full node or using cli. I want to do all the processes in python.

This should give you all you need to start generating keys for Cardano in your language of choice. Also check out CIP-1852 and CIP-19


text:
How to get PubKeyHash of an address without vkey?
How to get Address -> PubKeyHash without vkey just with addr like addr_test1wrf230u95zr26lut09mchmt82d235v6335jvszme2jevklslg5lfz?
It must be possible, because when you build unlocking transaction from smartcontract locked funds  with cardano-cli transaction build ... you pass --change-address parameter which doesn't require vkey like cardano-cli address key-hash command does. Smartcontract manages to get PubKeyHash from provided addr_... which it can get from txOutputs :: [txOut]

You can see the CDDL spec for full details: https://github.com/input-output-hk/cardano-ledger/blob/master/eras/shelley/test-suite/cddl-files/shelley.cddl
In the case of a payment base address (the most common address on the chain at the moment), the address when converted from bech32 -> hex will have a prefix of 00 (on testnet, 01 on mainnet), followed by the payment credential, followed by the stake credential. The payment and stake credentials are hashes of those pubkeys.
Here's an example output (and cardano-address inspect output so you can see an example matching the pieces):
cardano-address address inspect <<< addr_test1qrkgclg3rsz8v8hnv2sqxmfk3yl87p9dme906h4ru859j9z076sepqv0ms7pud50lrgfh3e72jrysy5wawg4hqgmzfrsvgallu
{
    "stake_reference": "by value",
    "stake_key_hash_bech32": "stake_vkh1flm2ryyp3lwrc83k3ludpx788e2gvjqj3m4ezkuprvfywejlp0j",
    "stake_key_hash": "4ff6a190818fdc3c1e368ff8d09bc73e548648128eeb915b811b1247",
    "spending_key_hash_bech32": "addr_test1ajx86yguq3mpaumz5qpk6d5f8elsftw7ft74aglpapv3g07qz53",
    "address_style": "Shelley",
    "spending_key_hash": "ec8c7d111c04761ef362a0036d36893e7f04adde4afd5ea3e1e85914",
    "network_tag": 0

bech32 <<< addr_test1qrkgclg3rsz8v8hnv2sqxmfk3yl87p9dme906h4ru859j9z076sepqv0ms7pud50lrgfh3e72jrysy5wawg4hqgmzfrsvgallu
00ec8c7d111c04761ef362a0036d36893e7f04adde4afd5ea3e1e859144ff6a190818fdc3c1e368ff8d09bc73e548648128eeb915b811b1247

Check out cardano-addresses, and scroll to the "how to inspect address" section


text:
Building a transaction using Nami api wallet and cardano-client-lib
I am trying to build a transaction with the libary of cardano-client-lib (java sdk).
Inorder to build a transaction one needs to provide an account object which can only be created with the mnemonic phase, which is clearly a problem.
I thought of using Nami wallet API as a walkaround, but seems unable to get the specific instance of the wallet in java.  is there a way to build a transaction in java with nami api?
thanks.

Nami is a web wallet and injects its API into your website. It is not supposed to work with desktop applications but only with web apps. I recommend you to build your app with react + typescript + emurgo/cardano-serialization-lib-browser. That is how I built this minting app

Another option:
Transaction can be built in Java backend and then sent to Nami for signing.
Here's a sample code for Multi-sig token mint where
(Not exactly same but similar approach can be used for your scenario)

Mint Transaction is built in Java backend
Sign by Nami extension in the browser
Send the witness back to Java backend
Assemble transaction again with other witnesses in Java backend and submit the final transaction

MultiSigTokenMint With Java + Nami

I don't think you can get the wallet instance from Nami as the whole point of a wallet is to hide the private key and pass transactions visually to the user so that she can approve and submit them.
I would rather try the other way and look if your java library has methods to generate an unbalanced transaction that can be passed to the Nami wallet. Such a method would only need the wallet's UTxOs and the address of the recipient.
But I also have no clue on which libraries do this. It is very difficult at the moment to find anything useful on the subject.

I have done this function, don't know if it will help you.
Two projects are required:
cardano-client-examples
https://github.com/zjavax/cardano-client-examples-zx/blob/main/src/main/java/cn/zjavax/BuildWithJavaBackend.java

public class BuildWithJavaBackend extends BaseTest {
    public static void main(String[] args) throws AddressExcepion, CborSerializationException, ApiException {
        new BuildWithJavaBackend().transfer();
        System.exit(1);
    }

    public void transfer() throws CborSerializationException, ApiException, AddressExcepion {
//        String senderMnemonic = "kit color frog trick speak employ suit sort bomb goddess jewel primary spoil fade person useless measure manage warfare reduce few scrub beyond era";
        String senderAddress = "addr_test1qqxnp3khzm7kcj9t23hskehat7428ghsenk0pfew4rqy5v9frnmht7uwrl073q4jvq20z82kh4rksyns540azhndqexqpvhgqr";
        String receiverAddress1 = "addr_test1qqwpl7h3g84mhr36wpetk904p7fchx2vst0z696lxk8ujsjyruqwmlsm344gfux3nsj6njyzj3ppvrqtt36cp9xyydzqzumz82";

        Output output1 = Output.builder()
                .address(receiverAddress1)
                .assetName(LOVELACE)
                .qty(adaToLovelace(1))
                .build();

        TxBuilder txBuilder = (output1.outputBuilder()
                .buildInputs(createFromSender(senderAddress, senderAddress))
        )
                .andThen(feeCalculator(senderAddress, 1))
                .andThen(adjustChangeOutput(senderAddress, 1));

        Transaction signedTransaction = TxBuilderContext.init(utxoSupplier, protocolParamsSupplier).build(txBuilder);

        System.out.println("txHexDraft=\"" +signedTransaction.serializeToHex()+"\"");

    }
}

cardano-walletconnector-demo

The result of calling cc wallet:

@Satya（don't know how @）


text:
Can a native asset have different rules for minting and burning when using SimpleScripts?
Could I for example have one key to only be used for minting tokens and another only for burning? Or does this require Plutus script?

I believe a plutus script is needed here. If minting with the cli i believe there is only value that can be used with keyhash. Multiple scripts can be combined with logical AND and OR but I don't see a way to include if it's a mint or burn so both keys would be able to mint and burn.
I haven't personally tried it but you can specify more than one public key hash in the validator. In my opinion this should be doable by specifying more than one pubkey hash and check if the mint amount is negative or positive. Then make sure only one key handles minting and one key handles burning.


text:
Registering policy ID programatically (pool.pm)
I'm seeing many NFT minting policies registered on pool.pm, and I noticed they can be registered manually there as well.
Is there a way to do this programmatically? And is this a pool.pm-specific thing, or is there some kind of central registry?

Welcome to the site!

Just open your network tools on yojr favorite browser and inspect the request which is made when submitting a script. Should be easy.

Yeah, that was kind of my last resort. I was just wondering if there was a more "official" way to do it, rather than hacking around it and risking things to be broken if Smaug decides to change their internal API.

No, there's no way to currently do this programmatically, and yes - this feature is specific to pool.pm.


text:
Why is ADA locked up with native assets and can it be detached from the native assets?
In Yoroi I can see that there is some ADA locked up with my native assets:

Can I spend this ADA without the native asset? If I would not care about the native asset, could I create a transaction that only spends the ADA and not the asset?

In Cardano, each UTXO can contain a heterogeneous mixture of tokens and data, but must contain at least some amount of ADA. This is done on purpose to prevent both inadvertent and malicious chain bloat. Read more about the intricacies of minUTXOvalues here.
On your Yoroi wallet, you probably have a couple UTXO's with token data such that the min amount of ADA in each of those UTXO's totals to the locked amount displayed to you by Yoroi. In your case, it's not much, but if you want to free up the ADA you can always consolidate your assets into fewer UTXOs.

On Cardano you cannot transfer or own native assets (i.e. any token other than Ada) without having it combined with a certain amount of Ada. This amount of Ada is called the minimum Ada value needed and it depends on the byte size of the native tokens. Native tokens with large token names have a large byte size, those with small token names a small byte size. This constraint ensures that the total byte size of the ledger (all unspent funds of all wallets) has a maximum value and thus does not explode.
So, as long as you keep your native assets, you cannot spend the minimum Ada amount. Also, if you want to transfer your native assets in a simple transaction you need to send them together with this minimum Ada value.


text:
Is it possible to manually derive Stake Pool Cold Keys from a Master Seed?
I am wondering if it is currently possible to manually derive stake pool cold keys using a low-level module like cardano-addresses. The idea behind this is to have a single master seed/mnemonic, downstream of which all other key paths (staking, payment, node management, etc) lie. In other words, is cardano-cli node key-gen currently the only command to create the cold keys, or is there another way?
CIP-1853 talks about such specifications, but I'm not sure if they are already implemented or if they can be manually implemented.
Thanks in advance!

Like other keys on cardano, a stakepool cold key is just a bunch of random bytes from the protocol's perspective. While it's highly recommended to be interoperable amount tools to use reserved derivation paths to generate keys, from a technical perspective it isn't necessary and you could make up any derivation path and extract the key using cardano-addresses, and then store the CBOR encoded key in a text file.
That being said, I'd highly recommend utilizing the CIP-1853 derivation path.

My question was more along the lines of - is it technically feasible to do this? Based on your answer I suppose it is - I'll have to give it a try on testnet and report back.

Yes, it's feasible. I have a pool on testnet utilizing CIP 1853. Only reason mainnet pool doesn't is changing the cold key would result in a new pool and needing to retire the old one. I highly recommend 1853 for any new pools.


text:
Nami wallet address format to addr_test1 format
lets say i have the following address for recieving funds:
addr_test1qzu70xm8hsez6nvmpgk4gjf48ev0y2hw5w7nf8xaxc658lzwczusckqvzzg630pxnzwj3pqza5q4c8r504ffq6v2zh6qgznxt7
when i try and get the wallet address  (by using Berry-Pool nami wallet) i get:
00b9e79b67bc322d4d9b0a2d5449353e58f22aeea3bd349cdd363543fc4ec0b90c580c1091a8bc26989d288402ed015c1c747d5290698a15f4
how can i go from 00b9e79b67bc322d4d9b0a2d5449353e58f22aeea3bd349cdd363543fc4ec0b90c580c1091a8bc26989d288402ed015c1c747d5290698a15f4
to addr_test1qzu70xm8hsez6nvmpgk4gjf48ev0y2hw5w7nf8xaxc658lzwczusckqvzzg630pxnzwj3pqza5q4c8r504ffq6v2zh6qgznxt7
Thank you

Also you can use Cardano Serialization Lib https://github.com/Emurgo/cardano-serialization-lib
with the class Adress and the method Address.toBech32() :
let HexAddress = "00b9e79b67bc322d4d9b0a2d5449353e58f22aeea3bd349cdd363543fc4ec0b90c580c1091a8bc26989d288402ed015c1c747d5290698a15f4"

console.log(Address.from_bytes(Buffer.from(HexAddress,"hex")).to_bech32())

this is exactly what i was looking for. is there a way to use this library in vuejs?

They are encoded in different formats as the followings:
Bech32 Format:

addr_test1qzu70xm8hsez6nvmpgk4gjf48ev0y2hw5w7nf8xaxc658lzwczusckqvzzg630pxnzwj3pqza5q4c8r504ffq6v2zh6qgznxt7

Hex Format:

0b9e79b67bc322d4d9b0a2d5449353e58f22aeea3bd349cdd363543fc4ec0b90c580c1091a8bc26989d288402ed015c1c747d5290698a15f4

IOHK provides an executable and haskell lib for that in this repo.
To Hex,
bech32 <<< addr_test1qzu70xm8hsez6nvmpgk4gjf48ev0y2hw5w7nf8xaxc658lzwczusckqvzzg630pxnzwj3pqza5q4c8r504ffq6v2zh6qgznxt7

To Bech32,
bech32 addr_test <<< 00b9e79b67bc322d4d9b0a2d5449353e58f22aeea3bd349cdd363543fc4ec0b90c580c1091a8bc26989d288402ed015c1c747d5290698a15f4


text:
How to derive cost from transaction?
Given a transaction where an NFT reached its final destination after a sale, how can I derive the cost of the NFT? For example, if I search for an asset on cardanoscan.io, the assets involved confuse me: RAVE and ROCKET.
Is there a calculation I can do on the inputs and outputs to derive the exact cost of the transaction? Not just the transaction fee but the cost of the token? Or do I have it conceptually wrong?
Thanks in advance for any insight!

If you can identify the size of the tx (bytes) you could utilise the fee calculation formula given the protocol parameters at the time of submission. (This might be tricky, but it is possible if you were inclined enough to find out a fairly accurate ball-park fee)

Cardano's fee structure is quite simple. Fees are constructed around two constants (a and b). The formula for calculating minimal fees for a transaction (tx) is a * size(tx) + b, where: a/b are protocol parameters.

https://docs.cardano.org/explore-cardano/fee-structure

Blockchains do not have an inherent notion of price; one cannot know the price of any asset, including ADA itself, simply by looking at on-chain data (until of-course we develop a robust oracle system). Currently, the price of cardano-assets like ADA, NFTs, e.t.c. is mostly dictated by off-chain markets (mostly centralized exchanges).
Until we have price/liquidity data being posted on chain, there will not be a way to derive asset prices purely from on-chain data. That being said, analyzing the inputs and outputs of transactions on chain may give you insight into the nature of a transaction that you can use to infer what kind of value transfer is going on.


text:
Remove Owner from Stake Pool
Good Morning,
I need clarity on the process to remove an owner from a stake pool.
Few epochs ago, I added my hardware wallet as a owner of my stake pool. This results in the fact that now my pool is owned by 2 owners, the hardware wallet and the first wallet. Now, 2 epochs are passed, and I want to remove the first wallet cause I have transferred all the pledge to the hardware wallet. From my knowledge, I only need to remove the unwanted: --pool-owner-stake-verification-key-file stake.vkey and then resubmit the certificate.
Is that correct? Do I need to do other things? I just wanted to be sure about that.
Thanks for your time

Yest, that is correct. You need to create a new stake pool certificate only with the hardware wallet as stake pool owner (instead of both owners) and submit the new certificate.


text:
Transaction fee
Doesn't the transaction cost increase with the increase of Cardano price?  Is there a way to keep the transaction cost constant while raising the price of the Cardano token?

The answers are yes, and yes, respectively.
Cardano is unique in the L1 space in that it has been designed from the start to scale with the number of unique participating nodes, rather than with the hardware capabilities of the whole constituency. For this to work, a separation of the settlement and computation layers is necessary. Until very recently, most of the developmental efforts were geared towards the backbone of the system: the Cardano Settlement Layer (CSL). In the coming months and years, much more focus will be placed on developing the Cardano Compute Layer(s), or CCL. Since the CSL is the backbone upon which  all of the compute layers will rely on, it is designed to be as rigid and stable as possible, almost like a constitution. And since ADA is it's native currency with similarly rigid/fixed qualities, TX fees on the CSL will likely continue to be denominated in ADA for the foreseeable future. The CCLs however, will be a lot more flexible in their capabilities and their governance, including in their ability to accept payments in assets other than ADA.
The purpose of transaction fees (aside from preventing malicious chain bloat) is to compensate node operators for processing data. Since there currently isn't much to "process" except for basic block production/validation on the CSL, operators have no choice but to all play the same game. However, this will not be the case forever, and there will be many games the operators can play on the CCLs (i.e. oracle pools, babel fees, DEX scooping, e.t.c.). As Cardano continues to mature, node operators (currently just SPO's) will become more specialized, and the network will become a lot more distributed as a result (here's a great video by Charles explaining this). In practice, this means that all validator nodes are in competition with each other; all offering the same kinds of services, though in slightly different ways. Likewise, they will be able to specify how much and in what asset they would like to be paid.
In summary, as Cardano evolves, more and more of its total throughput will rely on the market-derived effort of all its constituent nodes, such that each node will have a greater say on what services it offers, and how to be compensated for said services. Therefore, nodes on the CCL will be able to specify that they wish to be paid in, for example, a USD-pegged stablecoin (or any other crypto-asset).


text:
get wallet skey/vkey from mnemonic
I am trying to get the skey, vkey and address of the first payment address in a wallet I created in cardano-wallet. I need them because I would like to make transactions with cardano-cli on the same wallet. I am working on the testnet.
With cardano-wallet I created the wallet using
cardano-wallet wallet create from-recovery-phrase "test"

I entered my mnemonic phrase, let the second factor empty and set a passphrase.
Everything seems fine and I can have a list of addresses
   {
        "derivation_path": [
            "1852H",
            "1815H",
            "0H",
            "0",
            "0"
        ],
        "id": "addr_test1qzwk908vw9lkpvuth4ch9xlmqxk593xtg7060ve775ja300ur5hrj7gda3wde08v8wx9k8dnf0n9ng0hh4ktmr3hjhts7yurnm",
        "state": "used"
    },
...

So the first address is addr_test1qzwk908vw9lkpvuth4ch9xlmqxk593xtg7060ve775ja300ur5hrj7gda3wde08v8wx9k8dnf0n9ng0hh4ktmr3hjhts7yurnm
I thought I could find the same address by doing:
cardano-wallet key from-recovery-phrase Shelley < phrase.prv > test.xsk
cat test.xsk | cardano-wallet key child 1852H/1815H/0H/0/0 > test.prv
cat test.prv | cardano-wallet key public --with-chain-code > test.pub
cat test.pub | cardano-address address payment --network-tag testnet > test.addr

But I got this address:
addr_test1vzwk908vw9lkpvuth4ch9xlmqxk593xtg7060ve775ja30gg6szrd
I tried with cardano-address I got the same address.
I also try this with cardano-cli:
cardano-cli key convert-cardano-address-key --shelley-payment-key --signing-key-file test.prv --out-file test.skey
cardano-cli key verification-key --signing-key-file keys/test1.skey --verification-key-file test.vkey
cardano-cli address build --payment-verification-key-file test.vkey --out-file test.addr --testnet-magic 1097911063

And I also got addr_test1vzwk908vw9lkpvuth4ch9xlmqxk593xtg7060ve775ja30gg6szrd
When I tried to make a transaction from my wallet to this address, it's seems to be a valid derivative address because all utxo appears when I am checking with
cardano-wallet wallet utxo-snapshot

But I don't understand why I don't have the same address with the same derivative path.
I also checked with yoroi and nami wallet and addr_test1qzwk908vw9lkpvuth4ch9xlmqxk593xtg7060ve775ja300ur5hrj7gda3wde08v8wx9k8dnf0n9ng0hh4ktmr3hjhts7yurnm is the usual address for them
Can someone tell me what I am missing ?
Thank you

You are missing the stake key.
You obtain the stake key pair like this:
cat rootkey.prv | cardano-address key child 1852H/1815H/0H/2/0 > stake.prv
cardano-cli key convert-cardano-address-key --signing-key-file stake.prv --shelley-stake-key --out-file stake.skey
cardano-cli key verification-key --signing-key-file stake.skey --verification-key-file Ext_ShelleyStake.vkey
cardano-cli key non-extended-key --extended-verification-key-file Ext_ShelleyStake.vkey --verification-key-file stake.vkey

And then you can build your address with the stake included (from the keys obtained with the cardano-cli version you posted):
cardano-cli address build --payment-verification-key-file test.vkey --stake-verification-key-file stake.vkey --out-file test.addr --testnet-magic 1097911063

And you use the same stake key pair for all addresses derived from the master key.

thank you, that's exactly what I was missing !


text:
How to decode a pointer from Shelley address?
I'm writing an address parser based on CIP-0019. The part I have problems with is the POINTER data structure which consists of three "variable-length positive numbers". The format of the number is described as:
VARIABLE-LENGTH-UINT = (%b1 | UINT7 | VARIABLE-LENGTH-UINT)
                     / (%b0 | UINT7)

So, IIUC, I should read bytes while their oldest bit is 1, then read one byte more. I should also clear the oldest bits from them. Then I finish with a bunch of UINT7.
How should I convert them to the final integer value?

The following Python code does the thing. Iterating from right, those 7-bit UINTs should be cleared of the oldest bit, then shifted right by their right-index.
def popvarlenuint(data):
    _intbytes = []
    while data:
        b = data[0]
        data = data[1:]
        _intbytes.append(b & 0x7F)
        if b & 0x80 == 0:
            break
    val = 0
    for idx, b in enumerate(reversed(_intbytes)):
        val = val | (b << (8 * idx) - idx)
    return val, data


text:
Building a bridge to Hedera Hashgraph HBAR
Hello Cardano community,
Does Cardano have a bridge to Hedera Hashgraph HBAR?  If not, how do I build one?  I need to be able to transfer NFTs and exchange cryptos directly avoiding intermediate cryptos routes.
Thank you,
Will W.

There is no such bridge to my knowledge.


text:
How to calculate the collateral minimun required for a Smart Contract Transaction, is always needed a Colateral?
I was asking to myself in which scenarios do I have to add a collateral when consuming an UTXO in a Script Address. I have just read the basics, but do you know if there is minimum needed in each collateral UTXO ? from the protocol parameters it appears to be as well that there is a maximum of collateral utxos, Do i need to provide one always even if the amount of ADA that I am sending is high enough to cover any any fee related to the  execution of the scripts? ... I guess the answer for the second is affirmative but i would appreciate  any insights about it.
Also I would appreciate any additional info about the cardano.getCollateral() endpoint of the NamiWallet.

Whenever a script is evaluated in a transaction, a collateral is needed. It is collected by the validating stake pool in case the transaction passes the first stage validation process but then fails because one of the script UTxOs cannot be validated (see: here). The collateral is not related to the transaction fees. Both need to be satisfied by the transaction: fees need to be covered and collateral provided.
The collateral is a special field of the transaction and needs to contain at least one UTxO. This UTxO can be one of the input UTxOs of the transaction. Nami wallet asks the user to generate a specially designated UTxO which is then never used as input UTxO so that it can always be used as collateral. I don't know of any constraints other than that this UTxO must contain the minimum Ada value (which is always satisfied as it wouldn't exist in the wallet otherwise). The value of the collateral determines the script execution budget. So the higher its Ada value the lower the risk that the transaction fails because script execution was aborted.

Responding point-by-point:

Consuming a UTXO at a script address requires phase-2 script validation, therefore it always requires collateral.  Without collateral, such transactions will be rejected during phase-1 validation.  (ref. IOHK no-surprises blog post)

There is no minimum Ada required per collateral UTXO, but every UTXO available in your wallet will have at least the min ADA constraint that was in effect when the UTXO was created.  (see protocol parameters)

You are correct, the protocol parameters currently stipulate a maximum of 3 collateral UTXOs.

Yes, you must always provide collateral inputs if phase-2 validation will be triggered. You can use the same UTXOs for spending, fees, and collateral as long as the UTXO contains enough ADA to cover the spending and fees or the collateral, whichever is higher.  In your example, where you're Input UTXO is only needed to pay the Tx fee (since you're consuming a UTXO at a script address), the collateral would have to be at least 150% of the calculated fee (per protocol parameter collateral_percentage=150). So, a single UTXO containing at least 1.5x the calculated fee could be provided as both the Tx input and Collateral input.

I can't speak to the getCollateral() endpoint of the Nami Wallet, but it's important to understand why Nami's requires a designated UTXO for collateral. It's probably a matter of convenience for them, but it's a matter of safety and readiness for you. Collateral UTXOs must only contain ADA, with no other native tokens. By having users explicitly create an internally designated Collateral UTXO up front and reserving it for that purpose, you're assured that you will have a valid UTXO readily available for script interactions.  Without it, you could end up in a situation where you're unable to interact with a script because all your UTXOs with sufficient collateral happen to also have non-ADA tokens attached. If the script you're trying to interact with is time sensitive (e.g., a sudden NFT bargain), the time required to reshuffle funds to create a collateral-qualified UTXO could be the deal breaker.

Some important related considerations:

Collateral is NOT an execution budget, as it's not used for paying as much as is needed for execution and then getting the rest in change. Instead, it's more like collateral against potential damages.  That is, against the damage caused to the validators if you send them an unprocessable transaction.  If the transaction isn't valid, the fee component of the transaction is also potentially invalid, so collateral is a separate guarantee that validators will be compensated for processing 'phase-2 invalid' or 'failed' transactions. While it is not an execution budget, there are protocal parameter limitations on execution memory and steps per transaction. If any such protocol limits are exceeded, transaction processing will terminate and (I believe) the validator keeps the collateral and marks the transaction as 'phase-2 invalid'.

re. my reference to 'safety' in item 5:  Per the No-Surprises blog post, "the total balance in the UTXOs corresponding to these specially marked [collateral] inputs is the transaction's collateral amount".  Then in the very next paragraph it says "good news! It is permitted to use the same inputs for both collateral and regular, since only one of the two sets ever gets [spent]".  Ironically, that is NOT good news! Because if you happen to have only one UTXO in your wallet containing your entire HODLing fortune, and you use that as both Tx Input and Collateral Input on a contract (that perhaps wasn't very well tested), you risk losing it ALL!  It seems unfair, really... on a failed phase-2 validation only 150% of the base fee should be extracted from the UTXO, and the remainder should be returned to the change address, but every reference I've found so far seem to suggest collateral forfeiture is all-or-none.  Note: If anyone has an authoritative source either supported or debunking all-or-none collateral forfeiture, please edit this portion of the answer.


text:
Balancing transactions with script inputs
Nami does not implement a function to balance an unbalanced transaction. Therefore, the Nami demo of the Plutus Github repository implements this step (as a temporary workaround) in the function exports.balanceTxImpl = txCbor => () that can be found here: https://github.com/input-output-hk/plutus-apps/blob/main/plutus-pab/demo/pab-nami/client/src/Cardano/Wallet/Nami.js
Taking a closer look at this function, one notices that it just fetches some stuff and calls the Nami implementation for building the transaction:
return buildTx({ 'paymentAddr': changeAddrBech32 }, utxos, tx.body().outputs(), pp)

What surprised me was that the inputs of the unbalanced transaction are not passed to buildTx ! How can this work ? It works in the demo because it only implements a simple transaction where A transfers some funds to B. But in a more complicated transaction, there could be some script UTxOs in the inputs of the unbalanced transaction. How are these taken into account ? I have the impression that they are not. Am I missing something ?


text:
How do I get the http endpoint to work for cardano-wallet?
Using a DigitalOcean Ubuntu droplet, I have:

successfully installed cardano-node according to:
https://developers.cardano.org/docs/get-started/installing-cardano-node/
cardano-cli 1.32.1 - linux-x86_64 - ghc-8.10
git rev 4f65fb9a27aa7e3a1873ab4211e412af780a3648

successful installed cardano-wallet according to:
https://developers.cardano.org/docs/get-started/installing-cardano-wallet
v2021-12-15 (git revision: 760140e238a5fbca61d1b286d7a80ece058dc729)

(in order to download/calculate the latest hashes) run

nohup cardano-node run
    --topology ~/cardano/mainnet/mainnet-topology.json
    --database-path ~/cardano/db
    --socket-path ~/cardano/db/node.socket
    --host-addr <my_ip>
    --port <port-number>
    --config ~/cardano/mainnet/mainnet-config.json & exit

And then asked the wallet to serve the http interface:

cardano-wallet serve \
  --mainnet \
  --node-socket ~/cardano/db/node.socket \
  --database ~/cardano/db
  --port 8090

However, when using Chrome to go to http://<my_ip>:8090/v2/network/information or http://<my_ip>:8090/v2, I only get:
This site can’t be reached
<my_ip> refused to connect.
Try:

Checking the connection
Checking the proxy and the firewall
ERR_CONNECTION_REFUSED

Now, when I run cardano-cli query tip --mainnet I am only at epoch 293 (and as time of this question we are at 310.
Do I need to wait till I get to 310 for the http api to work? Is there anything else that is needed to get this connected?

By default cardano-wallet listens on loopback ip only - 127.0.0.1, to listen on server external ip, you need to add --listen-address parameter
So at the end command should be:
cardano-wallet serve \
  --listen-address 0.0.0.0 \
  --mainnet \
  --node-socket ~/cardano/db/node.socket \
  --database ~/cardano/db
  --port 8090

Or put dropleat real ip instead of 0.0.0.0 if it doesn't works.
Keep in mind that this is very, very dangerous to keep your wallet open to whole world especially on mainnet, so use this with caution and please use digitalocean FW and allow only your own IPs.

I'm worried I may have a fundamental misunderstanding of this whole thing. I wanted to make it open to the whole world, so I can create wallets for people via this service. (specifically, I wanted to make an iOS app that among other things can generate a wallet and give people their 12-15 word passphrase and let them enter/change a password)

@JeffreyBerthiaume, yes, never do that. The generation of the wallet needs to stay in the application itself, having a hosted service to do this is an extremely bad idea.

I'm no networking wiz (working on it) - but I just played around with the above:
I got the same error when I used my public IP address. However, when I use the loopback address (127.0.0.1) it seems to work for me.
Try running: http://127.0.0.1:8090/v2/network/information in chrome and see if that works.
If anyone knows why the public IP doesn't work but the loopback does, please explain why! :)

I'm not running this locally - this is on a Digital Ocean droplet, kind of like having a mini server running.

Ah I see. Then it won't be so simple - my naive and non-technical answer would be that you'd have to configure your droplet firewall to open port 8090 so that you could access it from the outside. Security is a concern here, but digital ocean has cloud-firewall options that make it relatively easy to allow connections to/from specific addresses (your home/office). I will work on this myself because it's piqued my curiosity; I'll get back here when I learn more.

FYI, I created and applied a firewall specifically letting traffic in from the node port as well as the wallet port. Still nothing on either.


text:
NFT Minting without Metadata
I hope all is well and everyone had a great holiday season. I am having an issue minting NFT's from the CLI they appear to be minting without metadata, even though I am referring to the fully populated metadata.json file used. All variables are correct ($variables are correct) Can anyone toss me a bone at what I'm doing wrong? The NFT does actually mint, just minus all metadata and thus no picture or details about the NFT.
My Minting Command =
cardano-cli transaction build \
--mainnet \
--alonzo-era \
--tx-in $txhash#$txix \
--tx-out $nftwallet+$output+"$tokenamount $policyid.$tokenname" \
--change-address $address \
--mint="$tokenamount $policyid.$tokenname" \
--minting-script-file $script \
--metadata-json-file metadata.json \
--invalid-hereafter $slotnumber \
--witness-override 2 \
--out-file matx.raw

Metadata file -
{
"721": {
"HIDDEN": {
"HIDDEN": {
"name": "NFT NAME HERE",
"image": "ipfs://IPFSLINKHERE",
"mediaType": "image/png",
"description": "DESCRIPTION HERE",
"files": [
{
"name": "PIC NAME HERE",
"mediaType": "image/png",
"src": "ipfs://IPFS LINK HERE"
}
]
}
},
"version": "1.0"
}
}

Please, take a look on this answer: https://cardano.stackexchange.com/a/4882/1231

Could you please include the error that you are getting?

It's likely because your token name doesnt match between the CLI and the metadata.json file. Hard to say since you've hidden them...

It looks like more of a data issue within the metadata json, rather then a problem in the transaction format.
It looks like you're following the https://developers.cardano.org/docs/native-tokens/minting-nfts/
Please note that the --mint="$tokenamount $policyid.$tokenname" \ $policyid and $tokenname, have to match the two HIDDEN fields in the metadata.json
Furthermore, the digital asset (eg. the image/audio/video/whatever) needs to be in a IPFS server. Sometimes some IPFS services are slow at serving/propagating the asset, so a workaround, is to create an account on pinata.cloud and load your asset there. Then you're sure everything is fine.
For further help, can you share a minting transaction hash? This way we can inspect the tx and tell you exactly whats wrong.
If you want to do a test, you can use new policy/image whatever, so you won't share private stuff.
Thanks and good luck

Your metadata file is not structured correctly. Please check CIP 25 - NFT Metadata Standard.
{
  "721": {
    "<policy_id>" {
       ...


text:
Will Cardano ever have anything more than validators on-chain?
I have been looking into creating a blackjack game on the Cardano Blockchain. I started with learning Haskell, and writing a simple blackjack CLI game. It was heaps of fun and a bit of a learning curve since I have never used functional languages before!
Unfortunately I misunderstood one critical thing about Plutus apps which mean that I could never implement this game in a truely decentralized way. That misunderstanding is that I could run arbitrary code and transform the datum in the on-chain code. This is true on Ethereum but not in Cardano, where the on-chain code can only determine if a transaction is valid.
I can't see any technical reason why a datum transformation couldn't be performed on a single UTXO, apart from performance considerations. So my main questions are:

Is there any technical limitation preventing Cardano from implementing this functionality on L1 in the future? Or is it just to prevent L1 from becoming bloated with excessive datum storage and code execution?

Will there be a layer 2 that allows this functionality? Is this the idea of IELE?

Appreciate any clarification here!

I should clarify that I need to draw a random card and update the state on-chain for this to be a truely decentralized app. It's true that I could probably setup some oracle off-chain to draw a card and update the game datum but this would be a lot more complex and a lot less decentralized.

Even if you had the functionality to change the datum on-chain, you would not be able to draw a random card. On-chain code is deterministic. Randomness can never be achieved, therefore. This is also true in Ethereum where you couldn‘t implement this as well. You can ask yourself, how would any node be able to verify that the card was really drawn randomly by another node of the network ? It is simply impossible: randomness cannot be proven and is therefore not implementable on-chain.

@Jey At least not until we have verifiable random oracles on chain

You're right, data transformations can be performed on UTXO's, and, to your first point, any app that requires rapid and/or complex data transformation produces too much bloat, as each transformation would produce at least one new UTXO.
Lil' Cardano Design Philosophy Review:
The "main-chain" (a.k.a., The CSL, Cardano L1, e.t.c.) is best suited for the settlement of data and logic, while a diverse ecosystem of "side-chains" (a.k.a. CCLs, Cardano L2s, e.t.c.) are best suited for execution of said data and logic. The extent of this bifurcation can be decided upon by the developer(s), and will vary widely depending on the security and throughput requirements of the dApp. Ultimately, it will be up to the dApp developer(s) to decide on a particular structure that makes sense.
In a PvP game like poker, settling and executing every move on main-chain can be done, but it would be slow, expensive, and uninspiring.
Instead, players/clients can commit their UTXOs as inputs-to-be-operated-on to a Hydra Head. Head operators can engage in data transformation that is only limited by their own network throughput, while periodically committing snapshots back to the mainchain for dispute resolution.
(FYI: maintaining high composability while bifurcating settlement and execution of logic is the essence of Cardano's ability to scale limitlessly)

Having a validator script with the ability to change the datum would not increase the power of Cardano's smart contract model. The reason is that, in the current model, validators can only use (as inputs to their logic) data that the transaction provides. The validator cannot run anything that the submitter of the transaction cannot also run. It makes, therefore, no difference if the datum is computed on- or off-chain.
The real reason you have the impression that the Ethereum model is more powerful is that, on the Ethereum blockchain, a smart contract can use the whole blockchain at execution time as input for its computation. This also means that the submitter of the transaction cannot know for sure the result of the smart contract execution as the blockchain could have changed between the moments of submitting and executing the transaction.
The biggest difference I see between Ethereum's and Cardano's smart contract models is that on Cardano it is more difficult to implement some uniqueness constraints in a decentralised way. For example, a minting policy cannot make sure that a token name is unique if the token name space is too large to fit into a script datum. A trusted party is necessary to enforce this uniqueness.
Apart from this, a random number generator is impossible on-chain and no existing blockchain implements one. Randomness always needs to be pushed to the chain from the outside world. This can be done by the means of oracles or by signed random numbers of a trusted off-chain source.

I'm not sure if you understand the question. I completely understand what UTXO is and no way calling Ethereum superior! But Cardano validators as they stand can only classify a transaction as valid or not. They still have access to the datum of the input UTXO/s to determine validity, but they cannot run code to set the outputs or datum of transactions that try to consume that UTXO. I don't see how not having access to the global blockchain state would be an issue here, hence my question.

Also there are a few ways of getting random numbers on-chain, it's not impossible.

I understood your question. Maybe you did not understand my reply. Also, I did not imply that you think Ethereum is superior. “Powerful” is meant in the programming sense.

Maybe it is not clear to you that the validator script really has access to nothing except the inputs; not even to the slot number. It is purely functional.

I could be wrong but the inputs include the datum hash (of the consumed UTXO), along with the datum and redeemer provided by the user input. So the validator script does have access to these things, but only for the specific UTXO being consumed by the transaction, not other UTXOs at the contract address. I believe that you can also validate based on the outputs of the provided transaction. So I don't see how it would be impossible to have a more advanced validator on-chain that takes a transaction and performs transformations on the outputs. That's what I'm trying to answer here.

In a purely theoretical sense! I don't expect it to happen anytime soon. Also isn't it the stake pool server that runs the on chain code? And all other nodes just validate that the SP produced a valid block? I didn't think all the nodes would have to run the validator script because they are validating blocks rather than individual transactions included in a block?

I don't know how else to explain. You already got the fundamental concept but you draw the wrong conclusions. Maybe you should try to write a validator that "performs transformations" to see that it does not make any difference. The reason being, as I said, that the validator can only act upon inputs that are completely determined by the actor constructing the transaction.

But the inputs are a UTXO right? So (transaction signing aside) it wouldn't be impossible to have a validator that transforms the output datum and enforces that the output goes back to the script address? I'm just trying to understand if it would be at all possible to append an on-chain calculated datum in a UTXO ledger, in the way that Ethereum is able to modify the global state using an account model. At the moment all a validator does is return a boolean indicating a valid transaction. But what if it returns a boolean, plus the updated datum to use if a transaction is valid?

So in a chain of transactions, the last transaction (UTXO) always holds the most updated datum which is used in subsequent transactions.

Also I'm really looking for a deeper understanding of some of the technical limitations here. You keep repeating that it's not possible at the moment, which I'm already aware of. My question is really related to it's theoretical possibility and the technical considerations that lead to creating smart validators rather than a full-blown state machine.

No, by inputs I meant the whole transaction. This transaction already includes the updated datums. So in a way, the model does already what you are describing. There is no need to have the validator return anything else than a boolean.

But the datums aren't updated by the on-chain script, they are completely arbitrary. Any user can provide any datum. There may be a way to validate the datum against the datum hash of the previous UTXO, but there's no way to transform that datum using the on-chain script. So I disagree that what I am asking is possible with the current state of Plutus scripts. But I do agree that this is the deterministic design of the current system. I think some use cases (like multi-round games i.e. blackjack) could benefit from non-deterministic datum output.

By your comments, I guess that you are misunderstanding something but I don’t know what. First, true randomness (needed for your game) is different from non-determinism for the triggerer of the tx. Second, having the script compile the datum makes only a difference in a non-determinististic model. In short: for your game, non-deterministic script execution is neither necessary nor sufficient. What you need is a trustworthy oracle.

Oh man I'm more confused by every response. I'm not talking about randomness here. The limitation I'm trying to address is that in Plutus, a whole transaction is submitted, including the new datum. The the on-chain code is only verifying transaction validity. There is no ability to transform and output a new datum on chain. That's what I'm talking about when I'm talking about a non deterministic script - a script that generates the output datum for the submitted transaction.

Ok, give me one more chance in my most simple words: On Cardano, the player knows if he won before he posted the transaction (because deterministic). This will almost certainly never change. And because of this, shifting the compilation of  the final datum from off-chain to on-chain doesn't solve anything.

Did the last comment help ?


text:
Transaction memory and cpu usage limits
Let's imagine I have AlwaysSucceeds Plutus validator script, which is:
mkValidator :: Params -> Datum -> Redeemer -> ScriptContext -> Bool
mkValidator _ _ _ _ = True

I locked many different utxos at the script address in the testnet. Let's image 15 in total. Now I want to spend all of those utxos at once from the script using cardano-cli.
Building transaction as usual, and providing those utxos as --tx-in:
--tx-in "abcdef#1" \
--tx-in-script-file alwaysSucceeds.plutus \
--tx-in-datum-value 420 \
--tx-in-redeemer-file redeemer.json \
--tx-in "abcdef#2" \
--tx-in-script-file alwaysSucceeds.plutus \
--tx-in-datum-value 420 \
--tx-in-redeemer-file redeemer.json \
...
...
--tx-in "abcdef#15" \
--tx-in-script-file alwaysSucceeds.plutus \
--tx-in-datum-value 420 \
--tx-in-redeemer-file redeemer.json \

I am pretty sure, that script is included only once in the transaction (is it?). Then submitting transaction to the testnet, I get the following error:
Command failed: transaction submit  Error: Error while submitting tx: ShelleyTxValidationError ShelleyBasedEraAlonzo (ApplyTxError [UtxowFailure (WrappedShelleyEraFailure (UtxoFailure (ExUnitsTooBigUTxO (ExUnits {exUnitsMem = 12500000, exUnitsSteps = 10000000000}) (ExUnits {exUnitsMem = 31256460, exUnitsSteps = 14103266205}))))])

This basically means that I exceeded memory limit by 3 times and CPU by 1.5.
When lowering utxo count to 14,13... it scales down pretty much linearly:
15 utxos: {exUnitsMem = 31256460, exUnitsSteps = 14103266205}
14: {exUnitsMem = 28008316, exUnitsSteps = 12629952076}
13: {exUnitsMem = 24926512, exUnitsSteps = 11232794573}
12: {exUnitsMem = 22011048, exUnitsSteps = 9911793696}
11: {exUnitsMem = 19261924, exUnitsSteps = 8666949445}
10: {exUnitsMem = 16679140, exUnitsSteps = 7498261820}
9: {exUnitsMem = 14262696, exUnitsSteps = 6405730821}
8: Transaction successfully submitted.

The validator script itself has no logic, it should not inflate memory and CPU usage (even though unfortunately it will be executed same amount of times as there are utxos).
My questions:

Does this really mean that somewhat around 10 inputs are the maximum possible to spend from the script?
Is there any way to overcome this, and allow way more inputs from the script to be spent at once?
Are exUnitsMem and exUnitsSteps the same on the mainnet?
Maybe there is a way to increase those parameters to be able to submit the transaction?
Is script really included only once then submitting/Am I building transaction correctly?
As I am validating multiple utxos at once, is it possible to run validator only once and not for each utxo?
If this is really the limit, how we are supposed to build something useful? When and by how much are those units are planned to increase?
Is there any plans, regarding running validator only once for all utxo set, instead of executing it for each utxo?

EDIT:
after updating node version to 1.32.1, error is thrown on the build step also, then utxo count is increased even further. Result is pretty much the same, only the error message is different:
Command failed: transaction build  Error: The following scripts have execution failures:
the script for transaction input 0 (in the order of the TxIds) failed with:
The Plutus script evaluation failed: An error has occurred:  User error:
The budget was overspent. Final negative state: ({ cpu: 5931879314
| mem: -1199
})

You could deserialise the transaction and check how many times the script is included and how large it is. This would be interesting. I read that SundaeSwap struggled with the size of its scripts and had to do some low level optimisations. But unfortunately there are no details on this to be found.

I am pretty sure that it is included only once, as signed transaction size is basically the same with either 1 or 15 utxos, and raw transaction size increases dramatically with each utxo. I can't think of any possible optimizations, as this seems to be lmited by design/architecture itself..

I understand now. It is not the transaction size constraint but the memory constraint that is hit here. I read in an article on iohk.io that the needed execution memory increases with every script-UTxO. I wondered on Twitter if the memory could not be cleared after each UTxO as they are independent of each other. I got no answer though and I don't know if this a yet unused optimisation or if something else is preventing this.

Out of curiosity, how large is the transaction-cbor, though ?

In my mind, the easiest solution for this would be to introduce some flag to allow executing validator script only once for the whole utxo input set and not for each utxo individually, as ScriptContext is aware of all of the utxos, and validation can be done in one iteration for all of them at once

transaction with my script (not AlwaysSuceeds), containing 10 utxo inputs, (and some other stuff) - {exUnitsMem = 19785600, exUnitsSteps = 8451556350}, built transaction - 104553 bytes, signed - 12619 bytes

found here: https://forum.cardano.org/t/max-number-of-transaction-inputs/60023/3, that each --tx-in generally uses about 38 bytes, so transaction size is not the main problem here, even though the utxo input limit is still somewhere in the hundreds for that limitation.

A script that always succeeds is a very special case. Optimisation this is certainly possible but I doubt if it is worthwhile.

Well it's the simplest possible script. Any further logic would additionally increase memory and CPU. From transaction building side, what else can we really do? And in general, I don't think this should be solved by optimizing individually, rather addressed by Cardano themselves, as this will be a blocker for many just a little bit more complicated use cases

I don't think we can do anything here. It looks to me like these memory and cpu consumptions are the result of some overhead to set up script execution (load redeemer, datum, and context). It is difficult to tell. Maybe it is possible to simplify the compiled Plutus code further and reduce resource consumption.

This is a known issue: https://github.com/input-output-hk/cardano-node/issues/3360
Out of curiosity, how many NFT's do you have per --tx-in? I've seen this increase memory usage dramatically with users on jpg.store who store a lot of NFT's in there wallet.
I have a few suggestions, knowing practically nothing about how this stuff works :P I'll share these in the Github issue as well.

Can we remove these limits entirely? Is there any reason why a user can't just pay more to execute a tx with higher mem/CPU requirements?

If #1 isn't possible, what is the reason for keeping the limits as low as they are currently?

Are there any efforts to optimize the Plutus compiler here? Surely adding a few more --tx-in's shouldn't blow up memory like this?

Thanks for the answer! well, these issues are only related. In the link you posted, I believe it is a simple transaction. This one is a transaction involving validator script. Also it is not NFT's. It's utxo's containing ADA or other CNT's, the main difference being the script inclusion in the transaction.

If the network had no computational bounds and was run on nuclear energy sure, but a lot of the nodes are people struggling to keep up with the current, ever increasing minimum requirements, and a lot of that energy is spinning turbines with steam from burning stuff. I don't understand why the contracts can't be iterated through... The network parameters are always known. If you can move them out in piecemeal then while it's a bug, it's not a blackhole.


text:
What are the security implications to having cardano-wallet run on a public server?
I want to use a public cardano-wallet server running on mainnet, so I can connect to it and create wallets for users of my iOS app.

How can I set up all transactions to be encrypted (over SSL) instead of over http?

Does the server keep logs of requests, and if so, how can I clear them? (I don't want to save a local record of anything I receive)

Are there any other security concerns?

In most cases, you should never manage users wallets with a hosted service. The whole point of a decentralized blockchain is that users are managing their own assets.
The best practice is to generate and keep the keys used in signing of a transaction within the iOS application managed by the user and use a hosted service to communicate with the Cardano blockchain (something like blockfrost.io or a hosted cardano-db-sync instance).

What if I'm using cardano-wallet to generate the pass-phrase and set a password - where does this get set? I can't use blockfrost to create a wallet, and I don't want to be responsible for the wallet either.

Your code needs to generate the passphrase, your application needs to protect the keys with a password. The user must be responsible for the wallet.


text:
Is there a publicly available Cardano API with pre-indexed blockchain data?
I'm looking for a public API that has idempotent endpoints that can be used to query for transaction data for a given address. Specifically, I'm looking for reward payout data. Does this exist in this ecosystem?
Thank you

Yes, have a look at blockfrost.io an API as a service that allows users to interact with the Cardano blockchain and parts of its ecosystem.

Thank you for this

Alternatively you can also try a community driven project https://dandelion.link/

Awesome ill check this one out


text:
Question about policy ID for native assets
If the policy ID for a some native token looks like this:
{

"keyHash": "wfwrfasdfasdfsadk4tjwljaldk1234567789123455678",

"type": "sig"

}

Can the token be minted and burned at any time by the owners of the keys? What are the limitations if any for a native token with a policy ID like this?
Thanks, Myles

Yes - this is an example of an unlocked policy. Tokens can be minted and burned under this policy forever with no limits.
Here would be an example of a time-locked policy:
{
  "type": "all",
  "scripts":
  [
    {
      "type": "before",
      "slot": 28515365
    },
    {
      "type": "sig",
      "keyHash": "3a25088ecd68bde986becda8ebc51077222f981cab4214025ccc7bfa"
    }
  ]
}

thanks so much!


text:
Automatically send funds out using a smart contract
I'm looking for an example or tutorial for how to write a smart contract which locks all ADA sent to it until a threshold of at least 1,000 ADA is reached. Once 1,000 ADA is reached, as much ADA as possible is sent to a pre-defined address and the counter resets. Is this possible with the current Plutus platform?
Thanks, Myles

I am not sure what you mean by automatically send funds out of smart contracts". If you mean without someone actually executing the contract in a transaction, this is not possible. Just people sending ADA to the smart contract address will not trigger the smart contract execution, someone has to do a transaction including the smart contract execution to do what you want.

Thanks for your reply, let me be more specific. I want a script which locks all ADA sent to it until a threshold is reached, like 1,000 ADA. Once the threshold is reached, there's a part of the script which sends out 1,000 ADA to a pre-defined address, and the cycle continues again until at least 1,000 ADA is locked in the contract again. It would be ideal for anyone to be able to send ADA to this script address. Also, what is the difference between triggering and not triggering a smart contract execution?

Just sending ADA to a smart contracts address will not execute the smart contract. Someone must execute the smart contract in a transaction.

Ok I understand that. I'm looking for an actual haskell code example/tutorial to carry this all out.

As @George pointed out, there is no such thing as "automatic" for smart contracts. Everything must be triggered manually by an off-chain actor.
That being said, you could definitely create a script that holds funds in escrow until a threshold is reached, at which point those funds become distributable/claimable.
This is similar to how the auction code works:
Each time someone bids, the auction datum is updated. In the case of the auction, once a deadline has been past, the bids are collectable by the seller and the bidder can claim their winnings.
You could follow a similar pattern where a datum tracks the ADA locked at the script address, and the datum is replaced with an updated datum each time more ADA is locked. At the point the locked ADA passes 1000, the funds become claimable.
There are many ways you could organize the distributions, but the simplest/closest to automatic might be as follows: any transaction that pushes the total equal to or over 1000ADA must distribute to the designated recipients, and all excess tokens will be rolled over to a new datum. That makes the last contribution more expensive, so it might discourage contributions, so you could consider paying the distribution fees with the pot or something else.

thanks so much!! this really helps me get on the right path


text:
Best practice for testing smart contract
Let's say you have your haskell code ready to test as a smart contract on the testnet, what is the best practice to go about testing if your smart contract works as intended? Does the same process work for the mainnet?
Thanks, Myles

This question is too broad. It really depends on the use case you are using the smart contract for. It is like asking what are best practices to test software.
Mainnet and testnet are just different networks, the smart contacts works the same way on both.


text:
Question about Plutus smart contract which always succeeds
Can anyone explain in detail why this script, https://github.com/james-iohk/Alonzo-testnet/blob/update-cabal-1.29.0/resources/plutus-sources/plutus-alwayssucceeds/src/Cardano/PlutusExample/AlwaysSucceeds.hs, results in the following output?
Writing output to:
alwayssucceeds.plutus
"Log output"
[]
"Ex Budget"
ExBudget {exBudgetCPU = ExCPU 297830, exBudgetMemory = ExMemory 1100}

Thanks, Myles

The output seems to be generated by this Haskell script (plutus-alwayssucceeds.hs) sitting in the parent folder of the script you linked. "plutus-alwayssucceeds.hs" is defined as the entry point of the executable defined in cabal file here.
When you run command like cabal build, cabal will build "plutus-alwayssucceeds.hs" as an executable, which, when executed, will print out the log pasted in the question above. Notice that the actual plutus script (alwayssucceeds.plutus) is generated by function "writePlutusScript" here.


text:
Error submiting Smart Contract with Nami, What does this error means?
I am running one smart contract with the Nami Wallet but I get this error:
""transaction submit error ShelleyTxValidationError ShelleyBasedEraAlonzo (ApplyTxError [UtxowFailure (WrappedShelleyEraFailure (UtxoFailure (UtxosFailure (ValidationTagMismatch (IsValid True) (FailedUnexpectedly [PlutusFailure \"\\nThe 3 arg plutus script (PlutusScript ScriptHash \\\"4b8980baf5b09f3573f26e100df813dd24a619d78188b9d56471e51f\\\") fails.\\nCekError An error has occurred:  User error:\\nThe provided Plutus code called 'error'.\\nThe data is: Constr 0 [B \\\"\\\\220\\\\166\\\\ETXW\\\\DC2\\\\241d\\\\219/\\\\153\\\\199\\\\DC4\\\\EOT\\\\211\\\\146\\\\DC1]+\\\\221\\\\227f\\\\251\\\\190\\\\&5\\\\154\\\\224\\\\US\\\\GS\\\",I 5000000,B \\\"\\\\233>\\\\198 \\\\150\\\\&1Q\\\\ETB\\\\DC3\\\\184\\\\&2\\\\229\\\\&"

It is from the Martify Repo https://github.com/MartifyLabs/martify.contracts in the buy endpoint. I just wanted to be sure.. The error comes from plutus contract not validating right? since there are not datum or another related error in the transaction that i can read. It is related to this post Cardano-cli error when submitting transaction when they get the same error in the cancel endpoint.
My doubt comes from the fact that the console does not logs the error messages provided in the on-Chain code:
{-# INLINABLE mkBuyValidator #-}
mkBuyValidator :: PubKeyHash -> NFTSale -> SaleAction -> ScriptContext -> Bool
mkBuyValidator pkh nfts r ctx =
    case r of
        Buy    -> traceIfFalse "NFT not sent to buyer" checkNFTOut &&
                  traceIfFalse "Seller not paid" checkSellerOut &&
                  traceIfFalse "Fee not paid" checkFee
        Update -> traceIfFalse "No rights to perform this action" checkUser &&
                  traceIfFalse "Modified datum other than price" checkDatum &&
                  traceIfFalse "NFT left the script" checkContinuingNFT
        Close  -> traceIfFalse "No rights to perform this action" checkUser &&
                  traceIfFalse "Close output invalid" checkCloseOut

So before start debugging i would like to know i am looking at the right place, I assume this traces are not shown because of the maximum size of the printed error that Nami allows, am I right?

Yup, it seems like the validation for your script fails, usually, when that happens you'll get this error ValidationTagMismatch (IsValid True) (and you got it).
There is probably something wrong with either datum or redeemer.


text:
Hacking (Nami) Wallet
When asking the user to sign a transaction, Nami Wallet displays a screen with a summary showing how the user wallet gets affected (e.g. how much Ada is payed or received).
To be able to compute this summary, Nami must have a complete list of the wallet's own funds (UTxOs). Otherwise, it could be that it does not recognise own input UTxOs consumed in the transaction (input UTxOs being only referred to by the hash of the originating transaction and index).
Now, is it possible that a dApp makes a timing attack where it uses —as input of a transaction— some fresh UTxOs, payed to the users address, that the wallet, however, has not indexed yet ? A user signing the transaction would have the wrong impression that he is not spending own funds, whereas in reality the transaction could spend and transfer to a random receiver the users funds.
The only way to protect against these attacks, I see, is that the wallet needs to query the blockchain for all transaction inputs that it has not indexed, before showing the summary screen. Is this done ? I doubt it, as the screen seems to appear very quickly.
(I use Nami as an example, but this scenario could apply to any wallet.)

Why would the user think they are not spending their own funds?
Obviously a user cannot sign a transaction for spending funds they do not own.

The funds spend in a transaction are referred to by a hash and an index. To know that it is part of the user's funds, the wallet must either have it in its cache or it must look up the blockchain to figure out at which address the input fund is sitting. The user can sign the transaction and it would be valid because it contains only his own funds. But a poorly designed wallet could think that these input funds do not belong to the user and display a wrong summary screen.

DApps merely prepare the transaction and invoke the wallet to get it signed and submitted to the blockchain. So I think the wallets would/should validate if the inputs of the transaction submitted by the dApp, contains just utxos indexed by the wallet and only then show the pop up asking user to sign it.
The scenario would be similar to trying to send more than what a wallet contains (even without a dApp).