# WEB

## Wallet SDK - Web

The Wallet SDK provides an easy way to connect to user wallets and manage user sessions.

💡ROLLUPS THIS SDK SUPPORTS

* XpansionChain

⚠️THIS SDK IS UNSTABLEThis SDK is not yet at v1.0 so its public interface should not be considered final. Future releases may include breaking changes without further notice. We will do our best to keep this documentation updated providing visibility on breaking changes planned.CONTENTS

* <mark style="color:blue;">Setup</mark>
  * <mark style="color:blue;">Install</mark>
  * <mark style="color:blue;">Initialize</mark>
* <mark style="color:blue;">Events</mark>
  * <mark style="color:blue;">Ensuring an up-to-date connection</mark>
  * <mark style="color:blue;">Handling screen statuses</mark>
* <mark style="color:blue;">Workflows</mark>
  * <mark style="color:blue;">Buy (Create trade)</mark>
* <mark style="color:blue;">Reference</mark>
  * <mark style="color:blue;">Supported environments</mark>
  * <mark style="color:blue;">Supported L1 wallets</mark>
  * <mark style="color:blue;">Supported events</mark>
* <mark style="color:blue;">Errors</mark>
* <mark style="color:blue;">Compatibility matrix</mark>
* <mark style="color:blue;">Further documentation</mark>

***

The Wallet SDK provides an easy way to:

* Connect to users' layer 1 Ethereum wallets and generate a layer 2 XpansionChain wallet for them
* Connect to users' layer 1 and layer 2 wallets to get "signers", which you can use to enable users to sign transactions within your application, like to authorise payments or trade assets

The Wallet SDK can then pass those signers to the Core SDK in order to execute functionality that requires the user's authorisation.

It also monitors and returns information about a user's wallet connection, allowing you to manage user sessions.

### Setup[​](https://docs.x.immutable.com/docs/sdks/wallet/web#setup) <a href="#setup" id="setup"></a>

#### Install[​](https://docs.x.immutable.com/docs/sdks/wallet/web#install) <a href="#install" id="install"></a>

The <mark style="color:blue;">Wallet SDK package</mark> can be downloaded via npm command line:

```
npm install @imtbl/wallet-sdk-web --save
```

#### Initialize[​](https://docs.x.immutable.com/docs/sdks/wallet/web#initialize) <a href="#initialize" id="initialize"></a>

It is easy to set up and start using the Wallet SDK:

```
import {
  ENVIRONMENTS,
  L1_PROVIDERS,
  WalletSDK,
} from '@imtbl/wallet-sdk-web';

(async () => {
  // Builds the Wallet SDK object
  const sdk = await WalletSDK.build({
    env: ENVIRONMENTS.STAGING,
    /*
      RPC config is only required if the WalletConnect provider (L1_PROVIDERS.WALLET_CONNECT)
      is being used. Follow this reference for the RPC config:
      https://docs.walletconnect.com/quick-start/dapps/web3-provider#provider-options
    */
    rpc: {
      5: 'https://goerli.mycustomnode.com',
    },
    /*
      Will switch the chain based on this configured chainID when connecting to the wallet.(Optional)
      Following the table below to get the chainID and name mapping. 
      Consult https://chainlist.org/ for more.
      ChainId   | Network
      --- --- | --- --- 
      1       | Ethereum Main Network (Mainnet)
      5       | Goerli Test Network
    */
    chainID: 5,
  });

  // Connects on the chosen provider - WalletConnect
  const walletConnection = await sdk.connect({ provider: L1_PROVIDERS.WALLET_CONNECT });
  // For Metamask:
  // const walletConnection = await sdk.connect({ provider: L1_PROVIDERS.METAMASK });

  // Register the user using the Core SDK
  await coreSdkWorkflows.registerOffchain(walletConnection);
})();
```

NOTE

The `coreSdkWorkflows` object setup was omitted for brevity.\
Check out the <mark style="color:blue;">Workflows examples</mark> to get examples of how to set up the Core SDK workflows.

TIP

The object `WalletConnection` can also be retrieved in the following ways:

```
// By calling the method `getWalletConnection`
const walletConnection = sdk.getWalletConnection();

// By listening to the event `WALLET_SDK_EVENTS.CONNECTION_UPDATED`
walletSdkEvents.on(
  WALLET_SDK_EVENTS.CONNECTION_UPDATED,
  (updatedWalletConnection: WalletConnection) =>
    { const walletConnection = updatedWalletConnection; },
);
```

### Events[​](https://docs.x.immutable.com/docs/sdks/wallet/web#events) <a href="#events" id="events"></a>

Events are a really powerful tool that can be used for a sort of different scenarios. Find below some different examples on how to control the application flow using the events provided by the Wallet SDK.

NOTE

Check out the <mark style="color:blue;">Supported events reference</mark> to get the complete list of events.

#### Ensuring an up-to-date connection[​](https://docs.x.immutable.com/docs/sdks/wallet/web#ensuring-an-up-to-date-connection) <a href="#ensuring-an-up-to-date-connection" id="ensuring-an-up-to-date-connection"></a>

It is important that applications have the most recent wallet connected for each user, to ensure that functions behave as expected. There may be instances where users change wallets or have two wallets connected, so the below code ensures the connection is up to date.

```
import {
  WALLET_SDK_EVENTS,
  WalletConnection,
  walletSdkEvents,
} from '@imtbl/wallet-sdk-web';
import { Workflows } from '@imtbl/core-sdk';

// Defines a simple state interface
type UserWallet = {
  connection: WalletConnection | null,
}

// Creates the state
let userWallet: UserWallet = {
  connection: null,
};

// Defines the function to update the state
function updateUserWallet(newUserWallet: UserWallet) {
  userWallet = newUserWallet;
}

// Listens for connection update notifications and when triggered, updates the state
walletSdkEvents.on(
  WALLET_SDK_EVENTS.CONNECTION_UPDATED,
  (updatedWalletConnection: WalletConnection) =>
    updateUserWallet({ connection: updatedWalletConnection }),
);

// Listens for disconnection notifications and when triggered, cleans the state up
walletSdkEvents.on(
  WALLET_SDK_EVENTS.WALLET_DISCONNECTED,
  () => updateUserWallet({ connection: null }),
);

// Provides a function to register a user with the up-to-date connection
async function registerUser(coreSdkWorkflows: Workflows) {
  const { connection } = userWallet;

  if (!connection) throw new Error('There is still no wallet connection available.');

  await coreSdkWorkflows.registerOffchain(connection);
}
```

#### Handling screen statuses[​](https://docs.x.immutable.com/docs/sdks/wallet/web#handling-screen-statuses) <a href="#handling-screen-statuses" id="handling-screen-statuses"></a>

It is useful for users to understand the status of their wallet (e.g Connected/disconnected). The below code allows developers to return the wallet status:

```
import {
  WALLET_SDK_EVENTS,
  walletSdkEvents,
} from '@imtbl/wallet-sdk-web';

// Defines possible wallet statuses
enum WalletStatus {
  CONNECTED = 'Connected',
  DISCONNECTED = 'Disconnected'
}

// Creates the state
let walletStatus = WalletStatus.DISCONNECTED;

// Listens for connection update notifications and when triggered, updates the state
walletSdkEvents.on(
  WALLET_SDK_EVENTS.CONNECTION_UPDATED,
  (_) => { walletStatus = WalletStatus.CONNECTED; },
);

// Listens for disconnection notifications and when triggered, updates the state
walletSdkEvents.on(
  WALLET_SDK_EVENTS.WALLET_DISCONNECTED,
  () => { walletStatus = WalletStatus.DISCONNECTED; },
);

// Provides a function to get the current status
function getWalletStatus(): WalletStatus {
  return walletStatus;
}
```

### Workflows[​](https://docs.x.immutable.com/docs/sdks/wallet/web#workflows) <a href="#workflows" id="workflows"></a>

The Wallet SDK was designed to work in tandem with Core SDK and, as such, you can use the signers provided by the Wallet SDK to perform the workflows available in the Core SDK. Below you can find some examples of how to use the Wallet SDK to perform some of the workflows.

NOTE

The following examples use a Core SDK package version compatible with Wallet SDK integration. Check out the <mark style="color:blue;">Compatibility matrix</mark> to get versions of the Core SDK which currently accepts Wallet SDK integration.

#### Buy (Create trade)[​](https://docs.x.immutable.com/docs/sdks/wallet/web#buy-create-trade) <a href="#buy-create-trade" id="buy-create-trade"></a>

```
import {
  ENVIRONMENTS,
  L1_PROVIDERS,
  WALLET_SDK_EVENTS,
  WalletConnection,
  walletSdkEvents,
  WalletSDK,
} from '@imtbl/wallet-sdk-web';
import {
  getConfig,
  Workflows,
  GetSignableTradeRequest,
} from '@imtbl/core-sdk';

// Creates the state
const state : { walletConnection: WalletConnection | null; } =
  { walletConnection: null };

// Listens for connection update notifications and when triggered, updates the state
walletSdkEvents.on(
  WALLET_SDK_EVENTS.CONNECTION_UPDATED,
  (updatedWalletConnection: WalletConnection) =>
    { state.walletConnection = updatedWalletConnection; },
);

// Listens for disconnection notifications and when triggered, cleans the state up
walletSdkEvents.on(
  WALLET_SDK_EVENTS.WALLET_DISCONNECTED,
  () => { state.walletConnection = null; },
);

// Provides a function to build the Wallet SDK and connect on the chosen provider
async function setupWalletSDK(): Promise<WalletConnection> {
  const sdk = await WalletSDK.build({ env: ENVIRONMENTS.STAGING });

  return await sdk.connect({ provider: L1_PROVIDERS.METAMASK });
}

// Provides a function to build the Core SDK workflows
function setupCoreSDKWorkflows(): Workflows {
  const coreSdkConfig = getConfig({
    coreContractAddress: '0x7917eDb51ecD6CdB3F9854c3cc593F33de10c623',
    registrationContractAddress: '0x1C97Ada273C9A52253f463042f29117090Cd7D83',
    chainID: 5, // Goerli
    basePath: 'https://api.sandbox.x.XpansionChain.com',
  });

  return new Workflows(coreSdkConfig);
}

// Provides a function to execute the Create Trade workflow
async function createTrade(
  walletConnection: WalletConnection,
  coreSdkWorkflows: Workflows,
  tradeRequest: GetSignableTradeRequest,
) {
  if (!walletConnection) throw new Error('There is still no wallet connection available.');

  await coreSdkWorkflows.registerOffchain(walletConnection);

  const createTradeResponse =
    await coreSdkWorkflows.createTrade(
      walletConnection,
      tradeRequest,
    );

  console.log(createTradeResponse);
}

(async () => {
  state.walletConnection = await setupWalletSDK();

  const coreSdkWorkflows = setupCoreSDKWorkflows();

  const fakeTradeRequest = {
    user: '0x00', // Ethereum address of the submitting user
    order_id: 1000, // The ID of the maker order involved
  };

  const { walletConnection } = state;

  await createTrade(walletConnection, coreSdkWorkflows, fakeTradeRequest);
})();
```

### Reference[​](https://docs.x.immutable.com/docs/sdks/wallet/web#reference) <a href="#reference" id="reference"></a>

#### Supported environments[​](https://docs.x.immutable.com/docs/sdks/wallet/web#supported-environments) <a href="#supported-environments" id="supported-environments"></a>

To facilitate the environment changes, there is a provided list of enums that helps to control the environments/networks used.

* `ENVIRONMENTS.DEVELOPMENT` For local development infrastructure. Usually combined with the Ropsten/Goerli Ethereum network.
* `ENVIRONMENTS.STAGING` For testing and validation infrastructure. Usually combined with the Ropsten/Goerli Ethereum network.
* `ENVIRONMENTS.PRODUCTION` For the live and fresh daily basis infrastructure. Usually combined with the Mainnet Ethereum network.

ROPSTEN DEPRECATION

Ropsten network is set to be deprecated in the near future.

#### Supported L1 wallets[​](https://docs.x.immutable.com/docs/sdks/wallet/web#supported-l1-wallets) <a href="#supported-l1-wallets" id="supported-l1-wallets"></a>

* `L1_PROVIDERS.WALLET_CONNECT` To connect using <mark style="color:blue;">WalletConnect.</mark>
* `L1_PROVIDERS.METAMASK` To connect using <mark style="color:blue;">MetaMask.</mark>

NOTE

XpansionChain does not recommend the use of hardware wallets, as some of them have non-deterministic signing. Please inform your users to select a soft wallet when connecting.

#### Supported events[​](https://docs.x.immutable.com/docs/sdks/wallet/web#supported-events) <a href="#supported-events" id="supported-events"></a>

To help keep the application up to date with possible wallet changes externally triggered by the user, the Wallet SDK uses the event system to provide meaningful indications of its current state through the emitter `walletSdkEvents` and the enum `WALLET_SDK_EVENTS`. Check out below the current list of events.

* `WALLET_SDK_EVENTS.CONNECTION_UPDATED` When the user connects a fresh wallet or opens the application with a wallet already connected before.
* `WALLET_SDK_EVENTS.WALLET_DISCONNECTED` When the user disconnects the wallet on purpose, changes the wallet itself or changes the network.

NOTE

Check out the <mark style="color:blue;">Events examples</mark> for code examples.

### Errors[​](https://docs.x.immutable.com/docs/sdks/wallet/web#errors) <a href="#errors" id="errors"></a>

Refer to the following list for the most common errors raised by the Wallet SDK and to get a guidance on how to solve them.

| Error message                                                              | Scenario                                                                                                  | Solution                                                                                                                                       |
| -------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| `The L1 provider {L1Provider} is not a valid option.`                      | When an invalid L1 provider option was informed when calling `connect()`.                                 | Provide a valid L1 provider option based on the <mark style="color:blue;">Supported L1 wallets.</mark>                                         |
| `The MetaMask provider was not found.`                                     | When a `connect()` using MetaMask was attempted but most likely the MetaMask extension was not installed. | Install the MetaMask extension or provide another valid L1 provider option based on the <mark style="color:blue;">Supported L1 wallets</mark>. |
| `You cannot connect to WalletConnect Provider because RPC is not defined.` | When a `connect()` using WalletConnect was attemped but the RPC was not provided.                         | Provide the RPC based on the <mark style="color:blue;">Quickstart example.</mark>                                                              |
| `The L2 IMX Wallet connection has failed.`                                 | When a `connect()` was attempted on L2 but did not succeed.                                               | Retry a connection, and if the error persists, <mark style="color:blue;">contact the support team.</mark>                                      |

### Compatibility matrix[​](https://docs.x.immutable.com/docs/sdks/wallet/web#compatibility-matrix) <a href="#compatibility-matrix" id="compatibility-matrix"></a>

|            Core SDK version            |           Wallet SDK version           |
| :------------------------------------: | :------------------------------------: |
| <mark style="color:blue;">0.7.0</mark> | <mark style="color:blue;">0.1.8</mark> |
| <mark style="color:blue;">0.7.0</mark> | <mark style="color:blue;">0.1.9</mark> |

### Further documentation[​](https://docs.x.immutable.com/docs/sdks/wallet/web#further-documentation) <a href="#further-documentation" id="further-documentation"></a>

Check out the <mark style="color:blue;">UI guide for implementing user wallet interactions.</mark>

* See the <mark style="color:blue;">Developer homepage</mark> for general information on building on XpansionChain.
* Build on XpansionChain zkEVM:
  * <mark style="color:blue;">Documentation</mark>
  * <mark style="color:blue;">API reference</mark>
  * <mark style="color:blue;">Support</mark>
* Build on XpansionChain:
  * <mark style="color:blue;">Documentation</mark>
  * <mark style="color:blue;">API reference</mark>
  * <mark style="color:blue;">Support</mark>


---

# 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://xpansionchain-1.gitbook.io/xpansionchain/sdks/wallet-sdk/web.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.
