text:
How to get all unSpent UTXOs at script address OnChain
Hi i am building CrowdFund where i need to know the total amount raised at the script as an OnChain validation.
i was looking at Contexts.findOwnInput but would this only return the tx-in's provided in this particular redeem call?
I am looking to get all the unspent UTXOs at the script address and i need that in the OnChain logic and not offChain- so i can total all the Ada to know how much is now at the Script. And if certain target is reached i can allow the Crowd Source owner to take that Ada.
appreciate your thoughts.

As far as I know, the on-chain validator does not have access to anything else than what you send it as parameters. So what you want is not possible. You need to do it off-chain.

yes thx George! i also realized that later. i think Cause script cannot see whole blockchain but only utXos submitted with the Txn. So i still am working but i think we can use NFT at script to instead use redeem actions to add contributions and that way update datum with target amount. and then i know if total target reached or not.

i was actually able to do this:
    txinfo :: Contexts.TxInfo
    txinfo = Contexts.scriptContextTxInfo context

    txInputs = Contexts.txInfoInputs txinfo

    validatedValue = Contexts.txOutValue . Contexts.txInInfoResolved <$> txInputs

With this i was able to get all the UTXOs submitted to the transaction.
It still means the submit transaction need to gather UTXO's and submit it with tx-in to the transaction.
Obviously there might be some limits on how many tx-in you can submit based on the transaction size etc.
But i was able to submit 2 UTXO as tx-in and with Contexts.txInfoInputs was able to get both amounts locked at the script at once.
Contexts.findOwnInput seems to validate 1 at a time even when 2 tx-in are submitted. So i would NOT know the combined value of both UTXOs at this script address.
I would be interested to know whats other solutions are there that could be even better

i realized later i think Cause script cannot see whole blockchain but only utXos submitted with the Txn. So i still am working but i think we can use NFT at script to instead use redeem actions to add contributions and that way update datum with target amount. and then i know if total target reached or not.


text:
pay collateral with cardano-cli
Followed the guide here to build preprod testnet wallets, was wondering however I can create the collateral utxo with cardano-cli ?

Sadly some of the developers.cardano.org documentation is outdated.
You need to use --tx-in-collateral to specify your collateral input, but might want to also use the --tx-out-return-collateral flag to specify your output.

Oh no I think my question is wrong - is there a way to even create the collateral input?

There is nothing specific about a collateral input, you can use any input.
In the past, this has been problematic as we did not have output return collateral, so the whole utxo was spend, therefore wallets introduced a term of collateral input setup to limit potential lost.

I ended up using web wallets e.g. Eternl to create the collateral utxo. And used cardano-address and cardano-cli to create payment and stake .skey files.

source: Stack Exchange

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

sort: votes


text:
Get pool reward for specific epoch
I want to get pool(private pool) reward for specific epoch.
I searched blockfrost.io apis, can't find reward api.
How can I get reward by api? Or other solution will be fine like graphql.

You need to look at the specific pool's history using the pools/{pool_id}/history endpoint.
[
  {
    "epoch": 233,
    "blocks": 22,
    "active_stake": "20485965693569",
    "active_size": 1.2345,
    "delegators_count": 115,
    "rewards": "206936253674159",
    "fees": "1290968354"
  }
]

See docs.blockfrost.io.

Thank you for your answer. For private pool, reward amount is always 0. It seems all reward value become margin. Is it possible to get margin value in the pool history?

It should not be 0 I think. Are you sure you're not looking at the first epoch of the pool, where it does not participate in staking yet?

The historical values of the pool margin value are available in db-sync.

As the main dev on db-sync I can tell you how to get it there.
In the simplest manner possible (with randomly chosen pool and epoch):
# select id, view from pool_hash where view =
    'pool19u64770wqp6s95gkajc8udheske5e6ljmpq33awxk326zjaza0q' ;
 id |                           view
----+----------------------------------------------------------
 13 | pool19u64770wqp6s95gkajc8udheske5e6ljmpq33awxk326zjaza0q
(1 row)
# select sum (amount) / 1000000 as ada_reward from reward where earned_epoch = 354
    and pool_id = 16 and type = 'member' ;
     ada_reward
--------------------
 13856.795160000000
(1 row)

This could be made into a single query with a join of the two tables.

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


text:
Get margin amount in private pool
I want to get reward amount for specific pool for specific epoch.
https://docs.blockfrost.io/#tag/Cardano-Pools/paths/~1pools~1%7Bpool_id%7D~1history/get
Above blockfrost api provides reward amount for specific epoch.
But for private pool, all rewards become margin, since its margin percent is 100%, so all rewards show as 0 in api response.
To get reward amount for private pool, I need to get margin amount.
How can I get margin amount for specific pool for specific epoch?

The rewards should show in the Blockfrost API, are you sure you're not looking at first epoch that did not participate in staking yet?
As example, here is one of the eToros' pools that has 100% margin:
$ curl -s  -H "project_id: xx"  https://cardano-mainnet.blockfrost.io/api/v0/pools/2bf5a031b46b34c07937a769ff6f82b6a78a25c71022eaaf1f20eec9/history?order=desc | jq
[
  {
    "epoch": 377,
    "blocks": 73,
    "active_stake": "65000004590510",
    "active_size": 0.0025796400554051256,
    "delegators_count": 3,
    "rewards": "44005384326",
    "fees": "44005384326"
  },

As you can see both rewards and fees are returned.

I was testing with this pool. 92dc054f2d52106de52ff081afe510e9d929ae597d476bbbb15527a9. Why is this pool reward always 0?

This is because this pool has never made a block, so it never got any rewards. https://cexplorer.io/pool/pool1jtwq2ned2ggxmef07zq6legsa8vjntje04rkhwa325n6j5689an/blocks#data

I see, thank you for your answer.


text:
Mesh Error: getUsedCollateral not implemented
I'm using mesh and follow this example of always-succeed smartcontract.
I successfully send Lovelace to the script address. But when building transaction for redeeming Lovelace from the script address, there comes this error:
Error: [Transaction] An error occurred during build: Error: getUsedCollateral not implemented..
at Object.build (/root/meshapp/node_modules/@martifylabs/mesh/dist/mesh.cjs:1:51612)
at processTicksAndRejections (node:internal/process/task_queues:96:5)

Everything is like the example except:

I use App Wallet (Example: Browser Wallet)
I send Lovelace (Example: 64af286...)
I use preview testnet (Example: preprod, I guess)

The error occur when building the transaction with
const tx = new Transaction({ initiator: wallet })
.redeemValue({
    value: assetUtxo,
    script: {
        version: 'V1',
        code: '4e4d01000033222220051200120011',
    },
    datum: '0000007',
})
.sendValue(address, assetUtxo)
.setRequiredSigners([address]);

const unsignedTx = await tx.build();

"address" is my wallet address and "assetUtxo" is the utxo where the fund is locked. Both are non nil.
How do I fix this?

Yes, getUsedCollateral isn't implemented yet on AppWallet.
It will be done really soon after we sort out other priorities.
for the time being, you can add Collateral from the Browser Wallet if possible

I assume you're in the team. Do you have an approximation of ETA? I really like working with mesh. AppWallet is much easier for my case.

Yes, you can expect it to be done within a month from now, maybe less. We will start working on it as soon as we finish the ongoing work we have right now.

Quickly glancing at Mesh code it looks like this function is not implemented yet and it might not be possible to create Plutus transactions just yet.

However the library is still under heavy development and I'm sure they will add this functionality soon.

Yeah, it is new. Any alternative to Mesh would you recommend?


text:
Public cardano-wallet service list
While I am checking cardano-wallet-js, I noticed requirement.
Before start using the library you will need a cardano-wallet server running.

Is there any public cardano-wallet server which I can use to initialize walletServer?

No, as the cardano-wallet service holds information about your keys, accounts and so on.
But you can use cardano-wallet with Blockfrost.io in light mode with the need to sync the entire chain which takes few days.


text:
How to decode the datum stored across records in the tx_metadata table for a given tx
For a given tx - where a contract has been used, outputs have been stored in the tx_metadata table - in this case key/value pairs where the values of keys 0 through 10, when appended together to form one contiguous string, make a value that when run through cbor.me decode to the representation of a json object that contains various values.
d8799f581cbaed3ae13d7eeb93bb4b4f44e10aff9f1fc052869f4a1cd1501be9289fd8799fd8799fd8799f581c4b031cbfd476d7efd6ec84012aeaa11a5ec9aa4ce53973764f5099bfffd8799fd8799fd8799f581ce1f33ea56cbc61dc3f9159175025efab8e55d92380482b4760360038ffffffffa140d8799f00a1401a10b07600ffffd8799fd8799fd8799f581c70e60f3b5ea7153e0acc7a803e4401d44b8ed1bae1c7baaad1a62a72ffd8799fd8799fd8799f581c1e78aae7c90cc36d624f7b3bb6d86b52696dc84e490f343eba89005fffffffffa140d8799f00a1401a04c4b400ffffd8799fd8799fd8799f581cbaed3ae13d7eeb93bb4b4f44e10aff9f1fc052869f4a1cd1501be928ffd8799fd8799fd8799f581c801c29c0f4e1b8c20b1849aa358f63f22a46fa9930ec447694a9bbf2ffffffffa140d8799f00a1401ad8f5fe00ffffffff

When above is decoded it produces:
121([h'BAED3AE13D7EEB93BB4B4F44E10AFF9F1FC052869F4A1CD1501BE928', [121([121([121([h'4B031CBFD476D7EFD6EC84012AEAA11A5EC9AA4CE53973764F5099BF']), 121([121([121([h'E1F33EA56CBC61DC3F9159175025EFAB8E55D92380482B4760360038'])])])]), {h'': 121([0, {h'': 280000000}])}]), 121([121([121([h'70E60F3B5EA7153E0ACC7A803E4401D44B8ED1BAE1C7BAAAD1A62A72']), 121([121([121([h'1E78AAE7C90CC36D624F7B3BB6D86B52696DC84E490F343EBA89005F'])])])]), {h'': 121([0, {h'': 80000000}])}]), 121([121([121([h'BAED3AE13D7EEB93BB4B4F44E10AFF9F1FC052869F4A1CD1501BE928']), 121([121([121([h'801C29C0F4E1B8C20B1849AA358F63F22A46FA9930EC447694A9BBF2'])])])]), {h'': 121([0, {h'': 3640000000}])}])]])

here we find the output values in lovelace:
280000000
80000000
3640000000

but there is also these other values, which do not seem to decode to addr - addresses as it seems they should...
BAED3AE13D7EEB93BB4B4F44E10AFF9F1FC052869F4A1CD1501BE928
4B031CBFD476D7EFD6EC84012AEAA11A5EC9AA4CE53973764F5099BF
...etc.

Does anyone know how to decode them to the wallet addresses they must be?

:/ edited but not answered Erik? aww. hehe

These values are the payment credentials of the address (or in case of a script its script hash).
You are probably looking for the payment_cred field of tx_out table in cardano-db-sync.
csyncdb=> select address from tx_out where payment_cred = '\xbaed3ae13d7eeb93bb4b4f44e10aff9f1fc052869f4a1cd1501be928' group by address;
                                                 address
---------------------------------------------------------------------------------------------------------
 addr1qxaw6whp84lwhyamfd85fcg2l703lszjs60558x32qd7j2yqrs5upa8phrpqkxzf4g6c7clj9fr04xfsa3z8d99fh0eqt5dw63
(1 row)

csyncdb=>

Keep in mind that this payment_cred value is only one part of the address and therefore they can more than one result.

THAT connects the dots for me, thank you!!
payment_cred
hash28type
The payment credential part of the Shelley address. (NULL for Byron addresses). For a script-locked address, this is the script hash.
From the tx_out table - and there they all are...
Thank you so much.


text:
Collateral for new Wallets
New users of Cardano sometime want to get started quickly and often face the daunting task of understanding what collateral is. Then faced with the fact that they need to send some collateral to their wallet ... the quickness aspect of it gets lost very quickly
This is particularly true for Mobile Apps running on Cardano. Where users download the mobile app and get a wallet generated for them in the background. The wallet cannot interact with smart contracts until some ada is sent to it from the outside. This is cumbersome and degrades the user experience.
Question: Is it possible for the Dapp provider to add collateral for the user from a centralized wallet?
Potential workflow:

User builds a transaction using the cardano-serialization-lib
User sends the transaction to a back-end service of the Dapp provider
The backend service adds the collateral field, partially signs the transaction and sends back to the user
The user signs the full transaction and submits it through their wallet

This would enhance the user experience in mobile apps and increase the adoption of Cardano by letting users download an app and strat using straight away
Is something like this currently possible, and what are the risks?
All the best,
DSIO

This does not answers your question directly, but might you give you an idea how to solve it in a different and potencialy better way.
In this twitter thread KtorZ explains the recent changes on how to handle collateral.

In case you wondered, here are some quick clarifications about the infamous 'collaterals' in #Cardano.
There was an interesting conversation I was brought into and thought it could be interesting to turn it into a proper thread.
All you ever wanted to know about collaterals
With the Alonzo era and the introduction of Plutus scripts was also added a new feature to transactions: collaterals.
In essence, a collateral is an input which is consumed when a script fails to execute in a transaction.
But, aren't scripts supposed to be deterministic?
Precisely.
So in principle, any user in their right mind would not submit a transaction with a failing script, because they would know the outcome in advance.
Yet, an attacker of the system might find that interesting...
In fact, a failed transaction consumes resources but does not reward block producers for it. No fees are collected. For basic transactions only involving public key signatures, that's okay since the resources involved are negligible.
Yet for Plutus scripts, that's another story.
Hence why a 'collateral' was introduced to transactions.
It is an input (or, UTxO) that is consumed when a well-formed transaction with a failing script is submitted through the system. It acts as a mechanism to prevent bad actors to waste resources of the network at no cost.
Any transaction that executes a script is required to have a collateral, but it's only consumed if the result of the script execution turns out wrong.
The amount of collateral depends on the cost of the script and some protocol parameters. Plus, some extra rules.
In particular, the collateral cannot itself be an input locked by a script.
Moreso, it must NOT contain any native asset, but be a pure Ada UTxO.
Of course, it must also be an existing input that can be rightfully spent by the transaction.
In practice, it means that wallets must manage this collateral. Wallets must make sure to keep a large enough Ada-only UTxO available for collateral.
This can be a little tricky, and also, a bit odd from a user perspective.
Most Ada holders that have interacted with DApps have probably went through the steps of 'setting a collateral' in their wallet prior to making any transaction to a smart-contract.
This is a, relatively transparent, way for wallet providers to inform users about collaterals.
Overall, this is an unsatisfactory user and developer experience, for both > Ada holders and wallet providers alike.
While the management of collaterals doesn't require users to explicitly set one, it's cumbersome and confusing to manage over time behind the scene.
So, with the Babbage era, a new feature was introduced called the 'collateral return'.
This allows wallets to not only define a collateral input to consume on failure, but also an output to send some change to in case it happens.
And this makes everyone's life a lot easier.
Remember the constraints about the collateral? In particular, that it needs to be Ada-only?
Well now, what matters is that the remainder between the collateral input > and return is an Ada value, of a minimum quantity depending on the script cost and protocol parameters.
Said differently, it makes management of collaterals easier for wallets that decide to make use of it. They no longer need to keep a particular Ada-only UTxO around but can simply use any sufficiently large input as collateral and dump whatever is left in a change output.
It's interesting to note that collaterals were never meant to be a user-facing feature in the first place.
This was supposed to happen behind the scene only, because in principle, users (or by extension wallets) do not normally submit failing transactions.
Yet, this somehow made its way through UIs in such a way that as Cardano users, we've grown accustomed to it.
Up to the point where, new wallets would even have to adopt the same strategy to not confuse people.
UX is a funny thing
Moving forward, and with collateral return available in the protocol, we can hope that wallet providers will gradually update to adopt this new approach and, put collaterals back in the shadow and not bother us users about them anymore

Thanks Marek, I posted a similar question on their Twitter thread before coming here :) I don't think the points answer the specific question, though, KtorZ recognizes that UX  "is a funny thing", and my question is to address the UX.

Yes this is possible but requires suitable UTxO(s) being already present in wallet. Due to virtues of CIP-40 any UTxO can be taken as collateral because we can set for return output and only this balance between input collateral(s) and return collateral output is required to satisfy the earlier collateral needs (such as being percentage of transaction fee and ada-only†). Note that as of now, we can take up to three UTxO(s) as collateral inputs (this is a protocol parameter).
Atlas by Genius Yield handles for collateral and the example project in their documentation utilises this approach where if wallet has already set collateral then that is used otherwise framework chooses suitable UTxO as collateral for building the transaction.

† Find more details in ledger specifications here.


text:
Get back my funds after a mistaken self transaction on Cardano
I accidentally made a self-transaction with my account and would like to know if I can get it back.
As you can see my account here, and this is my self-transaction sent 2 weeks ago.
I'm using cardano-cli to run all my commands and was wondering if a script can give me my funds back. This was related to a pool already deregistered.
Thank you guys if you can help me.

Two possibility for given description (I am assuming you meant second case below, but for completion will answer for both cases)

If you're referring to ~1671 ADA left after spending 500 ADA to register WINS pool, you made an outgoing transaction here, which is when most of your funds on mentioned address were depleted. Since this isn't an internal transaction, you should check your target wallet where you sent funds.
In case it helps remember, this target wallet was since delegated to 4ADA pool

If instead you're referring to 500 ADA you spent as pool deposit in referred transaction, then your post is misleading. That was deposit you paid which could have only be returned IF your pool deregistration was fully complete (as long as your stake account remained registered), but seems your reward address is NOT registered, and thus - that account was left dangling and cannot get a refund, it would instead go back to reserves - unfortunately that'd mean you've lost that part due to the human error.

When you make a self transaction, the only loss you should be seeing are the transaction fees.

give me my funds back

Sorry, there is no way to reverse a transaction. You should already have you funds (minus the transaction fees).


text:
Nix-shell in plutus-apps
I'm using Ubuntu 20.04.5 with an 11th Gen Intel® Core™ i7-1195G7 @ 2.90GHz × 8.
After cloning the plutus-apps repo and setting my nix config, i can't get pass the following nix-shell error:
trace: To materialize project.plan-nix for haskell-project entirely, pass a writable path as the `materialized` argument and run the 'updateMaterialized' script in 'passthru'.
warning: error: unable to download 'https://hydra.iohk.io/nix-cache-info': Timeout was reached (28); retrying in 280 ms

my etc/nix/nix.conf is set to the parameters from README.adoc :
substituters        = https://hydra.iohk.io https://iohk.cachix.org https://cache.nixos.org/
trusted-public-keys = hydra.iohk.io:f/Ea+s+dFdN+3Y/G+FDgSq+a5NEWhJGzdjvKNGv0/EQ= iohk.cachix.org-1:DpRUyj7h7V830dp/i6Nti+NEO2/nhblbov/8MW7Rqoo= cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY=
extra-experimental-features = nix-command flakes

any advice appreciated
Updates:
The compilation with nix-shell completed bringing me to
[nix-shell:~/Documents/Plutus/plutus-apps]$
However, along the way I get lots of warnings. Should I be concerned? For example:
System/Remote/Snap.hs:7:1: warning: [-Wunused-imports]
    The import of ‘<$>’ from module ‘Control.Applicative’ is redundant
  |
7 | import Control.Applicative ((<$>), (<|>))
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

The nix cache is now located at cache.iog.io
With a /etc/nix/nix.conf (or ~/.config/nix/nix.conf) that looks like this:
experimental-features = nix-command flakes
allow-import-from-derivation = true
substituters = https://cache.nixos.org https://cache.iog.io
trusted-public-keys = hydra.iohk.io:f/Ea+s+dFdN+3Y/G+FDgSq+a5NEWhJGzdjvKNGv0/EQ= cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY=

then you should have the binary cache from IOG working again.
(you many need to log out and log back in and or restart the nix daemon to get these changes to take)
Doc source

thanks. So the nix-shell has been running for over an hour now. should it be taking so long?

It depends on what is specified in the shell.nix but that doesn't sound like a good sign. If you can build and run the cardano node as per these commands in a few min you are pulling from the cache. You should also be able to see cache.iog.io in the output from nix.
Rebooting is also a sure fire way to make sure the new config has applied.

You need to replace hydra.iohk.io with cache.iog.io, as the hydra server has been decommissioned.
Leave the key as it is: f/Ea+s+dFdN+3Y/G+FDgSq+a5NEWhJGzdjvKNGv0/EQ=.

thanks! however now i'm getting the error:
warning: ignoring untrusted substituter https://cache.iog.io

I resolved the issue by changing substituter to trusted-substituter


text:
How is protocol.json used when minting NFTs?
I'm tinkering with creating NFTs via the cardano-cli. The various "how-to" pages I have found all have me download protocol.json using
cardano-cli query protocol-parameters \
--testnet-magic 1097911063 \
--out-file protocol.json

What I do not see is how that file is then utilized. It is never accessed or referenced in any of the steps needed to create the NFT, and certainly not in any of the code. Every other piece of code has very precise file references. Can anyone shed light? Thanks.

In my understanding, their are various parameters like the constants involved when computing minimum ada requirement in a UTxO, etc., which are mentioned in protocol.json file.

protocol.json file from cardano-cli contains protocol parameters of the current network (mainnet, preview, preprod...).
It is used by cardano-cli when using various subcommands, such as cardano-cli transaction calculate-min-fee.
Actually, I do not know of any other subcommand using this file, so you are are not using it, you do not need to generate it.

Thanks. Development is happening so quickly that "how to" pages from only 16 months ago are already out of date.


text:
Module `Ledger.Typed.Scripts' does not export `wrapValidator'
I try to compile code from Plutus Pioneer Program week 4. These lines cause error.
typedValidator :: Scripts.TypedValidator Vesting
typedValidator = Scripts.mkTypedValidator @Vesting
    $$(PlutusTx.compile [|| mkValidator ||])
    $$(PlutusTx.compile [|| wrap ||])
  where
    wrap = Scripts.wrapValidator @VestingDatum @()

Here is the error:
Not in scope: `Scripts.wrapValidator'
Perhaps you meant one of these:
`Scripts.tvValidator' (imported from Ledger.Typed.Scripts),
data constructor `Scripts.TypedValidator' (imported from Ledger.Typed.Scripts)
Module `Ledger.Typed.Scripts' does not export `wrapValidator'.

That is strange because from the documentation there is the instance wrapValidator in Ledger.Typed.Scripts

wrapValidator :: forall d r. (UnsafeFromData d, UnsafeFromData r) => (d -> r -> ScriptContext -> Bool) -> WrappedValidatorType

How do I fix this?

Assuming the week04 code is unchanged, ensure you have run checked out commit ea1bfc in the plutus-apps repo and run nix-shell within plutus-apps. Then switch to the week 4 directory in the nix shell and cabal build should work.


text:
building cardano-node and cardano-cli on nix
I'm following the instructions here:
https://github.com/input-output-hk/cardano-node/blob/master/doc/getting-started/building-the-node-using-nix.md/
But I'm not sure how to get it to compile the 1.35.3 versions. The commands at nix build .#cardano-node -o cardano-node-build and nix build .#cardano-cli -o cardano-cli-build ./cardano-cli-build/bin/cardano-cli build versions 1.31.0 after completion

I resolved this by updating my path variable to point to the new builds. In /.bashrc, i appended
export PATH="$HOME/Cardano/cardano-node/cardano-node-build/bin/:$PATH"


text:
Send native tokens without running node
is there any library or proper guide to send custom/native tokens in NodeJS?
i don't want to run full node (cardano-node/cardano-wallet), just want to build and sign a transaction and submit it via Blockfrost's API?
want something like this: https://github.com/blockfrost/blockfrost-js/blob/fb9a55fee07927f8d7c8b0a5aa9efd2d3daf6c77/examples/simple-transaction/src/index.ts
but with Native token option. thanks!
p.s: I want to do it in MAINNET if matters.

Yes, you can use libraries like lucid & mesh.

hey, thanks for suggesting these. i have already tried Mesh, but I was not really able to use it, because it was more like TS friendly (import style), and I was not able to import "type" in my node js backend, and I did not find any example for this in lucid. mesh's examples: https://mesh.martify.io/apis/transaction/basic

Regarding "import style", did you try this?

yeah, didn't work. can't really find a way to convert "import type { ... } from '...'" to require format

this worked: const { AppWallet, BlockfrostProvider, Asset, Transaction } = require('@martifylabs/mesh');

You could try Helios.
Here is a guide to building transactions: https://www.hyperion-bt.org/Helios-Book/api/building/index.html
The following links will help you define a UTxO containing native assets:

https://www.hyperion-bt.org/Helios-Book/api/reference/utxo.html
https://www.hyperion-bt.org/Helios-Book/api/reference/txoutput.html
https://www.hyperion-bt.org/Helios-Book/api/reference/value.html
https://www.hyperion-bt.org/Helios-Book/api/reference/assets.html
https://www.hyperion-bt.org/Helios-Book/api/reference/mintingpolicyhash.html

If you're struggling with using ES imports, then you can try the following import style:
import("/path/to/helios.js").then( helios=>{
   const tx = new helios.Tx()

   ...
})

Note: Helios is more low-level than Lucid/Mesh because you need to take care of calling the Blockfrost API yourself.

Thanks! figured out how to import via mesh tho

How did you end up doing it? (might be helpful for others who are struggling with the same issue)


text:
Possible inconsistence data in db-sync
I've this query on Preprod:
SELECT
    ENCODE(TX.HASH, 'hex') as tx_hash,
    TX_OUT.INDEX,
    TX_OUT.ADDRESS_HAS_SCRIPT,
    ENCODE(TX_OUT.DATA_HASH,'hex') AS DATUM_HASH,
    SCRIPT.ID as script_id,
    TX_OUT.REFERENCE_SCRIPT_ID,
ENCODE(INLINE_DATUM.HASH,'hex') AS INLINE_DATUM_HASH
FROM TX_OUT
INNER JOIN TX ON TX.ID = TX_OUT.TX_ID
LEFT JOIN "script" ON "script"."hash" = "tx_out"."payment_cred"
LEFT JOIN "datum" AS "inline_datum" ON "inline_datum"."id" =
"tx_out"."inline_datum_id"
WHERE TX.HASH =
DECODE('8502fe3617b70d12fc65c8c17dab8483f5a7f847e0fba0376fe7abacf4773262','hex')
AND TX_OUT.INDEX = 3;

Where I'm getting some info about a specific UTxO. The result is this:
 tx_hash                                                          | index | address_has_script |                            datum_hash                            | script_id | reference_script_id |                        inline_datum_hash
------------------------------------------------------------------+-------+--------------------+------------------------------------------------------------------+-----------+---------------------+------------------------------------------------------------------
 8502fe3617b70d12fc65c8c17dab8483f5a7f847e0fba0376fe7abacf4773262 |     3 | f                  | 93892d0c469bd1228f0e94621d3101e755523e97ea0a837c9b509b1aeb9d8c42 |           |                     | 93892d0c469bd1228f0e94621d3101e755523e97ea0a837c9b509b1aeb9d8c42

You can see the UTxO doesn't have script address_has_script = f and left join to script table is null (LEFT JOIN "script" ON "script"."hash" = "tx_out"."payment_cred") resulting on empty column script_id. The same goes to column reference_script_id .
So we can we can assume no script is involved in this UTxO but we can see it has data_hash and according to db-sync schema doc:

You can also notice the UTxO has inline datum (column inline_datum_hash in the query) which value is the same as data_hash. I know strictly speaking having data_hash doesn't mean it must have a script but I just cannot understand this UTxO.
Why data_hash is the same as inline_datum_hash, and what does it means?

data_hash is always expected to be the same as the hash of the referenced inline_datum_hash. The existence of the latter simply shows that the datum is in fact inlined.
About your other question, you're right that the ledger rules technically allow to create an output that has a datum even if it's not locked by a script. In this case, the output is unspendable.


text:
Is hydra.iohk.io just down or has there been a change in .json configs’ provisioning?
Where does one get the basic .*-config.json, .*-topology.json and .*-genesis.json files for package building nowadays? The URLs that always worked for me seem down, e.g.:
https://hydra.iohk.io/job/Cardano/cardano-node/cardano-deployment/latest-finished/download/1/mainnet-config.json
This makes it quite hard to rebuild this package that depends on the configs. Somewhere on the interwebs they mention a switch from hydra.iohk.io to cache.iog.io, but nope, that doesn’t work either. (Or perhaps the URL structure is completely different.)
I could probably just reuse the files from 1.35.3 for 1.35.4, but (sort of) dislike the idea; I like to keep things clean & correct & buildable long-term.
So what’s the issue here? Is it just temporary downtime? Has there been a change in the config file provisioning? Or have the config files themselves been replaced? (If so, is there a migration guide?) Looking at the 1.35.4 release notes, I can’t spot any news concerning the .json files.

The hydra.iohk.io site went through unexpected retirement (and may not be restored). But the release notes for 1.35.4 already have updated links for binary download (which points to update-cardano-mainnet.iohk.io) and configs (which points to https://book.world.dev.cardano.org/environments.html).
Also, the config files you download from that site are available on github here

Well, the cardano-world repo doesn’t have tags, but I assume that the 1.35.4-node-bump branch might do.  In retrospect, the reason why my vigorous GitHub searches found nothing was … the renaming of mainnet-config.json to config.json. That’s a level of encryption that my brain just could not penetrate.


text:
Transaction in Cardano
I created transfer function with blockfrost.js and cardano-serialization-lib.
I refered following code.
https://github.com/blockfrost/blockfrost-js/tree/master/examples/simple-transaction
When I try to transfer with above code, I am getting following error.
"transaction submit error ShelleyTxValidationError ShelleyBasedEraBabbage (ApplyTxError [UtxowFailure (UtxoFailure (FromAlonzoUtxoFail (ValueNotConservedUTxO (Value 0 (fromList [])) (Value 2663366 (fromList []))))),UtxowFailure (UtxoFailure (FromAlonzoUtxoFail (BadInputsUTxO (fromList [TxIn (TxId {_unTxId = SafeHash \"***\"}) (TxIx 1)]))))])"

Interesting thing is, transaction is success also, I can see success transaction in cardano explorer.
Can I ignore above error? Or how can I fix above error?

I think this error means you are spending a UTxO that is no longer available.

This probably means that you are trying to spend an UTxO that is already spent.
This can mean few things, but most probably that you are submitting the transaction for the second time.
If you are using Blockfrost, check the /mempool endpoint to see if you transaction is in the mempool or /txs if it is already on-chain.

It is on on-chain. So, what can I know from it? Can I ignore this error?

Depending on your use case. Why are you getting this error in the first place? Are you trying to retry the transaction more times?

Yes. you are correct.

In that case you can ignore the error. :)

Thank you. Could you explain in detail?

The error just says that the utxo you are trying to spend is already spend, so you cannot do it again. Ideally, you would submit transaction once and check if it is in the mempool or txs and only if it is not there, you would resubmit ti again.


text:
How to get balance of enterprise address
https://docs.blockfrost.io/#tag/Cardano-Addresses/paths/~1addresses~1%7Baddress%7D~1extended/get
I am using above blockfrost api to get address balance.
However, it isn't working with enterprise address, I am getting 504 error for enterprise address.
I also tried https://api.koios.rest/#post-/address_assets, getting same 504 error.
How can I get balance for enterprise address?

This endpoint also works with enterprise addresses for me.

Can you let me know address?

The endpoint is working with enterprise addresses too (as well as with payment credentials or any other addresses).

$ curl -s  -H "project_id: ..." \
   https://cardano-mainnet.blockfrost.io/api/v0/addresses/addr1v8px4syex8e07e6c2ucfheh27t2tcxxjm5el22g0cw32m5g77jc7x \
   | jq
{
  "address": "addr1v8px4syex8e07e6c2ucfheh27t2tcxxjm5el22g0cw32m5g77jc7x",
  "amount": [
    {
      "unit": "lovelace",
      "quantity": "17374229558"
    }
  ],
  "stake_address": null,
  "type": "shelley",
  "script": false
}

$

As you can see in the example above, this address does not contain any stake_address.

Thank you for your answer. Could you check this address ? addr1v9u7va2sktlnz8dp3qadpnxxlv4m03672jy6elmntlxxs7q9nnwl9 Why is it not working?

It works fine for me. When you open https://cardano-mainnet.blockfrost.io/api/v0/addresses/addr1v9u7va2sktlnz8dp3qadpnxxlv4m03672jy6elmntlxxs7q9nnwl9 what do you get?

Oh, /addresses/{address}api is working. I was trying /addresses/${address}/extended

Not sure why, .../extended also works for enterprise addresses generally, but not for this particular one. Maybe related to the high number of transactions, so could be a bug in blockfrost.


text:
nix shell did not work in plutus-apps
I checkout to branch c2b310968d0915e2af0ea4680186b41ad88ffbe9 and run nix-shell at plutus-apps. No error, nothing change when I run nix-shell.I reinstalled nix, changed iohk-cache, reinstalled ubuntu. I still can't run nix-shell. Maybe that's my PC's wrong but I don't know. I need any help.
➜  plutus-apps git:(c2b310968) nix-shell
trace: To make project.plan-nix for haskell-project a fixed-output derivation but not materialized, set `plan-sha256` to the output of the 'calculateMaterializedSha' script in 'passthru'.
trace: To materialize project.plan-nix for haskell-project entirely, pass a writable path as the `materialized` argument and run the 'updateMaterialized' script in 'passthru'.
trace: To make project.plan-nix for cabal-install a fixed-output derivation but not materialized, set `plan-sha256` to the output of the 'calculateMaterializedSha' script in 'passthru'.
trace: To materialize project.plan-nix for cabal-install entirely, pass a writable path as the `materialized` argument and run the 'updateMaterialized' script in 'passthru'.
trace: To make project.plan-nix for cardano-node a fixed-output derivation but not materialized, set `plan-sha256` to the output of the 'calculateMaterializedSha' script in 'passthru'.
trace: To materialize project.plan-nix for cardano-node entirely, pass a writable path as the `materialized` argument and run the 'updateMaterialized' script in 'passthru'.
trace: To make project.plan-nix for haskell-project a fixed-output derivation but not materialized, set `plan-sha256` to the output of the 'calculateMaterializedSha' script in 'passthru'.
trace: To materialize project.plan-nix for haskell-project entirely, pass a writable path as the `materialized` argument and run the 'updateMaterialized' script in 'passthru'.
trace: To make project.plan-nix for haskell-project a fixed-output derivation but not materialized, set `plan-sha256` to the output of the 'calculateMaterializedSha' script in 'passthru'.
trace: To materialize project.plan-nix for haskell-project entirely, pass a writable path as the `materialized` argument and run the 'updateMaterialized' script in 'passthru'.
trace: To make project.plan-nix for haskell-project a fixed-output derivation but not materialized, set `plan-sha256` to the output of the 'calculateMaterializedSha' script in 'passthru'.
trace: To materialize project.plan-nix for haskell-project entirely, pass a writable path as the `materialized` argument and run the 'updateMaterialized' script in 'passthru'.

It looks like your nix-shell is running, just give it time until it return the command line prompt again.

Yes, It's already done but nothing change. I thought its theme is wrong so I tried to build my project but It can not run.

You should try nix develop. If you are using a new version of Nix.

Please add a bit more details to this answer. What is nix develop and how does it help to solve the problem?


text:
Unable to attach two reference inputs to a transaction with Plutus Emulator
I have written a script that will fail unless it receives both oref1 and oref2 as reference inputs. I have the following emulator code:
let rule = mempty
                     <> C.mustReferenceOutput oref1
                     <> C.mustReferenceOutput oref2
                     <> C.mustMintValue val
                     <> (C.mustBeSignedBy ppkh)
tx <- mkTxConstraints @Void (plutusV2MintingPolicy policy) rule
submitTxConfirmed tx

The script fails saying that oref1 is not a reference input. But if I comment out C.mustReferenceOutput oref2 then the script fails saying it has not received oref2 as a reference input. It seems I can attach oref1 or oref2 as a reference input, but not both.
On the testnet, this issue does not occur, so it isn't a problem with the script. Is it not possible with the Plutus emulator to attach more than one reference input to a transaction?

It does work with the emulator. Here's a test that demonstrates this being validated on-chain.
https://github.com/input-output-hk/plutus-apps/blob/9bb44b617212fa195701f0c4a59d6f0e60b7764d/plutus-contract/test/Spec/Contract/Tx/Constraints/MustReferenceOutput.hs#L195-L196


text:
when and where to use different types of addresses in cardano
From here https://docs.cardano.org/learn/cardano-addresses
I know that there are 4 types of addresses:

base addresses
pointer addresses
enterprise addresses
reward account addresses

For my understanding, I think

base addresses is for sending/receiving funds
reward account addresses is for receiving rewards when you delegate to a pool

I have 3 questions

What is the meaning of pointer and enterprise addresses. When and where we use it?

From this CIPs, I see the following description of Shelly addresses.

Am I right that

(0), (1) are stake addresses, (2),(3) are base addresses?
(4) and (5) are pointer addresses and (6), (7) are enterprise addresses?

PaymentKeyHash means the hash of payment key? So, What is the meaning of ScriptHash?

There is a lot of terms which are not clear to me. Any hints from you will help me a lot.
Thanks very much.

a) An enterprise address is such that does not contain the delegation part and cannot therefore participate in staking. The general idea was that organizations such as exchanges will use the addresses so they cannot participate in staking. It was pretty naive I guess.
b) A pointer address does not contain the key directly, but instead points directly to a slot, tx and certificate that is already on-chain. The advantage is that the pointer is smaller in size, but also can be used with a certificate that is not registration on-chain yet.

Stake address is any address with the delegation part. Stake address is also a base address. (1) to (5), they are all considered stake addresses as they can participate in staking. (4) and (5) are pointer addresses as they are pointing to a certificate. (6) and (7) are enterprise addresses as they do not contain any delegation part.

Yes, PaymentKeyHash is the hash of a payment key. ScriptHash is the hash of the script such as Plutus.

Thanks for your answers. I have some follow-up questions.

Can we (nomal users) can create pointer address  and  enterprise address?
Is there any instruction  on how to create these address?

(0) has delegation part but it is not stake address?

stake address is address which starts with stake1xxxxx(after decoded with bech32)?
That means if we convert (1) to (5) to Bech32,  all these address will be stake1xxxx?

Little clarification: what is typically called stake addresses are not typical payment address. None of types (0) to (7) are stake addresses (they are in a separate table).

Stake addresses are special in the sense that they can receive rewards, you can spend from them but you can't sent to them.

From this https://github.com/cardano-foundation/CIPs/blob/master/CIP-0019/README.md
I understand that the stake _address should start by 14, or 15 in decimal, while the base address should start by 0, or 1 in decimal. Is it right?
So, I did not understand what Marek Mahut says " Stake address is also a base address".?


text:
Failure building documentation
I've been trying to build documentation to no avail: Below is the log of the output i get after running nix build -f default.nix docs.site --extra-experimental-features nix-command
@nix { "action": "setPhase", "phase": "unpackPhase" }
unpacking sources
unpacking source archive /nix/store/v2rkjvsh6559c5mrix371zzf10jjf64k-openapi3-3.2.2.tar.gz
source root is openapi3-3.2.2
setting SOURCE_DATE_EPOCH to timestamp 1000000000 of file openapi3-3.2.2/test/Spec.hs
@nix { "action": "setPhase", "phase": "patchPhase" }
patching sources
@nix { "action": "setPhase", "phase": "configurePhase" }
configuring
Configure flags:
--prefix=/nix/store/54gdr97lm30cjrhybh3jhzgvyqf0gs3m-openapi3-lib-openapi3-3.2.2 lib:openapi3 --package-db=clear --package-db=/nix/store/5wc>Configuring library for openapi3-3.2.2..
@nix { "action": "setPhase", "phase": "buildPhase" }
building
Preprocessing library for openapi3-3.2.2..
Building library for openapi3-3.2.2..
[ 1 of 18] Compiling Data.OpenApi.Aeson.Compat ( src/Data/OpenApi/Aeson/Compat.hs, dist/build/Data/OpenApi/Aeson/Compat.o, dist/build/Data/O>[ 2 of 18] Compiling Data.OpenApi.Declare ( src/Data/OpenApi/Declare.hs, dist/build/Data/OpenApi/Declare.o, dist/build/Data/OpenApi/Declare.>exprType TYPE: p_akIy
exprType TYPE: p_akIy
exprType TYPE: p_akIy
exprType TYPE: p_akIy
exprType TYPE: p_akIy
exprType TYPE: p_akIy
exprType TYPE: p_akIy
exprType TYPE: p_akIy
exprType TYPE: p_akIy
exprType TYPE: p_akIy
exprType TYPE: p_akIy
exprType TYPE: p_akIy
exprType TYPE: p_akIy
exprType TYPE: p_akIy
exprType TYPE: p_akIy
exprType TYPE: p_akIy
exprType TYPE: Text
exprType TYPE: Text
[ 3 of 18] Compiling Data.OpenApi.Internal.AesonUtils ( src/Data/OpenApi/Internal/AesonUtils.hs, dist/build/Data/OpenApi/Internal/AesonUtils>[ 4 of 18] Compiling Data.OpenApi.Internal.TypeShape ( src/Data/OpenApi/Internal/TypeShape.hs, dist/build/Data/OpenApi/Internal/TypeShape.o,>[ 5 of 18] Compiling Data.OpenApi.Internal.Utils ( src/Data/OpenApi/Internal/Utils.hs, dist/build/Data/OpenApi/Internal/Utils.o, dist/build/>[ 6 of 18] Compiling Data.OpenApi.Internal ( src/Data/OpenApi/Internal.hs, dist/build/Data/OpenApi/Internal.o, dist/build/Data/OpenApi/Inter>exprType TYPE: Text
exprType TYPE: Text
exprType TYPE: Text
exprType TYPE: Text
exprType TYPE: Text
exprType TYPE: Text
exprType TYPE: Text
exprType TYPE: Text
exprType TYPE: Text
exprType TYPE: Text
exprType TYPE: Text
exprType TYPE: Text
/nix/store/cjl2qfa8h01l0qk1748ynbhwi1zv8vf6-stdenv-linux/setup: line 1400:   120 Killed                  $SETUP_HS build lib:openapi3 -j$(($>

What documentation are you trying to build?

I'm trying to build the plutus-apps documentation

Works for me. Have you correctly configured the binary cache as per docs? Note it changed last month.
You could also try entering nix-shell and running build-and-serve-docs to build and host docs.

Thanks for the suggestion. I just tried it and got the same... ... error: 1 dependencies of derivation '/nix/store/m1ss6ik6fh7q5il3b9lznf8kd8bjwqvf-plutus-use-cases-lib-plutus-use-cases-1.0.0.0.drv' failed to build error: 1 dependencies of derivation '/nix/store/q1m6kkkk94rlmiqxrvbn0wcw9nqpq7vk-haddock-join.drv' failed to build error: 1 dependencies of derivation '/nix/store/b8wj79ccfhjhx1jj58b4dmn4p27ad2qs-plutus-docs.drv' failed to build Serving HTTP on 0.0.0.0 port 8002 (http://0.0.0.0:8002/) ...

It turns out the issue was a memory issue. I closed all applications running on the pc and restarted the build and... voila!


text:
How to detect a wallet change event
How do i detect that my user has switched their wallet to a different one in browser. When a user connects their wallet to my web app, we store their wallet address temporarily for use in the future.Let's say they are currently interacting with my web app using Nami wallet. Nami wallet allows user to switch multiple different wallets. How do i detect that a user has switched to a different wallet.
In Solana and Ethereum they have something like this.
connector.on(...)

Is there an equivilant of that for Cardano.

     var handle: any = await window.cardano.nami.enable() handle.experimental.on('accountChange',(addresses: any ) => {
    console.log(addresses)
  }

As far as I know, there isn't.
You probably need to check the cardano.wallet.name periodically.


text:
How to install/use cardano-serialization-lib
I follow this guide to get start with cardano-serialization-lib.
Install nodejs package with:
npm i @emurgo/cardano-serialization-lib-nodejs

Still can't get it running. The module 'rust-lib' can't be found. And of course when try to import 'rust-lib' there is an error:
error TS2307: Cannot find module 'rust-lib' or its corresponding type declarations.

So how do I get the module visible?
Step-by-step guide would be really appreciated. I don't have very deep knowledge about how nodejs or rust works.

I thought I have to import 'rust-lib' but instead I have to
import CardanoWasm = require('@emurgo/cardano-serialization-lib-nodejs')

Get the idea from this answer.


text:
How to use reward withdrawing via cardano-cli?
Has anyone played around or stumbled upon tutorial examples on how to use reward withdrawing via cardano-cli? I want to study the commands related with "withdraw" keyword. I have not seen examples illustrating their functionality. The commands/args are the one in the photo below

Note: Originally posted at IOG discord ask-plutus channel https://discord.com/channels/826816523368005654/826829805387120690/1049778750625169528

At first, try the following command to query the payment address balance:
cardano-cli query utxo \
    --address $(cat payment.addr) \
    --allegra-era \
    --mainnet

Then use the command that looks like that (do not forget to calculate transaction fees):
cardano-cli transaction build raw \
    --tx-in <YourTxHash>#1
    --tx-out $(cat payment.addr)+0
    --withdrawal $(cat stake.addr)+25000000
    --ttl 12345678
    --fee 72500
    --out-file withdraw_rewards.raw


text:
Unable to compile script
I'm stuck trying to compile my minting policy - getting the following error message:
    • Couldn't match type ‘Colony’ with ‘BuiltinData’
      Expected type: template-haskell-2.16.0.0:Language.Haskell.TH.Syntax.Q
                       (template-haskell-2.16.0.0:Language.Haskell.TH.Syntax.TExp
                          (PlutusTx.CompiledCode (BuiltinData -> BuiltinData -> ())))
        Actual type: th-compat-0.1.4:Language.Haskell.TH.Syntax.Compat.SpliceQ
                       (PlutusTx.CompiledCode (Colony -> UntypedMintingPolicy))
    • In the expression: PlutusTx.compile [|| wrap ||]
      In the Template Haskell splice $$(PlutusTx.compile [|| wrap ||])
      In the first argument of ‘V2.mkMintingPolicyScript’, namely
        ‘$$(PlutusTx.compile [|| wrap ||])’

I'm making of CHaP in my cabal.project file.
When I tried compiling without CHaP, I got the following:
Resolving dependencies...
cabal: Could not resolve dependencies:
[__0] trying: cardano-streaming-1.0.0.0 (user goal)
[__1] unknown package: cardano-api (dependency of cardano-streaming)
[__1] fail (backjumping, conflict set: cardano-api, cardano-streaming)
After searching the rest of the dependency tree exhaustively, these were the
goals I've had most trouble fulfilling: cardano-streaming, cardano-api

Any help would be appreciated.

Can you try the following?
import           Cardano.Api                          (PlutusScriptV2,
                                                       writeFileTextEnvelope)
import           Cardano.Api.Shelley                  (PlutusScript (..))
import           Codec.Serialise
import qualified Data.ByteString.Lazy                 as LBS
import qualified Data.ByteString.Short                as SBS
import           Data.Functor                         (void)
import qualified Ledger.Typed.Scripts                 as Scripts
import           Plutus.V1.Ledger.Api                 as PlutusV1
import           Plutus.V1.Ledger.Value               as PlutusV1
import qualified Plutus.V2.Ledger.Api                 as PlutusV2
import qualified Plutus.V2.Ledger.Contexts            as PlutusV2
import qualified PlutusTx
import           PlutusTx.Prelude                     as P
import           Prelude                              (IO, print)

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

{-# INLINEABLE mintingValidator #-}
mintingValidator :: MyRedeemer -> ScriptContext -> Bool
mintingValidator red ctx = True

Policy :: Scripts.MintingPolicy
Policy = PlutusV2.MintingPolicy $ PlutusV2.fromCompiledCode ($$(PlutusTx.compile [|| wrap ||]))
    where
        wrap = Scripts.mkUntypedMintingPolicy $ mintingValidator

Here the custom data type MyRedeemer is lifted, something that your custom datatype colony did not have (Couldn't match type ‘Colony’ with).‘BuiltinData’).

Thanks for the suggestion. Colony is actually lifted using unstableMakeIsData. Changing it to makeIsDataIndexed got me Couldn't match type ‘[(template-haskell-2.16.0.0:Language.Haskell.TH.Syntax.Name,                              Int)]                            -> template-haskell-2.16.0.0:Language.Haskell.TH.Syntax.Q                                 [template-haskell-2.16.0.0:Language.Haskell.TH.Syntax.Dec]’                      with ‘template-haskell-2.16.0.0:Language.Haskell.TH.Syntax.Q                              [template-haskell-2.16.0.0:Language.Haskell.TH.Syntax.Dec]’


text:
Track incoming payment of an address using cardano-db-sync
I have a cardano-node with cardano-db-sync installed. In this node, I also have a separate database named CDT, and a web UI to connect to this CDT database.
I defined an address named addr1xxxxxx which I want to track incoming payment. In the web, I display this address as QR code to users.
When users see this QR code, they have to send a certain ADA to this address within a certain time. If they do send enough ADA, they will be redirected to the next step and so on.
What I want to do this to get know whether users have sent enough ADA to this address or not. I can check cexplorer database to know this, but in many cases I am afraid that cardano-db-sync is not synced fast enough to get the latest from the blockchain.
I have heard of webhooks services of blockfrost or tangocrypto. They maybe a good solutions. But it relies on third-party services.
Can you suggest another solution?

Check out Oura which gets you a tail feed of events. Should be the fastest solution not relying on third parties.


text:
Getting the CurrencySymbol of PlutusV2 MintingPolicy
I'd like to get the CurrencySymbol of a PlutusV2 MintingPolicy. There's a function defined in Plutus.Script.Utils.Scripts with the following signature:
scriptCurrencySymbol :: Versioned MintingPolicy -> CurrencySymbol
But I have no idea how get the Versioned MintingPolicy of a MintingPolicy

You can use Plutus.Script.Utils.V2.Scripts.scriptCurrencySymbol


text:
How does Cardano Halving work?
Does Cardano Halving work similar to Bitcoin Halving? The next Bitcoin halving is projected to take place in March 2024, will Cardano Halving happen the same year?
The Cardano price prediction for 2023 (by coinpedia) with an extended bullish trend is to $1.1308, Will the Halving event effect this price prediction?

Cardano's staking and Bitcoin's mining are built on completely different principles. Cardano staking rewards gradually get reduced by 0.2...0.3% every 5 days (One Epoch), whereas the reward for creating a new block in Bitcoin is halved every 4 years.

Cardano does not have a halving. Available rewards per block decrease gradually, not stepwise as in Bitcoin.


text:
Key derivation are unclear

I watch this video on Key Derivation process (https://www.youtube.com/watch?v=4tSQBK75CPU&t=722s). Basically, from mnemonic phrase --> create root key --> create public addresses
Then, I see another tutorial to create payment address.
https://developers.cardano.org/docs/stake-pool-course/handbook/keys-addresses/
I can create payment address without any mnemonic phrase or root key

The two all above are the process to create addresses, but they are a little different, which I could not understand.
I have 3 questions

Why in the tutorial, we can create payment address without mnemonic phrase?

In the tutorial, there is no step to create root key. What is the root key? It is verification key?

The video says that we can create multiple addresses from the root key.
I tried to create different addresses using the below command, but they all generated the same address. How can I generate different addresses by using cardano-cli?

cardano-cli address build \
    --payment-verification-key-file payment.vkey \
    --stake-verification-key-file stake.vkey \
    --out-file payment.addr \
    --mainnet

Any hint would help me a lot. Thank you

If you want to find out how to create the root key from the mnemonic and how to derivate the keys and create the signing keys and addresses, take a look here: https://gist.github.com/cardano-apexpool/99784308812bdf7aa01446fa95f47fd2

You're mixing up between an HD Wallet and payment/stake address keys. HD Wallet is off-chain concept, creating root keys for which are described here.
You'd essentially be able to derive root key of HD wallet using mnemonics and then derive the address by following the derivation paths, as explained here.

Thanks very much. I did not know that. When I create address (addrxxxxx) in my Yoroi wallet, that follows the concept of HD Wallet? If so, my address is on-chain. So, I did not understand why "HD Wallet is off-chain concept"?

Wallet created in Yoroi is HD Wallet, yes. As regards why concept is off-chain, that's because protocol does not know about these wallets, it only knows about addresses - the cryptography explained above is what allows you to have multiple payment keys derived from a root key that's derived from mnemonics

Thanks, I understand. So, the tutorial above (https://developers.cardano.org/docs/stake-pool-course/handbook/keys-addresses/ ) is also about creating addresses which do not follow the concept of HD wallet. Both doing the same thing (creating address), but why we need both of them?

That particular link is about creating keys/addresses indeed, you dont need both - it just depends on your use-case. It gives the option that's available from using cardano-cli, for HD wallets - you'd need to work with cardano-address/ cardano-wallet (if using CLI) or one of the libraries

Thanks, it helps me a lot


text:
How often do we see chain reorgs in Cardano?
Is there a specific metric we can follow on-chain, or how we can observe or infere a chain reorg has happened?

On my cardano-db-sync instance I see a one block reorganisation a couple of times a day. Two block reorgs maybe once a week or month and I have never seen a 3 block reorg. That does not mean they don't happen, just that they are rare.
There is no on-chain metric which would show reorgs. Furthermore different parts of the network may see different sets of reorgs. That is simply the way distributed ledgers work.
The only "truth" is for blocks which are unlikely to be reorganized (more than 5 blocks deep and less than 2160 blocks deep) or cannot be reorganized (more than 2160 blocks deep).
If you wanted to view reorgs, you could do if from the logs of a running node, but even then you would only see reorgs that your node sees. There may be other reorgs on other more remote (not remove geographically, but remote in terms of network connection and latency) parts of the chain.

Thank you, very explanatory! Unfortunately I can't still vote your answer as useful


text:
How to run a simple Fib function offline?
On Ethereum, I'm able to run and test a Fibonacci function by writing a Solidity smart-contract with a fib method, compiling to the EVM, deploying and running offline by using any EVM implementation, such as Sputnick:
function fib(uint n) public constant returns(uint result) {
  if (n <= 1) {
    return 1;
  } else {
    return Fib.fib(n - 1) + Fib.fib(n - 2);
  }
}

On Cardano, I'm aware I can use Haskell to create contracts, which is then compiled to Plutus. But, despite having spent some time googling, I'm still not sure how to achieve that. How do I run and test a "fib" function offline on Cardano?

That is indeed possible. The following will compile a fib function to plutus and execute it given the default cost model.
{-# LANGUAGE DataKinds             #-}
{-# LANGUAGE DeriveAnyClass        #-}
{-# LANGUAGE DeriveGeneric         #-}
{-# LANGUAGE FlexibleContexts      #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NamedFieldPuns        #-}
{-# LANGUAGE NoImplicitPrelude     #-}
{-# LANGUAGE OverloadedStrings     #-}
{-# LANGUAGE RankNTypes            #-}
{-# LANGUAGE RecordWildCards       #-}
{-# LANGUAGE ScopedTypeVariables   #-}
{-# LANGUAGE TemplateHaskell       #-}
{-# LANGUAGE TypeApplications      #-}
{-# LANGUAGE TypeFamilies          #-}
{-# LANGUAGE TypeOperators         #-}

module Onchain where

import           Cardano.Api                          (PlutusScriptV2,
                                                       writeFileTextEnvelope)
import           Cardano.Api.Shelley                  (PlutusScript (..))
import           Codec.Serialise
import qualified Data.ByteString.Lazy                 as LBS
import qualified Data.ByteString.Short                as SBS
import           Data.Functor                         (void)
import qualified Ledger.Typed.Scripts                 as Scripts
import           Plutus.V1.Ledger.Api                 as PlutusV1
import           Plutus.V1.Ledger.Value               as PlutusV1
import qualified Plutus.V2.Ledger.Api                 as PlutusV2
import qualified Plutus.V2.Ledger.Contexts            as PlutusV2
import qualified PlutusTx
import           PlutusTx.Prelude                     as P
import           Prelude                              (IO, print, map)

import           PlutusCore.Evaluation.Machine.ExBudgetingDefaults (defaultCostModelParams)

{-# INLINEABLE fib #-}
fib :: Integer -> Integer
fib n = go n (0,1)
  where
    go x (a, b) | x==0      = a
                | otherwise = go (x-1) (b, a+b)

fibScript :: Script
fibScript = PlutusV2.fromCompiledCode ($$(PlutusTx.compile [|| fib ||]))

serialisedScript :: PlutusV2.SerializedScript
serialisedScript = SBS.toShort . LBS.toStrict $ serialise fibScript

getEvalCtx :: MonadError CostModelApplyError m => m EvaluationContext
getEvalCtx = case defaultCostModelParams of
              Nothing -> Err.throwError CMInternalReadError
              Just n  -> mkEvaluationContext n

runScript :: MonadError CostModelApplyError m => Integer -> m (LogOutput, Either EvaluationError ExBudget)
runScript n = getEvalCtx >>= (\c -> return (evaluateScriptCounting a b c serialisedScript [I n]))
              where
                a :: PlutusV1.ProtocolVersion
                a = ProtocolVersion 7 0
                b :: PlutusV1.VerboseMode
                b = Quiet

Thank you very much. Makes a lot of sense to me now. I think these evaluation functions should be documented somewhere.

What I always do, git clone the latest release plutus app repo (not main), then enter a nix-shell and execute build-and-serve-docs. This will run a local haddock server with all functions, really handy if you are searching for something! It's an up-to-date version of https://playground.plutus.iohkdev.io/doc/haddock/

What do you want to do with the output of your fib-function ? Also with "offline" you probably mean off-chain. If you want to compute the Fibonacci sequence off-chain you can use pure Haskell. There are many examples like this one:
fib 0 = 0
fib 1 = 1
fib n = fib (n-1) + fib (n-2)

This is just an inefficient naive way. Other solutions can be found here: https://wiki.haskell.org/The_Fibonacci_sequence
And then in your contract:
fibonacci :: forall w s. FibParams -> Contract w s Text ()
fibonacci param = do
    pkh <- ownPaymentPubKeyHash
    ... --do stuff with f
    unbalTx <- ...
    ledgerTx <- submitUnbalancedTx $ Constraints.adjustUnbalancedTx unbalTx
    awaitTxConfirmed $ getCardanoTxId ledgerTx
    Contract.logInfo @String $ "submitted tx"
  where
    f = fib (param num)

For testing you need to look into runEmulatorTraceIO.

I want to run fib in the context of Cardano's VM (is there one?) in order to benchmark its performance. Cardano doesn't run Haskell directly on nodes, right? It compiles to Plutus, and then interprets. I want to go through it to benchmark the Plutus interpreter versus native GHC Fib.


text:
SlotToPOSIXTime in English Auction Demo
in my cabal repl, i'm getting the following error from trying to replicate the week1 demo of Plutus-pioneer-program. I'm also unable to simulate the example scenario in the playground (i can see genesis transaction, but none of the subsequent bids), but I'm hoping the issue lies here:
Prelude Ledger.TimeSlot Week01.EnglishAuction> slotToEndPOSIXTime 10

<interactive>:10:20: error:
    • No instance for (Num SlotConfig) arising from the literal ‘10’
    • In the first argument of ‘slotToEndPOSIXTime’, namely ‘10’
      In the expression: slotToEndPOSIXTime 10
      In an equation for ‘it’: it = slotToEndPOSIXTime 10
Prelude Ledger.TimeSlot Week01.EnglishAuction>

That error occurs because your code has a number literal (ie 10) in a code position where a value of type SlotCOnfig is expected and the the compiler can't figure out how to convert the literal to a SlotConfig (ie "No instance for (Num SlotConfig)").
I would need to see more of the code (possibly all of it) to figure out a solution.
Ah, so the type of slotToEndPOSIXTime is:
slotToEndPOSIXTime :: SlotConfig -> Slot -> POSIXTime

Getting a correct SlotConfig value is going to be tricky, but the good news is that Slot does have a Num instance, so the literal 10 is a valid slot.

I'm not sure what other context to provide. The complete one-line command was simply that: slotToEndPOSIXTime 10

Five lines, the like to error occurs on and two lines before and after. Also what is the type of the function slotToEndPOSIXTime ?

I expanded the answer I gave above. Basically the problem is that you can calling the slotToEndPOSIXTime with one parameter (10) when it really needs two parameters; a SlotConfig type and then the 10 that you are currently giving it.


text:
Is validator script needed to spend a UTXO locked by its hash?
When a UTXO is produced, it is locked to an address, i.e., the hash of a script, not the script itself. When a transaction spends it, does the tx have to provide the script in its input? There are conflicting answers here/no, here/yes, and here/yes. Can someone please give a definite answer? I believe the answer should be yes, otherwise a validator cannot run the script and verifies it evaluates to true. However, I can't find it in the tx input.

The definite answer is the following...
Any transaction that consumes an unspent output has to provide a witness that proofs that the transaction is allowed to spend that output.
What this witness is, depends on the address that locks the output, as you indicated. The output could be locked by a simple public key that requires the signature of the associated private key. Or it could be a plutus script that locks these funds. In both cases, a witness needs to be provided.
For a script address, a witness consists of multiple things. The first is of course the script itself; otherwise, no validator could run the validity check of the transaction. Moreover, each unspent output at such an address also needs a redeemer to be added. Together with the already available datum at the output and the context of the transaction, a validator can now check if the spending of that output was valid.
Now, where are these things located from the perspective of a validator? If we take a look at the TxInfo in the ScriptContext we see the txInfoInputs as a list of TxInInfo. These are the unspent outputs that we are trying to spend in the transaction that is currently run. Then, if we scope further in on the txInInfoResolved we get a TxOut that captures the address, the value and maybe the presence of a datum. It could also be locked by a public key that does not need a datum, that the reason for maybe a datum.
Now to check how these outputs are locked we can futher scope in on the the Address type. We see that this consists of a credential and maybe a staking key (not all addresses have staking). If we again scope in on the Credential type, it is either a public key hash or a script hash.
We see that a validator can deduce by hashing the script if there are any outputs available that are associated with that witness. Additionally, in the TxInfo there is the txInfoRedeemers which captures the redeemers and the outputs that they are a witness of.


text:
Can there be duplicate Policy IDs?

An asset is uniquely identified by an asset ID, which is a pair of both the policy ID and asset name.

The Policy ID is a hash of the monetary policy script that was used to mint the token. What prevents someone from minting more of the same tokens using the same policy script?

The thing that prevents other people to (successfully) use the same policy script is that the policy needs to be validated by the blockchain. Minting transactions where the policy script is not successfully validated do not go through. This can be used for instance to make the policy require that the minting transaction is signed by a specific secret key. Or the policy can require that a specific UTxO is spend within the minting transaction. The latter would make a true NFT as UTxO are unique and thus the policy can only ever evaluate once to true.

One part of the policy is usually about signatures associated with it.
If you want to use the same script again, you will need the corresponding private keys.
If you have them and policy permits it, you can mint more tokens.
This is very important, as if your "NFT project" does not have a policy that prevents them to
mint more tokens, it is really unfair to claim one as such.


text:
Column does not exist when querying Rosetta endpoint
I'm currently running cardano-node version 1.35.0 and rosetta-server 1.8.2. The node is synced and I have blocks in postgres, however each query to rosetta throws an error:
curl -vvv -X POST 'http://<node-url>:8080/network/status' -H 'Content-Type: application/json' -d '{"network_identifier": {"blockchain": "cardano", "network": "mainnet"}}' | jq

{
  "code": 5000,
  "message": "An error occurred",
  "retriable": true,
  "details": {
    "message": "An error occurred for request 9149: column b.previous_id does not exist"
  }
}

The log shows an issue with the query, specifically the join.
2022-12-13T21:50:05Z 2022-12-13 21:50:05.011 UTC [11737] postgres@cexplorer STATEMENT:
2022-12-13T21:50:05Z    SELECT
2022-12-13T21:50:05Z      b.hash as hash,
2022-12-13T21:50:05Z      b.block_no as number,
2022-12-13T21:50:05Z      (b.time at time zone 'utc') as "createdAt",
2022-12-13T21:50:05Z      CASE
2022-12-13T21:50:05Z        WHEN b2.block_no IS NOT NULL THEN b2.block_no
2022-12-13T21:50:05Z        WHEN b3.block_no IS NOT NULL THEN b3.block_no
2022-12-13T21:50:05Z        ELSE 0
2022-12-13T21:50:05Z      END AS "previousBlockNumber",
2022-12-13T21:50:05Z      CASE
2022-12-13T21:50:05Z        WHEN b2.block_no IS NOT NULL THEN b2.hash
2022-12-13T21:50:05Z        WHEN b3.block_no IS NOT NULL THEN b3.hash
2022-12-13T21:50:05Z        WHEN b.block_no = 1 THEN b3.hash -- block 1
2022-12-13T21:50:05Z {"level":50,"time":1670968205012,"pid":125,"hostname":"coin-node-ada-kilo-coin-node-ada-kilo-0","reqId":8544,"length":112,"name":"error","severity":"ERROR","code":"42703","position":"684","file":"parse_relation.c","line":"3393","routine":"errorMissingColumn","msg":"[errorHandler] An error ocurred and will be sent as response","stack":"error: column b.previous_id does not exist\n    at Parser.parseErrorMessage (/cardano-rosetta-server/node_modules/pg-protocol/dist/parser.js:278:15)\n    at Parser.handlePacket (/cardano-rosetta-server/node_modules/pg-protocol/dist/parser.js:126:29)\n    at Parser.parse (/cardano-rosetta-server/node_modules/pg-protocol/dist/parser.js:39:38)\n    at Socket.<anonymous> (/cardano-rosetta-server/node_modules/pg-protocol/dist/index.js:8:42)\n    at Socket.emit (events.js:400:28)\n    at addChunk (internal/streams/readable.js:293:12)\n    at readableAddChunk (internal/streams/readable.js:267:9)\n    at Socket.Readable.push (internal/streams/readable.js:206:10)\n    at Pipe.onStreamRead (internal/stream_base_commons.js:188:23)","type":"Error","v":1}
2022-12-13T21:50:05Z        ELSE b.hash -- genesis
2022-12-13T21:50:05Z      END AS "previousBlockHash",
2022-12-13T21:50:05Z      b.tx_count as "transactionsCount",
2022-12-13T21:50:05Z      s.description as "createdBy",
2022-12-13T21:50:05Z      b.size as size,
2022-12-13T21:50:05Z      b.epoch_no as "epochNo",
2022-12-13T21:50:05Z      b.slot_no as "slotNo"
2022-12-13T21:50:05Z    FROM
2022-12-13T21:50:05Z      block b
2022-12-13T21:50:05Z      LEFT JOIN slot_leader s ON b.slot_leader_id = s.id
2022-12-13T21:50:05Z      LEFT JOIN block b2 ON b.previous_id = b2.id
2022-12-13T21:50:05Z      LEFT JOIN block b3 ON b2.previous_id = b3.id
2022-12-13T21:50:05Z    WHERE
2022-12-13T21:50:05Z      b.block_no = $1 AND
2022-12-13T21:50:05Z      $2 = $2
2022-12-13T21:50:05Z    LIMIT 1
2022-12-13T21:50:05Z null

I'm using this Dockerfile: https://github.com/input-output-hk/cardano-rosetta/blob/master/Dockerfile
I have tried syncing from scratch to no avail. Not sure what else I can do to make this work.

I was able to fix this by re-running the db migration cardano-db-tool run-migrations --mdir /cardano-db-sync/schema/


text:
E042:Error: Unsupported feature: Type constructor: GHC.Prim.Addr
Has anyone encountered such an issue?
Validator works fine and cborHex is generated when "writeSerialisedScript" run in cabal's repl. But when building with cabal build app, the following error is thrown:
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: Model.TypeD.TypeD
Context: Compiling type: Model.TypeD.TypeD
Context: Compiling type: Model.TypeD.TypeD
                         -> Model.TypeDAction.TypeDAction
                         -> Plutus.V2.Ledger.Contexts.ScriptContext
                         -> GHC.Types.Bool
Context: Compiling type: Model.ColonySettings.ColonySettings
                         -> Model.TypeD.TypeD
                         -> Model.TypeDAction.TypeDAction
                         -> Plutus.V2.Ledger.Contexts.ScriptContext
                         -> GHC.Types.Bool
Context: Compiling definition of: Validators.TypeD.mkColonyValidator
Context: Compiling expr: Validators.TypeD.mkColonyValidator
Context: Compiling expr at "ship-shift-0.1.0.0-inplace:Validators.TypeD:(171,8)-(171,50)"

Running cabal configure -f defer-plugin-errors before building seems to work, but I get the following linker warning:
/nix/store/jfkmqz20q8fsaqizcml86adxqyzlwllx-binutils-2.38/bin/ld: warning: type and size of dynamic symbol cardanozmapizm1zi35zi4zm8209ae821a2638d4c1d3e2b96141de65263d756436220f129fed7d2f300d13d8_CardanoziApiziSerialiseTextEnvelope_zdfIsStringTextEnvelopeDescr_closure are not defined

I've tried troubleshooting by commenting out lines to find the culprit to no avail.
Definition of Model.TypeD.TypeD is as follows:

type TypeA = (TypeB, Value)

data TypeB = A
            | B
            | C
            | D
            | E
            deriving (Show, Generic, Prelude.Eq, ToJSON, FromJSON)

PlutusTx.makeLift ''TypeB
PlutusTx.makeIsDataIndexed ''TypeB [('A, 0), ('B, 1), ('C, 2), ('D, 3), ('E, 4)]

data TypeC = TypeC
    { y :: !Rational
    , z :: !Address
    } deriving (Prelude.Show, Generic, Prelude.Eq, ToJSON, FromJSON)

PlutusTx.makeLift ''TypeC
PlutusTx.unstableMakeIsData ''TypeC

data TypeD = TypeD
    {
      a  :: !BuiltinByteString
    , b  :: ![PaymentPubKeyHash]
    , c  :: !Integer
    , d  :: ![TypeB]
    , e  :: ![TypeA]
    , f  :: !(Maybe TypeC)
    } deriving (Prelude.Show, Generic, Prelude.Eq, ToJSON, FromJSON)

PlutusTx.makeLift ''TypeD
PlutusTx.unstableMakeIsData ''TypeD

I have had similar issues.
I don't understand the Core to PLC plugin enough to explain why this happens, but I am fairly sure this is related to using types on-chain that have a strict field of type BuiltinByteString.
So removing the ! in front of field a in TypeD should avoid running into this error.


text:
Possible to get the total supply of a native token in a smart contract?
Is it possible to get the total supply of a native token in a smart contract, similar to the following Solidity code from here? One can easily query it from an external API.
address token = 0xE592427A0AEce92De3Edee1F18E0157C05861564;
IERC20(token).totalSupply();

A stated in the other question on this topic, in general, no you can not get the total supply of any native asset available in a plutus script.
The Cardano blockchain is inherently local and deterministic, this means that any data is strictly separated from other data. Global questions like, how many are there of token x on the blockchain, implies knowledge of all these little pieces of data.
This knowledge can be constructed off chain, but is harder to be deduced onchain in a trustless setting. In the off chain case, anyone who has a copy of the chain can just count the amount of minting/burning transactions and add these up (you can use the blockfrost api for this, for example). For a plutus script, the scope is limited by only the inputs you provide in its transaction, adding all these little pieces of data will overflow the available transaction size. Moreover, a plutus script is blind to any historic transactions of the chain, so there is even no way to add knowledge of previous transactions!
That said, there are ways to introduce this knowledge onchain for plutus to use. The first is writing a stateful minting script. This means a script that keeps track of the number of tokens it already minted! This is something that for example liquidity pools use, here they need to keep track of how many tokens they already put out to make sure any new issuance is done according to its protocol.
Secondly, one can use an oracle to introduce trustworthy knowledge on the total supply of a token. This is especially handy for tokens that already have a fixed minting policy and thus cannot introduce a stateful minting script.
Lastly, there is a new token standard for fungible tokens (CIP 67 and CIP 68). This allows the addition of metadata to tokens onchain, such as the total supply! This means that creators of tokens can add the amount of the supply there such that it is available onchain. Note, however, that this is something the creators can put in themselves, in no way does this ensure that the minting policy used abides that amount.
I suppose that in the future, as these things mature, there will come a standard open source stateful minting script that will ensure these things. Similar to the ECR20 standard you referred to.


text:
Full stack dApp example/tutorial
Now that I am comfortable with Plutus, I want to build a full-stack dApp with frontend and wallet support, so users can interact with it easily.
This auction dApp is a good example, but it does not detail how to integrate the dApp with a wallet and it uses customized Javascript to build off-chain transactions.
Is there a full-stack example/tutorial, such as Cryptozombies in Ethereum, or TicTacToe in Bitcoin SV.

You have a few open-source options to use and learn from:

See RoundTable for an example of a multisig wallet which uses CML (Cardano Multiplatform Library) + Submit API + Cardano GraphQL - https://github.com/ADAOcommunity/round-table
Checkout examples from Lucid which use the Blockfrost API and Helios for smart contract code https://github.com/spacebudz/lucid/tree/main/src/examples
See PicoSwap for an example of Atomic Swaps which uses Helios for both off-chain and on-chain code https://github.com/Hyperion-BT/PicoSwap
Look at some of the starter templates from MeshJS https://meshjs.dev/starter-templates

Option 4 is nice.

I created a library of offchain/onchain examples using helios that are open source and located here:
https://github.com/lley154/helios-examples
List of examples in increasing order of complexity

transfer-ada - builds a simple transaction to transfer Ada
nft - mints an NFT
nft-multisig - mints a multi signature NFT
vesting - creates a vesting contract that locks funds until deadline
donation - tracks donations on-chain when purchasing an eCommerce order
events - block chain event monitoring example

Look here I found it genuinely nice to learn
https://github.com/adaplays


text:
Custom currency error: Cannot build the initial state: Tag "toCardanoPolicyId"
I try to set an initial state of the emulator like so:
test :: IO ()
test = runEmulatorTraceIO' def emCfg myTrace
  where
    dist = Map.fromList [ (senderWallet, Ada.lovelaceValueOf 100_000_000)
                        , (receiverWallet, Ada.lovelaceValueOf 100_000_000)
                        ]

    emCfg :: EmulatorConfig
    emCfg = EmulatorConfig (Left dist) def

myTrace :: EmulatorTrace ()
myTrace = do
  void $ Emulator.payToWallet (senderWallet) (receiverWallet) $ Ada.lovelaceValueOf 5_000_000
  void $ Emulator.waitNSlots 1

It works perfectly. However when I set a custom currency ff with:
    dist = Map.fromList [ (senderWallet, Ada.lovelaceValueOf 100_000_000
                           <> Value.singleton "ff" "TokenName" 100_000_000)
                        , (receiverWallet, Ada.lovelaceValueOf 100_000_000)
                        ]

The script compiles but after running test I get this error:

*** Exception: Cannot build the initial state: Tag "toCardanoPolicyId" (Tag "1 bytes" DeserialisationError) CallStack (from HasCallStack):
error, called at src/Wallet/Emulator/Stream.hs:171:12 in
plutus-contract-1.0.0.0-68585fe6251fbab3f7ee7ae8755133e693587e4f6afa588ae8db3b056e79dcc0:Wallet.Emulator.Stream

This is plutus-apps v.1.0.0. This code works with some other tags.
How do I fix this? Is this a bug?

ff is not a valid PolicyId (aka CurrencySymbol). It must be 28 bytes.
For examples, see this answer on this similar Github issue https://github.com/input-output-hk/plutus-apps/issues/732#issuecomment-1265261105

Thanks. That solves it. "ff" seems to be ok with earlier version of plutus. Not anymore.


text:
What is the best IPFS provider for Cardano NFT that uses CidV0?
I am relatively new to the IPFS and NFT world. I am interested in finding the best IPFS provider for storing NFT files that are later used for minting a Cardano NFT. Currently, I am using Nft.Storage, which seems to be the complete leader in the IPFS and NFT world, but I have a problem that Nft.Storage exclusively works with CidV1 while Cardano has a metadata limitation that restricts me to CidV0.
Also, when I convert CidV1 to CidV0, I am unable to find the uploaded file in the IPFS explorer. I don't know if I need to map something somewhere, not sure how gateway resolve file if cidv1 is converted to cidv0?
So what is the best IPFS provider for Cardano that support CidV0, or do you know how IPFS gateway can resolved converted CidV0?

Blockfrost.io is probably the most popular within the Cardano ecosystem right now. (I'm from the BF team).
If you mint using NMKR, they are pinning your files too.
Also, nftcdn.io is launching their service very soon.


text:
Error - Building Cardano Node 1.35.4 in Ubuntu Linux 22.04
When building cardano-node-1.35.4 using
git checkout tags/1.35.4
cabal update
cabal build all

I get the following error
cabal: Failed to build tx-generator-2.2 (which is required by

test:tx-generator-test from tx-generator-2.2 and exe:tx-generator from

tx-generator-2.2).

Upon scrolling up a few lines, I see this
src/Cardano/Benchmarking/Script/Setters.hs:40:1: error:

    • Illegal constraint: c NumberOfInputsPerTx

        (Use ConstraintKinds to permit this)

    • In the instance declaration for

        ‘Data.Constraint.Extras.Has c_a3mLE Tag’

   |

40 | deriveArgDict ''Tag

   | ^^^^^^^^^^^^^^^^^^^

Can someone please help me understand what this error means and on how to solve this? Thanks in advance.

I think between CHaP movements and upstream updates the build process has started failing for 1.35.4, they've been fixed since on master branch. But for visibility of those using 1.35.4 to build:

Failed to build tx-generator-2.2 => This error itself would not prevent you to build cardano-node and cardano-cli binaries.
For those who receive an error with openssl, they'd need to modify cabal.project file as per this issue.
cabal install (running as-is for any component) was broken on that tag, fixed later on master

Thank you for your response. I will try this out. Yes, it wouldn’t prevent us from building binaries but the nodes won’t sync up to preview/prepped after that. That is the major issue am facing.

Sync of node should work fine on preview/preprod once node binary is built, and is actually used for node startup (you can confirm running node version via logs as well if using ScJson)

Hi @RdLrt, Sadly adjusting the cabal.project file did not work. However, I didn't receive any error on the master branch.

You should not use master branch, it may often contain changes that may not be supported by current network[s] or tools

What version of ghc are you using? Currently the only supported version is ghc-8.10.*.
Work is being done to support ghc-9.2.* and when that is supported across the complete stake, then support for ghc-9.10.* will be dropped.

Hi there, Thank you for your response. I am using the 8.10.7.


text:
Example/documentation of Reference Input (CIP31) and Inline Datum (CIP32) with Emulator?
I am finding an example implementation of Reference Input (CIP31) and Inline Datum (CIP32) and want to test it with the Plutus.Trace.Emulator. I see some answers like here talking about mustReferenceOutput and mustPayWithInlineDatumToPubKey. Not sure if they are them. playground.plutus.iohkdev.io is my main go-to for plutus documentation. But both are not shown in it. An example cabal project would be very helpful.
Is there one out there?

You can run an updated version of the Haddock documentation via the plutus-apps repo. Git clone this repo and checkout v1.0.0. Enter a nix-shell in the repo and perform build-and-serve-docs. The hosted version you refer to is outdated. The functions that you want are defined in the Ledger.Constraints module.

I've been assuming the hosted version is updated or at least fairly so. This helps. Thanks.

@Fermat BTW, is there a way to get to the documentation without entering a nix-shell and compile the whole thing?

@Adam There's a new hosted alternative coming very soon, should be a few weeks max. Look out for PR in plutus and plutus-apps repos for hosted Haddock docs.

Plutus Playground is no longer maintained and that instance will soon be taken down in favour of using the Trace Emulator.
Take a look at some of the plutus-contract integration tests for examples of using each of these constraints with the Trace Emulator. https://github.com/input-output-hk/plutus-apps/tree/main/plutus-contract/test/Spec/Contract/Tx/Constraints.
Note that mustPayWithInlineDatumToPubKey is deprecated in favour of mustPayToPubKeyWithInlineDatum

This is one hell of examples I didn't know existed. Right there in the git. Thanks.


text:
Not Able to watch my Cardano faucets when i query the node
I am using following command to query node.
./cardano-cli query utxo --address $(cat payment.addr)    --testnet-magic 1097911063
Getting the Faucets in preview testnet by the following site
https://docs.cardano.org/cardano-testnet/tools/faucet
The funding gets successful, also i can see the transaction hash on https://preview.cexplorer.io/tx ,But not getting faucets on node query.
Although my node is also synced to 64% with Alonzo era. Kindly guide me what i am missing.
Also i am using the latest cardano-node version ie. 1.35.4

First, in order to be able to query your address after you just used the faucet, the node must be in sync (100%). The version 1.35.4 is correct, it is the only one that will sync your node to 100%.
Second, if you are on the preview testnet, the testnet magic is 2. The testnet magic 1097911063 is for the legacy testnet.

Hi thanks for your answer, ill check it again when it gets 100% synced. Also i checked my testnet magic from db created which shows me 1097911063. And if i query the node with magic 2 then it gives me error of "cardano-cli: HandshakeError (Refused NodeToClientV_13 "version data mismatch: NodeToClientVersionData {networkMagic = NetworkMagic {unNetworkMagic = 1097911063}} /= NodeToClientVersionData {networkMagic = NetworkMagic {unNetworkMagic = 2}}")"

If your magic in the db folder is 1097911063, then you are on the legacy testnet, not on preview.

To switch to preview, you need to stop the node, download the configuration files for preview from here: https://book.world.dev.cardano.org/environments.html, delete the db folder and start your node.
Also, 1.35.4 will never sync the legacy testnet to 100%. Only 1.35.2 will sync it to 100%.

Yah, I have tried the prepod testnet also, but its syncing doesn't go beyond 0.01% even after a whole day. With that syncing speed i am unable to get any faucets. Can you please recommend its solution. I have also tried cardano 1.35.3 (preview and also preprod), but again its not syncing enough then how can i get faucets and proceed with that?

Syncing on preview and preprod should be a matter of minutes, you are probably doing something wrong.
For preview and preprod use 1.35.4, 1.35.3 will still go for a while for preprod, but not for preview.
You should check the logs to see what the problem is. If you are not starting your node as a systemd service, take a look at the tutorial I wrote here: https://apexpool.gitbook.io/stake-pool-scripts/running-a-cardano-node
To see the logs if you set it like I described, run:
journalctl -f -n 50 -u cardano-node.service

Ok after alot of research, finally i got the solution. I checked my log, it was giving error of  TrConnectError (Just 127.0.0.1:1337) 3.72.231.105:30000 Network.Socket.connect: <socket: 55>: invalid argument (Invalid argument) . So i resolved this error by running the node with host-addr 0.0.0.0 So final command is cardano-node run --config $HOME/cardano/preprod/config.json --database-path $HOME/cardano/db --socket-path $HOME/cardano/db/node.socket --host-addr 0.0.0.0 --port 1337 --topology $HOME/cardano/preprod/topology.json


text:
PlutusV2: Error when spending script output
This is how I spend script's utxos with the Emulator. This one from this example.
grab :: forall w s e. AsContractError e => Contract w s e ()
grab = do
  utxos <- utxosAt scrAddress
  let orefs   = fst <$> Map.toList utxos
    lookups = Constraints.unspentOutputs utxos <>
              Constraints.plutusV1OtherScript validator
    tx :: TxConstraints Void Void
    tx      = mconcat [mustSpendScriptOutput oref $ Redeemer $ Builtins.mkI 17 | oref <- orefs]

  ledgerTx <- submitTxConstraintsWith @Void lookups tx
  void $ awaitTxConfirmed $ getCardanoTxId ledgerTx
  Plutus.Contract.logInfo @String $ "collected gifts"

This is PlutusV1. This works as expected. But with PlutusV2, the lookups now is like:
    lookups = Constraints.unspentOutputs utxos <>
              Constraints.plutusV2OtherScript validator

Note the version difference in Constraints.plutusV2OtherScript validator.
The rest of the code is the same except that this time the package is plutus-apps v1.0.0.
The V2 script compiles but when grab is called I get this error:

*** CONTRACT STOPPED WITH ERROR: ""ConstraintResolutionContractError (DatumNotFound
03170a2e7597b7b7e3d84c05391d139a62b157e78786d8c082f29dcf4c111314)""

I try Constraints.otherScript (Versioned validator PlutusV2). Same error.
I try Plutus.Trace instead of Plutus.Trace.Emulator. Same error.
This is just one example. I see this "DatumNotFound" error in other projects when trying to work with plutus-apps v1.0.0.
How do I fix this. Or is it just a bug?

The cause is mustPayToOtherScript in the give endpoint where
give :: AsContractError e => Integer -> Contract w s e ()
give amount = do
  let tx = mustPayToOtherScript valHash (Datum $ Builtins.mkI 0) $ Ada.lovelaceValueOf amount
  ledgerTx <- submitTx tx
  void $ awaitTxConfirmed $ getCardanoTxId ledgerTx
  Plutus.Contract.logInfo @String $ printf "made a gift of %d lovelace" amount

The error is fixed by replacing mustPayToOtherScript with mustPayToOtherScriptWithDatumInTx.
Get the answer from mlabs-haskell/plutip. Thanks to their warning:

-- WARN: at the moment 'mustPayToOtherScript' causes 'DatumNotFound' error during constraints resolution


text:
Automatic Token Distribution?
Is there a way to automatically distribute a token to every wallet that holds ada?
This would be a mechanism to distribute DAO voting rights automatically to all ada wallets. Voting power would be proportional to the amount of ada in the wallet. 1 DAO token per 10000 ADA. A wallet owner could choose to either burn the token or sell them to someone else if they are not interested in participating in the DAO.
Could this be executed in a single trasaction?

If you are talking about all ADA wallets that exist, this is certainly not possible in a single transaction.
If there are 142 addresses or less (that you are distributing to), it should be possible in a single transaction, otherwise the transaction size will be too large (above the 16 KB limit). You also need to send about 1.3 ADA (depending on the token name and the amount of tokens you send) to each address together with the tokens.

Ok, thanks for the information.


text:
How to use webhook on Blockfrost?
I want to trigger a function when someone sent ADA to an address addr1xxxxxx.
I use webhook from Blockfrost. I see this link (https://blockfrost.dev/docs/start-building/webhooks/using-webhooks) to describe how to use it.
I works fine if I use public webhook site (https://webhook.site/)
but it fails to trigger on my own server.
I set up as follows:

I create a webhook on blockfrost website as follows.

The endpoint URL is set to the static address of my server, at port 6666.
Trigger condition is set when someone sends ADA to the address addr1xxxx

After creating this, Blockfrost will generate an Auth token.

I replace SECRET_AUTH_TOKEN in the following script by the above Auth token.

# Example of Python Flask app with /webhook endpoint
# for processing events sent by Blockfrost Secure Webhooks
from flask import Flask, request, json
from blockfrost import verify_webhook_signature

# You will find your webhook secret auth token in your webhook settings in the Blockfrost Dashboard
SECRET_AUTH_TOKEN = "SECRET-WEBHOOK-AUTH-TOKEN"

app = Flask(__name__)

# Define endpoint /webhook that accepts POST requests
@app.route('/webhook', methods=['POST'])
def webhook():
    if request.method == 'POST':
        # Validate webhook signature
        request_bytes = request.get_data()
        try:
            verify_webhook_signature(
                request_bytes, request.headers['Blockfrost-Signature'], SECRET_AUTH_TOKEN)
        except SignatureVerificationError as e:
            # In case of invalid signature verify_webhook_signature will raise SignatureVerificationError
            # for easier debugging you can access passed header and request_body values (e.header, e.request_body)
            print('Webhook signature is invalid.', e)
            return 'Invalid signature', 403

        # Get the payload as JSON
        event = request.json

        print('Received request id {}, webhook_id: {}'.format(
            event['id'], event['webhook_id']))

        if event['type'] == "transaction":
            # process Transaction event
            print('Received {} transactions'.format(len(event['payload'])))
            # loop through the payload (payload is an array of Transaction events)
            for transaction in event['payload']:
                print('Transaction id: {}, block: {} ({})'.format(
                    transaction['tx']['hash'], transaction['tx']['block'], transaction['tx']['block_height']))

        elif event['type'] == "block":
            # process Block event
            print('Received block hash {}'.format(event['payload']['hash']))

        elif event['type'] == "delegation":
            # process Delegation event
            print('Received {} delegations'.format(len(event['payload'])))
            # loop through the payload, payload is an array of objects with fields: "tx" (an object) and "delegations" (an array)
            for transaction in event['payload']:
                for delegation in transaction['delegations']:
                    print('Delegation from an address {} included in tx {}'.format(
                        delegation['address'], transaction['tx']['hash'])
                    )

        elif event['type'] == "epoch":
            # process Epoch event
            print('Epoch switch from {} to {}'.format(
                event['payload']['previous_epoch']['epoch'], event['payload']['current_epoch']['epoch']))

        else:
            # Unexpected event type
            print('Unexpected event type {}'.format(event['type']))

        return 'Webhook received', 200
    else:
        return 'POST Method not supported', 405

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=6666)

I run the script on my own server. My server has static as same as set in Endpoint URL

But when addr1xxx received ADA, the script was not trigger. I do not know where I am wrong.
I am new to webhook. Your help would help me a lot.Thanks

If it works on the public side, it probably a problem with your script. When you go to the Blockfrost dashboard and click on your webhook, what do you see in Failed requests?

The script is copied from here ( https://blockfrost.dev/docs/start-building/webhooks/using-webhooks.) with no change except the "SECRET-WEBHOOK-AUTH-TOKEN".
In "Failed request" of the dashboard, It says "Timeout awaiting 'request' for 5000ms". I think it could not reach my public website. But I dont know how to set it.

Yeah, it appears your website is not public. Firewall? Not listening on correct interface? Can you reach it from outside of your server?

yes. My site has public IP and domain. I can access it through Internet through port 80.

What do you mean on different port? If you go to https://portchecker.co/, put in the same IP and port you have put in your webhook, is it open?

Should I config URL endpoint in the dashboard is http://xxxxx:6060/webhook or just http://xxxxx:6060. I actually do not fully understand the script.

Definitely /webhook, as it says in the comment Define endpoint /webhook that accepts POST requests.

Thanks. One more question. Should I set the endpoint by the domain or IP address (of my server), or either of them is fine?

Ether is fine, it just needs to resolve correctly.

Thanks for quick guide. I will check the port and report later.

It works. Thanks for your support

I’m voting to close this question because the problem has been on end-user's network configuration and not related to Blockfrost.


text:
Verify Tx Signature
Say I created a multi-sig transaction and I am now gathering signatures using the Cardano-multiplatform-library.
How can I check that the signature is correct for my transaction body, and the signers pub-key ?

Found it.
In case you find your self coming here to find the answer, you can create an instance of TransactionWitnessSet, using the witness you got from the wallet api.
const witness  =  C.TransactionWitnessSet.from_bytes(hexToBytes(signature))

You can then derive the publicKey of the signer, and use the publicKey method verify() to verify against your transaction.
Const validSignature =   witness.vkeys().get(0).vkey().public_key().verify(tx, witness.vkeys().get(0).signature()))