In order to start interacting with Twetch Wallet you must first establish a connection. This connection request will prompt the user for permission to share their public key and paymail, and indicate that they are willing to interact further.

Once permission is established the first time, the web application's domain will be whitelisted for future connection requests. The user may also indicate that they are willing to auto-approve certain transactions from the application as well.

Similarly, it is possible to terminate the connection both on the application and the user side.

Connecting

The way to connect to Twetch Wallet is by calling window.bitcoin.connect().

connect()

try {
  const resp = await window.bitcoin.connect();
  resp.publicKey.toString();
  // 26qv4GCcx98RihuK3c4T6ozB3J7L6VwCuFVc7Ta2A3Uo
  resp.paymail.toString();
  // 1@twetch.me
} catch (err) {
  // { code: 4001, message: 'User rejected the request.' }
}

The call will return a Promise that resolves when the user has accepted the connection request, and reject (throw when awaited) when the user declines the request or closes the pop-up. See Errors for a breakdown of error messages Twetch Wallet may emit.

Eagerly Connecting

After a web application connects to Twetch Wallet for the first time it becomes trusted, and it is possible for the application to automatically connect to Twetch Wallet on subsequent visits, or page refreshes. This is often called "eagerly connecting".

To implement this, Twetch Wallet allows an onlyIfTrusted option to be passed into the connect() call.

connect()

window.bitcoin.connect({ onlyIfTrusted: true });

When using this flag, Twetch Wallet will only connect and emit a connect event if the application is trusted. Therefore, this can be safely called on page load for new users, as they won't be bothered by a pop-up window even if they have never connected to Twetch Wallet.

Here is an example of how you might use this to implement "eagerly connecting" in a React application

import { useEffect } from "react";

useEffect(() => {
    // Will either automatically connect to Twetch Wallet, or do nothing.
    window.bitcoin.connect({ onlyIfTrusted: true })
        .then(({ publicKey }) => {
            // Handle successful eager connection
        });
        .catch(() => {
            // Handle connection failure as usual
        })
}, []);