spacebudz / lucid

Lucid is a library, which allows you to create Cardano transactions and off-chain code for your Plutus contracts in JavaScript, Deno and Node.js.
https://lucid.spacebudz.io
MIT License
341 stars 142 forks source link

Unclear mapping of data structures between lucid and aiken #224

Open ThomasHawel opened 1 year ago

ThomasHawel commented 1 year ago

hi!

I am struggling for a while now finding the proper off chain implementations of a given smart contract. In my implementation I have an Value and Dict<Int, Int> type in the aiken smart contract:

type MyDatum {
    sales: Dict<Int, Int>,
    asset: Value
}

I tried multiple options, e.g. Data.Map(...) but always got some deserialising error.

Uncaught (in promise) Redeemer (Spend, 1): Failed to deserialise PlutusData using UnConstrData:
Con(
    Data(
        Map(
            Def(
                [
                    (
                        BigInt(
                            Int(
                                Int(
                                    Int {
                                        neg: false,
                                        val: 10,
                                    },
                                ),
                            ),
                        ),
                        BigInt(
                            Int(
                                Int(
                                    Int {
                                        neg: false,
                                        val: 9,
                                    },
                                ),
                            ),
                        ),
                    ),
                ],
            ),
        ),
    ),
)

ExBudget {
    mem: 710,
    cpu: 1269487,
}

So in general, how can I find out what data types I should use in lucid, given some on chain types? Did I miss something in the docs? Specifically, how do I represent and encode a Dict and Value aiken types in lucid? Thanks a lot!

joacohoyos commented 1 year ago

Seems like a little old thread so I guess you already fixed it. But leaving this for anyone else with doubts.

Dict will be mapped to a Map in plutus data, so when mapping to lucid you should use a Map. Value is just a dict with the following shape Dict<PolicyId, Dict<AssetName, Int>> so we should also use a JS Map.

I haven't tested but If I'm not wrong your jS code should look something like this.

const sales = new Map<bigint, bigint>();
const value = new Map<string, Map<string, bigint>>();
const assetMap = new Map<string, bigint>(); // This would be the map that goes inside the value map

const datum = new Constr(0, [
  sales,
  value
])