Skip to content
Logo

Building a Notes dApp

In this tutorial you'll build Notes, a small dApp on Canton dAppBooster. In it, one party writes a note for another, the reader sees the note and acknowledges it, and the ledger archives it.

You'll build it by changing the Starter dApp. The finished app is in canton-dappbooster-getting-started.

Watch: Building a Notes dAppWatch: Building a Notes dAppBuild Notes, a small dApp where one party writes a note for another.

Start the stack

Make sure Docker is running. Then, from your project folder, run:

Terminal
pnpm stack up

Create two parties

You'll need two parties for the tutorial. Open Wallet Gateway at http://localhost:3030. When it asks for a client secret, enter unsafe.

Create the two parties in the gateway:

  • Create a party with alice in Party ID Hint, the readable start of the party ID. Pick wallet-kernel as the signing provider and tick Set as primary wallet.
  • Create a second party the same way, with bob in Party ID Hint, but don't tick Set as primary wallet.

Creating a party in Wallet Gateway

Set up the Notes page

The Starter dApp already connects a wallet. In src/App.tsx, WalletButton shows Connect wallet, and Session shows the party you're connected as.

In src/App.tsx, rename the app to Notes:

src/App.tsx
const connectConfig: CantonConnectConfig = {
  appName: 'Notes',
  additionalAdapters: [...mockWallet, ...gateway],
}
src/App.tsx
<h1>Notes</h1>

Open http://localhost:3012 and press Connect wallet. Choose Wallet Gateway, not Mock Wallet: the mock wallet connects, but it can't send anything to the ledger. The gateway asks for the client secret again, so enter unsafe.

You should see Notes and Connected as alice::….

Add the Note contract

Delete the Starter dApp's sample contract:

Terminal
rm daml/Main.daml

Create daml/Note.daml with the Note template:

daml/Note.daml
module Note where
 
-- A line of text one party writes for another.
-- The author signs it, so only the author can create it.
-- The reader sees it, and is the only one who can acknowledge it.
template Note
  with
    author : Party
    reader : Party
    text : Text
  where
    signatory author
    observer reader
 
    -- Consuming, so acknowledging archives the note.
    choice Acknowledge : ()
      controller reader
      do pure ()

LocalNet already has a package called starter at this version, from pnpm stack up, and it refuses a different package with the same name and version. In daml/daml.yaml, rename the package to notes:

daml/daml.yaml
name: notes

Build the DAR, the package that holds the compiled contract, and upload it:

Terminal
pnpm build-dar
pnpm deploy-dar -- daml/.daml/dist/notes-0.1.0.dar

You should see this line at the end:

Output
deployed notes-0.1.0.dar to app-user

Write a note

Create src/notes.ts. It holds the two ledger commands and the code that reads notes from the ledger:

src/notes.ts
// A template id in `#package-name:Module:Template` form. The participant resolves it to whichever
// package id it holds, so a rebuild of the DAR needs no edit here.
export const NOTE_TEMPLATE_ID = '#notes:Note:Note'
 
export type Note = {
  author: string
  contractId: string
  reader: string
  text: string
}
 
// JSON Ledger API v2 create command.
export const createNoteCommand = (author: string, reader: string, text: string) => ({
  CreateCommand: {
    templateId: NOTE_TEMPLATE_ID,
    createArguments: { author, reader, text },
  },
})
 
// JSON Ledger API v2 exercise command. Acknowledge takes no arguments.
export const acknowledgeCommand = (contractId: string) => ({
  ExerciseCommand: {
    choice: 'Acknowledge',
    choiceArgument: {},
    contractId,
    templateId: NOTE_TEMPLATE_ID,
  },
})
 
// The active-contracts read: every Note the party is a stakeholder of, at the given offset.
export const notesRequest = (partyId: string, offset: string | number) => ({
  requestMethod: 'post' as const,
  resource: '/v2/state/active-contracts',
  body: {
    eventFormat: {
      filtersByParty: {
        [partyId]: {
          cumulative: [
            { identifierFilter: { TemplateFilter: { value: { templateId: NOTE_TEMPLATE_ID } } } },
          ],
        },
      },
      verbose: true,
    },
    activeAtOffset: offset,
  },
})
 
type AcsRow = {
  contractEntry?: {
    JsActiveContract?: {
      createdEvent?: {
        contractId?: string
        createArgument?: { author?: string; reader?: string; text?: string }
      }
    }
  }
}
 
export const toNotes = (rows: unknown): Note[] => {
  if (!Array.isArray(rows)) return []
 
  return (rows as AcsRow[]).flatMap((row) => {
    const created = row.contractEntry?.JsActiveContract?.createdEvent
    const { author, reader, text } = created?.createArgument ?? {}
 
    if (
      created?.contractId === undefined ||
      author === undefined ||
      reader === undefined ||
      text === undefined
    ) {
      return []
    }
 
    return [{ author, contractId: created.contractId, reader, text }]
  })
}

The form uses two hooks from @bootnodedev/canton-connect, the package that connects the dApp to the wallet:

  • useAccount returns the connected account, with its partyId. It's undefined until you connect.
  • useExecute sends ledger commands through the wallet, acting as the connected party.

You don't need more than that for now. A later guide, Connecting with canton-connect, covers more of the package.

Create src/components/NoteForm.tsx, the form that sends a note:

src/components/NoteForm.tsx
import { useAccount, useExecute } from '@bootnodedev/canton-connect'
import { PartyIdInput } from '@bootnodedev/canton-dappbooster'
import { type FormEvent, type ReactElement, useState } from 'react'
import { createNoteCommand } from '../notes'
 
export const NoteForm = (): ReactElement | null => {
  const { account } = useAccount()
  const { execute, error } = useExecute()
  const [reader, setReader] = useState('')
  const [text, setText] = useState('')
 
  if (account === undefined) {
    return null
  }
 
  const submit = (event: FormEvent): void => {
    event.preventDefault()
    // Sends the command through the wallet
    void execute({ commands: [createNoteCommand(account.partyId, reader, text)] })
    setText('')
  }
 
  return (
    <form onSubmit={submit}>
      <h2>Write a note</h2>
      <PartyIdInput
        onChange={setReader}
        placeholder="Reader party ID"
        style={{ boxSizing: 'border-box' }}
        value={reader}
      />
      <textarea
        onChange={(event) => setText(event.target.value)}
        placeholder="Your note"
        value={text}
      />
      <button disabled={reader === '' || text === ''} type="submit">
        Send
      </button>
      {error !== undefined && <p>{error.message}</p>}
    </form>
  )
}

Import the form in src/App.tsx and put it under <Session />:

src/App.tsx
import { NoteForm } from './components/NoteForm'
src/App.tsx
<main>
  <h1>Notes</h1>
  <WalletButton />
  <Session />
  <NoteForm />
</main>

In Wallet Gateway, open Parties and press Copy party ID on the bob card with wallet-kernel as its signing provider. If you ran this guide before, the cards left from that run show participant.

In the dApp, paste bob's party ID, write a line and press Send. The gateway opens a window that asks you to approve the transaction. Press Approve.

Approving a transaction in Wallet Gateway

List the notes and acknowledge them

To read the ledger, canton-connect has a third hook, useLedger. Its ledgerApi sends a request to the participant's JSON Ledger API through the wallet, and isReady says when it can.

Create src/useNotes.ts. The hook reads the active Note contracts through Wallet Gateway every 3 seconds:

src/useNotes.ts
import { useAccount, useLedger } from '@bootnodedev/canton-connect'
import { useCallback, useEffect, useState } from 'react'
import { type Note, notesRequest, toNotes } from './notes'
 
const POLL_MS = 3000
 
/** Every Note the connected party can see, read again every few seconds. */
export const useNotes = (): { notes: Note[] } => {
  const { ledgerApi, isReady } = useLedger()
  const { account } = useAccount()
  const partyId = account?.partyId
  const [notes, setNotes] = useState<Note[]>([])
 
  const read = useCallback(async (): Promise<void> => {
    if (!isReady || partyId === undefined) {
      setNotes([])
      return
    }
 
    // A read is always taken at one offset, so the answer is a snapshot and not a moving target.
    const end = (await ledgerApi({ requestMethod: 'get', resource: '/v2/state/ledger-end' })) as {
      offset: string | number
    }
 
    setNotes(toNotes(await ledgerApi(notesRequest(partyId, end.offset))))
  }, [isReady, ledgerApi, partyId])
 
  // The wallet does not tell the page when a transaction lands, so the page asks.
  useEffect(() => {
    void read()
    const timer = setInterval(() => void read(), POLL_MS)
    return () => clearInterval(timer)
  }, [read])
 
  return { notes }
}

Create src/components/NoteList.tsx. It lists the notes and shows Acknowledge only to the reader, because only the reader can exercise the Acknowledge choice:

src/components/NoteList.tsx
import { useAccount, useExecute } from '@bootnodedev/canton-connect'
import { partyHint } from '@bootnodedev/canton-dappbooster'
import type { ReactElement } from 'react'
import { acknowledgeCommand } from '../notes'
import { useNotes } from '../useNotes'
 
export const NoteList = (): ReactElement | null => {
  const { account } = useAccount()
  const { notes } = useNotes()
  const { execute } = useExecute()
 
  if (account === undefined) {
    return null
  }
 
  return (
    <section>
      <h2>Your notes</h2>
      {notes.length === 0 ? (
        <p>Nothing here yet.</p>
      ) : (
        <ul>
          {notes.map((note) => (
            <li key={note.contractId}>
              <div>
                <p>{note.text}</p>
                <small>from {partyHint(note.author)}</small>
              </div>
              {note.reader === account.partyId && (
                <button
                  onClick={() => void execute({ commands: [acknowledgeCommand(note.contractId)] })}
                  type="button"
                >
                  Acknowledge
                </button>
              )}
            </li>
          ))}
        </ul>
      )}
    </section>
  )
}

Import the list in src/App.tsx and put it under <NoteForm />:

src/App.tsx
import { NoteList } from './components/NoteList'
src/App.tsx
<main>
  <h1>Notes</h1>
  <WalletButton />
  <Session />
  <NoteForm />
  <NoteList />
</main>

You should see the note you sent, from alice. It has no Acknowledge button, because alice wrote it.

Read the note as bob

In Wallet Gateway, open Parties and press Set as primary on the same bob card.

The dApp switches to bob without reconnecting. You should see the note from alice and an Acknowledge button:

The finished Notes app with a note waiting for Acknowledge

Press Acknowledge, then Approve in the gateway. The ledger archives the note, and it disappears from the list the next time useNotes reads the ledger.

And that's it. You built a dApp where alice writes a note, bob reads it and acknowledges it, and the ledger archives it. Congratulations.

Next, Connecting with canton-connect replaces the Starter dApp's connect button with your own.