# Implementation Guide

### Install Mirai Package

`npm i @kanalabs/mirai`

`or`

`yarn add @kanalabs/mirai`

## Social Login Using Web3Auth

### Installation&#x20;

First, let us create a wallet using Web3Auth for Social Login. For this, we have to sign up at <https://dashboard.web3auth.io/> to create an account to create a web3Auth Client ID which is available after you are signed into the dashboard and create a project under 'Plug and Play'. Copy the Client ID shown and keep it ready before continuing.

> You can view a detailed steps on how to get started with Web3Auth : <https://web3auth.io/docs/integration-builder?lang=REACT&chain=ETH&evmFramework=ETHERS&customAuth=NONE&mfa=DEFAULT&whitelabel=NO&useModal=NO&web3AuthNetwork=TESTNET&rnMode=EXPO&stepIndex=0&stepIndex=10#step-10>

### Install Web3Auth Packages

```typescript
npm: npm install --save @web3auth/no-modal @web3auth/openlogin-adapter

yarn: yarn add @web3auth/no-modal @web3auth/openlogin-adapter
```

```typescript
import { Web3AuthNoModal } from "@web3auth/no-modal";
import {
  CHAIN_NAMESPACES,
  WALLET_ADAPTERS,
  ADAPTER_EVENTS,
  CONNECTED_EVENT_DATA,
} from "@web3auth/base";
import { OpenloginAdapter } from "@web3auth/openlogin-adapter";

```

## Whitelisting

The Client ID is unique for each project, if we use different Client IDs the same account login will give us different private keys. So if anyone uses our client ID, it will give a private key similar to the one we give. So it is necessary to add website links before allowing it to share our web3auth login.

## Initialise web3auth

```typescript
  const web3auth = new Web3AuthNoModal({
          clientId,
          web3AuthNetwork: "testnet", // mainnet, aqua,  cyan or testnet
          chainConfig: {
            chainNamespace: CHAIN_NAMESPACES.EIP155,
            chainId: "0x13881",
            rpcTarget: "https://rpc.ankr.com/polygon_mumbai", // This is the public RPC we have added, please pass on your own endpoint while creating an app
          },
        });
```

Defining the Web3Auth openLogin Adapter which is responsible for sign-in options. You can see the list of all sign-in options provided :  <https://web3auth.io/docs/auth-provider-setup/social-providers/>

<pre class="language-typescript"><code class="lang-typescript"><strong>        const openloginAdapter = new OpenloginAdapter({
</strong>          adapterSettings: {
            network: "testnet",
            clientId: clientId,
          },
          loginSettings: {
            mfaLevel: "none",
          },
        });
        web3auth.configureAdapter(openloginAdapter);
</code></pre>

Listen to events emitted by the Web3Auth Adapter

<pre class="language-typescript"><code class="lang-typescript"><strong>// Emits an event when connection completed
</strong><strong>web3auth.on(ADAPTER_EVENTS.CONNECTED, () => {
</strong>  if (!web3AuthInstance?.provider) {
    return
  }
})

// Emits an event when an error occurs during connection
web3auth.on(ADAPTER_EVENTS.ERRORED, (error) => {
  console.log(error);
})
</code></pre>

Initialize the web3Auth instance after setting up the Adapter Configuration

```typescript
await web3auth.init();
```

## Login with web3auth

Now, log in to web3Auth with valid credentials from any of the supported social platforms that web3auth supports..

For this example, Let us take Google as the social platform that we are looking to login

```typescript
try {
  if (!web3auth) {
      console.log("web3auth not initialized yet");
      return;
    }
  const web3authProvider = await web3auth.connectTo(
      WALLET_ADAPTERS.OPENLOGIN,
      {
        mfaLevel: "default", 
        loginProvider: "google",
      }
    );
    const privateKey = (await web3auth.provider?.request({
      method: "private_key",
    })) as string;
}
catch (e) {
  console.log(`Failed to login! Reason: ${e instanceof Error && e?.message ? e.message : 'unknown'}.`)
  return
}

if (!web3authProvider) {
  console.log(`Failed to get the provider connected`)
  return
}
```

After completing the login process, you can obtain the private key. Before initializing the Mirai SDK with it, it is necessary to format the private key.

#### Format privateKey

```typescript
  function formatPrivateKey(privateKey: any): string {
    if (privateKey.startsWith("0x")) {
      return privateKey;
    } else {
      return "0x" + privateKey;
    }
  }
```

## Initialize Mirai SDK

To initialize the wallet SDK - specify the required networks and it will be initialize SDK for all networks.

```typescript
    const sdk = await initializeSdkGateway(
      { privateKey: process.env.PRIVATE_KEY as string },
      {
        networks: [NetworkNames.Mumbai],
        bundlerApiKey: process.env.BUNDLER_API_KEY
      },
    );
```

```typescript
 * @param bundlerApiKey - Contact kanalabs to obtain the bundlerApiKey for authentication.
```

### Set Current SDK Instance

After initializing the sdk with the array required chains, we can set the default instance of SDK for any initialized network. with this function

#### Example

```typescript
const networkInstance = sdk.setCurrentInstance(NetworkNames.Mumbai);
```

To get the smart wallet address

```typescript
const address = await networkInstance.getCounterFactualAddress();    
```

## Destroy Instances

To destroy all SDK instances for the session

```typescript
await sdk.destroy();
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.kanalabs.io/smart-wallet-sdk/mirai-sdk-the-evm-smart-wallet-and-paymaster/implementation-guide.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
