Skip to main content

Simple Example

The following example will show:

  1. How to connect a dApp to a wallet
  2. How to re-use an existing connection after a page refreshed
  3. How to send an operation request
Example
import {
  BeaconEvent,
  DAppClient,
  TezosOperationType,
} from "@airgap/beacon-sdk";

const dAppClient = new DAppClient({ name: "Beacon Docs" });

// Listen for all the active account changes
dAppClient.subscribeToEvent(BeaconEvent.ACTIVE_ACCOUNT_SET, async (account) => {
  // An active account has been set, update the dApp UI
  console.log(`${BeaconEvent.ACTIVE_ACCOUNT_SET} triggered: `, account);
});

let myAddress: string | undefined;

// This code should be called every time the page is loaded or refreshed to see if the user has already connected to a wallet.
const activeAccount = await dAppClient.getActiveAccount();
if (activeAccount) {
  // If defined, the user is connected to a wallet.
  // You can now do an operation request, sign request, or send another permission request to switch wallet
  console.log("Already connected:", activeAccount.address);
  myAddress = activeAccount.address;
} else {
  const permissions = await dAppClient.requestPermissions();
  console.log("New connection:", permissions.address);
  myAddress = permissions.address;
}

// At this point we are connected to an account.
// Let's send a simple transaction to the wallet that sends 1 mutez to ourselves.
const response = await dAppClient.requestOperation({
  operationDetails: [
    {
      kind: TezosOperationType.TRANSACTION,
      destination: myAddress, // Send to ourselves
      amount: "1", // Amount in mutez, the smallest unit in Tezos
    },
  ],
});

console.log("Operation Hash: ", response.transactionHash);
Loading...