Skip to content
Logo

Connecting with canton-connect

In this guide you'll replace the Starter dApp's Connect wallet button with a custom connect button, built on the hooks in @bootnodedev/canton-connect. You'll also use the wallet for more than connecting: you'll sign a note, check that signature in the browser and handle a party that can't sign.

The finished app is in the custom-connect-button branch of canton-dappbooster-getting-started.


Write your own connect button

The Starter dApp's WalletButton comes ready-made from @bootnodedev/canton-dappbooster. You'll use three hooks from @bootnodedev/canton-connect for the custom connect button instead:

  • useAccount returns the connected account, and the session's status.
  • useConnect returns connect, which opens the wallet picker, and cancelConnect, which closes it. isPending is true while the picker is open.
  • useDisconnect returns disconnect, which ends the session.

Create src/components/ConnectButton.tsx:

src/components/ConnectButton.tsx
import {
  ConnectCancelledError,
  useAccount,
  useConnect,
  useDisconnect,
} from '@bootnodedev/canton-connect'
import type { ReactElement } from 'react'
 
const ignoreCancel = (error: unknown): void => {
  if (!(error instanceof ConnectCancelledError)) {
    throw error
  }
}
 
export const ConnectButton = (): ReactElement | null => {
  const { account, status } = useAccount()
  const { connect, cancelConnect, isPending } = useConnect()
  const { disconnect } = useDisconnect()
 
  if (status === 'idle') {
    return null
  }
 
  if (account !== undefined) {
    return (
      <button onClick={() => void disconnect()} type="button">
        Disconnect
      </button>
    )
  }
 
  if (isPending) {
    return (
      <button onClick={cancelConnect} type="button">
        Cancel
      </button>
    )
  }
 
  return (
    <button onClick={() => void connect().catch(ignoreCancel)} type="button">
      Connect wallet
    </button>
  )
}

Two parts of the button handle cases you don't see at first:

  • Lines 20 to 22: after a reload, the provider restores your last session, and status is 'idle' until it knows. Without this check, the button says Connect wallet for a moment before it says Disconnect.
  • Line 41: connect() rejects with ConnectCancelledError when you press Cancel. ignoreCancel, on lines 9 to 13, drops that error and throws any other again, so a real failure still reaches the browser console. Without the .catch, the console also shows ConnectCancelledError: Wallet connection cancelled on every cancel.

In src/App.tsx, delete the WalletButton import and import your button instead:

src/App.tsx
import { ConnectButton } from './components/ConnectButton'

Replace <WalletButton /> with your button:

src/App.tsx
<main>
  <h1>Notes</h1>
  <ConnectButton />
  <Session />
  <NoteForm />
  <NoteList />
</main>

Press Disconnect. You should see Connect wallet and No wallet connected.

Press Connect wallet. The button says Cancel while the picker is open. Choose Wallet Gateway, and enter unsafe if the gateway asks for the client secret. You should see Disconnect and Connected as with your party.

Sign a note

The ledger already records who wrote each Note: the author is its signatory. A signed note is for someone outside the ledger. They get the text and its signature, and they can check which party signed it with no wallet and no ledger.

useSignMessage returns signMessage, which asks the wallet to sign a text with the party's key, and the last error.

Create src/components/SignNote.tsx, the form that signs a note:

src/components/SignNote.tsx
import { useAccount, useSignMessage } from '@bootnodedev/canton-connect'
import { type FormEvent, type ReactElement, useState } from 'react'
 
export const SignNote = (): ReactElement | null => {
  const { account } = useAccount()
  const { signMessage, error } = useSignMessage()
  const [text, setText] = useState('')
  const [proof, setProof] = useState('')
 
  if (account === undefined) {
    return null
  }
 
  const sign = async (event: FormEvent): Promise<void> => {
    event.preventDefault()
    const signature = await signMessage(text)
    // Saved together now: the hook keeps its last signature after you switch party.
    setProof(
      JSON.stringify({
        message: text,
        partyId: account.partyId,
        publicKey: account.publicKey,
        signature,
      }),
    )
  }
 
  return (
    <form onSubmit={(event) => void sign(event).catch(() => undefined)}>
      <h2>Sign a note</h2>
      <textarea
        onChange={(event) => setText(event.target.value)}
        placeholder="Your note"
        value={text}
      />
      <button disabled={text === ''} type="submit">
        Sign
      </button>
      {error !== undefined && <p>{error.message}</p>}
      {proof !== '' && <textarea readOnly value={proof} />}
    </form>
  )
}

The form shows a proof: the text, the party ID, the party's public key from account.publicKey and the signature. It saves them together when you sign, because useSignMessage keeps its last signature after you switch party.

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

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

Write a line under Sign a note and press Sign. The gateway opens a window that asks you to approve the message:

Approving a message in Wallet Gateway

Press Approve. You should see the proof under the button. Yours has your own party ID, key and signature:

Output
{"message":"Lunch at noon?","partyId":"bob::122051937ecd8ab598f2e6ec77f17f293626e9292302a847462f3afb89507b008121","publicKey":"ggkFuSvJxHWEiyrcQld6cCo3MWt22P9WgZRIEsNzzbM=","signature":"MCsitLTy4hFD+4YbfAgWuA8X/Cv21/+3QjxeV9wCqc+RBa3j9ztInzddJM3/fIhgaojep32NQrmS1bFJFgp0Dg=="}

Check a proof

A party ID ends in the fingerprint of the party's public key. So a proof passes two checks: the key matches the party ID, and the signature matches the key and the text. Both run in the browser.

@canton-network/core-types has fingerprintPublicKey, which computes the fingerprint the way Canton does. Add it to the project:

Terminal
pnpm add @canton-network/core-types

Create src/proof.ts. It checks the key with fingerprintPublicKey, then the signature with the browser's Web Crypto API:

src/proof.ts
import { fingerprintPublicKey } from '@canton-network/core-types'
 
export type Proof = {
  message: string
  partyId: string
  publicKey: string
  signature: string
}
 
const bytes = (base64: string) => Uint8Array.from(atob(base64), (char) => char.charCodeAt(0))
 
export const checkProof = async ({ message, partyId, publicKey, signature }: Proof) => {
  // A party ID ends in the fingerprint of the party's key, so a key from anyone else fails here.
  if (partyId.split('::')[1] !== (await fingerprintPublicKey(publicKey))) {
    return false
  }
 
  const key = await crypto.subtle.importKey('raw', bytes(publicKey), 'Ed25519', false, ['verify'])
  return crypto.subtle.verify('Ed25519', key, bytes(signature), new TextEncoder().encode(message))
}

Create src/components/CheckProof.tsx, the form that checks a proof:

src/components/CheckProof.tsx
import { partyHint } from '@bootnodedev/canton-dappbooster'
import { type FormEvent, type ReactElement, useState } from 'react'
import { checkProof, type Proof } from '../proof'
 
export const CheckProof = (): ReactElement => {
  const [input, setInput] = useState('')
  const [result, setResult] = useState('')
 
  const check = async (event: FormEvent): Promise<void> => {
    event.preventDefault()
    const proof = JSON.parse(input) as Proof
    setResult((await checkProof(proof)) ? `Signed by ${partyHint(proof.partyId)}` : 'Not valid')
  }
 
  return (
    <form onSubmit={(event) => void check(event).catch(() => setResult('Not valid'))}>
      <h2>Check a proof</h2>
      <textarea
        onChange={(event) => {
          setInput(event.target.value)
          setResult('')
        }}
        placeholder="Proof"
        value={input}
      />
      <button disabled={input === ''} type="submit">
        Check
      </button>
      {result !== '' && <p>{result}</p>}
    </form>
  )
}

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

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

The dApp reloads, so sign a line again. Copy the proof, paste it under Check a proof and press Check. You should see Signed by and the party you signed with.

Change one word of the text inside the pasted proof and press Check again. You should see Not valid.

Undo the change, press Disconnect and press Check. The proof still passes, because checking needs no wallet:

A proof checked with no wallet connected

Hide signing for a local party

Wallet Gateway signs only for a party it holds the key of, one made with wallet-kernel. A party made with participant is a local party: its key belongs to the participant, and the gateway refuses to sign for it.

In Wallet Gateway, create a party with carol in Party ID Hint. Pick participant as the signing provider and tick Set as primary wallet.

If the gateway answers Party already exists, this LocalNet already has a carol, for example from an earlier run of this guide. A local party's ID comes from the participant, so the same hint gives the same ID. Use another hint, like carol2.

In the dApp, press Connect wallet and choose Wallet Gateway. You should see Connected as carol::….

Write a line under Sign a note, press Sign, then Approve in the gateway. Oops, the gateway refuses:

Wallet Gateway refusing to sign for a local party

The dApp shows the same error under the form:

Output
Message signing failed for messageId <id>: signMessage is only supported for wallet-kernel, dfns, fireblocks, securosys wallets, got participant

usePartyType tells the two kinds apart before you try. Its readPartyType returns 'local' or 'external', and isReady says when you can call it. readPartyType changes when the account does, so the form reads the type again after you switch party.

Edit src/components/SignNote.tsx so it looks like this:

src/components/SignNote.tsx
import { useAccount, usePartyType, useSignMessage } from '@bootnodedev/canton-connect'
import { type FormEvent, type ReactElement, useEffect, useState } from 'react'
 
export const SignNote = (): ReactElement | null => {
  const { account } = useAccount()
  const { signMessage, error } = useSignMessage()
  const { readPartyType, isReady } = usePartyType()
  const [isLocal, setIsLocal] = useState(false)
  const [text, setText] = useState('')
  const [proof, setProof] = useState('')
 
  useEffect(() => {
    if (isReady) {
      void readPartyType().then(
        (type) => setIsLocal(type === 'local'),
        () => setIsLocal(false),
      )
    }
  }, [isReady, readPartyType])
 
  if (account === undefined) {
    return null
  }
 
  if (isLocal) {
    return <p>A local party can't sign messages.</p>
  }
 
  const sign = async (event: FormEvent): Promise<void> => {
    event.preventDefault()
    const signature = await signMessage(text)
    // Saved together now: the hook keeps its last signature after you switch party.
    setProof(
      JSON.stringify({
        message: text,
        partyId: account.partyId,
        publicKey: account.publicKey,
        signature,
      }),
    )
  }
 
  return (
    <form onSubmit={(event) => void sign(event).catch(() => undefined)}>
      <h2>Sign a note</h2>
      <textarea
        onChange={(event) => setText(event.target.value)}
        placeholder="Your note"
        value={text}
      />
      <button disabled={text === ''} type="submit">
        Sign
      </button>
      {error !== undefined && <p>{error.message}</p>}
      {proof !== '' && <textarea readOnly value={proof} />}
    </form>
  )
}

You should see A local party can't sign messages. instead of the form.

In Wallet Gateway, press Set as primary on the alice card with wallet-kernel as its signing provider. The dApp switches to alice, and the Sign a note form comes back.

And that's it. You built your own connect button and signed a note with the wallet. Then you checked the proof in the browser and kept a local party from trying to sign.

For every hook in @bootnodedev/canton-connect, see its API reference.