Skip to main content

Connecting aeWallet

This example attempts to connect to aeWallet and writes a log when connection status is updated.

tip

Ensure that the aeWallet application is running and unlocked before attempting connection.

info

This snippet uses Javascript language to keep things simple.

But @archethicjs/sdk can be used in a TypeScript or Javascript project.

index.html
<html>
<head>
<script type="module" src="main.js"/>
</head>
</html>
main.js
import Archethic, { ConnectionState } from "https://esm.sh/@archethicjs/sdk";

/// Creates an Archethic client.
/// This checks aeWallet RPC available transport methods and creates
/// an ArchethicWalletClient accordingly.
/// - If Archethic Wallet desktop is running and unlocked, Websocket will be used
/// - If Archethic Wallet Chrome extension is installed, it will be opened
const archethicClient = new Archethic()

/// Listen to rpc wallet connection status changes
archethicClient.rpcWallet.onconnectionstatechange(async (state) => {
switch (state) {
case ConnectionState.Connecting:
console.log("Connecting ...")
break
case ConnectionState.Closed:
console.log("Connection closed")
break
case ConnectionState.Closing:
console.log("Disconnecting ...")
break
case ConnectionState.Open:
const { endpointUrl } = await archethicClient.rpcWallet.getEndpoint()
const walletAccount = await archethicClient.rpcWallet.getCurrentAccount()
console.log(`Connected as ${walletAccount.shortName} to ${endpointUrl}`)
break
}
})

/// Attempts to connect to `aeWallet`.
///
/// Then it sets `archethicClient` up to
/// use the same chain as aeWallet.
///
/// This way, you can use :
/// - `archethicClient` to interact directly with the chain
/// - `archethicClient.rpcWallet` to interact with `aeWallet`
await archethicClient.connect()

/// Disconnect after 2 seconds
setTimeout(
async () => {

await archethicClient.rpcWallet.close()
archethicClient.rpcWallet.unsubscribeconnectionstatechange()
},
2000,
)