XE Connect for native apps
How an iOS or Android app gets a person's XE account and a spend permission in one wallet visit, by app link, with the answer sealed to the app.
A native app never holds a wallet key. It makes its own key K, sends the person to their wallet once, and gets back two things: the account they chose and a spend permission that lets K pay for services from that account, within limits the wallet showed them. Later, one more visit ends the permission.
There are three ways to reach a wallet:
| Wallet | The app sends | The answer comes back |
|---|---|---|
| XE Web Wallet | A link to https://wallet.xe.marketized.io/connect/app with the request in the fragment | A redirect to the app's https return link, sealed to a one-use key the app made |
| XE Wallet on the same phone | XE Connect's relay pairing link, with a return link b | Over the relay; the wallet then opens b to bring the person back |
| XE Vault (offline) | QR codes on the app's screen | QR codes on XE Vault's screen, which the app scans |
This page covers the first two. The request and the answer are the same JSON in every case, so an app that handles the link can add the others later.
#Before you start
The XE Web Wallet answers only apps on its own list. Each entry names the app's origin, the paths its return links may use and its iOS app IDs. A request from any other origin is refused on the wallet's page and nothing is sent anywhere. To have an app added, send XE:
- the
httpsorigin of the app's site; - the return paths, for example
/m/(any path below it) and/connect/return; - the iOS app IDs (team ID and bundle ID) and the Android package names with their signing certificate fingerprints.
The wallet shows the app by the name on its list, never by the name in the request.
#Universal links and App Links
The answer travels in the fragment of an https URL on your own site. iOS hands that URL only to the app that your site's apple-app-site-association names, and Android only to the app your assetlinks.json names. Serve both from /.well-known/, as application/json, without redirects.
// https://your.app/.well-known/apple-app-site-association{ "applinks": { "details": [ { "appIDs": ["TEAMID.com.example.app"], "components": [ { "/": "/m/*", "comment": "A wallet hands the person back" }, { "/": "/connect/return" }, { "/": "/connect/return/*" } ] } ] }, "webcredentials": { "apps": ["TEAMID.com.example.app"] }}// https://your.app/.well-known/assetlinks.json[ { "relation": ["delegate_permission/common.handle_all_urls"], "target": { "namespace": "android_app", "package_name": "com.example.app", "sha256_cert_fingerprints": ["AB:CD:…"] } }]In the app, add applinks:your.app (and webcredentials:your.app if you use passkeys) to the Associated Domains entitlement. On Android, add an intent filter with android:autoVerify="true" for the same host and paths.
Serve the return paths on the web as plain pages without script: if the app isn't installed, the browser opens the page, and nothing on it may read the fragment.
XE AI Chat's files are a working reference: apple-app-site-association and assetlinks.json.
#The request
The app opens:
https://wallet.xe.marketized.io/connect/app#xeca=1&req=<base64url of the request JSON>On iOS, open it in an ASWebAuthenticationSession with an https callback on your domain. On Android, open it in a Custom Tab; your App Link receives the return.
{ "xeca": 1, "id": "<16 random bytes, base64url: 22 characters>", "origin": "https://your.app", "name": "Your App", "return": "https://your.app/m/wallet", "answerKey": "<P-256 public key, 65 bytes uncompressed, base64url>", "expires": 1792500000000, // unix ms, at most 10 minutes ahead "network": "xenet:xe-sim-0002", "kind": "grant", "connect": { "families": ["sim"], "request": ["xe:permissions@1", "xe:permissions@2"], "app": { "name": "Your App" } }, "grant": { "network": "xenet:xe-sim-0002", "key": "<K: 64 hex>", "permission": "<xe-permission:v1 text>", "label": "Your App" }}| Member | Rule |
|---|---|
id | 16 random bytes, base64url without padding |
origin | Your site's https origin, on the default port |
return | An https URL on origin, under one of your return paths, with no query |
answerKey | A fresh P-256 key for this request only. Keep the private half in memory and drop it after one answer |
expires | Unix milliseconds, no more than 10 minutes ahead. The wallet allows 60 seconds of clock skew |
network | xenet:xe-sim-0002 for XE Sim Interop. connect.families is ["sim"] for it |
kind | grant, revoke or sign, with exactly the member of that name |
The whole URL must stay under 8 KiB. A permission text is at most 1024 bytes.
#Kinds
grant connects one account and asks for a spend permission for K. connect holds xe_connect's parameters; grant holds xe_grantPermissions' parameters without address, because the account is the one the person picks in this visit. The permission text is described in Spend permissions. Its issuer line must be your origin's host.
revoke ends a permission. revoke holds xe_revokePermissions' parameters: { address, network, id, key }. The wallet reviews it like any revoke and publishes it itself, because ending a key can't be abused.
sign asks the account the app already connected to sign one to three exact texts. Only XE's sync messages are accepted: every text must start with xe-sync: and be at most 1024 characters. Each text goes through the wallet's own review, which holds a sync message to the site it names. If the wallet in this browser hasn't connected that account to the app yet, it connects first, and only that account may sign.
"kind": "sign","sign": { "address": "<64 hex>", "messages": ["xe-sync:grant:v1:your.app:…", "xe-sync:unlock:v1:your.app:…"] }#Sign in with Apple or Google first
A person who has no wallet yet can create one on the wallet's page with Apple or Google. Add signin after req:
https://wallet.xe.marketized.io/connect/app#xeca=1&req=<…>&signin=applesignin is apple or google. It is outside req on purpose: it only tells the page how to start, and it isn't part of what the answer is sealed to.
- With no wallet in that browser, the page opens on that provider's sign-in (one tap; a browser opens a provider's window only after a click), then goes on to the review. The other provider is offered beside it, at the same size.
- With a wallet already there,
signinis ignored and the person unlocks as usual. - Your app holds no part of that wallet's key and links no provider SDK.
#A new account on the test network
A permission is a block on the person's account, and a new account has no block yet. So, when the account is new and the network is a test network, the page asks the network's faucet for test XE and receives it before the review ("Opening your account with test XE"). The app's first paid request can then go through at once.
If the faucet says no (busy, the day's cap, or a limit per connection or account), the page answers with the account and an error in grant:
{ "kind": "grant", "connect": { "accounts": [ … ] }, "grant": { "error": { "code": 4900, "message": "…", "data": { "reason": "faucet" } } } }Nothing is granted. Tell the person to try again in a few minutes or to use a wallet that already has test XE. On a network with real value there is no faucet: the page says the account needs a first payment.
#The answer
The wallet redirects to your return link with one of:
<return>#xeca=1&id=<id>&ans=<base64url(enc ‖ ciphertext)> the sealed answer<return>#xeca=1&id=<id>&error=<token> the wallet stopped before it could answerAn unsealed error grants nothing. Its token is invalid-request or expired. Show "The wallet didn't finish" and let the person start again.
ans is HPKE (RFC 9180) base mode, single shot, with DHKEM(P-256, HKDF-SHA256), HKDF-SHA256 and AES-256-GCM, sealed to answerKey:
enc | The first 65 bytes: the encapsulated key, uncompressed |
info | xe-connect-app/v1 \n id \n origin \n return, as UTF-8 |
aad | The request's id, as UTF-8 |
The plaintext is JSON:
// grant, approved{ "xeca": 1, "id": "…", "kind": "grant", "connect": { "accounts": [{ "address": "…", "publicKey": "…", "custody": "hot" }], "families": ["sim"], "granted": [ … ] }, "grant": { "id": "…", "proof": { … }, "grantBlock": "…", "expiresAt": 1795000000, "mode": "v2", "payFrom": "…", "enforced": { "node": [ … ], "app": [] }, "blocks": [{ "type": "delegate_set", "hash": "…", "body": "<the signed block as a node takes it>" }] } }// grant: connected, but the permission was declined or refused{ "xeca": 1, "id": "…", "kind": "grant", "connect": { … }, "grant": { "error": { "code": 4001, … } } }// revoke{ "xeca": 1, "id": "…", "kind": "revoke", "revoke": { "revocation": { … }, "revokeBlock": "…" } }// sign{ "xeca": 1, "id": "…", "kind": "sign", "sign": [{ "signature": "…", "publicKey": "…", … }] }// anything else{ "xeca": 1, "id": "…", "kind": "grant", "error": { "code": 4001, "message": "…", "data": { "reason": "declined" } } }Check that id and kind match your request before you read anything else.
#Building the request and opening the answer (TypeScript)
This runs in a browser, React Native with WebCrypto, Deno, or Node 22 and later. It needs nothing but WebCrypto.
const WALLET = "https://wallet.xe.marketized.io";const te = new TextEncoder();const b64url = (b: Uint8Array) => btoa(String.fromCharCode(...b)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");const unb64url = (s: string) => Uint8Array.from(atob(s.replace(/-/g, "+").replace(/_/g, "/")), (c) => c.charCodeAt(0)); export async function makeRequest(o: { origin: string; name: string; returnUrl: string; network: string; kind: "grant" | "revoke" | "sign"; body: object }) { // one-use answer key: the private half never leaves WebCrypto const keys = (await crypto.subtle.generateKey({ name: "ECDH", namedCurve: "P-256" }, false, ["deriveBits"])) as CryptoKeyPair; const answerKey = new Uint8Array(await crypto.subtle.exportKey("raw", keys.publicKey)); const request = { xeca: 1, id: b64url(crypto.getRandomValues(new Uint8Array(16))), origin: o.origin, name: o.name, return: o.returnUrl, answerKey: b64url(answerKey), expires: Date.now() + 5 * 60_000, network: o.network, kind: o.kind, ...o.body, }; const url = `${WALLET}/connect/app#xeca=1&req=${b64url(te.encode(JSON.stringify(request)))}`; return { request, url, privateKey: keys.privateKey, answerKey };} // HPKE base mode: DHKEM(P-256, HKDF-SHA256), HKDF-SHA256, AES-256-GCMconst cat = (...a: Uint8Array[]) => { const o = new Uint8Array(a.reduce((n, x) => n + x.length, 0)); let i = 0; for (const x of a) { o.set(x, i); i += x.length; } return o; };const u16 = (n: number) => Uint8Array.of(n >> 8, n & 255);const hmac = async (key: Uint8Array, data: Uint8Array) => new Uint8Array(await crypto.subtle.sign("HMAC", await crypto.subtle.importKey("raw", key.length ? key : new Uint8Array(32), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]), data));async function expand(prk: Uint8Array, info: Uint8Array, len: number) { let t = new Uint8Array(0), out = new Uint8Array(0); for (let i = 1; out.length < len; i++) { t = await hmac(prk, cat(t, info, Uint8Array.of(i))); out = cat(out, t); } return out.slice(0, len);}const KEM = cat(te.encode("KEM"), u16(0x0010));const SUITE = cat(te.encode("HPKE"), u16(0x0010), u16(0x0001), u16(0x0002));const lExtract = (id: Uint8Array, salt: Uint8Array, label: string, ikm: Uint8Array) => hmac(salt, cat(te.encode("HPKE-v1"), id, te.encode(label), ikm));const lExpand = (id: Uint8Array, prk: Uint8Array, label: string, info: Uint8Array, len: number) => expand(prk, cat(u16(len), te.encode("HPKE-v1"), id, te.encode(label), info), len); export async function openAnswer(returned: string, request: { id: string; origin: string; return: string }, privateKey: CryptoKey, answerKey: Uint8Array) { const p = new URLSearchParams(new URL(returned).hash.slice(1)); if (p.get("xeca") !== "1" || p.get("id") !== request.id) throw new Error("Not an answer to this request"); if (p.get("error")) return { unfinished: p.get("error") }; const sealed = unb64url(p.get("ans")!); const enc = sealed.slice(0, 65), ct = sealed.slice(65); const pub = await crypto.subtle.importKey("raw", enc, { name: "ECDH", namedCurve: "P-256" }, false, []); const dh = new Uint8Array(await crypto.subtle.deriveBits({ name: "ECDH", public: pub }, privateKey, 256)); const none = new Uint8Array(0); const shared = await lExpand(KEM, await lExtract(KEM, none, "eae_prk", dh), "shared_secret", cat(enc, answerKey), 32); const info = te.encode(`xe-connect-app/v1\n${request.id}\n${request.origin}\n${request.return}`); const ctx = cat(Uint8Array.of(0), await lExtract(SUITE, none, "psk_id_hash", none), await lExtract(SUITE, none, "info_hash", info)); const secret = await lExtract(SUITE, shared, "secret", none); const key = await crypto.subtle.importKey("raw", await lExpand(SUITE, secret, "key", ctx, 32), "AES-GCM", false, ["decrypt"]); const iv = await lExpand(SUITE, secret, "base_nonce", ctx, 12); const plain = await crypto.subtle.decrypt({ name: "AES-GCM", iv, additionalData: te.encode(request.id) }, key, ct); const answer = JSON.parse(new TextDecoder().decode(plain)); if (answer.xeca !== 1 || answer.id !== request.id) throw new Error("The answer is for another request"); return { answer };}#Opening the answer (Swift)
CryptoKit has the same HPKE suite (iOS 17 and later):
import CryptoKitimport Foundation func openAnswer(returnedURL: URL, requestID: String, origin: String, returnLink: String, answerKey: P256.KeyAgreement.PrivateKey) throws -> [String: Any] { guard let fragment = returnedURL.fragment else { throw URLError(.badURL) } var items: [String: String] = [:] for pair in fragment.split(separator: "&") { let kv = pair.split(separator: "=", maxSplits: 1).map(String.init) if kv.count == 2 { items[kv[0]] = kv[1] } } guard items["xeca"] == "1", items["id"] == requestID else { throw URLError(.badServerResponse) } if let error = items["error"] { return ["unfinished": error] } guard let sealed = Data(base64URL: items["ans"] ?? ""), sealed.count > 65 else { throw URLError(.cannotDecodeContentData) } let info = Data("xe-connect-app/v1\n\(requestID)\n\(origin)\n\(returnLink)".utf8) var recipient = try HPKE.Recipient(privateKey: answerKey, ciphersuite: .P256_SHA256_AES_GCM_256, info: info, encapsulatedKey: sealed.prefix(65)) let plaintext = try recipient.open(sealed.dropFirst(65), authenticating: Data(requestID.utf8)) let answer = try JSONSerialization.jsonObject(with: plaintext) as! [String: Any] guard answer["id"] as? String == requestID else { throw URLError(.badServerResponse) } return answer} extension Data { init?(base64URL s: String) { var b = s.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/") b += String(repeating: "=", count: (4 - b.count % 4) % 4) self.init(base64Encoded: b) }}Make the key with P256.KeyAgreement.PrivateKey() and send key.publicKey.x963Representation (65 bytes) as answerKey.
#Publish the grant, then check it on XE
Anyone can make a /connect/app link that names your origin and their own key. So the Web Wallet signs the grant but doesn't publish it: grant.blocks holds the signed delegate_set blocks, with their proof of work, and the answer goes only to your return link. Only your app can put the grant in force.
Trust nothing in the answer about XE until XE says it:
- Publish each block in
grant.blocks, in order: POST itsbody, with"hash"added, to<node>/blocks/delegate_set. Wait untilGET <node>/blocks/{hash}serves it. A permission in two assets has two blocks: the XE grant first, then the XUSD one. - Check the proof.
grant.proofis the account's signature over the exact permission text you sent (xe/message/v1), and its address isconnect.accounts[0].address. - Check the mode.
modeisv2andpayFromis that address. - Check the grant.
GET <node>/blocks/{grantBlock}is a finaldelegate_seton that account for K, andGET <node>/accounts/{address}/delegateslists K as active with your text's limits.
Only then keep the grant: the owner, K, the permission's id and text, the grant block and the expiry. After a revoke, check that the delegates list shows K as ended before you forget it.
Over XE Wallet's relay, the wallet publishes the grant before it answers, so step 1 is already done. Steps 2 to 4 are the same.
#XE Wallet on the same phone: the return link b
XE Connect's relay pairing link takes one more optional member, b, after n:
https://xe-ai.marketized.io/m/connect#xec=1&c=…&k=…&s=…&o=https%3A%2F%2Fyour.app&r=…&e=…&n=Your+App&b=https%3A%2F%2Fyour.app%2Fm%2Fbackbmust behttps, on the same origin aso, with a path under/m/and no query or fragment. Otherwise the wallet ignores it and pairs as usual.- When the person has answered (approved, declined or closed), the wallet opens
bas a universal link, with nothing added. Read the answer from the relay; keep polling while the app is in the foreground, in case the person switches back by hand. - A pairing that came in by a scan or a paste never opens
b, since the person isn't on the app's device. Show the same link as a QR code and as text so XE Wallet on another phone, or the Web Wallet on a computer, can pair. - Send
xe_connectfirst, thenxe_grantPermissionsorxe_revokePermissions, as ordinary relay frames.
#Errors
Errors are XE Connect's. data.reason is stable; show your own words for it.
| Code | data.reason | Meaning | What to do |
|---|---|---|---|
| 4001 | declined, closed | The person said no or closed the page | Nothing was granted. Let them try again |
| 4100 | account-not-granted | A sign request for an account this wallet can't sign for | Ask the person to connect that account |
| 4200 | unsupported | The wallet or the network can't do this, for example a spend permission on a network without services grants | Fall back to approving each request, or pick another network |
| 4900 | faucet | A new test-network account couldn't get test XE before the review | Ask the person to try again in a few minutes, or to use a wallet that has test XE |
| -32602 | invalid-params, wrong-site | The request breaks a rule, or the permission's issuer isn't your host | Fix the request |
| -32603 | internal | The wallet couldn't finish | Try again |
Unsealed error= tokens at the return link: invalid-request and expired. A request from an app the wallet doesn't know is refused on its page, and nothing comes back.
#Deleting an account in your app
App Store review asks apps that create accounts to let people delete them. In one sheet: revoke the grant (kind: "revoke"), delete K and everything the app stored, and sign out. The wallet created with Apple or Google belongs to the Web Wallet, and its recovery stays with that sign-in provider. The XE account on the test network isn't erased. Say so in the app.