Hello, World!
End-to-End
with Lucid (TypeScript)

Hello, World! - with Lucid

Covered in this tutorial


Pre-requisites

We assume that you have followed the Hello, World!'s First steps and thus, have Aiken installed an ready-to-use. We will also use Lucid (opens in a new tab), so make sure you have your dev environment ready for some TypeScript★.

★ For TypeScript and the rest of this tutorial, we recommend installing deno (opens in a new tab)

Getting funds

For this tutorial, we will use the validator we built in First steps. Yet, before moving on, we'll need some funds, and a public/private key pair to hold them. We can generate a private key and an address using Lucid.

Let's write our first script as generate-credentials.ts:

generate-credentials.ts
import { Lucid } from "https://deno.land/x/[email protected]/mod.ts";
 
const lucid = await Lucid.new(undefined, "Preview");
 
const privateKey = lucid.utils.generatePrivateKey();
await Deno.writeTextFile("me.sk", privateKey);
 
const address = await lucid
  .selectWalletFromPrivateKey(privateKey)
  .wallet.address();
await Deno.writeTextFile("me.addr", address);

You can run the instructions above using Deno via:

deno run --allow-net --allow-write generate-credentials.ts

Now, we can head to the Cardano faucet (opens in a new tab) to get some funds on the preview network to our newly created address (inside me.addr).

👉 Make sure to select "Preview Testnet" as network.

Using CardanoScan (opens in a new tab) we can watch for the faucet sending some ADA our way. This should be pretty fast (a couple of seconds).

Using the contract

Now that we have some funds, we can lock them in our newly created contract. We'll use Lucid (opens in a new tab) to construct and submit our transaction through Blockfrost (opens in a new tab).

This is only one example of possible setup using tools we love. For more tools, make sure to check out the Cardano Developer Portal (opens in a new tab)!

Setup

First, we setup Lucid with Blockfrost as a provider. This will allow us to let Lucid handle transaction building for us, which includes managing changes. It also gives us a direct way to submit the transaction later on.

Create a file named hello-world-lock.ts in the root of your project and add the following code:

hello-world-lock.ts
import {
  Blockfrost,
  C,
  Constr,
  Data,
  Lucid,
  SpendingValidator,
  TxHash,
  fromHex,
  toHex,
  utf8ToHex,
} from "https://deno.land/x/[email protected]/mod.ts";
import * as cbor from "https://deno.land/x/[email protected]/index.js";
 
const lucid = await Lucid.new(
  new Blockfrost(
    "https://cardano-preview.blockfrost.io/api/v0",
    Deno.env.get("BLOCKFROST_PROJECT_ID")
  ),
  "Preview"
);
⚠️

Note that the highlighted line above looks for an environment variable named BLOCKFROST_PROJECT_ID which its value must be set to your Blockfrost project id. You can define a new environment variable in your terminal by running (in the same session you're also executing the script!):

export BLOCKFROST_PROJECT_ID=preview...

Replace preview... with your actual project id.

Next, we'll need to read the validator from the blueprint (plutus.json) we generated earlier. We'll also need to convert it to a format that Lucid understands. This is done by serializing the validator and then converting it to a hexadecimal text string as shown below:

hello-world-lock.ts
lucid.selectWalletFromPrivateKey(await Deno.readTextFile("./me.sk"));
 
const validator = await readValidator();
 
// --- Supporting functions
 
async function readValidator(): Promise<SpendingValidator> {
  const validator = JSON.parse(await Deno.readTextFile("plutus.json")).validators[0];
  return {
    type: "PlutusV2",
    script: toHex(cbor.encode(fromHex(validator.compiledCode))),
  };
}

Locking funds into the contract

Now that we can read our validator, we can make our first transaction to lock funds into the contract. The datum must match the representation expected by the validator (and as specified in the blueprint), so this is a constructor with a single field that is a byte array.

As value for that byte array, we provide a hash digest of our public key (from the wallet created with our me.sk) . This will be needed to unlock the funds.

hello-world-lock.ts
const publicKeyHash = lucid.utils.getAddressDetails(
  await lucid.wallet.address()
).paymentCredential?.hash;
 
const datum = Data.to(new Constr(0, [publicKeyHash]));
 
const txHash = await lock(1000000n, { into: validator, owner: datum });
 
await lucid.awaitTx(txHash);
 
console.log(`1 tADA locked into the contract at:
    Tx ID: ${txHash}
    Datum: ${datum}
`);
 
// --- Supporting functions
 
async function lock(
  lovelace: bigint,
  { into, owner }: { into: SpendingValidator; owner: string }
): Promise<TxHash> {
  const contractAddress = lucid.utils.validatorToAddress(into);
 
  const tx = await lucid
    .newTx()
    .payToContract(contractAddress, { inline: owner }, { lovelace })
    .complete();
 
  const signedTx = await tx.sign().complete();
 
  return signedTx.submit();
}

You can run the excerpt above by executing:

deno run --allow-net --allow-read --allow-env hello-world-lock.ts

The above code requires you to:

At this stage, your folder should look roughly like this:

./hello-world

├── README.md
├── aiken.toml
├── plutus.json
├── generate-credentials.ts
├── hello-world-lock.ts
├── me.addr
├── me.sk
├── lib
│   └── ...
└── validators
    └── hello-world.ak

If everything went well, you should see something like this:

1 tADA locked into the contract at:
    Tx ID: 8559f57234407204d8e9a6bf57ef6943c65ec7119eb1c2ca6224f8bad8e71c1e
    Datum: d8799f581c10073fd2997d2f7dc6dadcf24966bd06b01930e5210e5de7aebf792dff

Inspecting the transaction

Now is a good moment to pause and have a look at CardanoScan. Here's an example of a Hello World transaction (opens in a new tab) that we generated using this tutorial.

If you notice the small icon next to the contract output address, we can even inspect the datum (opens in a new tab):

d8799f581c10073fd2997d2f7dc6dadcf24966bd06b01930e5210e5de7aebf792dff
{
  "constructor": 0,
  "fields": [
    {
      "bytes": "10073fd2997d2f7dc6dadcf24966bd06b01930e5210e5de7aebf792d"
    }
  ]
}

Unlocking funds from the contract

Finally, as a last step: we now want to spend the UTxO that is locked by our hello-world contract.

To be valid, our transaction must meet two conditions:

  • it must provide "Hello, World!" as a redeemer; and
  • it must be signed by the key referenced as datum (i.e. the owner).

Let's make a new file hello-world-unlock.ts and copy over some of the boilerplate from the first one.

hello-world-unlock.ts
import {
  Blockfrost,
  C,
  Constr,
  Data,
  Lucid,
  SpendingValidator,
  TxHash,
  fromHex,
  toHex,
  utf8ToHex,
} from "https://deno.land/x/[email protected]/mod.ts";
import * as cbor from "https://deno.land/x/[email protected]/index.js";
 
const lucid = await Lucid.new(
  new Blockfrost(
    "https://cardano-preview.blockfrost.io/api/v0",
    Deno.env.get("BLOCKFROST_PROJECT_ID")
  ),
  "Preview"
);
 
lucid.selectWalletFromPrivateKey(await Deno.readTextFile("./me.sk"));
 
const validator = await readValidator();
 
// --- Supporting functions
 
async function readValidator(): Promise<SpendingValidator> {
  const validator = JSON.parse(await Deno.readTextFile("plutus.json"))
    .validators[0];
  return {
    type: "PlutusV2",
    script: toHex(cbor.encode(fromHex(validator.compiledCode))),
  };
}

Now, let's add the bits to unlock the funds in the contract. We'll need the transaction identifier (i.e. Tx ID) obtained when you ran the previous script (hello-world-lock.ts)

That transaction identifier (a.k.a. transaction hash), and the corresponding output index (here, 0) uniquely identify the UTxO (Unspent Transaction Output) in which the funds are currently locked. And that's the one we're about to unlock.

⚠️

Note that we need to explicitly add a signer using .addSigner so that it gets added to the extra_signatories of our transaction—and becomes accessible for our script.

hello-world-unlock.ts
const utxo: OutRef = { txHash: Deno.args[0], outputIndex: 0 };
 
const redeemer = Data.to(new Constr(0, [utf8ToHex("Hello, World!")]));
 
const txHash = await unlock(utxo, {
  from: validator,
  using: redeemer,
});
 
await lucid.awaitTx(txHash);
 
console.log(`1 tADA unlocked from the contract
    Tx ID:    ${txHash}
    Redeemer: ${redeemer}
`);
 
// --- Supporting functions
 
async function unlock(
  ref: OutRef,
  { from, using }: { from: SpendingValidator; using: Redeemer }
): Promise<TxHash> {
  const [utxo] = await lucid.utxosByOutRef([ref]);
 
  const tx = await lucid
    .newTx()
    .collectFrom([utxo], using)
    .addSigner(await lucid.wallet.address())
    .attachSpendingValidator(from)
    .complete();
 
  const signedTx = await tx
    .sign()
    .complete();
 
  return signedTx.submit();
}

Run this script as usual, but this time, also passing the transaction id obtained from the previous command locking the funds. For example:

deno run --allow-net --allow-read --allow-env hello-world-unlock.ts 8559f57234407204d8e9a6bf57ef6943c65ec7119eb1c2ca6224f8bad8e71c1e

If everything worked as planned you should see something resembling the following output:

1 tADA unlocked from the contract
    Tx ID:    d3d5e828a3989691b0960d22a265c8c9ae4723134b52aa05ec0fb7d40f060392
    Redeemer: d8799f4d48656c6c6f2c20576f726c6421ff

And, tada 🎉!

We can inspect our redeeming transaction on CardanoScan (opens in a new tab) and see that it successfully executed our Hello World contract.