# Integrating the EXTRA SAFE Chat widget

The widget drops end-to-end encrypted 1:1 chat and in-chat stablecoin transfers
into your web product. One script tag, one `init()` call. Your server never sees
keys, mnemonics or message content — only the transfer events your users agree
to share. This is the document your developers read; the full type surface is in
[`extrasafe-widget.d.ts`](./extrasafe-widget.d.ts).

Everything is **additive and backward-compatible**: the two-tag synchronous
embed still works, and every new capability is opt-in.

---

## 1. Quick start (5 minutes, demo mode)

Paste two tags. With no `endpoints` configured the widget runs in **demo mode**:
a fully usable, in-browser simulated network — no backend, no accounts to set up.

```html
<script src="https://widget.extrasafe.net/v0/widget.js"></script>
<script>
  ExtraSafe.init({
    host: "yourhost",
    brand: { name: "Your Brand", accentColor: "#0b5fff" }
  });
</script>
```

A floating **Messages** button appears. Activate (Create / Import), message a
demo counterparty, send a demo transfer.

### Async loader (non-blocking)

For production, load `widget.js` with `async` using the stub-and-queue snippet so
it never blocks first paint. Calls made before the script finishes loading are
queued and replayed. The ready-made snippet is served at
`https://widget.extrasafe.net/loader-snippet.html`; it looks like:

```html
<script>
  (function (w, d) {
    if (w.ExtraSafe && w.ExtraSafe._q) return;
    var q = []; var chain = function (n){ return function(){ q.push([n,[].slice.call(arguments)]); return w.ExtraSafe; }; };
    var api = { _q: q };
    ['init','open','close','toggle','openChatWith','startTransferTo','activate','setMembers','logout','on','destroy']
      .forEach(function (m){ api[m] = chain(m); });
    w.ExtraSafe = api;
    var s = d.createElement('script'); s.async = true; s.src = 'https://widget.extrasafe.net/v0/widget.js';
    d.head.appendChild(s);
  })(window, document);

  ExtraSafe.init({ host: "yourhost", brand: { name: "Your Brand" } });
</script>
```

### Versioned URLs and SRI

| URL | Cache | Use |
| --- | --- | --- |
| `/widget.js` | short | convenience / demos |
| `/v0/widget.js` | short | pin the major; receives compatible updates |
| `/v0.2.0/widget.js` | **immutable** | pin the exact build |

Hashes for Subresource Integrity are published at
[`/integrity.json`](https://widget.extrasafe.net/integrity.json):

```html
<script
  src="https://widget.extrasafe.net/v0.2.0/widget.js"
  integrity="sha384-…from integrity.json…"
  crossorigin="anonymous"></script>
```

---

## 2. Bind your signed-in user

Pass the host user. This **namespaces the browser key store** to that user
(`wallet-blob:{host}:{platformUserId}`), so two of your users on one browser
profile never share a wallet, and it pre-fills the activation nickname.

```js
ExtraSafe.init({
  host: "yourhost",
  brand: { name: "Your Brand" },
  user: { platformUserId: currentUser.id, displayName: currentUser.name },
  mode: "live",
  endpoints: { serverUrl: "https://your-server.example" }
});
```

- On sign-out call `ExtraSafe.logout()` (clears the in-memory wallet and
  disconnects; keeps the PIN-wrapped blob so the same user can unlock again).
- On user switch, call `init()` again with the new `user`.
- **Key your users on `address`, not ESID.** In demo mode the ESID is a local
  placeholder; in live mode it is the server's canonical ESID taken from
  `GET /users/me`. The wallet address is the stable identifier across both.

---

## 3. Your own buttons

Mark up your existing elements — one delegated listener wires them, including
elements added after `init()`:

```html
<button data-extrasafe-message="0x71C7…9A3f">Message</button>
<button data-extrasafe-pay="0x71C7…9A3f"
        data-amount="2500" data-token="USDT" data-network="BNB Smart Chain"
        data-reference="D-1042">Pay</button>
<button data-extrasafe-open>Open Messages</button>
```

Or imperatively:

```js
ExtraSafe.openChatWith(addressOrEsid);
ExtraSafe.startTransferTo(addressOrEsid, {
  amount: "2500", token: "USDT", network: "BNB Smart Chain",
  reason: "Deal D-1042", reference: dealId   // reference is opaque, echoed back
});
```

An action issued before the user has activated is remembered and completed the
moment they activate.

### Members

Pass your community so counterparties are suggested with their KYC chip; replace
the list at runtime without re-mounting:

```js
ExtraSafe.init({ /* … */ members });
ExtraSafe.setMembers(updatedMembers); // e.g. on directory refresh
```

A member with `esid`/`address` is on the network ("Message"); without, the
widget offers "Invite". Members are only ever *suggested* — adding one is always
a consent-gated contact request.

---

## 4. Receiving transfers — and what to verify server-side

When an in-chat transfer completes and the user consented to share it, you get a
`TransferEvent`:

```js
ExtraSafe.init({
  /* … */
  onTransfer: (e) => fetch("/api/ledger", { method: "POST", body: JSON.stringify(e) })
});
```

```ts
interface TransferEvent {
  txHash: string; amount: string; token: string; network: string;
  from: string; to: string; reason: string; timestamp: number;
  counterpartyPlatformUserId?: string; // your member id, when known
  reference?: string;                  // your opaque reference, echoed back
  sandbox?: boolean;                   // true when simulated (no chain)
}
```

**`onTransfer` is a browser callback — treat it as a claim, not proof.** Before
you credit anything, verify on your server:

1. The session user owns `from` (see §5, identity binding).
2. `e.txHash` exists on `e.network` and is an ERC-20 `Transfer(from,to,value)`
   from the expected token contract matching `from`, `to` and `amount`. Match on
   the **logs**, not `tx.from` — the account is an EIP-7702 / ERC-4337 wallet and
   a relayer submits the transaction.
3. If `e.sandbox` is true, it was simulated — never credit it as real funds.

A production integration should additionally receive a signed server-to-server
webhook; that is on the roadmap and not part of the widget today.

---

## 5. Proof of address ownership (identity binding)

Don't trust the address reported in `onActivate`. Challenge the widget to sign a
nonce and verify the signature on your server.

```js
// client
const challenge = await fetch("/api/challenge").then(r => r.json()); // { nonce }
const proof = await ExtraSafe.proveIdentity(challenge.nonce);
await fetch("/api/bind", { method: "POST", body: JSON.stringify(proof) });
// proof = { address, message, signature }
```

```ts
// server (ethers v6)
import { verifyMessage } from "ethers";
const recovered = verifyMessage(proof.message, proof.signature);
const ok =
  recovered.toLowerCase() === proof.address.toLowerCase() &&
  proof.message.startsWith("EXTRA SAFE Chat host binding") &&
  proof.message.includes(`nonce: ${issuedNonce}`) &&
  proof.message.includes(`host: ${yourHostId}`) &&
  proof.message.includes(`origin: ${yourOrigin}`);
```

The signed message is a fixed, human-readable template (not valid JSON, constant
prefix) so it can never collide with the login signature. Reject reused or
expired nonces, and reject an address already bound to another user.

---

## 6. Consent

Two toggles the user controls, surfaced in activation and settings:

- **Show me to my counterparties** — honour this in your own directory.
- **Send my transfers to this platform's ledger** — gates `onTransfer`.

Both persist per user and are reported on change:

```js
ExtraSafe.on("consent", (c) => {
  // c = { shareWithCounterparties, shareTransfersToLedger }
  if (!c.shareWithCounterparties) hideFromDirectory(currentUser.id);
});
```

If a user turns off ledger sharing, no `onTransfer` arrives for their sends — do
not work around that.

---

## 7. Modes

| | `mode` | `wallet` | Chat | Transfers |
| --- | --- | --- | --- | --- |
| Demo | `demo` | `sandbox` | simulated, in-browser | simulated |
| Sandbox | `live` | `sandbox` | real backend | simulated (`sandbox: true`) |
| Live | `live` | `live` | real backend | real on-chain |

`wallet` is independent of `mode`: you can run real chat with simulated
transfers (the default for a public demo). Sandbox transfers are badged in the
UI and flagged on the event.

---

## 8. Inline mount

Render the panel inside your own element (a chat column on a deal page) instead
of a floating launcher:

```js
ExtraSafe.init({ /* … */ container: "#deal-chat" });   // selector or HTMLElement
```

No launcher, no fixed positioning; `open()`/`close()` become no-ops. To keep the
floating panel but drive it from your own nav button, use `launcher: false` and
call `open()` yourself; badge your button from the `unread` event.

---

## 9. Content-Security-Policy

The widget injects one `<style>` into its shadow root. For a strict policy:

- `script-src https://widget.extrasafe.net` (the widget origin)
- `connect-src https://your-server wss://your-server` (REST + WebSocket, live mode)
- `style-src 'nonce-…'` — pass the same nonce to the widget:

```js
ExtraSafe.init({ /* … */ nonce: "<your-csp-nonce>" });
```

---

## 10. Events and error codes

```js
const off = ExtraSafe.on("ready", () => {});   // fires once, at mount
ExtraSafe.on("activate", (info) => {});          // { platformUserId?, esid, address? }
ExtraSafe.on("transfer", (e) => {});             // same payload as onTransfer
ExtraSafe.on("open", () => {});
ExtraSafe.on("close", () => {});
ExtraSafe.on("unread", (n) => {});               // total unread, badge your nav
ExtraSafe.on("consent", (c) => {});
ExtraSafe.on("error", (err) => {});              // ExtraSafeError, see codes
off(); // unsubscribe
```

`ExtraSafe.getState()` → `{ mounted, activated, locked, open, address?, esid?,
unread, consent, mode, wallet, version }`.

Error codes (`err.code`): `transport_connect`, `chat_open`, `send`, `transfer`,
`activation`, `identity`, `config`.

---

## 11. Going live — checklist

- [ ] Set `mode: "live"` and `endpoints: { serverUrl }`.
- [ ] Decide `wallet`: `sandbox` for staging, `live` for real funds.
- [ ] Pass `user: { platformUserId, displayName }`; key your records on `address`.
- [ ] Pass your `members`; refresh with `setMembers()`.
- [ ] Add an endpoint that receives `onTransfer` and **verifies `txHash`
      on-chain** before crediting.
- [ ] Add identity binding (§5): challenge → `proveIdentity` → verify server-side.
- [ ] Honour both consent toggles.
- [ ] Ensure your server allows your origin(s) in its CORS / WebSocket allowlist.
- [ ] Set CSP directives (§9); pass `nonce` if `style-src` is locked down.
- [ ] Pin a version (`/v0/…` or an exact `/v0.2.0/…` with SRI).

---

## Not supported yet

TRON, group chat, calls in the widget, approvals, multisig, escrow, and a signed
server-to-server transfer webhook. The browser key storage is awaiting a
security review before a real launch.
