GithubHelp home page GithubHelp logo

spacebudz / lucid Goto Github PK

View Code? Open in Web Editor NEW
334.0 334.0 132.0 94.64 MB

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.

Home Page: https://lucid.spacebudz.io

License: MIT License

TypeScript 17.85% Rust 82.15%
cardano deno typescript

lucid's Introduction

SpaceBudz

SpaceBudz is an NFT collection built on Cardano, featuring 10,000 little astronauts. Leveraging Cardano's multi-asset ledger, each SpaceBudz NFT is uniquely identified and traceable on the blockchain. Moreover, the project utilizes Plutus validators to create a secure and efficient marketplace for buyers and sellers to exchange SpaceBudz NFTs. Our official website: spacebudz.io

Validity

To make sure you have a real SpaceBud the policy id must match the following: 4523c5e21d409b81c95b45b0aea275b8ea1406e6cafea5583b9f8a5f

You can find the contract based policy in the Wormhole repository.

The contract address for the official SpaceBudz marketplace: addr1w944m8a98j3gk5mm0as7lqep763t5csdlpzvua5a92h7t8g9dc2c9

Metadata

We follow CIP-0068, the Datum NFT metadata standard on Cardano, which was co-created by SpaceBudz.

Images are stored on IPFS and you find the image link as well as the SHA-256 hash to the image inside the metadata of the SpaceBud.

Marketplace

The SpaceBudz marketplace is built on top of the Nebula protocol.

Community tools

Here you can find helpful and useful tools created by the community.

You have created something for SpaceBudz and it's not in the list? Make a PR!

Add your tool to the registry under ./src/data/toolsRegistry.json with the following format:

  {
    name: string,
    description: string (max 70 characters),
    image: string (relative path to image),
    url: string (e.g. https://spacebudz.io)
  }

The image property contains the relative path to the image: ../image/toolsRegistry/{image}. Place the actual image under ./src/images/toolsRegistry/. The image should be in landscape mode (e.g. 600px width, 400px height). You could use the other tools in the registry as template in case something is unclear.

lucid's People

Contributors

alessandrokonrad avatar caike avatar chrism-paella avatar cjkoepke avatar danielfarrelly avatar ggalansmithee avatar itsmestale avatar leo42 avatar martinschere avatar riley-kilgore avatar sailoshi avatar scriptalchemist avatar sourabhxyz avatar thaddeusdiamond avatar totallynotchase avatar ysfdev avatar zachyking avatar zing-rsa avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

lucid's Issues

Appears to be Incompatible with Plutarch generated CBOR

If I use https://github.com/Liqwid-Labs/agora/tree/staging/agora/Agora to obtain CBOR hex for scripts relating to Agora, I have found that all transactions that require validation with these scripts will throw
"ScriptFailures": { "mint:0": [ { "validatorFailed": { "error": "DeserialiseFailure 0 \"expected bytes\"", "traces": [] } } ] }

I believe this to be an issue related more generally to Plutarch (but haven't verified), it would appear based on conversations with other engineers, that the same process to procure CBOR for these scripts, the scripts are working fine with an alternative to Lucid that we would prefer to avoid due to overhead (https://github.com/Plutonomicon/cardano-transaction-lib), I am almost sure that this is a discrepancy in deserialization between the libraries used (custom CSL from mlabs vs custom CML in Lucid).

I'm not even really sure where to start looking, but will be spending my day trying to figure this out. Any help would be appreciated.

error 'BigInt' is not defined no-undef

I try to define mintAssets as

// ...
const token = {
    policyId: lucid.utils.validatorToScriptHash(mintingScript),
    assetName: 'HelloAxu'
}

const mintAssets = {
        [token.policyId + token.assetName] : BigInt(1)
    }
console.log(mintAssets);

but I got this error when running npm run start

error  'BigInt' is not defined  no-undef

Anyone know how to to fix this, thank you so much!

Usage with nodejs on a server

This library supports node environments, however, the complete method calls wallet methods that are not available on a server.

I think a better alternative would be to only depend on wallet functionality in specific methods like .sign() and have the ability to get the serialized transaction. That way, if you're building an API, you can still use this library and have the user send their UTxOs and collateral, and you would have the user sign the resulting CBOR.

How to adding `--invalid-before` option when buiding tnx for a vesting script?

From this vesting script.
This line is the on chain part to validate whether deadline is reached.

    deadlineReached = contains (from $ deadline p) $ txInfoValidRange info

This is the offchain part using lucid

export const redeemUtxo = async (plutusScript, number) => {
    const vestingScript = {
       type: 'PlutusV1',
       script: plutusScript,
    };

    const vestingAddress = lucid.utils.validatorToAddress(
              vestingScript
        );

      const utxo = (await lucid.utxosAt(vestingAddress)).slice(-1)[0];

      const tx = await lucid
        .newTx()
        .collectFrom([utxo], Redeemer(number))
        .attachSpendingValidator(vestingScript)
        .addSigner(benificialAddress)
        .complete()

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

      const txHash = await signedTx.submit();

      return txHash;
};

However, its always failed when building tnx to redeem the vesting script, even i set the deadline to a specified time which less than the redeem time.

localhost/:1 Uncaught (in promise) {
  "ScriptFailures": {
    "spend:0": [
      {
        "validatorFailed": {
          "error": "An error has occurred:  User error:\nThe machine terminated because of an error, either from a built-in function or from an explicit use of 'error'.",
          "traces": [
            "deadline not reached",
            "PT5"
          ]
        }
      }
    ]
  }
}

I saw that there is work around for this case which is adding --invalid-before 48866954 in cardano-cli transaction build
https://github.com/input-output-hk/plutus-pioneer-program/blob/main/code/week03/testnet/grab.sh#L11
can we do the same with lucid when building tnx ?

Thank you!

Question about leveraging `selectWalletFromPrivateKey`

I am trying to use Lucid within a project that does not leverage the browser -- as such I need to select a wallet from a private key instead of from a wallet provider. I continue to get the same error after repeated attempts to create a valid PrivateKey. I was wondering if someone, maybe @alessandrokonrad, would be able to provide some guidance around where I am going wrong?

  1. Generate a new key-pair with cardano-cli address key-gen.
  2. Run echo <PRIVATE_KEY_STRING> | bech32 addr_sk > skeybech
  3. Use the value now present in the file skeybech to call selectWalletFromPrivateKey(skeybech)

Result: (node:75356) UnhandledPromiseRejectionWarning: Invalid secret key

Thank you :)

npm commands showing errors on windows 10 command line

I followed steps on how to install and run build, run test, etc on windows 10 command line but got these errors:

C:\Users\besib>npm run build
npm WARN config global --global, --local are deprecated. Use --location=global instead.
npm ERR! Missing script: "build"
npm ERR!
npm ERR! To see a list of scripts, run:
npm ERR! npm run

npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\besib\AppData\Local\npm-cache_logs\2022-07-09T21_41_56_808Z-debug-0.log

C:\Users\besib>npm test
npm WARN config global --global, --local are deprecated. Use --location=global instead.
npm ERR! Missing script: "test"
npm ERR!
npm ERR! To see a list of scripts, run:
npm ERR! npm run

npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\besib\AppData\Local\npm-cache_logs\2022-07-09T21_42_34_864Z-debug-0.log

C:\Users\besib>npm run
npm WARN config global --global, --local are deprecated. Use --location=global instead.

C:\Users\besib>npm run build
npm WARN config global --global, --local are deprecated. Use --location=global instead.
npm ERR! Missing script: "build"
npm ERR!
npm ERR! To see a list of scripts, run:
npm ERR! npm run

npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\besib\AppData\Local\npm-cache_logs\2022-07-09T21_43_07_528Z-debug-0.log

C:\Users\besib>code .
'code' is not recognized as an internal or external command,
operable program or batch file.

C:\Users\besib>cd lucid

C:\Users\besib\lucid>npm build
npm WARN config global --global, --local are deprecated. Use --location=global instead.
Unknown command: "build"

Did you mean this?
npm run build # run the "build" package script

To see a list of supported npm commands, run:
npm help

C:\Users\besib\lucid>npm run build
npm WARN config global --global, --local are deprecated. Use --location=global instead.

[email protected] build
tsdx build --format esm

'tsdx' is not recognized as an internal or external command,
operable program or batch file.

C:\Users\besib\lucid>npm run test
npm WARN config global --global, --local are deprecated. Use --location=global instead.

[email protected] test
node --no-warnings --experimental-vm-modules node_modules/jest/bin/jest.js

node:internal/modules/cjs/loader:936
throw err;
^

Error: Cannot find module 'C:\Users\besib\lucid\node_modules\jest\bin\jest.js'
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
at Function.Module._load (node:internal/modules/cjs/loader:778:27)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
at node:internal/main/run_main_module:17:47 {
code: 'MODULE_NOT_FOUND',
requireStack: []
}

C:\Users\besib\lucid>npm run doc
npm WARN config global --global, --local are deprecated. Use --location=global instead.
npm ERR! Missing script: "doc"
npm ERR!
npm ERR! Did you mean one of these?
npm ERR! npm docs # Open documentation for a package in a web browser
npm ERR! npm run docs # run the "docs" package script
npm ERR!
npm ERR! To see a list of scripts, run:
npm ERR! npm run

npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\besib\AppData\Local\npm-cache_logs\2022-07-09T21_45_41_321Z-debug-0.log

C:\Users\besib\lucid>npm run docs
npm WARN config global --global, --local are deprecated. Use --location=global instead.

[email protected] docs
typedoc --entryPoints ./custom_modules/cardano-multiplatform-lib-browser/cardano_multiplatform_lib.d.ts --entryPoints ./custom_modules/cardano-multiplatform-lib-nodejs/cardano_multiplatform_lib.d.ts --entryPoints src --entryPointStrategy expand --exclude '/core/' --exclude '/examples/' --plugin ./node_modules/typedoc-theme-category/dist/index.js --theme category

'typedoc' is not recognized as an internal or external command,
operable program or batch file.

C:\Users\besib\lucid>cd C:\Users\besib\lucid\src\examples\sample-ada-transfer

C:\Users\besib\lucid\src\examples\sample-ada-transfer>npm start
npm WARN config global --global, --local are deprecated. Use --location=global instead.

[email protected] start
npm run build && ./node_modules/http-server/bin/http-server ./dist

npm WARN config global --global, --local are deprecated. Use --location=global instead.

[email protected] build
./node_modules/webpack/bin/webpack.js

'.' is not recognized as an internal or external command,
operable program or batch file.

C:\Users\besib\lucid\src\examples\sample-ada-transfer>npm run build
npm WARN config global --global, --local are deprecated. Use --location=global instead.

[email protected] build
./node_modules/webpack/bin/webpack.js

'.' is not recognized as an internal or external command,
operable program or batch file.

C:\Users\besib\lucid\src\examples\sample-ada-transfer>

How to use with mnemonics?

First of all thanks for this library! CSL's syntax, documentation, and api's could've been more better. Anyway, I've tried creating bech32 private keys form 24-word mnemonics (generated from Nami / Eternl) but i'm not able to make them work here. Would love an example!

Lucid type error when trying to run simple transaction code

Hello!

I am trying to write a simple code that sends ADA, modeling it similar to your simple transaction code. Last week, I had issues running my code in Vasil, but it seemed this error was resolved. Now, I am getting an error when trying to compile my ts code. However, the error seems to be originating from the lucid code itself. Is this an error needing to be addressed here?

node_modules/lucid-cardano/types/src/types/types.d.ts:208:5 - error TS2411: Property 'version' of type 'number' is not assignable to 'string' index type '{ [assetName: string]: NFTMetadataDetails; }'.

208     version?: number;
        ~~~~~~~


Found 1 error in node_modules/lucid-cardano/types/src/types/types.d.ts:208```

Problem submitting tx

I seem to be experiencing this issue

{ "code": 2, "info": "Wallet could not send the tx.", "message": "\"transaction submit error ShelleyTxValidationError ShelleyBasedEraBabbage (ApplyTxError [UtxowFailure (FromAlonzoUtxowFail (PPViewHashesDontMatch (SJust (SafeHash \\\"f9e25ae86d80df1ac9713bd0ccc9d8e7fbe3b7c930fa2220bce514553f5993f5\\\")) (SJust (SafeHash \\\"4c8d7c07c919729a865b1f2e63a79603d4a68a43e28f079ad7e9e87bebc25075\\\"))))])\"" }

with the following code

const transaction = await lucid .newTx() .payToContract(scriptAddress , Lucid.Data.empty() , { lovelace: BigInt(Number(3000000)), 'fda1b6b487bee2e7f64ecf24d24b1224342484c0195ee1b7b943db50434c415353494342414259424c55453031': BigInt(Number(4)) }) .collectFrom([utxo], serializedRedeemer) .attachSpendingValidator(radSaleScript) .addSigner(await lucid.wallet.address()) .payToAddress('addr_test1vrh0kkuahtz28qpfdhsx2hm2eekf06des8h03xnm757u65sd6egwy' , { lovelace: lovelaceAmount }) .payToAddress(await lucid.wallet.address(), { lovelace: minLovelaceAmount , 'fda1b6b487bee2e7f64ecf24d24b1224342484c0195ee1b7b943db50434c415353494342414259424c55453031': BigInt(Number(1)) }) .complete()

I'm using lucid-cardano version 0.3.5. I first experienced this using the cli as a start endpoint and lucid as a buy endpoint. I created a lucid start endpoint to rule out a protocol parameters mismatch but still encountered the error

I seem to have a similar problem to this

#14

Actually I'm also experiencing that error with the following transactions

const redeemer = new Lucid.Construct(1, []) const serializedRedeemer = Lucid.Data.to(redeemer) const datumHash = '923918e403bf43c34b4ef6b48eb2ee04babed17320d8d1b9ff9ad086e86f44ec' const utxo = (await lucid.utxosAt(scriptAddress)).filter(utxo => utxo.datumHash === datumHash && utxo.assets[currencySymbol + assetNameHex] !== undefined) console.log(utxo) const transaction = await lucid .newTx() .payToAddress('addr_test1qqfaj02yn24e38q8q4sea086yqem4tyt4n6seaxjaa4cnpzydjptew90z2m64jvqwxhzlke5kgkw82w3v52tfuwu3zssn2770q' , { lovelace: BigInt(Number(3000000)) , [currencySymbol + assetNameHex]: BigInt(Number(2)) }) .collectFrom(utxo, serializedRedeemer) .attachSpendingValidator(radSaleScript) .addSigner(await lucid.wallet.address()) .complete() const signedTx = await transaction .sign() .complete() const transactionHash = await signedTx .submit()

Also getting this error with the matching numbers example?

Can't dynamically build transactions

Building a transaction in a single step works ✅

const tx = await Tx.new()
      .payToAddress(
        "addr1qypx6d4y85wdnxmklaj9wwz7l5mk5nph9fxvsys53d4qk39p83d9g58ft54dyrp5gv05zhk4j8g9yneft4qtm7yd4zfs6c7rj5",
        { lovelace: 5000000n }
      )
      .complete();

Building a transaction over multiple lines does not ❌

const tx = await Tx.new();
tx.payToAddress(
       "addr1qypx6d4y85wdnxmklaj9wwz7l5mk5nph9fxvsys53d4qk39p83d9g58ft54dyrp5gv05zhk4j8g9yneft4qtm7yd4zfs6c7rj5",
        { lovelace: 5000000n }
      );
tx.complete();

I don't see how we can dynamically construct transactions if the we have to do everything in a single code block :/

Import issues inside AWS Lambda node.js 16

I have tried adding {"type": "module"} to the package.json and that gets me the error:
"[SyntaxError: Cannot use import statement outside a module]".

I have tried using full file extension " ./lucid-cardano.js".

I have also tried using the older require('') syntax, this nets me another, different error:
"Error: Cannot find module 'lucid-cardano'\nRequire stack:\n- /var/task/index.js\n- /var/runtime/index.mjs","

This also occurs with bip39 inside AWS Lambda, I am not sure what is causing this. Blockfrost API works just fine with require('') syntax in other parts of my project.

"BabbageOutputTooSmallUtxo" error submitting testnet native asset transactions

This was working pre-Vasil so I'm presuming it's related to the network fork; Attempting to build a simple tx containing an NFT and allowing Lucid to calculate the minimum required amount results in txs which error out in the wallet. Tested with Nami, Flint and Eternl with similar "OutputTooSmallUtxo" errors.

Can't resolve 'wbg' in vasil version

I noticed this error when i removed the 0.3.5 version and install 0.5.0 vasil version

Module not found: Error: Can't resolve 'wbg' in 'node_modules/lucid-cardano/esm/src/core/wasm_modules/cardano-multiplatform-lib-web'

Insufficient input in transaction when using selectWalletFromSeed

Hey, I am trying to use this new function of selectWalletFromSeed so I can generate addresses using seed phrases. I replaced my previous address code with the new one in code that I can confirm works (except it still sends the wrong # of ADA, supposedly because I am running Vasil code pre-fork).

Trouble is, with using the selectWalletFromSeed, I am unable to execute the code properly because I get the "Insufficient input in transaction" error. I am telling the code to only send 1 ADA (1000000 lovelace). When using lucid addresses, it'll send around 9 ADA. However, this new seed phrase wallet has around 44 ADA. So, I am not sure why I am getting this error. Any thoughts?

Lucid sending incorrect # of ADA

Hey,

I have gotten the code to run via javascript with no errors. However, no matter what I input as lovelace amount, the transaction always sends exactly 7758450 lovelace. The number is different if I include tokens in the transaction though. Here is a snipped of my code. Are there any glaring errors here? I thought it looked similar to your simple transaction example, but unsure why the amount sending is always wrong.

lucid.selectWalletFromPrivateKey(serverKey);
lucid.wallet.address = async () => {
    return "addr1"; //user adress
};
let address = await lucid.wallet.address();
console.log(address);
let tx = await lucid.newTx().payToAddress("addr2", { lovelace: BigInt(100000) }).complete(); //pool addres
let txSigned = await tx.sign().complete();
let hash = await txSigned.submit();
console.log('txHash:', hash);```

Insufficient input in transaction

I am using a wallet on the testnet with 220 tADA on 2 UTxOs. This is a single address wallet. I am trying to send a 50 tADA transaction to another wallet using lucid. I am building the entropy from a mnemonic.

This is what I have for building the tx:

const lucid = await Lucid.new(
            new Blockfrost('https://cardano-testnet.blockfrost.io/api/v0', 'testnet63vSq.....odkACx5'),
            'Testnet'
);
const rootKey = CardanoWasm.Bip32PrivateKey.from_bip39_entropy(
            Buffer.from(entropy, 'hex'),
            Buffer.from(''),
);
        
const privateKey = rootKey.to_raw_key().to_bech32();

ucid.selectWalletFromPrivateKey(privateKey);
        
const lovelaces = parseInt(requestedAmount, 10) * 1000000.0;
        
const tx = await lucid.newTx()
            .payToAddress(receiveAddress, {lovelace: lovelaces})
            .complete();
            
const signedTx = await tx.sign().complete();

const txHash = await signedTx.submit();

console.log(txHash);

I get the error:
Insufficient input in transaction

I dont understand why there is insufficient input if I have more than 50 tADA in the wallet? Does this not automatically select UTxOs for input?

Avoid global state

Could you provide stateless API. Current design use global state which should be avoided in API and in this case for example makes it hard to integrate with multiple wallets at the same time. My proposition is to provide non static API like that:

const lucid = Lucid.initialize(
     new Blockfrost(new Blockfrost('https://cardano-testnet.blockfrost.io/api/v0', '<projectId>'),
     'Testnet'
).selectWallet(api); // here it would be nice if I could provide instance of the API instead of name

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

How to import in browser properly?

Steps I have done so far:

  1. Convert wasm to asm.js and then using browserify to allow it as standard js
  2. importing the module in index.html succesfully!
  3. Lucid is not in the cardano_multiplatform_lib_bg.js module :/

Where do I find the Lucid class?

Unable to sign TX

Hi,

First of all, thank you very much for creating this library.
I've been trying to set this up in a Vue project but I'm getting an error when trying to sign the tx.

import {Blockfrost, Lucid} from "lucid-cardano";

const lucid = await Lucid.new(
    new Blockfrost('https://cardano-testnet.blockfrost.io/api/v0', 'testnetnuzYcuNW9XxZ......4ynWX'),
    'Testnet'
);

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

const tx = await lucid.newTx()
.payToAddress('addr_test1qqm5k4qh02favw48dutgrwd5czqpddp4tn5nx7u2t5l0wu7027lyuwxkqk7ruc93hfknt6jsgdp8eh4fw3zly3fqwwcq3cwryn', {'lovelace': 500n} )
    .complete();
const signedTx = await tx.sign().complete();
const txHash = await signedTx.submit();

The error I get:
Uncaught (in promise) {code: -1, info: 'Inputs do not conform to this spec or are otherwise invalid.'}

The wallet has enough tADA in it. Nami is in testnet mode.
When trying with Eternl it opens the sign window but there's no information about the tx and I also can't sign it.

I've tried to check if it can 'see' the wallet, when I enter invalid address it will tell me. If I exceed the amount of available tADA it will tell me. So it has access to the UTXO's

The solution is probably very simple, but after 4 hours, I'm unable to determine the cause.
Any help would be greatly appreciated!

Do we need that top level await?

In core.ts:

export const C =
  typeof window !== 'undefined'
    ? await import(
        '../../custom_modules/cardano-multiplatform-lib-browser/cardano_multiplatform_lib'
      )
    : await import(
        '../../custom_modules/cardano-multiplatform-lib-nodejs/cardano_multiplatform_lib'
      );

This is acknowledged in the README, but is it even necessary? Declaring "type":"module" in the package.json and adding extra flags can break other packages. Can't we just initialize the serialization lib when we call Lucid.initialize()?

Is it possible to burn tokens?

let mintAssets = {
 [token.policyId + token.assetName]: BigInt(-1)
}

const tx = await Tx.new()
   .attachMintingPolicy({
    type: "Native",
    script: Buffer.from(policy.script.to_bytes()).toString('hex')
   })
  .mintAssets(mintAssets)
  .complete()

This doesn't burn the token and submit fails with value not conserved. Changing BigInt(-1) to BigInt(1) makes asset minted and submits successfuly. Are there any extra steps for burning?

gitpage docs failing

I wanted to note that the docs aren't building. This is the local error I receive. There is a 404 on gitpages

`npm run docs

[email protected] docs
typedoc --entryPoints ./custom_modules/cardano-multiplatform-lib-browser/cardano_multiplatform_lib.d.ts --entryPoints ./custom_modules/cardano-multiplatform-lib-nodejs/cardano_multiplatform_lib.d.ts --entryPoints src --entryPointStrategy expand --exclude '/core/' --exclude '/examples/' --plugin ./node_modules/typedoc-theme-category/dist/index.js --theme category

Info: Loaded plugin typedoc-theme-category/dist/index.js
Warning: NFTFile, defined at src/types/types.ts:193, is referenced by src/types/types.NFTMetadataDetails.__type.files but not included in the documentation.
Warning:
Unsupported highlight language "hs" will not be highlighted. Run typedoc --help for a list of supported languages.
target code block :
data Data =
Constr Integer [Data]
| Map [(Data, Data)]
| List [Data]
| I Integer
| B BS.ByteString
deriving stock (Show, Eq, Ord, Generic)
deriving anyclass (NFData)
source files :undefined
output file :
undefined
Info: Documentation generated at ./docs
node:internal/process/promises:279
triggerUncaughtException(err, true /* fromPromise */);
^

[Error: EACCES: permission denied, mkdir '/assets'] {
errno: -13,
code: 'EACCES',
syscall: 'mkdir',
path: '/assets'
}`

Creating a js-friendly version of PlutusData

We are currently needing to use the serialization library to build the PlutusData for datums and redeemers, and I think there is an enhancement to be made.

We could extend the PlutusData class and add a fromJS method that accepts a javascript object and serializes it.

Minimal browser implementation

Hey there, great project, Sebastien pointed me towards this... I am looking into solutions for One-Click-Payments for the browser.

Can anyone post a minimal Webpack setup to get this up and running in the browser? I dont get beyond

WARNING in ./node_modules/lucid-cardano/custom_modules/cardano-multiplatform-lib-browser/cardano_multiplatform_lib_bg.js 16704:14-53

Critical dependency: the request of a dependency is an expression

This is on Webpack 5.72.0 with the experimental settings posted.

Also I can't figure out a way to get Buffer working in the browser, do you use browserify?

Multiple Addresses

I don't know if it went unnoticed by me, but does the package transact to multiple addresses? If not, do you have plans to have? Or, can we send a PR with this function? Thanks!

Package doesn't work for me with NextJS

I tried to use this package with NextJS, unfortunately, unsuccessfuly.

  • Create next app
  • NPM install lucid-cardano
  • Create component with a button using Lucid
  • dynamically load on a page
  • build -> error with topLevelAwait
  • add webpack conf experiments: { asyncWebAssembly: true, topLevelAwait: true }
  • build -> error with node-fetch dependencies

I managed to create a custom build that works with NextJS, however I didn't manage to create version suitable for all out of it.
I did two things:

  1. I removed node-fetch import, NextJS has fetch out of the box,
  2. I installed 'buffer' and added import { Buffer } from 'buffer' where it's used

I would really prefer to not use custom version of the lib, so if there is a way to fix it on my side, or if I can help for example with testing for this, please let me know.

Cannot spend from script and pay back to script in the same transaction.

When trying to spend a UTxO from a contract and spend a subset of that UTxO back to the contract the following error occurs:

{"code":2,"info":"Wallet could not send the tx.","message":"\"transaction submit error ShelleyTxValidationError ShelleyBasedEraAlonzo (ApplyTxError [UtxowFailure (PPViewHashesDontMatch (SJust (SafeHash \\\"8418cd2dd198020bc9569dc564b3459bb820340b6ea04e2090360af4c5e61073\\\")) (SJust (SafeHash \\\"e0c20279f42f99018f0d5727e1336654f8f5209e0d9cb5699f9e0b7b1309afb9\\\")))])\""}

Steps to reproduce:

1: Construct address for always successful validator.

`const exampleScript: SpendingValidator = { // This always evaluates true.
type: 'Plutus',
script:
'4e4d01000033222220051200120011',
}

const exampleAddress: Address = C.EnterpriseAddress.new(
0, // testnet
C.StakeCredential.from_scripthash(
C.PlutusScript.from_bytes(
Buffer.from(exampleScript.script, 'hex'),
).hash(C.ScriptHashNamespace.PlutusV1),
),
)
.to_address()
.to_bech32();`

2: Fund the validator script.

`let tx: TxComplete
tx = await Tx.new()
.payToContract(exampleAddress, ANY_DATUM(), { lovelace: BigInt(5000000) })
.complete();

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

await signedTx.submit();
`

3: Spend from the validator, but send 2 ADA back to the contract.

`const utxo = (await Lucid.utxosAt(exampleAddress))[0];

let tx: TxComplete
tx = await Tx.new()
.payToContract(exampleAddress, ANY_DATUM(), { lovelace: BigInt(2000000) }) // This breaks.
.collectFrom([utxo], ANY_REDEEMER())
.attachSpendingValidator(exampleScript)
.complete();

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

await signedTx.submit();
`

Build issue in a node/typescript project

As instructed by the README, I added the following to the top level of my package.json:

"type" : "module",

However I'm getting an error like this:

yarn run v1.22.18
$ ts-node src/index.ts
TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /REDACTED/src/index.ts
    at new NodeError (node:internal/errors:372:5)
    at Object.getFileProtocolModuleFormat [as file:] (node:internal/modules/esm/get_format:76:11)
    at defaultGetFormat (node:internal/modules/esm/get_format:118:38)
    at defaultLoad (node:internal/modules/esm/load:21:20)
    at ESMLoader.load (node:internal/modules/esm/loader:407:26)
    at ESMLoader.moduleProvider (node:internal/modules/esm/loader:326:22)
    at new ModuleJob (node:internal/modules/esm/module_job:66:26)
    at ESMLoader.#createModuleJob (node:internal/modules/esm/loader:345:17)
    at ESMLoader.getModuleJob (node:internal/modules/esm/loader:304:34)
    at async Promise.all (index 0) {
  code: 'ERR_UNKNOWN_FILE_EXTENSION'
}
error Command failed with exit code 1.

The command I run:

ts-node src/index.ts

I've also tried node instead of ts-node with various parameters like --experimental-specifier-resolution, no idea what I'm doing just trying different things I find, without success.

Being a TS noob, I've search on the internet about solutions, e.g. setting different combinations of the following in tsconfig.json, but none has worked for me.

    "target": "esnext",
    "module": "commonjs",
    "moduleResolution": "node"

Can i please get some assistance or direction here? Thanks.

EDIT: Some extra info

$ node --version
v16.15.0

yarn --version
1.22.18

macOS Monterey 12.3.1

Better ES module support

ES modules require to add the full path including the extension when making imports/exports. E.g. import ./foo does not work, import ./foo.js. works.

TypeScript can't unfortunately resolve .ts extensions, but you rather have to use .js, since TypeScript is transpiled to JavaScript. However this is quite ugly and kinda confusing.

I looked for solutions which let you write TypeScript the way you used to, but add the .js extension after building. What I found so far is: https://github.com/antongolub/tsc-esm-fix. I just did not get it working yet.

A big advantage of using file extensions is that we don't even need to specifiy the flag --es-module-specifier-resolution=node when working in a node.js environment. The module just works out of the box.

Add full example for browser integration usage

Hello,

I would like to add a contribution to help provide a simple end-to-end integration example to help new users quickly and easily get to test the library in their local environment without having to research additional setup requirements.

I have created a sample-ada-transfer to demonstrate a simple sample integration usage of the library on the client side.

If you think it will be useful, I can create a PR to include the sample app in src/examples

BTW, thank you for working on this great library!

Thanks

Burning tokens using Lucid txs

Is it possible to create a token burn tx using Lucid? The current payToAddress implementation doesn't seem to accept negative quantities in asset amounts.

Fourty two example fix

Redeeming example currently not working because the utxo array's last index needs to be retrieved first followed by the first index
await lucid.utxosAt(matchingNumberAddress))[0] -> await lucid.utxosAt(matchingNumberAddress)).slice(-1)[0] or pop()

Invalid normal secret key

const sKey = C.PrivateKey.from_normal_bytes(Buffer.from(sKeyStr, 'hex'))
where sKeyStr is the cborHex from a Private Key created with cardano-cli
cardano-cli address key-gen --verification-key-file test.vkey --signing-key-file test.skey --normal-key

This line of code always returns invalid normal secret key.
Did anyone run into the same problem and has a solution? Am I passing a wrong format to .from_normal_bytes?

Error when lucid sets protocol params

Has anyone had a similar problem? The server worked for most of the day, but after the last restart, I get the error on the picture. No code changes on my side.
image

How to get the `policyId` from `policyScript` file ?

Hi every one,

Via cardano-cli we can get the policyId from policyScript file

cardano-cli transaction policyid \
    --script-file sample.plutus.script

Is there any way to get policyID if we use lucid ?

Thank you!

How do we construct a TX output with --tx-out-datum-embed-file in Lucid?

I have a got a TX with --tx-out-datum-embed-file?

is payToAddressWithDatum the right function to call.

The full TX in Cardano-cli is

cardano-cli transaction build \
  --alonzo-era \
  $BLOCKCHAIN \
  --tx-in $utxoScript \
  --tx-in-script-file $nftValidatorFile \
  --tx-in-datum-file $datumFile \
  --tx-in-redeemer-file $redeemerFile \
  --required-signer $signingKey \
  --tx-in-collateral --address $spenderAddress $BLOCKCHAIN ) \
  --tx-out "$scriptHash + $output1 + $amount lovelace" \
  --tx-out-datum-hash $outDatumHash \
  --tx-out-datum-embed-file $outDatumFile \
  --tx-out "$spenderAddress + 3000000 lovelace $extraOutput" \
  --change-address $spenderAddress \
  --protocol-params-file $baseDir/$BLOCKCHAIN_PREFIX/protocol-parameters.json \
  --invalid-before $startSlot \
  --invalid-hereafter $nextTenSlots \
  --out-file $bodyFile

what's the right way to chain this TX in lucid , I am sure of others except --tx-out-datum-embed-file

Thanks @alessandrokonrad

Coin Selection

I've been thinking about coin selection recently. I looked at other coin selection algorithms and specificially CIP-2. None of these take multi assets into consideration and some other contraints like execution unit costs (having a lot of unnecessary assets in the inputs could easily exceed plutus script cost limits).

I took some of the ideas of Random Improve, because I think it's a good algorithm, but it simply needs to be adjusted for multiassets. Also the core principles are:

  • keep it simple
  • universally applicable to all kind of transaction types
  • low complexity and fast calculation
  • keep the amount of assets in inputs as small as possible
  • good utxo distribution over time

1. Random sampling:

a) Loop through all assets and ada in the outputs and randomly select inputs (inputs that contain the asset) until at least the target amount is reached.

b) If the target amount for the next asset is already reached through the selection of previous assets, don't look further (this helps with not overadding too many inputs).

2. Improvement phase

a) Our goal is to find better inputs. We consider something as better if:

  • we get closer to an ideal ADA amount (twice the target amount) => less utxo fractions overtime and better for covering fees and change outputs min ada requirements

  • we get closer to an ideal amount for all assets (here also twice the target amount for each asset). We model this through vectors, where the dimension represents the amount of assets and the coordinate the quantity (e.g. x = [1,1,5], target = [2,4,8]). Then we normalize these vectors and take the euclidean distance. The closer the distance to 0 the better. (We do not want to do this when we interact with plutus scripts, then these weights are simply 0)

  • we have less assets in our inputs (when we interact with plutus scripts we put even more weight on this)

  • we never go below the least required amount for ada and all assets (put a very high weight, so this never happens)

    We can model this through a cost function, where we apply weights to each criteria described above. Basically we try to punish the coin selection and try to find the best input set were it gets least punished:

     cost = 100000 * has_least_required_amount + w_1 * ideal_ada + w_2 * ideal_assets + w_3 * asset_len
    

    w_n ∈ ℤ
    has_least_required_amount ∈ {0,1}
    ideal_ada, ideal_assets, asset_len ∈ [0,1]

b) We have 3 actions we can take to make improvements to our currently selected input set:

  • Replace: We replace a random utxo from our selected input set with a random utxo from the remaining set
  • Append: Append a utxo from the remaining set to the selected input set
  • Remove: Remove a random utxo from the selected input set

c) Loop for n iterations (n = 100 currently) and do:

  • Take an action and compare our previous state s_prev with our new state state s_new. If cost(s_new) < cost(s_prev) we apply s_new as our new input set.
  • In each iteration we try out different actions until one applies and then we go into the next iteration. If no applies we also go into the next iteration.

d) After the improvement iterations we get our final input set.

Deserialization failed in NativeScriptEnum when attempting to attach minting policy to tx

I'm refactoring a minting application built on cardanocli-js, but am stuck with attaching the minting policy to the transaction.

I have a simple sig policy .json file generated by cardano-cli, which I need to pass to tx.attachMintingPolicy(), however cannot seem to correctly format the data required. I've tried much fiddling with the utility functions within Lucid and the cardano-multi-platform-lib with no success.

Attempting to call tx.attachMintingPolicy() results in a deserialization error:

Deserialization failed in NativeScriptEnum because: Invalid cbor: not the right type, expected 'Array' byte received 'Text'.

I'm guessing I'm just missing a conversion somewhere, but can't seem to see it.

minting-policy.json

{
    "type": "all",
    "scripts": [
        {
            "type": "sig",
            "keyHash": "{HEX KEYHASH REMOVED FOR SECURITY}"
        }
    ]
}

node.js code

const scriptString = fs.readFileSync("./policies/test_utility/mint-policy.json")

const scriptHex = Buffer.from(scriptString, "utf-8").toString("hex")

tx = await tx.mintAssets(mintAssets)
    .attachMetadata("721", mintMetadata)
    .attachMintingPolicy({
        type:"Native",
        script: scriptHex
    })
    .addSigner(STAKING_WALLET.paymentAddr)
    .complete()

My understanding is that attachMintingPolicy() drills down to attachScript(), where script.script is expected to be a hex string:

const attachScript = (tx, script) => {
    if (script.type === "Native") {
        return tx.txBuilder.add_native_script(C.NativeScript.from_bytes(fromHex(script.script)));
    }
...

Node.js Usage

I have a current cardano-integrated application based on cardanocli-js (and a local cardano node), which I'd like to refactor to leverage Lucid for utxo input selection, but am having difficulty getting my head around the initial setup steps for a non-browser Node.js environment.

Would it be possible to get some pointers on the equivalent steps to this, but in a desktop environment where I have key files for the wallet generated by cardanocli (wallet.payment.vkey, etc.):

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

Need documentation on how to import Lucid into a simple project

Currently, if a user tries to create a simple new typescript project by doing the following

npx tsc --init
npm install lucid-cardano
npm install
echo import {Lucid} from "lucid-cardano" > index.ts
tsc index.ts

They are faced with a myriad of type errors.

`node_modules/lucid-cardano/dist/lucid/lucid.d.ts:1:18 - error TS2307: Cannot find module 'core/types' or its corresponding type declarations.

1 import Core from 'core/types';
~~~~~~~~~~~~

node_modules/lucid-cardano/dist/lucid/lucid.d.ts:24:23 - error TS2304: Cannot find name 'WalletApi'.

24 selectWallet(api: WalletApi): this;
~~~~~~~~~

node_modules/lucid-cardano/dist/lucid/tx.d.ts:1:18 - error TS2307: Cannot find module 'core/types' or its corresponding type declarations.

1 import Core from 'core/types';
~~~~~~~~~~~~

node_modules/lucid-cardano/dist/lucid/txComplete.d.ts:1:18 - error TS2307: Cannot find module 'core/types' or its corresponding type declarations.

1 import Core from 'core/types';
~~~~~~~~~~~~

node_modules/lucid-cardano/dist/lucid/txSigned.d.ts:1:18 - error TS2307: Cannot find module 'core/types' or its corresponding type declarations.

1 import Core from 'core/types';
~~~~~~~~~~~~

node_modules/lucid-cardano/dist/provider/blockfrost.d.ts:1:18 - error TS2307: Cannot find module 'core/types' or its corresponding type declarations.

1 import Core from 'core/types';
~~~~~~~~~~~~

node_modules/lucid-cardano/dist/types/types.d.ts:1:18 - error TS2307: Cannot find module 'core/types' or its corresponding type declarations.

1 import Core from 'core/types';
~~~~~~~~~~~~

node_modules/lucid-cardano/dist/types/types.d.ts:2:27 - error TS2307: Cannot find module 'utils' or its corresponding type declarations.

2 import { Construct } from 'utils';
~~~~~~~

node_modules/lucid-cardano/dist/types/types.d.ts:10:17 - error TS2583: Cannot find name 'BigInt'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later.

10 keyDeposit: BigInt;
~~~~~~

node_modules/lucid-cardano/dist/types/types.d.ts:11:18 - error TS2583: Cannot find name 'BigInt'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later.

11 poolDeposit: BigInt;
~~~~~~

node_modules/lucid-cardano/dist/types/types.d.ts:14:23 - error TS2583: Cannot find name 'BigInt'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later.

14 coinsPerUtxoWord: BigInt;
~~~~~~

node_modules/lucid-cardano/dist/types/types.d.ts:33:21 - error TS2583: Cannot find name 'BigInt'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later.

33 [unit: string]: BigInt;
~~~~~~

node_modules/lucid-cardano/dist/types/types.d.ts:89:32 - error TS2583: Cannot find name 'BigInt'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later.

89 export declare type Lovelace = BigInt;
~~~~~~

node_modules/lucid-cardano/dist/types/types.d.ts:160:21 - error TS2456: Type alias 'PlutusData' circularly references itself.

160 export declare type PlutusData = string | bigint | PlutusData[] | Map<PlutusData, PlutusData> | Construct;
~~~~~~~~~~

node_modules/lucid-cardano/dist/types/types.d.ts:160:67 - error TS2583: Cannot find name 'Map'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2015' or later.

160 export declare type PlutusData = string | bigint | PlutusData[] | Map<PlutusData, PlutusData> | Construct;
~~~

node_modules/lucid-cardano/dist/utils/utils.d.ts:1:23 - error TS2688: Cannot find type definition file for 'node'.

1 ///
~~~~

node_modules/lucid-cardano/dist/utils/utils.d.ts:2:18 - error TS2307: Cannot find module 'core/types' or its corresponding type declarations.

2 import Core from 'core/types';
~~~~~~~~~~~~

node_modules/lucid-cardano/dist/utils/utils.d.ts:22:48 - error TS2580: Cannot find name 'Buffer'. Do you need to install type definitions for node? Try npm i --save-dev @types/node.

22 export declare const fromHex: (hex: string) => Buffer;
~~~~~~

node_modules/lucid-cardano/dist/utils/utils.d.ts:23:37 - error TS2580: Cannot find name 'Buffer'. Do you need to install type definitions for node? Try npm i --save-dev @types/node.

23 export declare const toHex: (bytes: Buffer | Uint8Array) => string;
~~~~~~

Found 19 errors in 7 files.

Errors Files
2 node_modules/lucid-cardano/dist/lucid/lucid.d.ts:1
1 node_modules/lucid-cardano/dist/lucid/tx.d.ts:1
1 node_modules/lucid-cardano/dist/lucid/txComplete.d.ts:1
1 node_modules/lucid-cardano/dist/lucid/txSigned.d.ts:1
1 node_modules/lucid-cardano/dist/provider/blockfrost.d.ts:1
9 node_modules/lucid-cardano/dist/types/types.d.ts:1
4 node_modules/lucid-cardano/dist/utils/utils.d.ts:1`

Can documentation be added to clarify what is needed to start doing something simple from Lucid? As newcomers come to develop for Cardano, being able to see simple projects start would really help.

Forgive me if this is a noob question or request, but I'm new to both typescript and javascript, but see Lucid as being the best way to submit transactions in the future, both for simple transactions, and contract interactions.

[Question] Converting minting NFT from `cardano-cli` to lucid js

Hi everyone, i want to build a tnx using lucid js from cardano-cli

This is the cardano-cli

value="1 $nftPolicyId.$nftTokenName"

cardano-cli transaction build \
    --alonzo-era \
    --testnet-magic $TESTNETMAGIC \
    --tx-in $1 \
    --mint-redeemer-value 1 \
    --tx-in-collateral $1 \ 
    --tx-out "$walletAddr + 1413762 lovelace + $value" \ 
    --change-address $walletAddr \
    --mint "$value" \
    --mint-script-file $nftPolicyFile \
    --metadata-json-file metadata.json  \
    --protocol-params-file  protocol-parameters.json \
    --out-file $bodyFile

corresponding js

 const tx = await lucid
        .newTx()
        .attachMintingPolicy(mintingScript)
        .attachMetadata(metaData)
        .collectFrom(utxos[0], Redeemer(1))
        .payToAddress(address, mintAssets)
        .complete();
    console.log("tx", tx);

    const signedTx = await tx.sign().complete();
    console.log("signedTx", signedTx);

    const txHash = await signedTx.submit();
    console.log("txHash", txHash);

    return txHash;

i dont know how to map these

    --tx-in-collateral $1 \ # 
    --tx-out "$walletAddr + 1413762 lovelace + $value" \ #
    --change-address $walletAddr \
    --mint "$value" \

Thank you so much!

Using Node modules in the Deno-based Vasil branch

I'm working on creating an Ogmios provider with the idea of creating a PR here when it's ready, but am having a hell of a time getting CDNs or std/node to work for the @cardano-ogmios typescript client.

I've never worked with Deno before. Do you have a preferred method for integrating node libraries that aren't available in deno.land or deno.land/x/? My next approach would probably be denoify but the process of re-denoifying after updates to the library seems unnecessarily burdensome.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.