text:
Creating Shelley Wallet Sync takes way too much time
Here is how I create a wallet:
  let recoveryPhrase = Seed.generateRecoveryPhrase();
  console.log(recoveryPhrase);

  let mnemonic_sentence = Seed.toMnemonicList(recoveryPhrase);
  //console.log(mnemonic_sentence);

  let passphrase = "pass";
  let name = "name";

  let wallet = await walletServer.createOrRestoreShelleyWallet(
    name,
    mnemonic_sentence,
    passphrase,
    null,
    10
  );

It does create a wallet, however, I'm also waiting for the wallet to get synced and while it gets syncing I cannot retrieve balance information.
Listing wallets in cli via cardano-wallet wallets list command:
"name": "name",
    "id": "wallet-id",
    "tip": {
        "height": {
            "quantity": 6015225,
            "unit": "block"
        },
        "epoch_number": 279,
        "time": "2021-07-23T02:30:50Z",
        "absolute_slot_number": 35441159,
        "slot_number": 276359
    },
    "passphrase": {
        "last_updated_at": "2022-09-09T07:58:21.052641502Z"
    },
    "address_pool_gap": 10,
    "state": {
        "status": "syncing",
        "progress": {
            "quantity": 77.19,
            "unit": "percent"
        }
    },
    "delegation": {
        "next": [],
        "active": {
            "status": "not_delegating"
        }
    },
    "assets": {
        "total": [],
        "available": []
    }
}

Why do Cardano Wallets need to be synced? Is there anything that I can do to speed up the syncing process?

Why do Cardano Wallets need to be synced?

An unsynced wallet will be empty. It is only by reading the chain that transactions to and from the wallet can be found and the balance adjusted accordingly.
You did not say how long its taking. Is it an hour, 10 hours, 3 days? What is your expectation?


text:
How to get TransactionUnspentOutput as a hex encoded bytes string programmatically
So basically I want to convert a normal UTxO hash like:
550665309dee7e2f64d13f999297f001763f65fe50bb05524afc0990c7dce0c3
to a TransactionUnspentOutput as a hex encoded bytes string like:
828258205537396d59c1b0546bb9cec5cb6b930238af2d8998d24ca1d47e89a3dd400a8701825839016af9a0d2c9b5bce8999bc6430eb48f424399b73f0ecc143f40e8cac89b130cc3198a8594862fe25df331cb79447304dcd49712c86834fdf1821a00150bd0a1581cb0df0ee7dbb96b18b682a1091514f250eb0ec1122e6c4bf3b4d45123a14b436f6e766963743033363701
This is how it is done with a nami wallet implementation:
cardano.getUtxos(amount?: Value, paginate?: {page: number, limit: number}) : [TransactionUnspentOutput]
I tried to pass a UTxO into the lucid utxoToCore() function:
export const utxoToCore = (utxo: UTxO): Core.TransactionUnspentOutput => {
  const output = C.TransactionOutput.new(
    C.Address.from_bech32(utxo.address),
    assetsToValue(utxo.assets)
  );
  if (utxo.datumHash) {
    output.set_datum(
      C.Datum.new_data_hash(C.DataHash.from_bytes(fromHex(utxo.datumHash)))
    );
  }
  return C.TransactionUnspentOutput.new(
    C.TransactionInput.new(
      C.TransactionHash.from_bytes(fromHex(utxo.txHash)),
      C.BigNum.from_str(utxo.outputIndex.toString())
    ),
    output
  );
};

However the only output I get is: TransactionUnspentOutput { ptr: 1247376 }
How to get the unpacked (?), or at least the right format I want,  TransactionUnspentOutput?

Fixed it with this code:
Buffer.from(utxoToCore(data).to_bytes()).toString("hex")
Data example:
  txHash: "5537396d59c1b0546bb9cec5cb6b930238af2d8998d24ca1d47e89a3dd400a87",
  outputIndex: 0,
  assets: { lovelace: 5000000 },
  address:
    "addr1q940ngxjex6me6yen0ryxr453apy8xdh8u8vc9plgr5v4jymzvxvxxv2sk2gvtlzthenrjmeg3esfhx5jufvs6p5lhcsak86ux",
};```

source: Stack Exchange

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

sort: votes


text:
How to get number of delegators of a pool?
Using cardano-db-sync, I want to get the number of delegators given a pool_id.
For example, this pool has 22 delegators.
https://cardanoscan.io/pool/18109d01af0c5c4495a64a9de061ad621156729afc699128c0ceee0e?tab=delegators
However, when I used the following query, the result did not match. The following query returns 66 unique values of stake_address.hash_raw.
select pool_hash.view,stake_address.hash_raw::text, stake_address.view,
delegation.active_epoch_no, delegation.slot_no
from delegation, pool_hash, stake_address
where delegation.pool_hash_id = pool_hash.id and delegation.addr_id =stake_address.id
and pool_hash.view ='pool1rqgf6qd0p3wyf9dxf2w7qcddvgg4vu56l35ez2xqemhqun2gn7y'

I want to ask that

It seems the the table delegation also contains the delegation history, not only the delegation at current time? If so, which table should I use to be able to filter out to get only the number of current delegators.

How can I get the number of delegators w.r.t a pool_id
(2.1) at the current epoch
(2.2) for each epoch

It seems the the table delegation also contains the delegation history, not only the delegation at current time?

Yes, that makes the delegation table a bit of a pain in the neck for something like this.
Its probably easier to use the epoch_stake table. The simplest query would be something like (choose the epoch you are interested in):
select epoch_no, pool_id, count(*), sum (amount) as delegated from epoch_stake
    where epoch_no = 362 group by (pool_id, epoch_no) ;

 epoch_no | pool_id | count |   delegated
----------+---------+-------+----------------
      362 |    3081 |     2 |       70449031
      362 |     361 |    10 |   264344058414
      362 |    1286 |    34 |   709992195312
      362 |     560 |     1 |      507621786
      362 |    5214 |    10 |  4983514457611
      362 |    4090 |     3 |     1893354467
      362 |    4791 |     9 |   335768752617
      362 |    3159 |     3 |     5945300103
      362 |    5215 |    99 |  1358232546301
      362 |    4765 |     7 | 13999900770537
      362 |    2623 |    52 |  3429179709353
...

The pool fingerprint (ie pool1rqgf6qd0...) can be obtained with a join on the pool_hash table like you have in your example. Also, note that unfortunately, the epoch_stake table for epoch N is updated late in epoch N - 1 (I think).
To get the delegation history for a pool, something like this should work:
select epoch_no, pool_id, count(*), sum (amount) as delegated from epoch_stake
    where pool_id = 3081 group by (pool_id, epoch_no) order by epoch_no asc  ;
 epoch_no | pool_id | count |   delegated
----------+---------+-------+---------------
      258 |    3081 |     2 |      70643792
      259 |    3081 |     4 | 2105455092524
      260 |    3081 |     4 | 2105455092524
      261 |    3081 |     4 | 2105455092524
      262 |    3081 |     4 | 2105455092524
...

A simple join with the pool_hash table will allow you to use the pool fingerprint.

Thanks so much. You save my day.

I would like to ask a follow-up question.
From this epoch_stake table, I can get the delegated amount for each stake_address per epoch.
Does this delegated amount already include the reward?
Or I need to add the reward mount (from reward table) to get proper delegated amount?

No, the reward for epoch N is not included in the delegated amount for that epoch because the rewards earned in epoch N are not distributed until epoch N + 2. From this I hope you can see that you should not add the reward amount to the delegated amount.

I see. Thank you. So the delegated amount for epoch N (in epoch_stake table)  already includes rewards for epoch N-2? Or not include yet?

Yes, the delegated amount for epoch N already includes rewards earned in epoch N - 2 and earlier.

Thanks very much

The poor man's way to find out is to go to pool.pm and type in the pool of interest ticker, and at the top header is the number of delegators.

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


text:
Cardano java lib
Can someone help me understand the below error message better. It first started appearing about 2 months ago when I mint tokens, and I cant seem to get to the bottom of it. I understand the BabbageOutputTooSmallUTxO to mean the output is from the tx is too small (ie. not enough input). The annoying thing is it worked well not that long ago
[cardano-wallet.wallet-engine:Error:9588] [2022-09-07 11:12:19.67 UTC] 9351a932: Transaction ef626e5b failed: ErrSubmitTxNetwork (ErrPostTxValidationError "TxValidationErrorInMode (ShelleyTxValidationError ShelleyBasedEraBabbage (ApplyTxError [UtxowFailure (UtxoFailure (BabbageOutputTooSmallUTxO [((Addr Testnet (KeyHashObj (KeyHash \"d27f32....b0ae3\")) (StakeRefBase (KeyHashObj (KeyHash \"ca75b4....44af711c\"))),Value 172400 (fromList [(PolicyID {policyID = ScriptHash \"e89fd72....cdfdd5\"},fromList [(5275626265724d616e,1)])]),NoDatum,SNothing),Coin 1159390)]))])) BabbageEraInCardanoMode")

I have tested the transaction on Blockfrost and Cardano Wallet API and both produce the same error.
I am using https://cardano-client.bloxbean.com Java library to build the transaction using the methods suggested in the documentation and here https://satran004.medium.com/cardano-client-lib-minting-a-new-native-token-in-java-part-iii-1a94a21cfeeb
This is my decompiled transaction
{
    "burn": {
        "tokens": []
    },
    "certificates": [],
    "collateral": [],
    "collateral_outputs": [],
    "deposits_returned": [],
    "deposits_taken": [],
    "fee": {
        "quantity": 186929,
        "unit": "lovelace"
    },
    "id": "91d16f5c982b401b7c3d039c3bc8b213eea97f6dfbfc0b311682facf34e1627c",
    "inputs": [
        {
            "address": "addr_test1qql63uhskkchjsy74kjyx9tk8azsl9gfjxfk8rarnvsshn3sl2jjsnfkffuhuuug5vywcyh0704hpyldjrzjacts4qpqa40yu4",
            "amount": {
                "quantity": 500000000,
                "unit": "lovelace"
            },
            "assets": [],
            "derivation_path": [
                "1852H",
                "1815H",
                "0H",
                "0",
                "0"
            ],
            "id": "d5432926ad3397aeef7b4287ef6eb09a236e7484a8b7d88ad747e72814333b19",
            "index": 0
        }
    ],
    "metadata": {
        "721": {
            "map": [
                {
                    "k": {
                        "string": "version"
                    },
                    "v": {
                        "string": "1.0"
                    }
                },
                {
                    "k": {
                        "string": "2037e837ffb5536a8795f493ed14c1f91fc9130df3466386750168a1"
                    },
                    "v": {
                        "map": [
                            {
                                "k": {
                                    "string": "TestAsset-Meta"
                                },
                                "v": {
                                    "map": [
                                        {
                                            "k": {
                                                "string": "name"
                                            },
                                            "v": {
                                                "string": "My-Cool_NFT"
                                            }
                                        },
                                        {
                                            "k": {
                                                "string": "image"
                                            },
                                            "v": {
                                                "string": "ipfs://Qme7ss3ARVgxv6rXqVPiikMJ8u2NLgmgszg13pYrDKEoiu"
                                            }
                                        }
                                    ]
                                }
                            }
                        ]
                    }
                }
            ]
        }
    },
    "mint": {
        "tokens": [
            {
                "assets": [
                    {
                        "asset_name": "546573744173736574",
                        "fingerprint": "asset1q0skl97csmvgxtewd2jrrpvdzw4hyg83wcyee2",
                        "quantity": 1
                    }
                ],
                "policy_id": "2037e837ffb5536a8795f493ed14c1f91fc9130df3466386750168a1",
                "policy_script": {
                    "script": "policy_vkh17g7njq60dfrx76xyelltw69lff2c6md7y2guhmdflxm2jgywwgz",
                    "script_type": "native"
                }
            }
        ],
        "wallet_policy_key_hash": "policy_vkh15cnjur9ld37p9gznxafzs2jtqf4qpxlyhwhccwt9kktt53gt76u",
        "wallet_policy_key_index": "0H"
    },
    "outputs": [
        {
            "address": "addr_test1qql63uhskkchjsy74kjyx9tk8azsl9gfjxfk8rarnvsshn3sl2jjsnfkffuhuuug5vywcyh0704hpyldjrzjacts4qpqa40yu4",
            "amount": {
                "quantity": 499640671,
                "unit": "lovelace"
            },
            "assets": [],
            "derivation_path": [
                "1852H",
                "1815H",
                "0H",
                "0",
                "0"
            ]
        },
        {
            "address": "addr_test1qrf87vnetzcmf4vdzhpyatzr90c036xpzkhsdjp4y5as4c72wk6fknuew0vvy6s7jklr2c92t7uf3plyuqvcw390wywql37usz",
            "amount": {
                "quantity": 172400,
                "unit": "lovelace"
            },
            "assets": [
                {
                    "asset_name": "546573744173736574",
                    "policy_id": "2037e837ffb5536a8795f493ed14c1f91fc9130df3466386750168a1",
                    "quantity": 1
                }
            ]
        }
    ],
    "script_validity": "valid",
    "validity_interval": {
        "invalid_before": {
            "quantity": 0,
            "unit": "slot"
        },
        "invalid_hereafter": {
            "quantity": 68437663,
            "unit": "slot"
        }
    },
    "withdrawals": []
}

I understand the BabbageOutputTooSmallUTxO to mean the output is from the tx is too small (ie. not enough input). The annoying thing is it worked well not that long ago

It might have worked in an earlier era (ie Alonzo) but my suspicion is that the rules have changed slightly for the new Babbage error.
The error message also gives the value of 172400 (in lovelace) as being too small and that value does appear in your transaction outputs. Again I suspect that value has increased slightly.

You were right. Thanks for the response

Does somebody know how to update the SDK? I would like to get documentations or something like this please <3

Yes the calculation of the min UTxO value has changed which is explained here. So Erik is correct!
I would try to update the library you're using to create your transaction, because whatever SDK or library you're using, I'd expect it to handle that change for you.

Thank you, I started using the beta version of the lib and it works now. I felt I had already tried it but anyway


text:
Using testnet with Nami
I want to test a dapp on the Prepod testnet with the Nami wallet. I tried to receive tAda with the faucet but nothing is showing up on the wallet interface.
This is the wallet
addr_test1qrgupcpekj8x5wzw4kk37g38eceh9wdyqeap3puky8yy2k5zpumumlqxeggrg9ezllhhnyrqr892v5tdevccaz780d8s7kw9xp
This is the tx hash
c5a3c23285e44688643f79d2be08ae54e50812e6fe6857028260ff80380ea6a0
What can I do to fix the Nami interface? Or what wallet can I use instead?

The currently released version of Nami runs on the old testnet, but here's a vasil-ready branch of it, that you can install separately for testing on the preprod (or preview) testnet:
https://github.com/berry-pool/nami/tree/vasil
You can download the build from here and

Extract the zip. Then go to chrome://extensions, click Load unpacked
at the top left and select the build folder.

Until Nami adds support for pre-prod testnet you'll need to use a wallet that already supports it, like Eternl.


text:
Convert ChainIndexTxOut to TxOutTx
I have this function that is expecting type TxOutTx, but it receives ChainIndexTxOut. I'm trying to convert to the type required but encountering issues
getTradeDatum o = case txOutDatum (txOutTxOut o) of
    Just h -> do
        let [(_,datum)] = P.filter (\(h',_) -> h == h') (Map.toList (txData (txOutTxTx o)))
        let parsedDatum = PlutusTx.fromBuiltinData (getDatum datum) :: Maybe TradeDatum
        case parsedDatum of
            Just b -> b
            _ -> traceError "expected datum"
    _ -> traceError "expected datum"

I get the error:
    * Couldn't match expected type `TxOutTx'
                  with actual type `ChainIndexTxOut'
    * In the first argument of `txOutTxOut', namely `o'
      In the first argument of `txOutDatum', namely `(txOutTxOut o)'
      In the expression: txOutDatum (txOutTxOut o)
    |
586 | getTradeDatum o = case txOutDatum (txOutTxOut o) of
    |

I've tried the following solution, changing the single line below, because _ciTxOutValue has worked for me before:
getTradeDatum o = case _ciTxOutDatum o of

But then I get this error:
 error:
    * Couldn't match expected type `Either DatumHash Datum'
                  with actual type `Maybe DatumHash'
    * In the pattern: Just h

Well the last error tells you that you don't have a Maybe but an Either type. You're trying to pattern match against a Maybe instead of Either at this point in your code:
case txOutDatum (txOutTxOut o) of
   (Left _)  -> ...
   (Right _) -> ...

My guess is you actually want to do something like this:
getMyDatum :: ChainIndexTxOut -> MyDatum
getMyDatum o = case _ciTxOutDatum o of
    Left _ -> traceError "Unexpected Datumhash"
    Right (Datum d) -> do
        let parsedDatum = PlutusTx.fromBuiltinData d :: Maybe MyDatum
        case parsedDatum of
            Just s -> s
            _ -> traceError "Unknown datum type"

Thank you so much I really appreciate the help, that solved it :)

No prob, glad I could help. Would appreciate if you can mark my response as answer with the checkmark icon :).


text:
Running preview/preprod Cardano-node on windows
Im trying to run preprod node .
steps i followed :
1- downloaded these files : https://book.world.dev.cardano.org/environments/preprod/
2- run this :
cardano-node.exe run --topology ./configuration/cardano/topology.json --database-path ./db --port 3001 --config ./configuration/cardano/config.json --socket-path .\pipe\cardano-node and
but i get this error :
doesnt happen with mainnet or old dead testnet .... any idea ?

it looks like your socket-path and the wrong facing slashes should be ./pipe/cardano-node.
Also not sure how you built your node but typically the socket path is in the DB folder so in your case ./db and typically socket is ./db/socket


text:
Can't submit (allegedly) correct transaction
Ok, here we go.
First, the balance:
$ cardano-cli query utxo --address addr1vx9z6r6pv5g8aprprvjj2jhamsj4szr6j502fk7wkzq6a3sx0736n --mainnet
                           TxHash                                 TxIx        Amount
--------------------------------------------------------------------------------------
6adeb2bb5e294bcaf4b3aaf555b121e20cfb1c69631d2a8ba64c6b935201e9de     0        4579280 lovelace + TxOutDatumNone

checking that my vkey is the correct one:
$ cardano-cli address build --payment-verification-key-file payment.vkey --mainnet
addr1vx9z6r6pv5g8aprprvjj2jhamsj4szr6j502fk7wkzq6a3sx0736n

building transaction:
$ txin=6adeb2bb5e294bcaf4b3aaf555b121e20cfb1c69631d2a8ba64c6b935201e9de
$ txix=0
$ utxo=4579280
cardano-cli transaction build-raw --tx-in "$txin#$txix" --tx-out "$(cat ../coldwallet.addr)+0" --invalid-hereafter 0 --fee 0 --out-file test.draft

Calculating fee, expiry & rebuilding transaction:
$ fee=( $(cardano-cli transaction calculate-min-fee --tx-body-file test.draft --tx-in-count 1 --tx-out-count 1 --witness-count 1 --byron-witness-count 0 --mainnet --protocol-params-file ../protocol.json) )
$ slot=$(( $(cardano-cli query tip --mainnet | jq '.slot')+3600 ))
$ cardano-cli transaction build-raw --tx-in "$txin#$txix" --tx-out "$(cat ../coldwallet.addr)+$(($utxo-$fee))" --invalid-hereafter $slot --fee ${fee[0]} --out-file test.draft

signing, checking and submitting it:
$ cardano-cli transaction sign --tx-body-file test.draft --signing-key-file payment.skey --mainnet --out-file signed.tx
$ cardano-cli transaction view --tx-file signed.tx
auxiliary scripts: null
certificates: null
collateral inputs: []
era: Alonzo
fee: 171045 Lovelace
inputs:
- 6adeb2bb5e294bcaf4b3aaf555b121e20cfb1c69631d2a8ba64c6b935201e9de#0
metadata: null
mint: null
outputs:
- address: [REDACTED]
  address era: Shelley
  amount:
    lovelace: 4408235
  datum: null
  network: Mainnet
  payment credential:
    key hash: a63e72099726eddcb7b8022bbf11284ba4f6c1f022413b4e9725bd6e
  stake reference:
    key hash: 1e87128217ca8baadf5af504d50fb4f08e406aa979c62a75998e85c5
update proposal: null
validity range:
  lower bound: null
  upper bound: 71465269
withdrawals: null
$ cardano-cli transaction submit --tx-file signed.tx --mainnet
Command failed: transaction submit  Error: Error while submitting tx: ShelleyTxValidationError ShelleyBasedEraAlonzo (ApplyTxError [UtxowFailure (WrappedShelleyEraFailure (MissingVKeyWitnessesUTXOW (WitHashes (fromList [KeyHash "8a2d0f4165107e84611b25254afddc2558087a951ea4dbceb081aec6"]))))])

I've tried everything within my knowledge to fix that, but i couldn't.
I've tried to generate the vkey from my skey again, using:
$ cardano-cli key verification-key --signing-key-file key.skey --verification-key-file key.vkey

but it generates a different vkey, which gives me a different address.
Any ideas?

I'm going to answer you the same thing I answered on the cardano forum: if the last command gives you a different vkey. which gives you a different address, it means you have the signing key from a different address, not from the address where the ADA is.


text:
cardano-cli Command failed: transaction sign Error: Failed to decode neither the cli's serialisation format nor the ledger's CDDL serialisation [...]
I have a CBOR and want to sign the transaction using the Cardano-cli.
This is the error I get:
Command failed: transaction sign  Error: Failed to decode neither the cli's serialisation format nor the ledger's CDDL serialisation format. TextEnvelope error: jpgCbor.body: TextEnvelope decode error: DecoderErrorDeserialiseFailure "Shelley TxBody" (DeserialiseFailure 568 "expected list start")
TextEnvelopeCddl error: jpgCbor.body: TextEnvelopeCddl type error:  Expected one of: Witnessed Tx Byron, Witnessed Tx Shelley, Witnessed Tx AllegraEra, Witnessed Tx MaryEra, Witnessed Tx AlonzoEra, Unwitnessed Tx Byron, Unwitnessed Tx Shelley, Unwitnessed Tx AllegraEra, Unwitnessed Tx MaryEra, Unwitnessed Tx AlonzoEra Actual: TxBodyAlonzo

And this is the jpgCbor.body file:
{
    "type": "TxBodyAlonzo",
    "description": "",
    "cborHex": "[encoded data, 9922 characters]"
}

What did I do wrong, or what do I have to do for it to succeed?
Do you have an idea? Would help me a lot!

Your CBOR is in cddl format, so the type must be "Unwitnessed Tx AlonzoEra".
When using one of the cli cmds to build the transaction body (build or build-raw) then using --cddl-format flag will do this for you.


text:
How can I convert the hex hash ID of a stake pool to "pool1..." format in Javascript or TypeScript?
I want to convert the hash of a pool in hexadecimal to pool1... format
How can I do this?

The encoding is called Bech32.
I suspect that cardano-addresses can do this conversion.

You can do it with the bech32 command (which comez in the cardano-wallet package, if you don't already have it):
bech32 pool <<< <hex_pool_id>


text:
What's a BabbageOutputTooSmallUTxO error? How to access minAda in Plutus code?
I'm trying to convert a V1 contract to V2, and I have offchain code that mints a token with a OneShotCurrency, and then pays the token plus 1 ada to my script.
It worked with Plutus libraries from Feb. 2022, but I'm trying to upgrade it to match the upcoming Vasil HF, so I'm using plutus-apps v1.0.0-alpha1
In the emulator it is currently giving me this error:
TxnValidationFail Phase1 d6dddf483108cdd66915dac9c81d5c41263de34272366f11517debd1597ba3fc:
    CardanoLedgerValidationError "ApplyTxError [UtxowFailure (UtxoFailure
                                 (BabbageOutputTooSmallUTxO [((Addr Testnet ...

It appears that the min Ada amount is higher than 1 Ada, because if I change it to 10 Ada, it works.
Does anyone know if there's Plutus code for checking for the minAda required for a tx, without using the cardano-cli?

This was just answered here.
The min UTxO output value calculation has changed for the Babbage era. Make sure you're using the latest version of whatever library/ sdk you're using to construct transactions.

Yes, you're correct, the Babbage era has changed the calculations. You can no longer submit a tx that pays an NFT to a script, such as an oracle script, without including an amount of Ada with it. This might have already been the rule on the testnet and mainnet, but the Emulator used to let it go. I've upgraded to the V2 libraries, so now the Emulator enforces this rule.

I unfortunately asked 2 questions in one, and since @william answered one of them he should get the credit for the answer.
To answer the second question for future reference, there is indeed a Plutus function that does get the min amount of Ada so you can add that to your Tx Constraints: maxMinAdaTxOut
    let c = Constraints.mustPayToOtherScript (oracleValidatorHash oupOracle)
                    (V1LedgerScripts.Datum $ PlutusTx.toBuiltinData oupNewFee)
                       $ ((assetClassValue (oracleAsset oupOracle) 1) <>
                          (Ada.toValue maxMinAdaTxOut))

I've tested this within the Emulator and it does indeed work.

Good point! I forgot to mention that. Great that you've found out yourself.

18.5 is a lot of ada to be passing around just to satisfy minUtxo. You'll probably find that most outputs only need a little more than 1 ada when they hold a few tokens and some datum. It would be best to calculate the realistic maximum for your application, see evaluateMinLovelaceOutput.


text:
Mobile app security concerns
I'm looking into creating a mobile app for learning purposes and using Blockfrost as a data provider.
My initial idea is:

Device:

control the keys;
present the data;

Server:

fetch data from blockfrost;
core application (aggregate data, construct txs)
notifications;

mobile -> server -> blockfrost
Mobile app will share only the stakeKeyAddress to the server.
Also, the server will construct the transactions, but the signature will be done on the mobile side.
Do you find any issues with this approach?
Many thanks!

In general, it looks good. The way you store signing keys on the device is critical. Ideally, you want to support hardware wallets. Otherwise, make use of the OS native keystore (android/iOS).
You might be able to decrease the number of requests to your server when you have clients construct their signed Txs locally and have them submit to your backend. That decreases the back and forth of sending unsigned txs to the client, have them sign the Tx and submit to the backend again.

@william-berlin-pool I'll take a look into OS native keystore! I decided to export the account public key and do coin selection + fee on the server side. (I might move this to the client tough)
Thanks for helping!

Cool! I'd recommend having the coin selection alg implemented where the wallet lives to avoid further utxo set exchanges.
This describes the preferred alg implementation well: https://cips.cardano.org/cips/cip2/


text:
Cannot find wrapMintingPolicy after updating to latest release of plutus-apps
I've just checked out the latest release of the plutus-apps repository and ensured to copy the respective cabal.project dependencies (including their commit hashes). But I get a weird error, I didn't receive running it with the older version.
src/Contract/MyPolicy.hs:44:43: error:
    • Not in scope: ‘Scripts.wrapMintingPolicy’
      Module ‘Ledger.Typed.Scripts’ does not export ‘wrapMintingPolicy’.
    • In the Template Haskell quotation
        [|| \ oref' tn'
              -> Scripts.wrapMintingPolicy $ mkMyPolicy oref' tn' ||]
      In the typed splice:
        $$(PlutusTx.compile
             [|| \ oref' tn'
                   -> Scripts.wrapMintingPolicy $ mkMyPolicy oref' tn' ||])
   |
44 |     $$(PlutusTx.compile [|| \oref' tn' -> Scripts.wrapMintingPolicy $ mkMyPolicy oref' tn' ||])

Usually, the Ledger.Typed.Scripts modules exported the wrapMintingPolicy function.
Source 1
cabal.project:
source-repository-package
  type: git
  location: https://github.com/input-output-hk/plutus-apps.git
  tag: v1.0.0-alpha1

...

source-repository-package
  type: git
  location: https://github.com/input-output-hk/plutus
  tag: a56c96598b4b25c9e28215214d25189331087244

You could try to replace Scripts.wrapMintingPolicy with Scripts.mkUntypedMintingPolicy
...

import Plutus.Script.Utils.V1.Typed.Scripts qualified as Scripts

...
$$(PlutusTx.compile
             [|| \ oref' tn'
                   -> Scripts.mkUntypedMintingPolicy $ mkMyPolicy oref' tn' ||])

Thanks a lot! I really appreciate it! It looks like all of these wrappers are being removed with the new Plutus version.
Just found this commit:
https://github.com/input-output-hk/plutus-apps/commit/91ee6f5b9d2cb6c620803ee367a2d1a145d63b48


text:
Ogmios: Follow the tutorial but the Server running for few seconds in Docker then auto terminate :?
I'm new to Ogmios. I'm having trouble using it and I would like someone to help me please. My story is I'm following the tutorial, running this command :

docker run -it \
--name cardano-node-ogmios
-p 1337:1337
-v cardano-node-ogmios-db:/db --platform linux/amd64
cardanosolutions/cardano-node-ogmios:latest

I add "--platform linux/amd64" to the command because the original command from the link produce error of not compatible between linux/amd64 (the images platform) and linux/arm64/v8 (my platform, I'm running on M1 mac).
The output of it is like this:

I guess the command run successfully, even though I don't understand what the last 2 lines mean.
However, whenever I start the container in Docker, it only run a few seconds then stop.
Here's the log of it in Docker:

I guess this should not be the behavior. I think the container is supposed to be running continuously so I can send API request to "localhost:1337" to get data from Cardano. Would anyone tell me what is the problem here please? Thank you!

you could check your system logs why those processes were killed, maybe out of memory. Or try running the docker again with as little as possible running in the background.

Hi @DaveStrider, I don't know what you mean about "system logs", all I can receive is the logs of docker, like this "/root/cardano-node-ogmios.sh: line 31:    14 Killed                  cardano-node run --topology /config/cardano-node/topology.json --database-path /db --port 3000 --host-addr 0.0.0.0 --config /config/cardano-node/config.json --socket-path /ipc/node.socket"
I don't know how to check memory exactly, I think my Mac M1 should not have this problem cause I only run this only one container and nothing in the background.

The docker container was build for Linux (with the ogmios binary compiled on Linux). It cannot work on Mac OS. The question was already answered on Discord, you will not get another answer by asking in different places.

@George-APEXStakePool yeah that's me asking, I ask here first but seem like no one answer so I move to discord.

Did you got it running finally?
I'm having similar issues with running with docker the latest version, with the usual command
docker run -it
--name cardano-node-ogmios
-p 1337:1337
-v cardano-node-ogmios-db:/db
cardanosolutions/cardano-node-ogmios:latest
28 16:58:44.61 UTC] Chain extended, new tip: d46c975338e913e14abad59702c8d0dd5dabbe512fd744032e9490cdf70d5b16 at slot 22060401
/root/cardano-node-ogmios.sh: line 31:    11 Killed                  cardano-node run --topology /config/cardano-node/topology.json --database-path /db --port 3000 --host-addr 0.0.0.0 --config /config/cardano-node/config.json --socket-path /ipc/node.socket
That it will just die out randomly and afterwards restarting it will start syncing but it could randomly fail any time, maybe i need to add something  to add to that command that it will automatically restart when it fails?

The main cause of the issue, was that memory was running out( nothing was telling me about it... on closer inspection noticed it), i had to increase to maximal memory capacity through settings, if somebody will run in to the same problem.


text:
How to get Integer from Cardano.Ledger.BaseTypes.TxIx
I am using the following function from the Plutus pioneer program:
stakeReferenceLedgerToPlutus :: Ledger.StakeReference StandardCrypto -> Maybe Plutus.StakingCredential
stakeReferenceLedgerToPlutus (StakeRefPtr (Ptr (SlotNo x) y z)) = Just $ StakingPtr (fromIntegral x) (fromIntegral y) (fromIntegral z)

But the latest release of Plutus-apps seems to require a change, because fromIntegral y does not work anymore. See error below:
error:
    • No instance for (Integral Cardano.Ledger.BaseTypes.TxIx)
        arising from a use of ‘fromIntegral’
    • In the second argument of ‘StakingPtr’, namely ‘(fromIntegral y)’

The same is true for fromIntegral z but for Cardano.Ledger.BaseTypes.CertIx.
Any help is appreciated.

The problem is that on the LHS you have:
StakeRefPtr (Ptr (SlotNo x) y z)

but StakeRefPtr is defined (in cardano-ledger repo, file libs/cardano-ledger-core/src/Cardano/Ledger/Credential.hs) as:
   | StakeRefPtr !Ptr

and Ptr is defined as:
data Ptr = Ptr !SlotNo !TxIx !CertIx

and TxIx is defined as:
newtype TxIx = TxIx Word64

That means, to get your code closer to working you should try:
stakeReferenceLedgerToPlutus :: Ledger.StakeReference StandardCrypto -> Maybe Plutus.StakingCredential
stakeReferenceLedgerToPlutus (StakeRefPtr (Ptr (SlotNo x) (TxIx y) z)) = Just $ StakingPtr (fromIntegral x) (fromIntegral y) (fromIntegral z)

You probably also need to do the same for the z which is defined as a:
newtype CertIx = CertIx Word64

Thanks! Pattern matching to get the wrapped type makes complete sense.


text:
Whether validation checks are necessary
In Plutonomicon github repo it says by the end of the page:

For example, you don't need to prevent an unexpected transaction from locking value away - that's the submitter's own problem - but you do need to stop them from inappropriately spending value.

As i understood, we dont need our on-chain part to fill in all variants of the off-chain code.
So, if we have, for example, some kind of dex Plutus script that sells tokens, assigned to script outputs: one output - one token. In that case we should avoid checking outputs' addresses of sell-transaction for correctness, even with probability of "dishonest" off-chain(for example, extra constraint "MustPayToPubKeyAddress")? Consider that fixed amount of minAda for each output is not set by script logic.

In your validator, you should check only for what is related to the script logic.
depending on your needs you may want your user only to perform that specific action in the transaction, so you can add additional checks that specify that only that action is intended (e.g. only one input from the buyer) but this of course means transactions with two inputs form the same PubKeyHash will fail.
So, if in order to sell some tokens you only need to pay a certain amount of lovealces and you don't require anything else; then you should check for anything else, allowing the transaction to succeed no matter the number of inputs, as long as the user paid the correct amount
this allows you to reduce your script size and often also optimize script execution.
the example of Plutonmicon says that if the user builds a transaction that doesn't respect the schema expected by your script, you should simply not care about it;
Why care about adding additional code to fail a transaction that would have failed anyway?

But in my case transaction wont be failed anyway. Worried about buyer's balance - the possibility of theft of a certain amount of Ada. This can happen if we have "dishonest" off-chain code and on-chain part without checking that transaction outputs are only assigned to seller or buyer and nobody else. Value of spent script output should go back to seller. And without specifying amount of Ada in each output, we can't say exactly how many buyer's Ada it will take for creating new seller's output. If there can be price of tokens < 1 Ada or even free. However, maybe i am just too scrupulous

What you are describing is logic that is necessary to the smart contract; so no problem with that. You should not check for example for the Data to be built as you  wish, because honest users will build the Data as intended, and if that is not the case then transfoming Data to a value already fails


text:
Nami getUtxos() method not as good as Eternl's
I am building a transaction that includes more than one asset in the output of a transaction. After I set up the output and try to build a transaction using getUtxos(outputValue) I get undefined from Nami while Eternal works fine using the same code.
outputValue contains both ada and several other assets.

Documentation for getUtxos():

cardano.getUtxos(amount, paginate)
cardano.getUtxos(amount?: Value, paginate?: {page: number, limit: number}) : [TransactionUnspentOutput]

TransactionUnspentOutput is a hex encoded bytes string.

Now just deserialize the hex-encoded cbor string, for example in Python using the cbor2 package:
import cbor2

utxos = cbor2.loads(bytes.fromhex("YOUR_CBOR_STRING"))

for k, v in utxos[1][1][1].items():
    print(k.hex(), v)

Thank you for the reply. I am aware of how to use getUtxos() method. My issue is that Nami wallet returns "undefined" while Eternl returns a correct list of utxos when I use the same code with both.
Looks like Nam's is less efficient in selecting utxos to fulfill the outputs of a transaction. Or is there a different method in Nami other than the default getUtxos()?
For example, try and build a tx where you need 3 or 4 NFTs sent from wallet along with some ADA. You will notice that Eternl has no issue, where Nami tried to include all utxos or none.


text:
Opening Hydra Heads & Other Cost Related Questions
So i have few questions here, which i wasn't able to find direct answers to.

Does it cost ADA from mainchain to activate/close a Hydra head ?
Does Hydra have similar "channel limits" as Lightning network does? as in i create a head and set limit as 5000 ADA, can that number be adjusted afterwards?
When im interacting with Hydra in general in which circumstances/possibilities i will be needing to use Cardano Mainnet to send/transfer/ funds.

I Tried to ask questions best to my ability based on my somewhat limited tech understanding.

You're technical understanding seems to be quite fine and let me point you to some additional resources / answer your questions:

Yes. Opening and closing a Hydra head costs ADA. It depends greatly on how many participants a Head has and how much funds need to be distributed. Also, different versions of the protocol will cost differently. These benchmarks are done on each commit to master and should give you a rough idea how much these transactions cost: https://hydra.family/head-protocol/benchmarks/transaction-cost/

There is no limit in how much value you can store in a Hydra Head. However, we do limit to only commit a single UTxO per party right now (this limit will be removed eventually)

The hydra-node will need a connection to the Cardano network and submit transactions for opening/closing a Head. Furthermore, in the opening of a Hydra Head, the funds to be made usable in it will need to be "comitted" to the head in a layer 1 (mainchain) transaction.


text:
Plutus playground error when running simulator: WalletContractError ToCardanoError (Tag \"toCardanoPolicyId\" (Tag \"1 bytes\" DeserialisationError))
Plutus-apps v2022-04-06
My smart contract compiles successfully however when i run the simulator i get this error
Contract instance stopped with error: "WalletContractError (ToCardanoError (Tag \"toCardanoPolicyId\" (Tag \"1 bytes\" DeserialisationError)))" ]

My plutus code is here: https://github.com/naeri-kailash/elysium-plutus/blob/master/src/Cardano/PlutusExample/Trade.hs
I have read another issue where someone got this error but their solution (CurrencySymbol needed to be changed to a policyID i believe - mine is already a policyID) was not relevant to me. Could I please have some guidance on how to go about debugging this error?
Much appreciated

It would be helpful if you could share the plutus code to reproduce this issue. This way someone could try to help you better.

Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer.

Thank you @eddex I have added the plutus contract

I have instead built the playground using the plutus-apps tag referenced in week 1 of the plutus-pioneer-program. This solved the issue although I do not know what the problem was with the tag I was using previously (v2022-04-06).
The plutus-apps tag that fixed it is 41149926c108c71831cfe8d244c83b0ee4bf5c8a.
The way I ended up trying this solution was that I tried to run the EnglishAuction contract in week01 content, and I encountered the same error so I then understood that the problem did not explicitly lie in my contract, rather the interaction between the contract and that version of the playground.

You could try
tkSymbol :: CurrencySymbol
tkSymbol = currencySymbol "8d803516132f6fb8ddfcf168065886bf44ecc9e0023b570963b4bac8"

elysiumtitan0 :: KnownCurrency
elysiumtitan0 = KnownCurrency (fromSymbol tkSymbol) "Token" ( (TokenName "ElysiumTitan0") :| [])

elysiumtitan1 :: KnownCurrency
elysiumtitan1 = KnownCurrency (fromSymbol tkSymbol) "Token" ( (TokenName "ElysiumTitan1") :| [])

...

Unfortunately still getting (nearly) the same error, different bytes
Contract instance stopped with error: "WalletContractError (ToCardanoError (Tag \"toCardanoPolicyId\" (Tag \"56 bytes\" DeserialisationError)))" ]

we can start to trace the error from here toCardanoPolicyId, but i'm not sure which on call to toCardanoPolicyId
You can try this way to generate some token for offchain emulator trace

I'm having trouble importing the Plutus.Contracts module even though its showing in the docs for my version, I'll see if I can get it working and get back to you, thanks :)


text:
Opportunity for theft of funds in Martify marketplace
I am some kinda embarrassed by "mkBuyValidator" in Martify Marketplace on-chain code . For buyer there is only one check for token transfer (on line 68):
(valueOf (valuePaidTo info sig) (nCurrency nfts) (nToken nfts) == 1).
And what about Ada amount or other funds that could be stolen from buyer in theory due to the fact of spending buyer's output (cause buyer is the signer)?
Am i right, that there should be some more checks?

Isn't that the responsibility of the buyer to verify before signing the transaction?

I suppose yes. However, don't sure about that stuff. As Ethereum developer, i d like to add some more checks. That's why asked the community :)

This is Leni from Martify Labs. Thanks for using our contract!
So here the buyer initiates the transaction and therefore sees in his wallet popup exactly what is leaving his wallet before he signs and submits. The contract’s job is to verify that the seller got paid, that the project owners received their royalties and that the marketplace operators receive their fees. We also check that the buyer gets his NFT. If a malicious marketplace builds a transaction that takes additional funds from the buyer, the buyer would see it clearly and would not sign the tx.
We know that this falls to the responsibility of the buyer, but it’s the same when you buy an item on an online shop with your credit card. You check that the price asked to be paid corresponds to the item you are buying.
Also, we wrote this contract for it to be very simple so that it can be used as a learning tool and also offer good flexibility. Let’s say you want to modify it a bit to allow bulk purchases or sales, or to allow a “buy and create new sale immediately” feature. There you would need to remove the checks you are talking about because you don’t know what user might want to include in their transaction.
Hope this helps!


text:
How to build a MultiSig wallet with a time delay element?
Any examples of tested libraries or code which enables multisig wallet where flow is more complex?
Example of requirements:

wallet transaction needs at least 2 signatures
wallet can be created with a "time delay" option, example "1 month"
if 1 signature initiated the transaction, confirmation (aka "second signature") can be either an actual signature by another person/key or a "time delay of 1 month" passed since transaction was initiated

What you want to use Cardano's Native Scripts (aka Simple Scripts).
This has been answered well here along with links to documentation: https://cardano.stackexchange.com/a/7959/1071

Arm chair response:
To add in, I don't think you can include the kind of time logic you're looking for via a Native Script but rather a Plutus script can better help with this.
It'll likely be a two step transaction process where the first is to initiate the transaction that marks the intent to spend a UTXO from the validator with say an NFT, and the second is to actually spend the UTXO using the NFT for access control and the script granting an isValid if either a certain second PK sig is included in Tx or a certain POSIX time has passed since since first transaction/NFT UTXO age

@EmmanuelBatse it can be done with a native script. Look at the link, specifically the "after" type which uses the "RequireTimeAfter" expression.
You're right that this is also possible with a Plutus script but it's unnecessarily complex and costly in this case.


text:
Can I run garbage collector after installing plutus-apps?
I just finished installing plutus-apps and running nix-shell for the first time on a new computer. I noticed that the file size is pushing 60gb is there anyway for me to clean up some of the unused files. I read that nix garbage collector or nix-store --gc will cut down on some of this but I'm afraid I might lose some of the plutus-apps files and have to rebuild again.
What should I do?

You can manually delete any nix store with nix store delete, just remember if there is a symbolic link pointing to a nix store, nix will refuse to delete it, you shoud remove any dependency first.


text:
scriptCurrencySymbol in V1 libs to mint assets
I'm using the latest Plutus-Stater project with this script
module FreeMinting where

import           Control.Monad          hiding (fmap)
import           Data.Aeson             (ToJSON, FromJSON)
import           Data.Text              (Text)
import           Data.Void              (Void)
import           GHC.Generics           (Generic)
import           Plutus.Contract        as Contract
import           Plutus.Trace.Emulator  as Emulator
import qualified PlutusTx
import           PlutusTx.Prelude       hiding (Semigroup(..), unless)
import           Ledger                 hiding (mint, singleton)
import           Ledger.Constraints     as Constraints
import qualified Ledger.Typed.Scripts   as Scripts
import           Ledger.Value           as Value
import           Playground.Contract    (printJson, printSchemas, ensureKnownCurrencies, stage, ToSchema)
import           Playground.TH          (mkKnownCurrencies, mkSchemaDefinitions)
import           Playground.Types       (KnownCurrency (..))
import           Prelude                (IO, Show (..), String)
import           Text.Printf            (printf)
import           Wallet.Emulator.Wallet

--ON-CHAIN

{-# INLINABLE freeMintingPolicy #-}
freeMintingPolicy :: () -> ScriptContext -> Bool
freeMintingPolicy _ _ = True

policy :: Scripts.MintingPolicy
policy = mkMintingPolicyScript $$(PlutusTx.compile [|| Scripts.wrapMintingPolicy freeMintingPolicy ||]) --unTypedValidator

curSymbol :: CurrencySymbol --aka PolicyID
curSymbol = scriptCurrencySymbol policy

But now scriptCurrencySymbol does not exists
Any tips on its substitute?

You should use
import Plutus.Script.Utils.V1.Scripts qualified as Scripts

-- ...

curSymbol = Scripts.scriptCurrencySymbol policy

You need to modify the cabal.project file to use v0.1.0 of plutus-apps which has Plutus.Script.Utils.V1.Scripts module
-- Plutus apps revision from 2022-04-06
source-repository-package
  type: git
  location: https://github.com/input-output-hk/plutus-apps.git
  tag: v0.1.0

Ref: Plutus.Script.Utils.V1.Scripts code

thanks a lot... still trying to get how documentation works with Cardano/Plutus ;)

my solution is copy the function which is not existed, and search on input-output-hk github (scope organization). There is some commit or code related to the function we need. in this case the function is scriptCurrencySymbol, then we infer to the correct module ;)


text:
Coin Selection for Multiasset
I am building an NFT marketplace on Cardano.
To build my transactions I use cardano-serialization-lib. When I try to use add_inputs_from() with LargestFirstMultiAsset strategy to choose inputs for the transaction that sends an NFT to the Plutus contract address, I get a UTxO Balance Insufficient.
I definitely have the NFT UTxO in the wallet, and I also have around 100 tAda that isn't locked with any tokens.
Could it be related to minAdaValue? Because it will be greater for the output that goes to the contract (because of datum hash) than what is currently locked with the token...

I have found the error. The function is completely fine. I passed the wrong amount to the output...

So back in the day when I received the UTxO Balance Insufficient error on Cardano-cli, it usually meant I didn't properly calculate the breakdown of the UTXO transitions in terms of transaction cost calculation, change, and UTXOs involved.
With that said, I think you should just double check the calculation for how the UTXOs are spent.
Since you're using the serialisation-lib I know that things can get very complex in that department so I recommend reaching out to teams like dcSpark who actively maintain and build with it.
Hope this helps (and if it doesn't hope help comes eventually)


text:
Is there a way to get the current circulating supply of an asset via API?
More specific, I am looking to fetch the circulating supply of native cardano tokens with the Blockfrost API. I know how to get the total supply, but I was wondering if there is any possibility to get the current circulating supply with a similar approach.

You can find out which addresses are used to store the amount not yet in circulation and subtract it from the total. I think there isn't much more behind the concept of "in circulation" than not being in the reserve wallet, vesting contract etc.

Yeah, that could be a solution. It's a nasty one for sure, but I think I'll give it a try.
Thank you for your response.

Given the native assets cannot be staked, they are all in circulation.
Just fetch it with /assets and see the quantity field.

Nah, the problem is essentially that this would include tokens that are in some sort of treasury, and since these tokens are not really in circulation yet, it doesn't make sense to use them for calculations.

Tokens cannot be locked in the treasury (which uses account-based mode), only ADA can be.


text:
Necessary changes for Vasil hard fork
First of all, congratulations to IOHK team for the Vasil hard fork update!
I'm running a node and building services on top of it, do I need to make any update manually on services or node to support Vasil hard fork?
(The purpose of running the node is to list Cardano in the exchange)

As long as you are running the latest release of the node (1.35.3) you are fine.


text:
How to turn (compile) “script.hs” into “script.plutus”?
I have a script that is developed in Plutus Playground. It is working well and now I want to deploy it to the Cardano blockchain via cardano-cli.
Following this answer, I have to use cabal to turn my Haskell script (.hs) into a plutus (.plutus) file. And then send it along with a transaction to the blockchain. The answer is vague and provides no details. I especially need to know how to configure .cabal file, dependencies, among other things. I find no other resource/tutorial that shows how it is done.
Question: How to turn (compile) my “script.hs” into “script.plutus”?
I am aware of this example by IOHK. But now I need to apply to own script and configurations.

You need to serialize your scripts. Take a look at the lines in this example here, made by Alessandro Konrad for the pacebudz project. https://github.com/spacebudz/spacebudz-identity/blob/main/src/onchain/app/contracts/Contract.hs#L238-L248
https://github.com/spacebudz/spacebudz-identity/blob/main/src/onchain/app/Main.hs#L14-L26
Subsequently use the serialized cbor to build the tx using cardano-cli or Pycardano/Lucid. I recommend the latter if you know Python/Js

Another way is to use a separate Utils.hs file (remember add it in your your-app.cabal file for config) for utility fucntions, example:
dataToScriptData :: Data -> ScriptData
dataToScriptData (Constr n xs) = ScriptDataConstructor n $ dataToScriptData <$> xs
dataToScriptData (Map xs)      = ScriptDataMap [(dataToScriptData x, dataToScriptData y) | (x, y) <- xs]
dataToScriptData (List xs)     = ScriptDataList $ dataToScriptData <$> xs
dataToScriptData (I n)         = ScriptDataNumber n
dataToScriptData (B bs)        = ScriptDataBytes bs

writeJSON :: PlutusTx.ToData a => FilePath -> a -> IO ()
writeJSON file = LBS.writeFile file . encode . scriptDataToJson ScriptDataJsonDetailedSchema . dataToScriptData . PlutusTx.toData

writeUnit :: IO ()
writeUnit = writeJSON "scripts/unit.json" ()

-- For validator:
writeValidator :: Plutus.Validator -> IO (Either (FileError ()) ())
writeValidator = writeValidator "scripts/demoContract.plutus" . validator

-- For minting policy:
writeMintingPolicy :: Plutus.MintingPolicy -> IO (Either (FileError ()) ())
writeMintingPolicy  = writeFileTextEnvelope @(PlutusScript PlutusScriptV1) "scripts/my-minting-script.plutus" Nothing . PlutusScriptSerialised . SBS.toShort . LBS.toStrict . serialise . Plutus.getMintingPolicy

Then pass your minting policy or validator in the above functions then you would get a script output.
Example of my implementation on a validator:
strToPpkh :: String -> Plutus.PaymentPubKeyHash
strToPpkh = Plutus.PaymentPubKeyHash . Plutus.PubKeyHash . stringToBuiltinByteString

tupleToAssetClass :: (String, String) -> AssetClass
tupleToAssetClass (cs, tn) = AssetClass (CurrencySymbol $ stringToBuiltinByteString cs, TokenName $ stringToBuiltinByteString tn)

makeParam :: (String, String) -> String -> (String, String) -> AppParam
makeParam ca fc tt = AppParam {
    cContractAsset = tupleToAssetClass ca
    , cFeeCollector  = strToPpkh fc
    , cTT            = tupleToAssetClass tt
}

writeSimplifiedValidator :: (String, String) -> String -> (String, String) -> IO (Either (FileError ()) ())
writeSimplifiedValidator ca fc tt = writeValidator "scripts/demoContract.plutus" $ Simplified.validator $ makeParam ca fc tt

An excessive import list as below, its from PPP lecture with wallet implementation as well, you could filtered out those not used for your own purposes:
{-# LANGUAGE GADTs            #-}
{-# LANGUAGE TypeApplications #-}

module Utils.Utils where

import           Cardano.Api                 as API
import           Cardano.Api.Shelley         (Address (..), PlutusScript (..))
import           Cardano.Crypto.Hash.Class   (hashToBytes)
import           Cardano.Ledger.Credential   as Ledger
import           Cardano.Ledger.Crypto       (StandardCrypto)
import           Cardano.Ledger.Hashes       (ScriptHash (..))
import           Cardano.Ledger.Keys         (KeyHash (..))
import           Codec.Serialise             (serialise)
import           Data.Aeson                  (decode, encode)
import qualified Data.ByteString.Char8       as BS8
import qualified Data.ByteString.Lazy        as LBS
import qualified Data.ByteString.Short       as SBS
import           Data.Maybe                  (fromJust, fromMaybe)
import           Data.String                 (IsString (..))
import           Data.Text                   (pack)
import           Plutus.PAB.Webserver.Types  (ContractActivationArgs (..))
import           Plutus.V1.Ledger.Credential as Plutus
import           Plutus.V1.Ledger.Crypto     as Plutus
import           Plutus.V1.Ledger.Value      (TokenName (..))
import           PlutusTx                    (Data (..))
import qualified PlutusTx
import           PlutusTx.Builtins           (toBuiltin)
import           PlutusTx.Builtins.Internal  (BuiltinByteString (..))
import qualified Ledger                      as Plutus
import           Ledger.Value
import           Wallet.Emulator.Wallet      (WalletId (..), Wallet (..))
import           Wallet.Types                (ContractInstanceId (..))
import           PlutusTx.Builtins.Class

import           MyApp.Onchain
import           MyApp.Types
import           MyToken.Onchain

I was stuck for a while, getting my head around things. But yeah this is the way to go. Thanks!

Take a look at this example: (https://github.com/Apexaverse-metaverse/P2E/blob/main/scripts/mint-token-cli.sh#L22), is a bit clunky but it works:
Using cabal repl. I call writePolicyFile function from https://github.com/Apexaverse-metaverse/P2E/blob/main/src/Deploy.hs#L58. This function builds the policy UPLC using hard-coded params, serialize it to plutus format and save it. Then, in the bash script, the tx is built and submitted using cardano-cli.

This works. Thanks!

You can base your cabal files and project from plutus-apps next-node branch. See here: https://github.com/input-output-hk/plutus-apps/blob/next-node/cabal.project
I have an example repo you can you as guideline here: https://github.com/james-iohk/plutus-scripts


text:
1.35.3 not syncing since epoch 365
I moved our stake pool LOXE to 1.35.3 (git rev 80b5637a5520648d50b0763d7677ddbe374cd598) on August 20th and it was producing blocks regularly. I noticed yesterday that our block producer was up as a slot leader, but the block was not adopted by the chain. Only later did I realize that our pool was stuck in Alonzo at the last block of epoch 364 (7791698).
I stopped the nodes and deleted some recent files from the db, fo force replaying of blocks on restart with no difference.
I complied cardano-node and cardano-cli - this time from commit ea6d78c7 - transferred the binaries and configs to my nodes and compiled the libsodium on the nodes as well. I changed the topology on the relays to just connect to the IOHK servers for the moment to try and just sync up, but I’m still getting nowhere with it.
Attached is a view from my journalctl from the relay in question.

UPDATE: Fixed!
Will compose and link a write-up

You say you upgraded the block producer machine, but did you also upgrade the relays? They must all be upgraded. Also, you should use the git tag rather than just using a particular commit near the tag.

I upgraded all nodes.

To be of help I would need a bit more info.
Are you running in P2P mode, how many incoming/outgoing connections for your block producer and relays?
Was the block you were leader for accepted in gLiveView but not by other pools?

Connections between BP and relays were stable. Connections to other nodes are impermanent and break soon after they were registered in gLiveView. I don't have any indication that the block was accepted by other pools as the tip is on the las slot in epoch 364.

The disconnect came from gLiveView reporting the version number of the cardano-node that it found, not the one that's actually running.
Here's a more complete answer:
https://forum.cardano.org/t/1-35-3-stuck-in-epoch-364/108111/22

I think what I am about to say is correct but check it out. If you are talking about a mainnet pool you are running the wrong node version. The correct git rev for mainnet is 950c4e222086fed5ca53564e642434ce9307b0b9. The node version you are running is for the test environments.
To get up and running quickly, when you're on the correct node version you could download a db snapshot from here:
https://csnapshots.io/

For those getting stuck with updating fully to 1.35.x.
This guide assumes that your user directory is named cardano, your git directory is in cardano/git, your working directory is in $NODE_HOME, and your systemd service is cardano-node.
Check your installed cardano-node version
cardano-node --version
now compare if it is the same as being executed by systemd
which cardano-node
/home/cardano/.local/bin/cardano-node --version

Assuming you're not sure where your 1.35.x file is located you are finding it by running:
find ~/ -name cardano-node
This list will also list directories with the name cardano-node.
Look for a path similar to this, where [YOUR_GIT] is the cloned repository.
/home/cardano/git/dist-newstyle/build/x86_64-linux/ghc-8.10.7/cardano-node-1.35.3/x/cardano-node/build/cardano-node/cardano-node
Now test this node's version
/home/cardano/git/dist-newstyle/build/x86_64-linux/ghc-8.10.7/cardano-node-1.35.3/x/cardano-node/build/cardano-node/cardano-node --version
Copy this cardano-node if the version is 1.35.x
 cp /home/cardano/git/cardano-node/dist-newstyle/build/x86_64-linux/ghc-8.10.7/cardano-node-1.35.3/x/cardano-node/build/cardano-node/cardano-node /home/cardano/.local/bin/cardano-node
and
 cp /home/cardano/git/cardano-node/dist-newstyle/build/x86_64-linux/ghc-8.10.7/cardano-node-1.35.3/x/cardano-node/build/cardano-node/cardano-node /usr/local/bin/cardano-node
Limit the permissions
sudo chmod 644 /etc/systemd/system/cardano-node.service
Check version
/home/cardano/.local/bin/cardano-node --version
/usr/local/bin/cardano-node --version
Reboot sudo reboot
or reload the daemon
sudo systemctl daemon-reload
sudo systemctl enable cardano-node.service

If it doesn't run now.
Stop the cardano-node.
sudo system stop cardano-node
Backup your old database.
mv db db_bak
Download your snapshot from cSnapshots.io and reboot.
sudo curl -o - https://downloads.csnapshots.io/mainnet/$(curl -s https://downloads.csnapshots.io/mainnet/mainnet-db-snapshot.json| jq -r .[].file_name ) | lz4 -c -d - | tar -x -C $NODE_HOME; sudo reboot
Your node should now hopefully be running again and you can delete the backup with
rm -r $NODE_HOME/db_bak


text:
Failed cardano-node build on mac m1
I've followed the installing-cardano-node#macos guide on the developer portal and about 10 things fail to build and all of them are giving me the same error.
Cannot specify -O# and --passes=/--foo-pass, use -passes='default<O#>,other-pass'
`opt' failed in phase `LLVM Optimiser'. (Exit code: 1)

I also followed the steps on this link and I'm still getting the same errors.
https://github.com/mallapurbharat/cardano-tx-sample/blob/main/0_installation/preview_preprod_network/1_macos_m1_process.md
Thank you for your help.

This looks to be an issue with LLVM version 15, as per https://gitlab.haskell.org/ghc/ghc/-/issues/21936
Looks like reverting to LLVM 14 should work for you.

Reverted to LLVM 13 and it worked! (I was getting some other errors on LLVM 14)

Nice one, glad it worked ok.


text:
Cardano GraphQL stuck Establish connection to cardano-node
I'm trying to run graphql following these instructions.
I do already have dbsync & cnode running for the preprod network, but I get this error:

{"name":"cardano-graphql","hostname":"DESKTOP-I38CEOE","pid":4332,"level":20,"msg":"Establishing connection to cardano-node: Attempt 3 of 101, retrying...","time":"2022-09-25T12:09:20.800Z","v":0}

Any idea what could be the issue? Maybe I need to edit/add some env var for the CNODE?

Well I don't know for sure what is going on and would require more information to practically help.
But I would investigate how graphQL is getting the node's params from.
Then check that those are correct, then make sure the host where graphQL is running from can connect to the node's host.
If both node and gQL run on the same host it is likely a parameter issue (port, socket).

thank you for your answer, actually yes i tried to look if there is anything regarding how it connect to the node ... but found nothing .. im new to this.

no worries, I'll try to find some time today to follow the instructions above, I'll revert back with my findings, although I'm not using cnode it will probably help me understand where gQL is getting the node's details from.
Actually could you print out your ${CNODE_HOME}/files/config.json file please?

hello this is the config file : https://justpaste.it/7nwn6


text:
GHC error when adding TokenName to NFTMint params
I get the following GHC error for code that I am trying to update to Plutus V2.   I can reproduce the error using the plutus-scripts below.   Is this a bug with Plutus V2 or can anyone explain how to resolve it.   I don’t have this issue with Plutus V1.
Thank you.
Steps to reproduce
Git clone https://github.com/james-iohk/plutus-scripts.git
Git clone https://github.com/input-output-hk/plutus-apps.git
Go into plutus-apps directory and checkout 87b647b05902a7cef37340fda9acb175f962f354
Type nix-shell --extra-experimental-features flakes
Cd ../plutus-scripts/src
Make the following changes 1,2,3,4 below

vi NFTMint.hs

     53 data NFTParams = NFTParams --  doesn't need more than the TxOutRef
     54     {  mpTokenName :: !PlutusV2.TokenName  -- << 1. uncommented code here
     55     , mpAmount   :: !Integer
     56     , mpTxOutRef :: !PlutusV2.TxOutRef
     57     --, mpPubKeyHs  :: !Plutus.PubKeyHash
     58     } deriving Show
     59
     60 PlutusTx.makeLift ''NFTParams
     61 PlutusTx.unstableMakeIsData ''NFTParams
     62
     63 tn :: PlutusV2.TokenName  -- << 2. added helper function definition
     64 tn = PlutusV2.TokenName "test" -- << 3. and here function body
     65
     66 redeemer :: NFTParams
     67 redeemer = NFTParams { mpTokenName = tn,  -- << 4. added tn to param
     68                        mpAmount = 1,
     69                        mpTxOutRef = PlutusV2.TxOutRef {txOutRefId = "82669eddc629c8ce5cc3cb908cec6de339281bb0a0ec111880ff0936132ac8b0", txOutRefIdx = 0}
     70                      }

This will generate the following error when running cabal build from the plutus-scripts directory.
GHC Core to PLC plugin: E042:Error: Unsupported feature: Type constructor: GHC.Prim.Addr#
Context: Compiling type: GHC.Prim.Addr#
Context: Compiling data constructor type: Data.ByteString.Internal.PS
Context: Compiling type: Data.ByteString.Internal.ByteString
Context: Compiling data constructor type: NFTMint.NFTParams
Context: Compiling type: NFTMint.NFTParams
Context: Compiling expr: \ (mp' [Occ=OnceL1] :: NFTMint.NFTParams) ->
                           PlutusTx.Base.$
                             @ (PlutusTx.Builtins.Internal.BuiltinData
                                -> Plutus.V2.Ledger.Contexts.ScriptContext -> GHC.Types.Bool)
                             @ Plutus.Script.Utils.V1.Typed.Scripts.MonetaryPolicies.UntypedMintingPolicy
                             (Plutus.Script.Utils.V2.Typed.Scripts.MonetaryPolicies.mkUntypedMintingPolicy
                                @ PlutusTx.Builtins.Internal.BuiltinData
                                PlutusTx.IsData.Class.$fUnsafeFromDataBuiltinData)
                             (\ _ [Occ=Dead] (ctx :: Plutus.V2.Ledger.Contexts.ScriptContext) ->
                                let {
                                  info :: Plutus.V2.Ledger.Contexts.TxInfo
                                  [LclId,
                                   Unf=Unf{Src=<vanilla>, TopLvl=False, Value=False, ConLike=False,
                                           WorkFree=False, Expandable=True, Guidance=IF_ARGS [] 20 0}]
                                  info = Plutus.V2.Ledger.Contexts.scriptContextTxInfo ctx } in
                                PlutusTx.Bool.&&
                                  (PlutusTx.Trace.traceIfFalse
                                     (Data.String.fromString
                                        @ PlutusTx.Builtins.Internal.BuiltinString
                                        PlutusTx.Builtins.Class.$fIsStringBuiltinString
                                        (GHC.CString.unpackCString# "UTxO not consumed"#))
                                     (PlutusTx.Base.$
                                        @ [Plutus.V2.Ledger.Contexts.TxInInfo]
                                        @ GHC.Types.Bool
                                        (PlutusTx.Foldable.any
                                           @ []
                                           @ Plutus.V2.Ledger.Contexts.TxInInfo
                                           PlutusTx.Foldable.$fFoldable[]
                                           (\ (i [Occ=Once1] :: Plutus.V2.Ledger.Contexts.TxInInfo) ->
                                              PlutusTx.Eq.==
                                                @ Plutus.V1.Ledger.Tx.TxOutRef
                                                Plutus.V1.Ledger.Tx.$fEqTxOutRef
                                                (Plutus.V2.Ledger.Contexts.txInInfoOutRef i)
                                                (NFTMint.mpTxOutRef mp')))
                                        (Plutus.V2.Ledger.Contexts.txInfoInputs info)))
                                  (PlutusTx.Trace.traceIfFalse
                                     (Data.String.fromString
                                        @ PlutusTx.Builtins.Internal.BuiltinString
                                        PlutusTx.Builtins.Class.$fIsStringBuiltinString
                                        (GHC.CString.unpackCString# "wrong amount minted"#))
                                     (join {
                                        fail_dCmD [Occ=Once2!T[1]] :: GHC.Prim.Void# -> GHC.Types.Bool
                                        [LclId[JoinId(1)],
                                         Arity=1,
                                         Str=<L,U>,
                                         Unf=Unf{Src=<vanilla>, TopLvl=False, Value=True, ConLike=True,
                                                 WorkFree=True, Expandable=True,
                                                 Guidance=ALWAYS_IF(arity=1,unsat_ok=True,boring_ok=True)}]
                                        fail_dCmD _ [Occ=Dead, OS=OneShot] = GHC.Types.False } in
                                      case Plutus.V1.Ledger.Value.flattenValue
                                             (Plutus.V2.Ledger.Contexts.txInfoMint info)
                                      of {
                                        [] -> jump fail_dCmD GHC.Prim.void#;
                                        : ds_dCmB [Occ=Once1!] ds_dCmC [Occ=Once1!] ->
                                          case ds_dCmB of
                                          { (cs [Occ=Once1], tn' [Occ=Once1], amt [Occ=Once1]) ->
                                          case ds_dCmC of {
                                            [] ->
                                              PlutusTx.Bool.&&
                                                (PlutusTx.Eq.==
                                                   @ Plutus.V1.Ledger.Value.CurrencySymbol
                                                   Plutus.V1.Ledger.Value.$fEqCurrencySymbol0
                                                   cs
                                                   (Plutus.V2.Ledger.Contexts.ownCurrencySymbol ctx))
                                                (PlutusTx.Bool.&&
                                                   (PlutusTx.Eq.==
                                                      @ Plutus.V1.Ledger.Value.TokenName
                                                      Plutus.V1.Ledger.Value.$fEqTokenName0
                                                      tn'
                                                      ((Data.String.fromString
                                                          @ PlutusTx.Builtins.Internal.BuiltinByteString
                                                          PlutusTx.Builtins.Class.$fIsStringBuiltinByteString
                                                          (GHC.Types.[] @ GHC.Types.Char))
                                                       `cast` (Sym (Plutus.V1.Ledger.Value.N:TokenName[0])
                                                               :: GHC.Types.Coercible
                                                                    PlutusTx.Builtins.Internal.BuiltinByteString
                                                                    Plutus.V1.Ledger.Value.TokenName)))
                                                   (PlutusTx.Eq.==
                                                      @ GHC.Integer.Type.Integer
                                                      PlutusTx.Eq.$fEqInteger
                                                      amt
                                                      1));
                                            : _ [Occ=Dead] _ [Occ=Dead] -> jump fail_dCmD GHC.Prim.void#
                                          }
                                          }
                                      })))
Context: Compiling expr at "plutus-script-0.1.0.0-inplace:NFTMint:(98,8)-(98,37)"

The issue is not with the Plutus version but the compiler. You need to remove ! from where mpTokenName is defined. This should be fixed in the near future.

Thanks James, greatly appreciated.  This will work for now but had to remove other ! references in custom datatypes I have used in my code to get it to work.   Let me know if there is a bug logged for this.

My pleasure @lley154! This bug has been reopened with reference to this question: https://github.com/input-output-hk/plutus/issues/4193

Great - thanks James.


text:
Plutus Playground WalletError: InsufficientFunds
I am running my smart contract on the plutus-playground and getting the error below:
Contract instance stopped with error: "WalletError (InsufficientFunds \"Total: Value (Map [(,Map [(\\\"\\\",100000000)]),(66,Map [(\\\"ElysiumTitanBid0\\\",1),(\\\"ElysiumTitanBid1\\\",1),(\\\"ElysiumTitanBid2\\\",1)])]) expected: Value (Map [(6db9b46374a778b2e2d2142ca25bc3bfcd4216dc42ebcefcc54ee4d3,Map [(\\\"ElysiumTitanBid0\\\",1),(\\\"ElysiumTitanBid1\\\",1),(\\\"ElysiumTitanBid2\\\",1)])])\")" ]

The script is here
It looks like the output is expected to contain something related to the policyID that I had declared in the script, how do I initialise this as a test value so I don't get this InsufficientFunds error?
I'm running the basic init action, and then a wait. I believe the init action is where the policyID is being required, my vague understanding is that the token should somehow be associated with the policyID? I'm not sure if this is correct or how to reflect that in the code.
Update:
I've tried changing  to this:
tkSymbol :: CurrencySymbol tkSymbol = currencySymbol "6db9b46374a778b2e2d2142ca25bc3bfcd4216dc42ebcefcc54ee4d3"
mkSchemaDefinitions ''TradeSchema elysiumtitan0 = KnownCurrency (fromSymbol tkSymbol) "Token" (TokenName "ElysiumTitan0" :| [])

And the error changes to this, which seems a step closer. However the policyId is coming through strangely, perhaps it is being encoded or something?:
Contract instance stopped with error: "WalletError (InsufficientFunds \"Total: Value (Map [(,Map [(\\\"\\\",100000000)]),(3664623962343633373461373738623265326432313432636132356263336266636434323136646334326562636566636335346565346433,Map [(\\\"ElysiumTitanBid0\\\",1),(\\\"ElysiumTitanBid1\\\",1),(\\\"ElysiumTitanBid2\\\",1)])]) expected: Value (Map [(6db9b46374a778b2e2d2142ca25bc3bfcd4216dc42ebcefcc54ee4d3,Map [(\\\"ElysiumTitanBid0\\\",1),(\\\"ElysiumTitanBid1\\\",1),(\\\"ElysiumTitanBid2\\\",1)])])\")" ]

It would be helpful if you would provide the actions you are trying to run and what inputs you entered for the actions.

Have edited, thanks @eddex

The init params schema is being defined here https://github.com/naeri-kailash/elysium-plutus/blob/a26b033f5dacee3f3c9303d4f75096517ade57f4/src/Cardano/PlutusExample/Trade.hs#L325, as you can see, it's (). If you need to pass a policy id you should define it there. But looking at your code, policy id is already hard-coded in the init function.

@WalkerLeite so it seems like while the expectation is for the policyID to be attached as stated in the init functions, when the test values are created https://github.com/naeri-kailash/elysium-plutus/blob/a26b033f5dacee3f3c9303d4f75096517ade57f4/src/Cardano/PlutusExample/Trade.hs#L593 it is with 66 rather than the policyID. Is the only way to amend this through the init function? I will make that change and test it now. Thanks for taking a look :)

Yeah, 66 feels not right. It works on EmulatorTrace?

@WalkerLeite
I've tried changing to this:
tkSymbol :: CurrencySymbol
tkSymbol = currencySymbol "6db9b46374a778b2e2d2142ca25bc3bfcd4216dc42ebcefcc54ee4d3"

mkSchemaDefinitions ''TradeSchema
elysiumtitan0 = KnownCurrency (fromSymbol tkSymbol) "Token" (TokenName "ElysiumTitan0" :| [])

And the error changes to this, which seems a step closer:
Contract instance stopped with error: "WalletError (InsufficientFunds \"Total: Value (Map [(,Map [(\\\"\\\",100000000)]),(3664623962343633373461373738623265326432313432636132356263336266636434323136646334326562636566636335346565346433,Map [(\\\"ElysiumTitanBid0\\\",1),(\\\"ElysiumTitanBid1\\\",1),(\\\"ElysiumTitanBid2\\\",1)])]) expected: Value (Map [(6db9b46374a778b2e2d2142ca25bc3bfcd4216dc42ebcefcc54ee4d3,Map [(\\\"ElysiumTitanBid0\\\",1),(\\\"ElysiumTitanBid1\\\",1),(\\\"ElysiumTitanBid2\\\",1)])])\")" ]


text:
Why NFTs on cardano use IPFS CIDv0 instead of recommended CIDv1
IPFS, nft.storage and most other ipfs providers default and recommend using CIDv1. In contrast, most recently (September 2022.) minted NFT's on cardano still use CIDv0: tarc citizen lagani r troublecats pegasus van.keulen cardano whale cardanoog mutation nation fluffy cardani hosky
Why recent NFT projects tend to choose CIDv0 instead of CIDv1 for ipfs link?
I am aware CIDv0 will be 46 chars long, while CIDv1 (if sha256 is used) will be 59 chars long so it is a bit cheaper (0.000044A * 13 = 0.000572A per NFT minted) to store it on chain. Also uri protocol+cid for CIDv0 (ipfs://Qm...) will be 7+46=53 chars while for CIDv1 (ipfs://baf...) will be 7+59=66 chars which exceeds 64 byte/char limit for bytes/string fields of metadata schema. This is not a problem because cip25 allows encoding image uri's as arrays (["ipfs://", "cid_part1", "cid_part2", ...]). Now if we used CIDv0 and in 10 years ipfs clients deprecate CIDv0 and decide to support only CIDv1, then we will have to compute CIDv1 manually from CIDv0 (or use some redirect system) and show the user CIDv1 link. Wouldn't that be confusing for the user? User will see his NFT metadata link starts with ipfs://Qm... but browser shows them ipfs://baf....
Anyway, I see most NFT projects on cardano today still use CIDv0 so I guess they don't think this is an issue - but I am not sure it isn't.

You are absolutely right with what you described. The reason is simply that most people are using tools like nmkr.io or other minting platforms that use CIDv0. Maybe it's to save some cost, maybe it's just because the devs don't see the point to change. It is more straight forward to create and parse a single line in the metadata with CIDv0, rather than a multi line array.
All that said you can without problems create an NFT on Cardano with a CIDv1 IPFS link.


text:
Use of multi-signature and multi-witness transaction creation
I'm working on a pseudo-centralized product that manages users wallets, protected by multi-signature verification.
I want to know if it is possible for me to batch about 50-100 transactions from various accounts to other accounts, and send them to other accounts but pay the least amount of fees.
For example, in a 1 minute period, there are 5 users sending transactions. Can I pay the fee from my account, while allowing the users to make their transactions.
Accounts/UTXO example:
A -> Z
B -> Y
C -> X
D -> W
E -> V
Pay with ADA from my account F.
How would I handle having each user sign the transaction including me for the fee? How would I even calculate that fee?
Thank you

If I understand correctly, what you are trying to achieve is:

User A indicates that he wants to send VAL1 to Z. Transaction TX1 is
created to implement the transfer, and user A signs it.
User B indicates that he wants to send VAL2 to Y. Transaction TX2 is
created to implement the transfer and includes TX1 inputs and outputs
and user B signs the transaction.
...
User E indicates that he wants to send VAL5 to V. Transaction TX5 is
created including TX4 inputs and outputs, to implement the transfer,
and user E signs the transaction.

This is not possible. The reason being after a transaction has been signed,the witness is only valid for this exact transaction, as it includes transaction's body hash. If you add an input or output that hash will change and the witness won't be valid for the transaction anymore.

What is possible instead :

User A indicates that he wants to send VAL1 to Z, he gets a loading screen 1.
User B indicates that he wants to send VAL2 to Y, he gets a loading screen 1.
...
User E indicates that he wants to send VAL5 to V, he gets a loading
screen 1.
You create the transaction TX with every needed inputs/outputs, calculate tx fees, and divide it among users A...E weighted by  VAL1...VAL5 for instance.
Loading screen 1 over for every users , users A...E sign TX, then get a loading screen 2.
When everybody has signed, loading screen 2 over, then you submit TX, and show a loading screen 3 until TX has been confirmed.


text:
Cardano-wallet doesn't work after 1.35.3 update
After Vasil hard fork I did update the node with version 1.35.3 and also updated cardano-wallet to version v2022-08-16 which is suitable with 1.35.3
Although the node is running without any problem and its sync, cardano-wallet cannot connect to the node. This is the error:
[cardano-wallet.pools-engine:Info:46] [2022-09-27 13:46:10.26 UTC] Still in sync. Applied 17 blocks, 0 rollbacks in the last 300.000680263s. Current tip is [point 7dbc1268 at slot 72720072].
[cardano-wallet.ntp-client:Notice:308] [2022-09-27 13:50:50.26 UTC] ntp client experienced error Network.Socket.ByteString.sendManyTo: does not exist (Network is unreachable) when sending packet
[cardano-wallet.ntp-client:Notice:311] [2022-09-27 13:50:51.36 UTC] ntp client experienced timeout using IPv6 protocol

This is how I start the node:
 cardano-node run \
   --topology /home/centos/data/cardano/cardano-node-1.35.3/mainnet-topology.json \
   --database-path /home/centos/data/cardano/cardano-node-1.35.3/data \
   --socket-path /home/centos/data/cardano/cardano-node-1.35.3/data/node.socket \
   --host-addr 0.0.0.0 \
   --port 1919 \
   --config /home/centos/data/cardano/cardano-node-1.35.3/mainnet-config.json

Start cardano-wallet:
cardano-wallet serve \
      --port 1912 \
      --node-socket /home/centos/data/cardano/cardano-node-1.35.3/data/node.socket \
      --mainnet \
      --database /home/centos/data/cardano/cardano-node-1.35.3/data \
      --listen-address 0.0.0.0 \

I looked at my cardano-wallet running v2022-07-01 and saw the same notice (infact it's not an error but a notice).
Then I upgraded to v2022-08-16 and the notice went away.
So make sure you are running the latest version by running
cardano-wallet version

Also make sure you are referencing the right binary by running
whereis cardano-wallet

and using that path in your startup script

Did you delete the cardano-wallet directory and binary files and re-install all again?

nope, just upgraded the binary and restarted the binary!

Your wallet may be actually connected, this line suggests that:
[cardano-wallet.pools-engine:Info:46] [2022-09-27 13:46:10.26 UTC] Still in sync. Applied 17 blocks, 0 rollbacks in the last 300.000680263s. Current tip is [point 7dbc1268 at slot 72720072].

Try if it responds with anything from GET network/information:
curl -X GET http://localhost:1912/v2/network/information

Yes, it does and gives a "ready" response. However, I cannot send requests from outside even if I started the wallet with  --listen-address 0.0.0.0 \ parameter.


text:
Downtime when upgrading or restarting a node
I run not only Cardano nodes but also Ethereum and other nodes.
I think the downtime is longer when upgrading or restarting a Cardano node compared to other nodes.
Downtime here is the time between when a node is restarted and when it starts synchronizing blocks again.
It took over an hour for Mainnet to start synchronizing.
It cannot be any other node.
I have three questions.

Why does it take so long for the Cardano node?
Is there any way to reduce the downtime?
Is there anything the community can do to improve downtime?

Best Regard!!
Any advice is welcome.
The specifications are as follows

Cardano-node

CPU: 4
Memory: 16Gi

Ogmios

CPU: 500m
Memory: 16Gi

Postgres

CPU: 8
Memory: 32Gi

GraphQL

CPU: 2
Memory: 4Gi

DBSync

CPU: 4
Memory: 32Gi

Hasura

CPU: 500m
Memory: 2Gi

How are you stopping the node? If the node is sent a SIGTERM the node will do a safe shutdown (I have seen this take up to 5 minutes) which results in a quicker restart (under 10 minutes in my experience). If the node does not shut down safely (or the safe shutdown did not complete) then startup will be longer. Also be aware that when there is a change in the on-disk storage format, a complete rebuild will be necessary.

Thanks for the reply!
I'm using ArgoCD to manage my nodes, but I don't shut them down and let them reboot or adapt to version changes without shutting them down.
How do I do a safe shutdown?
Best Regard!! Thank you.

Sorry, no idea. you should ask the people who develop ArgoCD.

The best step is stopping the node correctly which can vary a bit on how you run the cardano-node
Another thing that I do is dump the ledger before rebooting
So I look at the current block. For example right now 72849870
Also you need to put the path to your ~/cardano-node/db/ledger (for my build for example)
The command then is as follows:
cardano-cli query ledger-state --mainnet --out-file ~/cardano-node/db/ledger/72849870

Thanks for the reply! I will try!


text:
Sending consecutive transactions will result in an error
Sending consecutive transactions will result in an error.
Using the simple-transaction example below, a transaction is created in Cardano-Serialization-Lib and sent to the blockchain using BrokFrost.
https://github.com/blockfrost/blockfrost-js/tree/master/examples/simple-transaction
At this time, after one transaction is sent. If I create and send transactions consecutively without waiting for a time, I may get the following error and not be able to send.
Transaction db6388f73ed195c30ea264dc968ea364d16fa7a097ddae0236d9fbf1fa150df8 rejected"transaction submit error ShelleyTxValidationError ShelleyBasedEraBabbage (ApplyTxError [UtxowFailure (UtxoFailure (FromAlonzoUtxoFail (ValueNotConservedUTxO (Value 0 (fromList [])) (Value 206069713 (fromList []))))),UtxowFailure (UtxoFailure (FromAlonzoUtxoFail (BadInputsUTxO (fromList [TxIn (TxId {_unTxId = SafeHash \"607d1531d04bb56da9a6145c784ae2c1b59980ca3703b78777404516d41e93b5\"}) (TxIx 1)]))))])"

I believe this is due to  trying to use the same Input for the first transaction and the second transaction , is there any way to resolve this?
Also, in this example, what condition is specified in the UTxO of the transaction's Input?
What I would like to achieve

We want to create and send a transaction without time after sending once.
Example Send 100 transactions per minute from one address.

What we want to know

If there is another way to specify the UTxO of Input, is it possible to create and send transactions continuously by changing it?

If you have a UTxO output A, and you submit a transaction that spends UTxO A, everything should be fine. If you submit a second transaction that also spends UTxO A, then the transaction should fail because the UTxO you are trying to spend has already been spent. This is how the UTxO accounting model works.
Also, I am rather unsure what you mean by

I believe this is due to the UTxO not being updated,

In the UTxO accounting model, UTxOs are never updated.
I suggest you read up on the differences between the account based model used in Ehtereum and the UTxO accounting model used in Cardano (and Bitcoin).

Thanks for the answer! As for the difference between UTxO and the account model you pointed out, I thought I understood it, but my explanation was incorrect in this question. UTxO is consumed and new UTxO is generated. I had represented this as an update. And you are trying to use the same Input for the first transaction and the second transaction, right? As for the language, I am Japanese and use machine translation for English, so forgive me if there are some oddities!

Yes, if a transaction consumes a UTxO, any subsequent transactions that try to consume the same UTxO will fail because the UTxO has already been spent and no longer exists in the UTxO set. Reading you original post, I would not have guessed that you were using machine translation.


text:
Cardano-Node Preview Testnet PeerSelection Error
I am running cardano-node 1.35.3 on Ubuntu 22.04 Docker container. I am attempting to run the node on the preview testnet. Below is the following error I get when running cardano-node.
Here is the Error that I am seeing
[22cbd0dd:cardano.node.PeerSelection:Error:52] [2022-09-29 04:11:19.93 UTC] TracePublicRootsFailure Network.Socket.getAddrInfo (called with preferred socket type/protocol: AddrInfo {addrFlags = [AI_ADDRCONFIG,AI_NUMERICHOST,AI_PASSIVE], addrFamily = AF_UNSPEC, addrSocketType = Datagram, addrProtocol = 0, addrAddress = 0.0.0.0:0, addrCanonName = Nothing}, host name: Just "192.168.65.5", service name: Just "domain"): does not exist (Unrecognized service) (-5) 32s
[22cbd0dd:cardano.node.PeerSelection:Info:52] [2022-09-29 04:11:51.89 UTC] TraceGovernorWakeup
[22cbd0dd:cardano.node.PeerSelection:Info:52] [2022-09-29 04:11:51.89 UTC] TracePublicRootsRequest 100 0
[22cbd0dd:cardano.node.LedgerPeers:Info:50] [2022-09-29 04:11:51.89 UTC] [String "FetchingNewLedgerState",Number 0.0]
[22cbd0dd:cardano.node.LedgerPeers:Info:50] [2022-09-29 04:11:51.89 UTC] [String "FallingBackToBootstrapPeers"]
[22cbd0dd:cardano.node.LedgerPeers:Info:50] [2022-09-29 04:11:51.89 UTC] [String "UseLedgerAfter",Number 322000.0]
[22cbd0dd:cardano.node.PublicRootPeers:Info:66] [2022-09-29 04:11:51.89 UTC] TracePublicRootRelayAccessPoint [RelayAccessDomain "preview-node.world.dev.cardano.org" 30002]

Here is my cardano-node run command
cardano-node run --topology topology.json --database-path db --socket-path db/node.socket --host-addr 127.0.0.1 --port 3001 --config config.json

Apparently the testnet does not work for cardano-node 1.35.3. I have to run cardano-node 1.35.2 to use the testnet

apt install netbase in your container. it worked out for me.

This worked for me. I'm running cardano-node in a base debian container image.

These logs look like an issue with you config.jason file in your public root section you are calling a service name that it can not find. Would need to see your config.jason file to comment more

https://book.world.dev.cardano.org/environments/preview/config.json

Sorry not config.json, topology.json. the config.json is fine

I had a similar issue. Have a look at the following answer, changing the host-addr worked in my case:
https://cardano.stackexchange.com/a/9203/7074


text:
Plutus Playground - mustPayToTheScript - unexpected char escapes - 0 converted to \NUL, 1 to \SOH
I am having trouble with the mustPayToTheScript function - I am getting this error
Contract instance stopped with error: "WalletError (InsufficientFunds \"Total: Value (Map [(,Map [(\\\"\\\",93999990)]),(3664623962343633373461373738623265326432313432636132356263336266636434323136646334326562636566636335346565346433,Map [(\\\"ElysiumTitan1\\\",1)])])
expected: Value (Map [(3664623962343633373461373738623265326432313432636132356263336266636434323136646334326562636566636335346565346433,Map [(\\\"ElysiumTitan\\NUL\\NUL\\SOH\\\",1)])])\")" ]

However, the value on the first line is what I'd would like to expect "ElysiumTitan1" - the expected value is strange and undesirable "ElysiumTitan\\NUL\\NUL\\SOH\\\".
From a google it looks like there's a character escape happening or something. Does anyone know why this is happening and how to prevent it?
Here is the line of code where i assume its happening: https://github.com/naeri-kailash/elysium-plutus/blob/master/src/Cardano/PlutusExample/Trade.hs#L524

If I just put 1 I get this error:
Contract instance stopped with error: "OtherError \"Error in $.id: invalid bytestring size\"" ]

I am a bit confused about this part:
"ElysiumTitan" <> id

In normal Haskell id is the identity function, but I could not see how that would type check if it was. However, in this case it seems to by the id field of the TradeParams struct (which is also of type BuiltInByteString). I can't seem to find where that value is constructed, but somewhere or other, the id field of the TradeParams struct is initialized to "\NUL\\NUL\\SOH\\\.
Also, just as an aside. I highly recommend against using the RecordWildCards language pragma as it makes code more difficult to read, especially for someone not the author.

Thanks, I've removed the recordwildcards pragma although it still compiles the same and doesnt seem to require code changes for that.
Im wondering why the id field is being initialised to "\NUL\\NUL\\SOH\\\" as this is preventing me from passing that condition... I didn't write most of this contract I've just been adapting it to my needs but it is proving very challenging. I haven't seen any other example contracts where there's bidding integrated though, do you know of any?

Do you have a link to your new version of the code?

Hey Erik sorry for late response, I've given up on the plutus-playground and am using the cli instead as it has been too much of a struggle. Thanks so much, I appreciate your input


text:
Cardano Transaction Submit Errors
I am currently building a dApp on cardano using cardano-serialization-lib and wallets (Nami, Typhon, Yoroi).
Since you have to configure TransactionBuilder with the latest Protocol Parameters, there is a chance that a transaction will fail due to wrong parameters being used while building the transaction (ex. FeeTooSmallUTXO if min_fee_a or min_fee_b was raised).
At the same time, not every error, thrown at transaction submit is related to these parameters (ex. NonOutputSupplementaryDatums).
Is there a page or a document that lists errors that can be caused by the protocol parameters mismatch or all errors, but with explanation for when they occur? I want to look through such list to figure out all the scenarios where I might want to check for a parameter update.

The Cardano ledger itself provides the list of UtxoPredicateFailure.


text:
get tAda for cardano legacy testnet
How can I get testnet ada for cardano testnet, Now that cardano faucet only has option to get tAda for preprod or preview testnet. I'm trying to mint NFT using this website. https://stage.cardahub.io/marketplace My nami wallet address addr_test1qppc30u4xqy3afe0vlpg65p850w88zw8zxa066r5rs980ltxfzqvxhdf33fnyepwwkhuua522lvyaajyk3l5lp7204kscn3pax Please send me 20 tAda if you have some.

The testnet is deprecated, latest release of node does not support it. Best to use pre-prod.

Yes I know its deprecated, I tried to use the above website mentioned in my question. I guess I'll just skip that. BTW do you know any testnet NFT marketplace.


text:
Importing wallets to cardano-node
when I'm upgrading cardano-node and cardano-wallet, I saved the wallets (.sqlite, sqlite-shm, sqlite,wal files) created in the node (cardano-node/data folder). After upgrading to the new node 1.35.3 I paste the wallet files to the same directory, but the cardano-wallet wallets list command isn't able to recognize the files. What should I do?

Make sure your cardano-wallet is pointing to the right database path by passing --database /path/to/your/db
Generally speaking you should manage cardano-wallet in a 'daemonized' manner (e.g. using systemd), this way you update your binary and restart the daemon, leaving the configuration untouched.

If you still have the mnemonic and the passphrase of the wallet, you can recover it with cardano-wallet.


text:
Multiple minting on one TX
I'm trying to mint a utility token and based on this quantity the investor will get different NFT bonus.
----------
mint :: MintParams -> Contract w FreeSchema Text ()
mint mp = do
        let yacada          = Value.singleton yacadaSymbol yacadaName (calculateYacada $ mpAdaAmount mp)
            yacadaNft       = Value.singleton yacadaNFTSymbol  "NFT" 1 --(giveReferalNFTN
            adas            = Ada.lovelaceValueOf $ mpAdaAmount mp
            lookups         = Constraints.mintingPolicy policy <> Constraints.mintingPolicy levelPolicy
            destinations    = paymentTo mp
            payment         = Constraints.mustPayToPubKey (treasury destinations) adas
            mintYacada      = Constraints.mustMintValue yacada <> Constraints.mustMintValue yacadaNFT
            tx              = mintYacada

        ledgerTx <- submitTxConstraintsWith @Void lookups tx
        void $ awaitTxConfirmed $ getCardanoTxId ledgerTx
        logInfo @String $ printf "------------------------------------------------------"
        logInfo @String $ printf "We forged y:%s NFT:%s" (show yacada)  (show yacadaNft)
        logInfo @String $ printf "------------------------------------------------------"

----------

The thing is that when I see the token in the wallet they both have the same policy :
(
Wallet 2:
{32d66bc1df769f6af0d37ccd9e3510ebf38b5e4c7235a2b2e4e9d08c, "NFT"}: 1
{32d66bc1df769f6af0d37ccd9e3510ebf38b5e4c7235a2b2e4e9d08c, "YACADA_TOKEN"}: 2000
{, ""}: 99697225
Wallet 1:
{32d66bc1df769f6af0d37ccd9e3510ebf38b5e4c7235a2b2e4e9d08c, "NFT"}: 1
{32d66bc1df769f6af0d37ccd9e3510ebf38b5e4c7235a2b2e4e9d08c, "YACADA_TOKEN"}: 1000
{, ""}: 99697137
Any ideas?
I have this "test code" on github if any needs it.

Just found my mistake. Just need to have the multiple policies in diferent files..