# Session signing with SignX

> Log a user in and sign transactions from a browser app with the IXO SignX SDK. The user scans one QR code with the Impacts X mobile wallet, then signs in turn.

Use this guide when your web app needs a user to log in and sign transactions, and the user's keys
are in their Impacts X mobile wallet. Your app shows a QR code, the user scans it with the
Impacts X app, and the IXO SignX SDK (`@ixo/signx-sdk`) long-polls a relayer server until the
wallet returns a login payload or a signed and broadcast transaction.

Once a transaction session is open, you add more transactions to the same session without scanning
the QR code again. The wallet activates the next transaction in sequence on each broadcast. This is
the publicly documented signing path. The browser holds no private key, and every signature comes
from the user's mobile wallet.

<Warning>
  Illustrative example. The code on this page shows the shape of each call. It is not a tested
  project you can run as written: you supply the relayer endpoint, the user and the transaction. Try
  it on a test network first.
</Warning>

## Before you start

You need:

- A web app (React or other) running over HTTPS.
- A reachable [`ixo-message-relayer`](https://github.com/ixofoundation/ixo-message-relayer)
  endpoint, or an IXO-operated equivalent for your network. See
  [Networks and endpoints](/reference/networks-and-endpoints).
- The Impacts X mobile app, installed by your user from the
  [App Store](https://apps.apple.com/app/impacts-x/id6444948058) or the
  [Play Store](https://play.google.com/store/apps/details?id=com.ixo.mobile).
- `@ixo/signx-sdk` and the IXO MultiClient SDK (`@ixo/impactxclient-sdk`) installed:

```bash
npm install @ixo/signx-sdk @ixo/impactxclient-sdk
```

## Steps

### 1. Create the SignX client

Illustrative example:

```ts
import { SignX } from "@ixo/signx-sdk";

const signXClient = new SignX({
  endpoint: "https://your-message-relayer.example.com",
  sitename: "Your dApp",
  network: "mainnet",
});
```

`network` is one of `mainnet | testnet | devnet`. The user sees the `sitename` inside the Impacts X
app on every confirmation.

### 2. Log the user in

`login()` returns the QR payload to render and starts long-polling for the wallet's response.
Subscribe to `SIGN_X_LOGIN_SUCCESS` and `SIGN_X_LOGIN_ERROR` to receive the result.

Illustrative example:

```ts
const loginRequest = await signXClient.login({ matrix: true });

signXClient.on("SIGN_X_LOGIN_SUCCESS", (event) => {
  const { name, address, pubKey, did, algo, matrix } = event.data;
  // persist the user; pubKey is hex-encoded, decode if you need bytes.
});

signXClient.on("SIGN_X_LOGIN_ERROR", (error) => {
  // user cancelled, polling timed out, or the wallet returned an error.
});
```

On a mobile device, pass `{ useDeeplink: true }`. The SDK then opens the Impacts X app through a
deeplink before it starts polling. This stops some mobile browsers from cancelling the long-polling
request when the user leaves the page.

### 3. Sign and broadcast a transaction

Build the transaction body with the `@ixo/impactxclient-sdk` registry, then pass the hex-encoded
`txBody` to `signXClient.transact()`. The wallet signs the transaction and broadcasts it for the
user.

Illustrative example:

```ts
import { createRegistry, ixo } from "@ixo/impactxclient-sdk";
import { toHex } from "@cosmjs/encoding";

const registry = createRegistry();

const messages = [
  {
    typeUrl: "/ixo.entity.v1beta1.MsgCreateEntity",
    value: ixo.entity.v1beta1.MsgCreateEntity.fromPartial({
      ownerAddress: user.address,
      entityType: "asset",
      context: [],
      verification: [],
      controller: [],
      service: [],
      linkedResource: [],
      accordedRight: [],
      linkedEntity: [],
      linkedClaim: [],
    }),
  },
];

const txBodyHex = toHex(registry.encodeTxBody({ messages, memo: "" }));

const transactRequest = await signXClient.transact({
  address: user.address,
  did: user.did,
  pubkey: user.pubKey,
  timestamp: new Date().toISOString(),
  transactions: [{ sequence: 1, txBodyHex }],
});

signXClient.on("SIGN_X_TRANSACT_SUCCESS", (event) => {
  // event.data.transactionHash, event.data.code (0 on success)
});

signXClient.on("SIGN_X_TRANSACT_ERROR", (error) => {
  // wallet rejected, broadcast failed, or session timed out.
});
```

What you do next depends on `transactRequest.sessionHash`:

- If it is present, a new session was opened. Render a QR code with `transactRequest`.
- If it is absent, the transaction was added to the existing session. Call
  `signXClient.pollNextTransaction()` and show the user that the next signature is waiting in their
  wallet.

The wallet returns the chain's broadcast result (`code`, `transactionHash`, …) directly through
`SIGN_X_TRANSACT_SUCCESS`.

### 4. Manage the session

Every transaction extends the session's `validUntil` timestamp. Read
`signXClient.transactSessionHash` to know whether a session is active, and
`signXClient.transactSequence` for the sequence the wallet is being asked to sign.

Illustrative example:

```ts
window.addEventListener("beforeunload", () => {
  signXClient.stopPolling("Page closing", "SIGN_X_TRANSACT_ERROR");
});
```

Sessions are deliberately not kept across a browser refresh. `transactSessionHash` lives in memory
only. After a refresh, the next `transact()` call starts a new session and renders a fresh QR code.

## Check the result

`SIGN_X_TRANSACT_SUCCESS` returns the transaction hash. To verify it independently, query
`cosmos.tx.v1beta1.GetTx` on the [gRPC gateway API](/api-reference/grpc-gateway-api) with that
hash, or fetch the transaction from the
[Blocksync GraphQL API](/api-reference/blocksync-graphql-api).

## Restrict what a session can sign

The wallet enforces which message types a session can sign. The Impacts X app checks each
transaction body against the user's saved policy before it signs. The web SDK applies no filter of
its own.

To limit what your app asks a session to sign, build the txBody only for the message types your
flow needs, and refuse to call `transact()` for anything else. For enforcement on chain, pair this
with smart-account authenticators. See [Manage smart accounts](/guides/dev/smart-accounts).

When you build a `MsgGrant` (`cosmos.authz.v1beta1.MsgGrant`) with a `GenericAuthorization`, the
`msg` field is the fully qualified message URL, for example `/ixo.entity.v1beta1.MsgCreateEntity`.
The same convention applies everywhere transaction filtering is configured.

## When something goes wrong

### The QR code never resolves

Confirm that `endpoint` points to a reachable Message Relayer for the same `network` as the user's
wallet, and that `network` matches the chain the user logged in on. Check that the relayer is
healthy.

### Long-polling is cancelled on mobile

Mobile browsers may cancel ongoing requests when navigating to deeplinks. Pass `useDeeplink: true`
to `login`, `matrixLogin`, `dataPass`, and as the third argument to `transact`, so the SDK opens
the deeplink first and waits 300 ms before polling.

### The wallet rejected the transaction

The wallet may reject a transaction if the message type is outside the user's signing policy, the
chain ID does not match, or the user denies it. `SIGN_X_TRANSACT_ERROR` carries the reason. Send
the transaction again after the user adjusts their policy.

### The session expired mid-flow

`transactSessionHash` is cleared when the relayer reports that the session expired. The next
`transact()` call starts a new session, so tell the user that a fresh QR code is needed. To stop
polling without clearing the session, call `stopPolling(message, event, false)`.

## Next steps

<CardGroup cols={2}>
  <Card title="IXO SignX SDK reference" icon="key" href="/sdk-reference/signx-sdk">
    Methods, events and types.
  </Card>
  <Card title="SignX SDK README" icon="github" href="https://github.com/ixofoundation/ixo-signx#readme">
    The SDK's own documentation, in its repository.
  </Card>
  <Card title="Manage smart accounts" icon="user-shield" href="/guides/dev/smart-accounts">
    Add on-chain enforcement of which message types may be signed.
  </Card>
  <Card title="Manage authz grants and fee allowances" icon="lock" href="/guides/dev/authz">
    Combine SignX with Cosmos `x/authz` and `x/feegrant`.
  </Card>
</CardGroup>
