Skip to content

Connect aepp to wallet

Petar Baykov edited this page Mar 19, 2020 · 1 revision

How to interact with wallet from aepp

This guide describing the process of building Aepp that interacts with wallet.

First we need to install aeternity javascript sdk

You can find guide here: https://github.com/aeternity/aepp-sdk-js#1-install-sdk

Then we need to initialize RpcAepp stamp

import { RpcAepp } from '@aeternity/aepp-sdk/es'

const NODE_URL = 'https://sdk-testnet.aepps.com'
const COMPILER_URL = 'https://latest.compiler.aepps.com' 
let publicKey
let balance
let client
(async function () {
  client = await RpcAepp({
    name: 'AEPP',
    nodes: [{ name: 'Testnet', instance: await Node({ url: NODE_URL, internalUrl: NODE_URL }) }],
    compilerUrl: COMPILER_URL,
    // call-back for update network notification
    onNetworkChange (params) {
      if (this.getNetworkId() !== params.networkId) alert(`Connected network ${this.getNetworkId()} is not supported`)
    },
    // call-back for update address notification
    onAddressChange:  async (addresses) => {
      publicKey = await client.address()
      balance = await client.balance(this.pub).catch(e => 0)
    },
    // call-back for disconnect notification
    onDisconnect (msg) {}
  })
  await scanForWallets()
})()

Sstart looking for available wallets

import WalletDetector from '@aeternity/aepp-sdk/es/utils/aepp-wallet-communication/wallet-detector'

async function scanForWallets () {
  let detector
  const handleWallets = async function ({ wallets, newWallet }) {
    newWallet = newWallet || Object.values(wallets)[0]
    // ask if you want to connect
    if (confirm(`Do you want to connect to wallet ${newWallet.name}`)) {
      // Stop scanning wallets
      detector.stopScan()
      // Connect to wallet
      await connectToWallet(newWallet)
    }
  }
  // Create connection object for WalletDetector
  const scannerConnection = await BrowserWindowMessageConnection({
    connectionInfo: { id: 'spy' }
  })
  // Initialize WalletDetector 
  detector = await WalletDetector({ connection: scannerConnection })
  // Start scanning
  detector.scan(handleWallets.bind(this))
}

Connect to wallet

async function connectToWallet (wallet) {
  // Connect to the wallet using wallet connection object
  // At this line sdk will send connection request to the wallet and waiting for response
  await client.connectToWallet(await wallet.getConnection())
  // After connection established we can subscribe for accounts
  const accounts = await client.subscribeAddress('subscribe', 'connected')
  // Now we have list of available account and we can get the selected account just using usual SDK interface
  const selectedAccountAddress = await client.address()
  // In `client.rpcClient` you can find all information regarding to connected waellet
  const walletName = client.rpcClient.info.name
}