Render your own native wallet list with a hidden WebView engine. Connect, sign messages, send a display-unit amount, and sign transactions. No wallet SDK in your app.
This is an enterprise-only feature. Please contact us to enable.
The same headless architecture as iOS: render your own native list, and drive a hiddenWebView that runs the Dynamic SDK and returns results (including message and transaction signatures) over a JS bridge. No wallet SDK in the app.The basic Android flow is the recommended default.
No SDK in your app. Your app links no wallet SDK. It needs a hidden WebView pointed at the hosted engine page (https://connect.dynamicauth.com/headless.html, set as ENGINE_URL in FireblocksHeadlessConnect) and your URL scheme. All WalletConnect / MetaMask / Phantom logic (and the wallet list) comes from that hosted view. Same bridge contract as iOS.
Copy FireblocksHeadlessConnect.kt and WalletAccount.kt (below), and FireblocksConnect.kt from the basic Android guide (visible fallback).
1. Get the wallet menu (no static file)
The engine derives the list live from the Dynamic catalog and pushes it over the bridge (a wallets message). Set FireblocksHeadlessConnect.onWallets.
Field
Type
Description
key
String
Catalog key you pass back on tap (e.g. metamask).
name / icon
String
Display name and icon URL for the row.
chains
List<String>
evm / solana. Drives a native chain picker.
mode
"headless" | "fallback"
headless connects silently; fallback opens the visible flow.
featured
Boolean
Show by default; the rest of the catalog rides along for search.
2. Drop in FireblocksHeadlessConnect
Owns a hidden WebView, bridges to it (addJavascriptInterface + evaluateJavascript), opens the wallet deeplink it returns, and calls you back. Pre-warm it at launch. Set environmentId before prewarm() to target a different Dynamic environment, and locale / theme the same way to override the engine’s UI locale and theme; all three are forwarded to the iframe app as query parameters.
MainActivity.kt
FireblocksHeadlessConnect.environmentId = "b1e3aca9-0646-411a-b4ab-c31ce49935b3"FireblocksHeadlessConnect.prewarm(this) // at launchFireblocksHeadlessConnect.onWallets = { render(it) } // the live listFireblocksHeadlessConnect.connect(this, "metamask", "evm") { result -> when (result) { is FireblocksHeadlessConnect.Result.Success -> { /* result.wallet */ } is FireblocksHeadlessConnect.Result.FallbackRequired -> { /* visible flow */ } is FireblocksHeadlessConnect.Result.Failure -> { /* result.code */ } }}
package com.fireblocks.connectimport android.annotation.SuppressLintimport android.app.Activityimport android.content.Contextimport android.content.Intentimport android.graphics.Bitmapimport android.net.Uriimport android.os.Handlerimport android.os.Looperimport android.util.Logimport android.view.ViewGroupimport android.webkit.JavascriptInterfaceimport android.webkit.WebResourceRequestimport android.webkit.WebViewimport android.webkit.WebViewClientimport java.util.UUIDimport org.json.JSONArrayimport org.json.JSONObject// ── Headless connect engine (Android) ────────────────────────────────────────/** * Runs the hosted Fireblocks connect logic (the Dynamic SDK) inside a HIDDEN * [WebView], so the app can render its own native wallet list and still keep * every bit of connection logic in the web layer. The Android analog of iOS's * `FireblocksHeadlessConnect`. * * For WalletConnect-protocol wallets (MetaMask, Rainbow, Trust, …) the pairing * is relay-based: the engine mints a URI, we open the wallet via deeplink, the * user approves, and the approval resolves over a WebSocket — no visible page. * Wallets with no such path (Base Account passkey/email, …) come back as * [Result.FallbackRequired] so the caller opens the visible [FireblocksConnect]. * * The app links **no wallet SDK**: it loads a URL, relays JSON messages over a * bridge, opens a deeplink, and renders a list. Everything wallet-specific is * JavaScript in the hidden WebView. * * ```kotlin * FireblocksHeadlessConnect.prewarm(activity) // at launch * FireblocksHeadlessConnect.connect(activity, "rainbow", "evm") { result -> * when (result) { * is FireblocksHeadlessConnect.Result.Success -> { /* result.wallet */ } * is FireblocksHeadlessConnect.Result.FallbackRequired -> { /* visible flow */ } * is FireblocksHeadlessConnect.Result.Failure -> { /* result.code */ } * } * } * ``` */object FireblocksHeadlessConnect { private const val TAG = "FireblocksHeadlessConnect" private const val DEFAULT_ENGINE_BASE_URL = "https://connect.dynamicauth.com/headless.html" /** * The no-UI engine page. Only this page's scheme, host and port may post * messages to the app or load top-level in the engine WebView. * * Set this BEFORE [prewarm]/[connect], like [environmentId]: the URL is * resolved when the hidden WebView is first created. Point it at your own * deployment of the engine, never at a URL taken from untrusted input. */ var engineBaseUrl: String = DEFAULT_ENGINE_BASE_URL /** Points Phantom's redirect at your app scheme so it returns to the app. * Replace `myapp` with your scheme. */ private const val RETURN_SCHEME = "myapp" /** * Dynamic environment ID for the engine page to use instead of the one it was * built with, sent as `?environmentId=<uuid>`. `null`/blank leaves the page on * its own default, which is the pre-existing behavior. * * Set this BEFORE [prewarm]/[connect]: the URL is resolved when the hidden * WebView is first created, so a later change only takes effect on the next * engine reload. Pass the same value to [FireblocksConnect.present] so the * visible fallback flow lands on the same environment. */ var environmentId: String? = null /** * UI locale for the iframe app, sent as `?locale=<value>` — e.g. `"en_US"`, * `"es_LA"`; see the iframe app's README for the current allow-list. * `null`/blank leaves the page on its own default (`en_US`). Never changes * anything on the native side — it's forwarded as-is to the iframe app. * * Set this BEFORE [prewarm]/[connect]: same resolution timing as [environmentId]. */ var locale: String? = null /** * UI theme for the iframe app, sent as `?theme=<value>` — `"light"` or * `"dark"`. `null`/blank leaves the page on its own default (`light`). * Never changes anything on the native side — it's forwarded as-is to * the iframe app. * * Set this BEFORE [prewarm]/[connect]: same resolution timing as [environmentId]. */ var theme: String? = null /** * How the iframe app connects Phantom, sent as `?phantomMode=<value>` — * `"in-app"` (default) or `"redirect"`; see the iframe app's README. * `null`/blank omits the param. Forwarded as-is to the iframe app. * * Set this BEFORE [prewarm]/[connect]: same resolution timing as [environmentId]. */ var phantomMode: String? = null /** * The app's own https URL Phantom returns to, sent as * `?walletReturnUrl=<value>` and used as Phantom's `redirect_link` when * [phantomMode] is `"redirect"`. `null`/blank omits the param and the * engine falls back to `<returnScheme>://phantom-headless`. Forwarded * as-is. * * Set this BEFORE [prewarm]/[connect]: same resolution timing as [environmentId]. */ var walletReturnUrl: String? = null /** If the engine hasn't produced a deeplink within this window, fall back to * the visible flow. Cancelled once the wallet opens. */ private const val STARTUP_TIMEOUT_MS = 20_000L private const val SIGN_TIMEOUT_MS = 60_000L /** Longer than [SIGN_TIMEOUT_MS]: a send can involve two sequential wallet * approvals (switch network, then send) rather than one, so 60s is too * tight a budget to fail loud on before the user's had a fair chance to * clear both prompts. */ private const val SEND_TIMEOUT_MS = 120_000L /** Wallet universal-link hosts iOS/Android won't hand to the wallet app from * inside a WebView (only Phantom's redirect navigates the WebView today) — * the WebViewClient opens these externally. */ private val WALLET_HOSTS = setOf( "phantom.app", "phantom.com", "link.metamask.io", "metamask.app.link", "link.trustwallet.com", "bkapp.vip", "rnbwapp.com", "rainbow.me", "www.okx.com", "link.okx.com", "zerion.io", ) internal fun isWalletHost(host: String): Boolean = WALLET_HOSTS.any { host == it || host.endsWith(".$it") } /** Bridge message types that aren't tied to a single connect() attempt, so * they're exempt from the per-attempt `requestId` check in `handleMessage`. * "openWallet" carries a sign/send requestId (informational), never a * connect attempt id — gating it on the connect slot would drop it. */ private val NO_REQUEST_ID_TYPES = setOf("ready", "wallets", "event", "openWallet") private val SIGN_TYPES = setOf("signed", "signFailed") private val SIGN_TX_TYPES = setOf("signedTx", "signTxFailed") private val SEND_TX_TYPES = setOf("sentTx", "sentTxFailed") private val WALLET_ACCOUNTS_TYPES = setOf("walletAccounts", "walletAccountsFailed") private val OPEN_URL_TYPES = setOf("walletBrowserOpen", "walletBrowserOpenFailed") /** [engineBaseUrl] plus the params the engine reads on load. */ private fun engineUrl(): String { val builder = Uri.parse(engineBaseUrl) .buildUpon() .appendQueryParameter("returnScheme", RETURN_SCHEME) environmentId ?.takeIf { it.isNotBlank() } ?.let { builder.appendQueryParameter("environmentId", it) } locale ?.takeIf { it.isNotBlank() } ?.let { builder.appendQueryParameter("locale", it) } theme ?.takeIf { it.isNotBlank() } ?.let { builder.appendQueryParameter("theme", it) } phantomMode ?.takeIf { it.isNotBlank() } ?.let { builder.appendQueryParameter("phantomMode", it) } walletReturnUrl ?.takeIf { it.isNotBlank() } ?.let { builder.appendQueryParameter("walletReturnUrl", it) } return builder.build().toString() } /** A wallet in the native list, delivered live by the engine (derived from * the Dynamic catalogue — no static file). */ data class Wallet( val key: String, val name: String, val icon: String?, val chains: List<String>, /** "headless" → drive this engine; "fallback" → the visible flow. */ val mode: String, /** Shown by default; the rest of the catalogue rides along for search. */ val featured: Boolean, /** * The wallet's in-app-browser URL template (`{{encodedDappURI}}`), when * the wallet book carries one — `null` otherwise. * * NOT one of [chains]: it means "this wallet can open a URL in its own * browser", where it injects its providers. Some wallets are only * reachable that way for some chains (Phantom on EVM — see * [FireblocksWalletBrowser]). The template says nothing about WHICH * chains that browser serves, so don't infer chain support from it. */ val inAppBrowser: String? = null, ) { val isMultiChain: Boolean get() = chains.size > 1 } sealed class Result { data class Success(val wallet: WalletConnection) : Result() data class FallbackRequired(val reason: String) : Result() data class Failure(val code: String, val message: String) : Result() } sealed class SignResult { data class Success(val signature: String) : SignResult() data class Failure(val code: String, val message: String) : SignResult() } /** Result of [signTransaction], which signs without broadcasting. */ sealed class SignTxResult { data class Success(val signedTransaction: String, val chain: String) : SignTxResult() data class Failure(val code: String, val message: String) : SignTxResult() } /** Result of [getWalletAccounts]. [accounts] holds one [WalletAccount] per * account the engine reports, empty when it holds none. */ sealed class WalletAccountsResult { data class Success(val accounts: List<WalletAccount>) : WalletAccountsResult() data class Failure(val code: String, val message: String) : WalletAccountsResult() } /** Result of [openUrlInWalletBrowser]. [url] is the wallet link the system * opened. The client does not validate it; the SDK owns that. */ sealed class OpenUrlInWalletBrowserResult { data class Success(val url: String) : OpenUrlInWalletBrowserResult() data class Failure(val code: String, val message: String) : OpenUrlInWalletBrowserResult() } sealed class SendResult { /** [chain] is "evm", "solana", or "bitcoin" — [txHash] is the * on-chain transaction hash (EVM), signature (Solana, which IS the * transaction's identifier), or transaction ID (Bitcoin); either way * it's already submitted. */ data class Success(val txHash: String, val chain: String) : SendResult() data class Failure(val code: String, val message: String) : SendResult() } private val main = Handler(Looper.getMainLooper()) private var appContext: Context? = null private var webView: WebView? = null private var ready = false private val pendingReady = mutableListOf<() -> Unit>() // Phantom return URLs that arrived before the page was ready (a cold start // or an engine reset): evaluating them then would hit an undefined headlessConnect. private val pendingReturnScripts = mutableListOf<String>() // Single in-flight attempt (mirrors the iOS engine). For production, hold // this in a ViewModel so it survives configuration changes / process death. private var handler: ((Result) -> Unit)? = null private var timeout: Runnable? = null // UUID per attempt, not a constant — a guessable/fixed request ID lets any // JS in this WebView forge a `connected` message for a request it never // made. `handleMessage` drops any message whose `requestId` doesn't match. // Written and read only on `main`. private var pendingRequestId: String? = null // Sign/signTx/sendTx are independent of the connect attempt above (a wallet // stays connected while the caller signs/sends any number of times), so // they get their own single-slot handler + requestId + timeout rather than // sharing `handler`/`pendingRequestId`/`timeout` — those three are (and // stay) connect-only. private var signHandler: ((SignResult) -> Unit)? = null private var signRequestId: String? = null private var signTimeout: Runnable? = null private var signTxHandler: ((SignTxResult) -> Unit)? = null private var signTxRequestId: String? = null private var signTxTimeout: Runnable? = null private var walletAccountsHandler: ((WalletAccountsResult) -> Unit)? = null private var walletAccountsRequestId: String? = null private var walletAccountsTimeout: Runnable? = null private var openUrlHandler: ((OpenUrlInWalletBrowserResult) -> Unit)? = null private var openUrlRequestId: String? = null private var openUrlTimeout: Runnable? = null private var sendTxHandler: ((SendResult) -> Unit)? = null private var sendTxRequestId: String? = null private var sendTxTimeout: Runnable? = null // The origin (scheme+host+port) of the page currently committed as this // WebView's top-level document. `@JavascriptInterface` gives no origin, so // this is tracked from the WebViewClient callbacks (main thread) and // consulted in `handleMessage` to reject bridge messages from anything // other than the engine. @Volatile because it's written on `main` and read // on the JS-interface binder thread in `Bridge.postMessage` — a single // immutable reference swap, so volatility alone (no lock) is sufficient. @Volatile private var committedOrigin: Uri? = null private var walletsList: List<Wallet> = emptyList() /** Set to receive the wallet menu. Replayed immediately if already delivered. */ var onWallets: ((List<Wallet>) -> Unit)? = null set(value) { field = value if (walletsList.isNotEmpty()) value?.invoke(walletsList) } // ── Public API ──────────────────────────────────────────────────────────── /** Build + load the hidden WebView ahead of time so the first connect is * fast. Safe to call more than once. */ fun prewarm(activity: Activity) = main.post { ensureWebView(activity) } fun connect( activity: Activity, walletKey: String, chain: String?, onResult: (Result) -> Unit, ) = main.post { ensureWebView(activity) // A previous attempt is still in flight (e.g. the user opened MetaMask, // ignored the prompt, and is now trying another wallet). The SDK can hold // a stuck pending connection that blocks the next mint — reset to a fresh // engine so the new wallet gets a clean slate. if (handler != null) resetEngine() handler = onResult val requestId = UUID.randomUUID().toString() pendingRequestId = requestId scheduleStartupTimeout() val work = { drive(requestId, walletKey, chain) } if (ready) work() else pendingReady.add(work) } // Reload the hidden WebView to abandon a stuck previous attempt. The reloaded // page re-fires `ready` (flushing any queued connect) and re-pushes the list. private fun resetEngine() { handler = null pendingRequestId = null clearTimeout() ready = false pendingReady.clear() pendingReturnScripts.clear() webView?.reload() } /** Abort the in-flight attempt (e.g. the user backed out of the list). */ fun cancel() = main.post { webView?.evaluateJavascript("window.headlessConnect && window.headlessConnect.cancel('');", null) clearTimeout() handler = null pendingRequestId = null } /** Sign [message] with the currently-connected wallet. Resolves once via * [onResult]. Requires the engine URL to point to a build that includes * sign support. Works for whatever chain the connected wallet is on * (EVM or Solana) — this method doesn't know or care which. */ fun sign(message: String, onResult: (SignResult) -> Unit) = main.post { signHandler?.let { finishSign(SignResult.Failure("superseded", "superseded by a new sign() call")) } val requestId = UUID.randomUUID().toString() signHandler = onResult signRequestId = requestId scheduleSignTimeout() val params = JSONObject().put("requestId", requestId).put("message", message) webView?.evaluateJavascript("window.headlessConnect && window.headlessConnect.sign($params);", null) } /** * Ask the engine which wallet accounts it currently holds. Resolves once * via [onResult]. A local read: no wallet prompt, so it answers fast. * * An engine build that predates this call answers with `unsupported_engine` * immediately. */ fun getWalletAccounts(onResult: (WalletAccountsResult) -> Unit) = main.post { walletAccountsHandler?.let { finishWalletAccounts(WalletAccountsResult.Failure("superseded", "superseded by a new getWalletAccounts() call")) } val requestId = UUID.randomUUID().toString() walletAccountsHandler = onResult walletAccountsRequestId = requestId walletAccountsTimeout = Runnable { finishWalletAccounts(WalletAccountsResult.Failure("timeout", "Engine did not respond in time")) }.also { main.postDelayed(it, SIGN_TIMEOUT_MS) } val params = JSONObject().put("requestId", requestId) webView?.evaluateJavascript( "if (window.headlessConnect && window.headlessConnect.getWalletAccounts) {" + " window.headlessConnect.getWalletAccounts($params);" + "} else if (window.walletNative && window.walletNative.postMessage) {" + " window.walletNative.postMessage(JSON.stringify({" + " type: 'walletAccountsFailed'," + " requestId: ${JSONObject.quote(requestId)}," + " code: 'unsupported_engine'," + " message: 'engine build predates getWalletAccounts — redeploy connect.dynamicauth.com'" + " }));" + "}", null, ) } /** * Open [url] in the in-app browser of the wallet [walletKey], through the * wallet's own link. Resolves once via [onResult], after the system has * handled the wallet link. No connection is needed. * * The client does not validate [url] or [walletKey]; the SDK does. An * engine build that predates this call answers with `unsupported_engine` * immediately. */ fun openUrlInWalletBrowser( walletKey: String, url: String, onResult: (OpenUrlInWalletBrowserResult) -> Unit, ) = main.post { openUrlHandler?.let { finishOpenUrl(OpenUrlInWalletBrowserResult.Failure("superseded", "superseded by a new openUrlInWalletBrowser() call")) } val requestId = UUID.randomUUID().toString() openUrlHandler = onResult openUrlRequestId = requestId openUrlTimeout = Runnable { finishOpenUrl(OpenUrlInWalletBrowserResult.Failure("timeout", "Engine did not respond in time")) }.also { main.postDelayed(it, SIGN_TIMEOUT_MS) } val params = JSONObject() .put("requestId", requestId) .put("walletKey", walletKey) .put("url", url) val work = work@{ val isPending = openUrlRequestId == requestId if (!isPending) return@work webView?.evaluateJavascript( "if (window.headlessConnect && window.headlessConnect.openUrlInWalletBrowser) {" + " window.headlessConnect.openUrlInWalletBrowser($params);" + "} else if (window.walletNative && window.walletNative.postMessage) {" + " window.walletNative.postMessage(JSON.stringify({" + " type: 'walletBrowserOpenFailed'," + " requestId: ${JSONObject.quote(requestId)}," + " code: 'unsupported_engine'," + " message: 'engine build predates openUrlInWalletBrowser — redeploy connect.dynamicauth.com'" + " }));" + "}", null, ) } if (ready) work() else pendingReady.add(work) } /** * Send a transaction with the currently-connected wallet — EVM, Solana, or * Bitcoin. * Resolves once via [onResult]. * * The wallet signs AND broadcasts in one step: `eth_sendTransaction` for * EVM, `signAndSendTransaction` for Solana (the wallet-adapter-standard * analog every Solana wallet implements). * * [transaction] format depends on which chain the connected wallet is on * — this method doesn't know or care which, it's just an opaque string * the engine interprets: * - EVM: JSON string `{"to":"0x…","value":"0x0","data":"0x","chainId":"0x1"}` * — `chainId` is required; the engine verifies it against the wallet's * own active network before sending (see [FireblocksConnect.sendTransaction] * for the same `SendResult.Failure` codes this can surface — * `chain_switch_unavailable`, `chain_not_configured`, * `chain_switch_rejected`, `chain_mismatch`). * - Solana: base64-encoded, pre-built `VersionedTransaction` (or legacy * `Transaction`) bytes — the caller is responsible for building it (a * native SOL transfer vs. an SPL-token transfer for USDC are both just * "whatever instructions are already in the bytes"); the engine only * signs and submits. * - Bitcoin: JSON string `{"recipientAddress":"bc1…","amountSats":"12345"}` * — `amountSats` is the amount in satoshis as a decimal-digit string. * The wallet's own `sendBitcoin` RPC signs and broadcasts it. */ fun sendTransaction(transaction: String, onResult: (SendResult) -> Unit) = dispatchSend( jsFunction = "sendTx", params = JSONObject().put("transaction", transaction), supersededMessage = "superseded by a new sendTransaction() call", unsupportedMessage = "engine build predates sendTx — redeploy connect.dynamicauth.com", onResult = onResult, ) /** ERC-20 / SPL token for [transferAmount]: contract (or mint) [address] * and the token's [decimals]. */ data class TransferToken(val address: String, val decimals: Int) /** * Send a display-unit amount from the connected wallet — EVM or Solana. * Resolves once via [onResult]; the caller never builds a transaction or * converts to wei/lamports. The engine owns all validation, so the * `SendResult.Failure` codes it surfaces include `invalid_amount`, * `missing_recipient`, `missing_from`, `invalid_token`, * `invalid_network_id`, `account_not_found`, `fallback_required`, * `unsupported_chain`, `unsupported_wallet`, `chain_not_configured`, * `chain_switch_unavailable`, `chain_switch_rejected`, `chain_mismatch`, * `invalid_param`, `method_unavailable`, `user_rejected`, `timeout` and * `unsupported_engine`. * * - [from]: address of the connected account to send from (EVM addresses * match case-insensitively). * - [amount]: positive decimal string in display units, e.g. `"0.01"`. * - [recipient]: destination address. * - [networkId]: optional. EVM: decimal chainId, e.g. `"137"`. Solana: * `"mainnet-beta"` or `"devnet"`. Omitting it on EVM means the engine * performs no network check and sends on whatever network the wallet is * currently on. * - [token]: optional ERC-20 / SPL token; omit for the native asset. * * v1 exclusions: Bitcoin returns `unsupported_chain`; Solana with Phantom * in redirect mode returns `unsupported_wallet`. */ fun transferAmount( from: String, amount: String, recipient: String, networkId: String? = null, token: TransferToken? = null, onResult: (SendResult) -> Unit, ) = dispatchSend( jsFunction = "transferAmount", params = JSONObject() .put("from", from) .put("amount", amount) .put("recipient", recipient) .also { params -> if (networkId != null) params.put("networkId", networkId) if (token != null) { params.put("token", JSONObject().put("address", token.address).put("decimals", token.decimals)) } }, supersededMessage = "superseded by a new transferAmount() call — the superseded transfer may still have been submitted; check the explorer before retrying.", unsupportedMessage = "engine build predates transferAmount — redeploy connect.dynamicauth.com", onResult = onResult, ) private fun dispatchSend( jsFunction: String, params: JSONObject, supersededMessage: String, unsupportedMessage: String, onResult: (SendResult) -> Unit, ) = main.post { sendTxHandler?.let { finishSendTx(SendResult.Failure("superseded", supersededMessage)) } val requestId = UUID.randomUUID().toString() sendTxHandler = onResult sendTxRequestId = requestId sendTxTimeout = Runnable { finishSendTx( SendResult.Failure( "timeout", "Wallet did not respond in time — if you approved it, the transaction " + "may still have been submitted; check the explorer before retrying.", ), ) }.also { main.postDelayed(it, SEND_TIMEOUT_MS) } params.put("requestId", requestId) // `sendTx` and `transferAmount` are newer additions to the engine than // everything else this class calls — a deployment that predates them // would otherwise leave this request silently unanswered until the // timeout, indistinguishable from a dead wallet. Self-report // immediately instead, straight over the same `walletNative` channel // `Bridge.postMessage` already listens on. webView?.evaluateJavascript( "if (window.headlessConnect && window.headlessConnect.$jsFunction) {" + " window.headlessConnect.$jsFunction($params);" + "} else if (window.walletNative && window.walletNative.postMessage) {" + " window.walletNative.postMessage(JSON.stringify({" + " type: 'sentTxFailed'," + " requestId: ${JSONObject.quote(requestId)}," + " code: 'unsupported_engine'," + " message: ${JSONObject.quote(unsupportedMessage)}" + " }));" + "}", null, ) } /** * Sign a transaction with the currently-connected wallet without * broadcasting it. Resolves once via [onResult]. * * [transaction] format depends on which chain the connected wallet is on: * - EVM: JSON string `{"to":"0x…","value":"0x0","data":"0x","chainId":"0x1"}` * - Solana: base64-encoded, pre-built `VersionedTransaction` (or legacy * `Transaction`) bytes. * - Bitcoin: JSON string * `{"unsignedPsbtBase64","allowedSighash","signature"}`. The result is * a base64 signed PSBT; the caller must finalize and broadcast it. */ fun signTransaction(transaction: String, onResult: (SignTxResult) -> Unit) = main.post { signTxHandler?.let { finishSignTx(SignTxResult.Failure("superseded", "superseded by a new signTransaction() call")) } val requestId = UUID.randomUUID().toString() signTxHandler = onResult signTxRequestId = requestId signTxTimeout = Runnable { finishSignTx(SignTxResult.Failure("timeout", "Wallet did not respond in time")) }.also { main.postDelayed(it, SIGN_TIMEOUT_MS) } val params = JSONObject().put("requestId", requestId).put("transaction", transaction) webView?.evaluateJavascript( "if (window.headlessConnect && window.headlessConnect.signTx) {" + " window.headlessConnect.signTx($params);" + "} else if (window.walletNative && window.walletNative.postMessage) {" + " window.walletNative.postMessage(JSON.stringify({" + " type: 'signTxFailed'," + " requestId: ${JSONObject.quote(requestId)}," + " code: 'unsupported_engine'," + " message: 'engine build predates signTx — redeploy connect.dynamicauth.com'" + " }));" + "}", null, ) } /** Called when Phantom returns to the app: `<scheme>://phantom-headless` * (from [FireblocksRedirectActivity]) or, when [walletReturnUrl] is set, * that https link (from the activity that owns your universal link). * Forwards the full URL into the WebView and lets the engine decide: in * `redirect` mode it completes the connection from Phantom's payload, in * `in-app` mode it ignores the payload-free tap. The engine re-checks the * https link itself. Returns true if it consumed the URL. */ fun handleReturnURL(uri: Uri): Boolean { val isPhantomReturn = isPhantomReturn(uri) if (!isPhantomReturn) return false val js = "window.headlessConnect && window.headlessConnect.handleReturnURL(${JSONObject.quote(uri.toString())});" main.post { if (ready) webView?.evaluateJavascript(js, null) else pendingReturnScripts.add(js) } return true } private fun isPhantomReturn(uri: Uri): Boolean { val isHeadlessHost = uri.host?.lowercase() == "phantom-headless" val configuredReturnUrl = walletReturnUrl?.trim()?.takeIf { it.isNotEmpty() }?.let(Uri::parse) val isReturnUrl = configuredReturnUrl != null && uri.isSameHttpsTarget(configuredReturnUrl) return isHeadlessHost || isReturnUrl } private fun Uri.isSameHttpsTarget(other: Uri): Boolean { val bothHttps = scheme.equals("https", ignoreCase = true) && other.scheme.equals("https", ignoreCase = true) val sameHost = host.equals(other.host, ignoreCase = true) val samePort = effectiveHttpsPort() == other.effectiveHttpsPort() val samePath = pathOrRoot() == other.pathOrRoot() return bothHttps && sameHost && samePort && samePath } private fun Uri.effectiveHttpsPort(): Int = if (port == -1) 443 else port private fun Uri.pathOrRoot(): String = path?.takeIf { it.isNotEmpty() } ?: "/" // ── WebView lifecycle ─────────────────────────────────────────────────── @SuppressLint("SetJavaScriptEnabled") private fun ensureWebView(activity: Activity) { if (webView != null) return appContext = activity.applicationContext val wv = WebView(activity) wv.settings.javaScriptEnabled = true wv.settings.domStorageEnabled = true wv.addJavascriptInterface(Bridge(), "walletNative") wv.webViewClient = object : WebViewClient() { // The engine navigates to wallet deeplinks (Phantom's redirect); the // system won't open those from inside a WebView, so we do. override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean { val url = request.url val scheme = url.scheme?.lowercase() if (scheme != "http" && scheme != "https") { openExternally(url); return true } val host = url.host?.lowercase() if (host != null && isWalletHost(host)) { openExternally(url); return true } // Deny-by-default: only the engine's own origin may load top-level // in this privileged WebView (the bridge is attached regardless of // what page is showing). Logged rather than silently dropped, since // a denial here means something unexpected tried to navigate this // WebView — see the Critical bridge-trust finding. // // Deliberately NOT scoped to `request.isForMainFrame()` — this also // denies subframe navigation. `@JavascriptInterface` exposes // `walletNative` to every frame in this WebView (Android gives no way // to restrict it to the top frame), while `committedOrigin` below // only ever tracks the *main*-frame origin. If this were narrowed // to main-frame-only, a hostile iframe could load here and post // forged bridge messages that `handleMessage`'s origin check would // wrongly accept (it'd still see the engine's own top-level // origin). Don't narrow this without also making the bridge // origin check frame-aware. if (!isEngineOrigin(url)) { Log.w(TAG, "Denying navigation to non-engine origin: $url") return true } return false } // Tracks the top-level origin currently loaded, so the bridge (which // gets no origin info from @JavascriptInterface) can validate against // it. Fires for every main-frame navigation, including the initial // `loadUrl` and `resetEngine()`'s reload — both same-origin already. override fun onPageStarted(view: WebView, url: String?, favicon: Bitmap?) { committedOrigin = url?.let(Uri::parse) } } // Keep it in the hierarchy (1×1) so its JS + relay socket keep running, // and DON'T call onPause() — that would suspend the socket. We rely on // Android keeping a short app-switch alive; for long approvals consider a // foreground service. val root = activity.findViewById<ViewGroup>(android.R.id.content) root.addView(wv, 1, 1) wv.loadUrl(engineUrl()) webView = wv } private fun drive(requestId: String, walletKey: String, chain: String?) { val params = JSONObject() .put("requestId", requestId) .put("walletKey", walletKey) if (chain != null) params.put("chain", chain) webView?.evaluateJavascript("window.headlessConnect && window.headlessConnect.connect($params);", null) } private fun openExternally(uri: Uri) { val ctx = appContext ?: return try { ctx.startActivity(Intent(Intent.ACTION_VIEW, uri).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) } catch (_: Exception) { // No app to handle it — the engine will surface an error/timeout. } } private fun tryOpenExternally(uri: Uri): Boolean { val ctx = appContext ?: return false return try { ctx.startActivity(Intent(Intent.ACTION_VIEW, uri).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) true } catch (_: Exception) { false } } // ── Origin gating ───────────────────────────────────────────────────────── // Shared by the bridge (below) and the WebViewClient above: only the // engine's own scheme+host+port may post a message or load top-level in // this privileged WebView. Compared this way — not just host — so a // same-host page served on a different scheme/port can't slip through. private fun isEngineOrigin(uri: Uri?): Boolean { if (uri == null) return false // Compared against the BASE url: this gate is about origin only, so a // caller-supplied `environmentId` can never widen what counts as the engine. return sameOrigin(uri, Uri.parse(engineBaseUrl)) } private fun sameOrigin(a: Uri, b: Uri): Boolean { val schemeA = a.scheme?.lowercase() val schemeB = b.scheme?.lowercase() if (schemeA == null || schemeA != schemeB) return false if (a.host?.lowercase() != b.host?.lowercase()) return false // Uri reports -1 for "no explicit port" — resolve that to the scheme's // real default so https://x.com and https://x.com:443 compare equal. val defaultPort = if (schemeA == "https") 443 else if (schemeA == "http") 80 else -1 val portA = if (a.port == -1) defaultPort else a.port val portB = if (b.port == -1) defaultPort else b.port return portA == portB } // ── Bridge (JS → native) ────────────────────────────────────────────────── // @JavascriptInterface methods run on a binder thread, with no origin info // of their own. Snapshot `committedOrigin` here — on the calling thread, // at the moment JS posted — rather than re-reading it after hopping to // main, so a navigation racing the hop can't retroactively change which // origin this message is attributed to. committedOrigin is @Volatile, so // this read is safe without a lock. private class Bridge { @JavascriptInterface fun postMessage(json: String) { val origin = committedOrigin main.post { handleMessage(json, origin) } } } private fun handleMessage(json: String, origin: Uri?) { // Reject anything not posted by the engine's own top-level frame. Without // this, any JS that ends up running in this WebView — a compromised // script, an XSS on the hosted page, or a page the navigation gate above // missed — could forge a `connected` message and native would believe an // attacker-chosen wallet address is connected. See the Critical // bridge-trust finding. if (!isEngineOrigin(origin)) { Log.w(TAG, "Dropping bridge message from non-engine origin: $origin") return } val o = runCatching { JSONObject(json) }.getOrNull() ?: return val type = o.optString("type") // "ready"/"wallets"/"event" aren't tied to one attempt; connect's own // messages ("deeplink"/"opening"/"connected"/"fallback"/"error") must // carry the requestId of the connect() attempt in flight — sign's and // sendTx's messages are checked against their OWN independent // requestId slot below, since all three kinds of request can be // in flight independently of each other. Stale or forged IDs (e.g. a // superseded attempt's late message) are dropped rather than resolved // against the current handler. if (type !in NO_REQUEST_ID_TYPES && type !in SIGN_TYPES && type !in SIGN_TX_TYPES && type !in SEND_TX_TYPES && type !in WALLET_ACCOUNTS_TYPES && type !in OPEN_URL_TYPES && !matchesPendingRequest(o)) return if (type in SIGN_TYPES && !matchesSignRequest(o)) return if (type in SIGN_TX_TYPES && !matchesSignTxRequest(o)) return if (type in SEND_TX_TYPES && !matchesSendTxRequest(o)) return if (type in WALLET_ACCOUNTS_TYPES && !matchesWalletAccountsRequest(o)) return if (type in OPEN_URL_TYPES && !matchesOpenUrlRequest(o)) return when (type) { "ready" -> { ready = true val returns = pendingReturnScripts.toList() pendingReturnScripts.clear() returns.forEach { webView?.evaluateJavascript(it, null) } val work = pendingReady.toList() pendingReady.clear() work.forEach { it() } } "wallets" -> { walletsList = parseWallets(o.optJSONArray("wallets")) onWallets?.invoke(walletsList) } "deeplink" -> { clearTimeout() // the wallet is opening; wait for the user now o.optString("url").takeIf { it.isNotEmpty() }?.let { openExternally(Uri.parse(it)) } } // A WalletConnect sign/send request is waiting — wake the wallet // app so its approval prompt surfaces (the request already went // over the relay; without this it sits invisibly until the user // opens the wallet by hand). No connect bookkeeping to touch. "openWallet" -> o.optString("url").takeIf { it.isNotEmpty() }?.let { openExternally(Uri.parse(it)) } "opening" -> clearTimeout() "connected" -> { // A missing/empty (or non-string — `optString` would otherwise // coerce e.g. a JSON number into a "successful" address) address // is a malformed payload, not a "connected" wallet with a blank // address — route it to failure instead of silently succeeding // (see Finding 19). val address = (o.opt("address") as? String)?.takeIf { it.isNotEmpty() } if (address == null) { finish(Result.Failure("malformed_result", "connected message missing address")) return } finish( Result.Success( WalletConnection( address = address, chain = o.optString("chain"), walletName = o.optString("walletName"), walletImage = o.optString("walletImage"), sessionId = o.optString("sessionId"), // Present only for session-cluster-bound wallets // (Phantom) — see WalletConnection.network's docs. network = o.optString("network").ifEmpty { null }, networkId = o.optString("networkId").ifEmpty { null }, ), ), ) } "fallback" -> finish(Result.FallbackRequired(o.optString("reason"))) "error" -> finish(Result.Failure(o.optString("code", "unknown"), o.optString("message"))) "signed" -> finishSign(SignResult.Success(o.optString("signature"))) "signFailed" -> finishSign(SignResult.Failure(o.optString("code", "unknown"), o.optString("message"))) "signedTx" -> finishSignTx(SignTxResult.Success(o.optString("signedTransaction"), o.optString("chain"))) "signTxFailed" -> finishSignTx(SignTxResult.Failure(o.optString("code", "unknown"), o.optString("message"))) "walletAccounts" -> finishWalletAccounts(WalletAccountsResult.Success(WalletAccount.fromJsonArray(o.optJSONArray("accounts")))) "walletAccountsFailed" -> finishWalletAccounts( WalletAccountsResult.Failure(o.optString("code", "unknown"), o.optString("message")), ) "walletBrowserOpen" -> { val url = o.optString("url") val opened = url.isNotBlank() && tryOpenExternally(Uri.parse(url)) val result = if (opened) { OpenUrlInWalletBrowserResult.Success(url) } else { OpenUrlInWalletBrowserResult.Failure("open_failed", "the system could not open the wallet link") } finishOpenUrl(result) } "walletBrowserOpenFailed" -> finishOpenUrl( OpenUrlInWalletBrowserResult.Failure(o.optString("code", "unknown"), o.optString("message")), ) "sentTx" -> finishSendTx(SendResult.Success(o.optString("txHash"), o.optString("chain"))) "sentTxFailed" -> finishSendTx(SendResult.Failure(o.optString("code", "unknown"), o.optString("message"))) // "event" — diagnostic timeline; hook up logging/analytics if wanted. } } private fun matchesPendingRequest(o: JSONObject): Boolean { val incoming = o.optString("requestId").takeIf { it.isNotEmpty() } ?: return false return incoming == pendingRequestId } private fun matchesSignRequest(o: JSONObject): Boolean { val incoming = o.optString("requestId").takeIf { it.isNotEmpty() } ?: return false return incoming == signRequestId } private fun matchesSignTxRequest(o: JSONObject): Boolean { val incoming = o.optString("requestId").takeIf { it.isNotEmpty() } ?: return false return incoming == signTxRequestId } private fun matchesSendTxRequest(o: JSONObject): Boolean { val incoming = o.optString("requestId").takeIf { it.isNotEmpty() } ?: return false return incoming == sendTxRequestId } private fun matchesWalletAccountsRequest(o: JSONObject): Boolean { val incoming = o.optString("requestId").takeIf { it.isNotEmpty() } ?: return false return incoming == walletAccountsRequestId } private fun matchesOpenUrlRequest(o: JSONObject): Boolean { val incoming = o.optString("requestId").takeIf { it.isNotEmpty() } ?: return false return incoming == openUrlRequestId } private fun parseWallets(arr: JSONArray?): List<Wallet> { if (arr == null) return emptyList() return (0 until arr.length()).mapNotNull { i -> val w = arr.optJSONObject(i) ?: return@mapNotNull null val chains = w.optJSONArray("chains") Wallet( key = w.optString("key"), name = w.optString("name"), icon = w.optString("icon").takeIf { it.isNotEmpty() }, chains = if (chains == null) emptyList() else (0 until chains.length()).map { chains.optString(it) }, mode = w.optString("mode", "fallback"), featured = w.optBoolean("featured", false), inAppBrowser = w.optString("inAppBrowser").takeIf { it.isNotEmpty() }, ) } } private fun finish(result: Result) { val cb = handler ?: return handler = null pendingRequestId = null clearTimeout() main.post { cb(result) } } private fun scheduleStartupTimeout() { clearTimeout() timeout = Runnable { finish(Result.FallbackRequired("headless startup timeout")) }.also { main.postDelayed(it, STARTUP_TIMEOUT_MS) } } private fun finishSign(result: SignResult) { val cb = signHandler ?: return signHandler = null signRequestId = null signTimeout?.let { main.removeCallbacks(it) } signTimeout = null main.post { cb(result) } } private fun scheduleSignTimeout() { signTimeout?.let { main.removeCallbacks(it) } signTimeout = Runnable { finishSign(SignResult.Failure("timeout", "Wallet did not respond in time")) }.also { main.postDelayed(it, SIGN_TIMEOUT_MS) } } private fun finishWalletAccounts(result: WalletAccountsResult) { val cb = walletAccountsHandler ?: return walletAccountsHandler = null walletAccountsRequestId = null walletAccountsTimeout?.let { main.removeCallbacks(it) } walletAccountsTimeout = null main.post { cb(result) } } private fun finishOpenUrl(result: OpenUrlInWalletBrowserResult) { val cb = openUrlHandler ?: return openUrlHandler = null openUrlRequestId = null openUrlTimeout?.let { main.removeCallbacks(it) } openUrlTimeout = null main.post { cb(result) } } private fun finishSignTx(result: SignTxResult) { val cb = signTxHandler ?: return signTxHandler = null signTxRequestId = null signTxTimeout?.let { main.removeCallbacks(it) } signTxTimeout = null main.post { cb(result) } } private fun finishSendTx(result: SendResult) { val cb = sendTxHandler ?: return sendTxHandler = null sendTxRequestId = null sendTxTimeout?.let { main.removeCallbacks(it) } sendTxTimeout = null main.post { cb(result) } } private fun clearTimeout() { timeout?.let { main.removeCallbacks(it) } timeout = null }}
View WalletAccount.kt (copy-paste ready)
WalletAccount.kt
package com.fireblocks.connectimport org.json.JSONArrayimport org.json.JSONObjectimport java.text.ParsePositionimport java.text.SimpleDateFormatimport java.util.Dateimport java.util.Localeimport java.util.TimeZone/** * One account the engine's SDK holds. [raw] is the untouched SDK object, so * fields not modelled here (such as `verifiedCredentialId`) stay readable. */data class WalletAccount( val id: String, val address: String, val chain: String, val walletProviderKey: String, val lastSelectedAt: Date?, val raw: JSONObject,) { companion object { // XXX reads "Z" and "+02:00"; X alone stops at "+02" and leaves ":00" unread. private val DATE_PATTERNS = listOf( "yyyy-MM-dd'T'HH:mm:ss.SSSXXX", "yyyy-MM-dd'T'HH:mm:ssXXX", "yyyy-MM-dd'T'HH:mm:ss.SSSX", "yyyy-MM-dd'T'HH:mm:ssX", ) /** * Decodes the host message's `accounts` array. A null array yields an * empty list, and entries that are not JSON objects are dropped. */ fun fromJsonArray(array: JSONArray?): List<WalletAccount> { if (array == null) return emptyList() val accounts = mutableListOf<WalletAccount>() for (index in 0 until array.length()) { val entry = array.optJSONObject(index) ?: continue accounts.add(fromJson(entry)) } return accounts } private fun fromJson(o: JSONObject) = WalletAccount( id = text(o, "id"), address = text(o, "address"), chain = text(o, "chain"), walletProviderKey = text(o, "walletProviderKey"), lastSelectedAt = parseDate(o.opt("lastSelectedAt")), raw = o, ) // optString would turn JSON null into the text "null". private fun text(o: JSONObject, k: String): String = if (o.isNull(k)) "" else (o.opt(k) as? String ?: "") private fun parseDate(value: Any?): Date? { if (value !is String) return null for (pattern in DATE_PATTERNS) { // SimpleDateFormat is not thread-safe, so build one per call. val format = SimpleDateFormat(pattern, Locale.US) format.timeZone = TimeZone.getTimeZone("UTC") format.isLenient = false val position = ParsePosition(0) val date = format.parse(value, position) val consumedAll = position.index == value.length if (date != null && consumedAll) return date } return null } }}
3. Sign a message
The hosted engine supports window.headlessConnect.sign. After a successful connect, invoke sign() with any string. The wallet app prompts the user; the callback delivers a hex signature.
MainActivity.kt
FireblocksHeadlessConnect.sign( message = "Sign in to MyApp · ${Instant.now()}") { result -> when (result) { is SignResult.Success -> { /* result.signature: hex string */ } is SignResult.Failure -> { /* result.code, result.message */ } }}
Only available for wallets connected through the headless engine. Visible-flow wallets do not hold an open session.
4. Sign a transaction
Pass a serialized transaction. Signing only, no broadcast.
MainActivity.kt (EVM)
FireblocksHeadlessConnect.signTransaction( transaction = """{"to":"${wallet.address}","value":"0x0","data":"0x","chainId":"0x1"}""") { result -> when (result) { is SignTxResult.Success -> /* result.signedTransaction: RLP-encoded hex, broadcast with eth_sendRawTransaction */ is SignTxResult.Failure -> { /* result.code */ } }}
MainActivity.kt (Solana)
// txBytes: ByteArray of your serialized VersionedTransactionval b64 = Base64.encodeToString(txBytes, Base64.NO_WRAP)FireblocksHeadlessConnect.signTransaction(transaction = b64) { result -> when (result) { is SignTxResult.Success -> /* result.signedTransaction: base64-encoded signed transaction bytes */ is SignTxResult.Failure -> { /* result.code */ } }}
5. Send an amount
transferAmount() sends a display-unit amount without a serialized transaction. The engine converts to wei or lamports and builds the transfer itself, for EVM or Solana. Bitcoin returns unsupported_chain, and Solana with Phantom in redirect mode returns unsupported_wallet.
MainActivity.kt
FireblocksHeadlessConnect.transferAmount( from = wallet.address, amount = "0.01", recipient = "0x…", networkId = "137", // optional: decimal chainId on EVM, "mainnet-beta" or "devnet" on Solana token = FireblocksHeadlessConnect.TransferToken(address = "0x…", decimals = 6), // optional; omit for the native asset) { result -> when (result) { is SendResult.Success -> { /* result.txHash, result.chain: already broadcast */ } is SendResult.Failure -> { /* result.code, result.message */ } }}
from is the connected account’s address and amount is a positive decimal string in display units. token is an ERC-20 or SPL token and takes the contract (or mint) address plus the token’s decimals; omit it for the native asset. Omitting networkId on EVM skips the engine’s network check and sends on the wallet’s active network. An engine deployment that predates transferAmount fails fast with unsupported_engine.
6. List wallet accounts
getWalletAccounts() returns the accounts the engine currently holds. It is a local read with no wallet prompt.
MainActivity.kt
FireblocksHeadlessConnect.getWalletAccounts { result -> when (result) { is FireblocksHeadlessConnect.WalletAccountsResult.Success -> { /* result.accounts: List<WalletAccount> */ } is FireblocksHeadlessConnect.WalletAccountsResult.Failure -> { /* result.code, result.message */ } }}
Each WalletAccount carries id, address, chain and walletProviderKey (empty strings when the SDK omits the field, sends null or sends a value that is not a string), lastSelectedAt (a Date, or null when the value is missing, null, not a string or not a parseable ISO-8601 string) and raw, the untouched SDK JSONObject for fields the type does not model, such as verifiedCredentialId. Entries that are not objects are dropped, and the list is empty when the engine holds no accounts. The call has its own in-flight slot, so a new call supersedes the previous one (superseded), and it fails with timeout if the engine does not answer. An engine deployment that predates getWalletAccounts fails fast with unsupported_engine.
Open a URL in a wallet browser
openUrlInWalletBrowser() opens your HTTPS page inside a supported wallet’s in-app browser. It needs no existing wallet connection. Pass the wallet’s catalog key as walletKey and your page’s full URL as url. The engine gets the wallet link from the Dynamic SDK, and the native wrapper asks the operating system to open it.
FireblocksHeadlessConnect.openUrlInWalletBrowser( walletKey = "metamask", url = "https://www.fireblocks.com",) { result -> when (result) { is FireblocksHeadlessConnect.OpenUrlInWalletBrowserResult.Success -> { android.util.Log.d("WalletBrowser", "Opened wallet link: ${result.url}") } is FireblocksHeadlessConnect.OpenUrlInWalletBrowserResult.Failure -> { android.util.Log.e("WalletBrowser", "Could not open wallet browser [${result.code}]: ${result.message}") } }}
The success result contains the wallet link the operating system accepted. It does not confirm that the page loaded or that a wallet connected or signed. If the wallet is not installed, an HTTPS wallet link can open in the default browser and still report success.For connect and sign during one visit, host a page that connects to the wallet and requests the signature inside that browser. Your page must submit the signed result to your backend for verification and provide the return path to your app. This method only opens the page; it does not return a signature, authenticate a Dynamic user, or send a webhook.Update the copy-paste wrapper in your app from this guide before calling the method. An older hosted engine returns unsupported_engine; update the engine deployment before testing. Other failure codes include wallet_not_found, no_in_app_browser, ambiguous_chain, no_link, invalid_params, open_failed, and timeout.Android keeps one opening request in flight. A new call completes the previous request with superseded.
7. Wire the manifest and redirect
Beyond the basic flow, headless needs two manifest additions: a phantom-headless host on the same FireblocksRedirectActivity intent-filter, and a <queries> block so the app can open wallet deeplinks on Android 11+.
Route the return activity to the engine first, then fall through to the visible flow. The engine only consumes <scheme>://phantom-headless, which carries no data: Phantom connects inside its own in-app browser, the engine receives the connection over the WalletConnect relay, and the link only brings your app forward.
FireblocksRedirectActivity
intent?.data?.let { uri -> if (!FireblocksHeadlessConnect.handleReturnURL(uri)) { FireblocksConnect.handleRedirect(uri) }}
The hidden WebView needs the INTERNET permission. Do not call webView.onPause() on it. That suspends the relay socket.
8. Render the list (your UI)
MainActivity is a sample list (search, chain picker, connecting state, auto-fallback) you would swap for your own design.
View MainActivity.kt (sample list UI)
MainActivity.kt
package com.fireblocks.connect.sampleimport android.animation.ObjectAnimatorimport android.animation.ValueAnimatorimport android.app.Activityimport android.content.Contextimport android.content.Intentimport android.net.Uriimport android.os.Buildimport android.os.Bundleimport android.view.MotionEventimport android.view.Gravityimport android.view.Viewimport android.view.ViewGroupimport android.view.ViewGroup.LayoutParams.MATCH_PARENTimport android.view.ViewGroup.LayoutParams.WRAP_CONTENTimport android.widget.EditTextimport android.widget.FrameLayoutimport android.widget.LinearLayoutimport android.widget.ProgressBarimport android.widget.ScrollViewimport android.widget.TextViewimport androidx.core.widget.doAfterTextChangedimport com.fireblocks.connect.FireblocksConnectimport com.fireblocks.connect.FireblocksConnectResultimport com.fireblocks.connect.FireblocksHeadlessConnectimport com.fireblocks.connect.FireblocksHeadlessConnect.SendResultimport com.fireblocks.connect.FireblocksHeadlessConnect.SignResultimport com.fireblocks.connect.FireblocksHeadlessConnect.TransferTokenimport com.fireblocks.connect.FireblocksHeadlessConnect.WalletAccountsResultimport com.fireblocks.connect.FireblocksHeadlessConnect.Walletimport com.fireblocks.connect.FireblocksFundResultimport com.fireblocks.connect.FireblocksSendResultimport com.fireblocks.connect.FireblocksSignResultimport com.fireblocks.connect.FireblocksWalletBrowserimport com.fireblocks.connect.WalletAccountimport com.fireblocks.connect.WalletConnectionimport com.fireblocks.connect.sample.harness.HarnessActivityimport com.fireblocks.connect.sample.harness.HarnessContractimport java.math.BigIntegerimport java.text.SimpleDateFormatimport java.util.Dateimport java.util.Localeimport java.util.TimeZoneprivate const val BARE_ROW_ID = "bare-auth-webview"private const val SEARCH_RESULT_LIMIT = 20// Base Account's passkey/email connect needs a visible page, so FallbackRequired// is the correct answer there and a bug anywhere else.private val EXPECTED_FALLBACK = setOf("baseaccount-evm")/** * Internal connect-API comparison demo, NOT the recommended integration * pattern (see git history for the original headless-first / auto-fallback * wallet picker). * * The wallet list has one tab per connect mode, and each tab lists every * wallet+chain pair the catalogue reports, so tapping a row shows, in * isolation, what that specific API does for that specific wallet+chain: * * 1. "Headless" — [FireblocksHeadlessConnect.connect], the hidden no-UI * WebView engine. A wallet/chain with no headless path reports back * `FallbackRequired` instead of connecting — shown inline rather than * auto-chaining into another flow. * 2. "Redirect" — [FireblocksConnect.present], the hosted flow in a Custom * Tab that redirects back to the app. Two sections: no wallet preselected * (the web app's own picker), and `?wallet=&chain=` preselected so it jumps * straight to one wallet+chain. * 3. "Embedded" — [EmbeddedConnectView], the same hosted page rendered in a * WebView inside the app. The page's own picker runs there; the app only * listens for the `<scheme>://wallet-callback` redirect and swaps the page * for the connected screen. * 4. "Meta Embedded" — [MetaEmbeddedConnectView], the same page with the fixed * navigation policy of Meta's own WebView: `http(s)` always loads in the * WebView, wallet universal links included. * * Once connected, the wallet gets one tab per action — sign a message, send a * transaction, transfer an amount, fund from Coinbase — so you can see the * full flow end-to-end. Send is EVM (a plain JSON tx object, no chain SDK * needed) or Solana (a native SOL transfer; the ENGINE builds the transaction, * this app only picks network/recipient/amount — see `resolveSolanaTx` in * `src/headless.ts` for why: a Solana tx needs a live blockhash, unlike EVM's * self-contained {to,value,data,chainId}). * * The look lives in DemoUi.kt; nothing there is part of the integration. */class MainActivity : Activity() { private val hostedPageUrl: String by lazy { debugWebviewUrl() ?: "https://connect.dynamicauth.com/" } private val scheme = "myapp" // must match the intent-filter in AndroidManifest // Which Dynamic environment the hosted pages should use. `null` leaves them on // whatever they were built with; set a UUID here (or read one from // BuildConfig / a remote config) to point this build at a specific // environment without redeploying the web layer. private val environmentId: String? = null // Manual test toggle ONLY — lets this sample exercise different iframe-app // locales/themes. These are NOT read by anything on the native side; // they're forwarded as-is to the iframe app (see // FireblocksHeadlessConnect.locale/.theme's doc comments). A real app // integrating this SDK does not need a toggle like this at all. In-memory, // resets to English/light on every relaunch. private var testLocale: String = "en_US" private var testTheme: String = "light" // Manual test toggle ONLY, like the two above: a real app sets // FireblocksHeadlessConnect.phantomMode once before prewarm and passes // phantomMode on the visible-flow calls (or neither, for the "in-app" // default). null is "Not set": nothing is sent, so the engine's own default // applies. A new choice is saved and takes effect on the next app launch. private var testPhantomMode: String? = null // Same launch semantics as testPhantomMode: the https URL Phantom returns // to in "redirect" mode, saved per-process until the app restarts. private var testWalletReturnUrl: String? = null // Manual test toggle ONLY: whether the Embedded tab hands wallet universal // links to the OS (a real app almost always wants this). In-memory. private var openWalletLinksExternally = true private var all: List<Wallet> = emptyList() private var connectingRowId: String? = null private val rowOutcomes = mutableMapOf<String, RowOutcome>() private var listError: String? = null private var connectedWallet: WalletConnection? = null private var connectedHeadlessly = false // Solana network toggle state — which cluster the NEXT send builds // against. See the Solana send panel for why the wallet itself must // already be set to the same one. private var solNetwork = "mainnet-beta" private val ui by lazy { Ui(this) } private lateinit var scroll: LockableScrollView private lateinit var stage: LinearLayout private lateinit var listScreen: LinearLayout private lateinit var connectedScreen: LinearLayout private lateinit var flowTabs: SegmentedControl private lateinit var flowDescription: TextView private lateinit var rowsContainer: LinearLayout private lateinit var searchInput: EditText private var embeddedView: EmbeddedConnectView? = null private var embeddedNotice: TextView? = null private var metaEmbeddedView: MetaEmbeddedConnectView? = null private var metaEmbeddedNotice: TextView? = null private var pendingFakeRedirect: WalletConnection? = null private lateinit var settingsSummary: TextView private lateinit var settingsCollapsible: Collapsible private var flowTab = 0 private data class RowOutcome(val text: String, val isExpected: Boolean) private data class WalletChainRow(val wallet: Wallet, val chain: String) { val id: String get() = "${wallet.key}-$chain" } private enum class Flow { AUTH_WEBVIEW, HIDDEN_WEBVIEW } private data class Preset(val label: String, val value: String) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val page = ui.vertical().apply { setPadding(ui.dp(20), ui.dp(24), ui.dp(20), ui.dp(32)) } val header = header() val settings = settingsCard() // The wrapper carries the top margin, so collapsing it removes the gap too. val settingsHolder = ui.vertical().apply { setPadding(0, ui.dp(20), 0, 0) addView(settings) } settingsCollapsible = Collapsible(ui, settingsHolder, expanded = true) page.addView(header) page.addView(settingsHolder) listScreen = buildListScreen() connectedScreen = ui.vertical().apply { visibility = View.GONE } stage = ui.vertical().apply { addView(listScreen) addView(connectedScreen) } page.addView(stage, ui.lp(top = 20)) scroll = LockableScrollView(this).apply { setBackgroundColor(Palette.bg) isFillViewport = true // Holds initial focus so no text field grabs it (and opens the keyboard) on launch or tab switches. isFocusableInTouchMode = true descendantFocusability = ViewGroup.FOCUS_BEFORE_DESCENDANTS addView(page) } setContentView(scroll) if (Build.VERSION.SDK_INT >= 26) { window.decorView.systemUiVisibility = window.decorView.systemUiVisibility or View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR } // Must be set before prewarm — the engine URL is resolved when the hidden // WebView is created. debugWebviewUrl()?.let { FireblocksHeadlessConnect.engineBaseUrl = "${it}headless.html" } FireblocksHeadlessConnect.environmentId = environmentId FireblocksHeadlessConnect.locale = testLocale FireblocksHeadlessConnect.theme = testTheme testPhantomMode = PhantomModeSetting.atLaunch(this) FireblocksHeadlessConnect.phantomMode = testPhantomMode testWalletReturnUrl = WalletReturnUrlSetting.atLaunch(this) FireblocksHeadlessConnect.walletReturnUrl = testWalletReturnUrl // Pre-warm the engine so the first connect is fast, and receive the // wallet list it derives from the catalogue. FireblocksHeadlessConnect.prewarm(this) FireblocksHeadlessConnect.onWallets = { wallets -> runOnUiThread { all = wallets; renderList() } } pendingFakeRedirect = debugFakeEmbeddedRedirect() renderList() ui.enter(listOf(header, settingsHolder, stage)) debugFakeWallet()?.let(::showConnected) } override fun onDestroy() { stopEmbedded() stopMetaEmbedded() super.onDestroy() } // ── Header + test settings ──────────────────────────────────────────────── private fun header(): View = ui.vertical().apply { addView(ui.text("HostedConnections Kotlin", 28f, weight = Weight.BOLD)) addView(ui.text("Sample app for the connect APIs", 15f, Palette.textSecondary), ui.lp(top = 4)) } private val locales = listOf( "English" to "en_US", "Spanish (LatAm)" to "es_LA", "Spanish (Colombia)" to "es_CO", "Filipino" to "tl_PH", ) private fun settingsSummaryText(): String { val locale = locales.firstOrNull { it.second == testLocale }?.first ?: testLocale val phantom = when (PhantomModeSetting.saved(this)) { "in-app" -> "in-app" "redirect" -> "redirect" else -> "not set" } return "$locale · ${testTheme.replaceFirstChar { it.uppercase() }} · Phantom $phantom" } /** Manual test toggles for the iframe app's locale/theme and the Phantom * mode — see the doc comments on [testLocale]/[testTheme]/[testPhantomMode]. * NOT part of the recommended integration pattern. Collapsed by default so * the screen is about the flows, not the knobs. */ private fun settingsCard(): View { val card = ui.card(padding = 0) settingsSummary = ui.text(settingsSummaryText(), 13f, Palette.textSecondary) val chevron = ui.text("›", 24f, Palette.textSecondary).apply { rotation = 90f } val headerRow = ui.horizontal().apply { setPadding(ui.dp(18), ui.dp(16), ui.dp(18), ui.dp(16)) background = ui.rippleOver(ui.rounded(0x00FFFFFF, 18), 18) isClickable = true val titles = ui.vertical().apply { addView(ui.text("Test settings", 16f, weight = Weight.MEDIUM)) addView(settingsSummary, ui.lp(top = 3)) } addView(titles, ui.lp(width = 0, weight = 1f)) addView(chevron) } val body = ui.vertical().apply { setPadding(ui.dp(18), 0, ui.dp(18), ui.dp(18)) } body.addView(ui.text("Locale", 13f, Palette.textSecondary, Weight.MEDIUM), ui.lp(bottom = 8)) body.addView( ChipGroup(ui, locales.map { it.first }, locales.indexOfFirst { it.second == testLocale }) { i -> testLocale = locales[i].second FireblocksHeadlessConnect.locale = testLocale settingsSummary.text = settingsSummaryText() }.view, ) body.addView(ui.text("Theme", 13f, Palette.textSecondary, Weight.MEDIUM), ui.lp(top = 16, bottom = 8)) body.addView( SegmentedControl(ui, listOf("Light", "Dark"), if (testTheme == "dark") 1 else 0) { i -> testTheme = if (i == 1) "dark" else "light" FireblocksHeadlessConnect.theme = testTheme settingsSummary.text = settingsSummaryText() }, ) body.addView(ui.text("Phantom mode", 13f, Palette.textSecondary, Weight.MEDIUM), ui.lp(top = 16, bottom = 8)) val modes = listOf<String?>(null, "in-app", "redirect") val restartNote = ui.text("Restart the app to apply.", 12f, Palette.warning).apply { background = ui.rounded(Palette.warningSoft, 10) setPadding(ui.dp(10), ui.dp(8), ui.dp(10), ui.dp(8)) } val restartHolder = ui.vertical().apply { addView(restartNote, ui.lp(top = 10)) } val restartCollapsible = Collapsible(ui, restartHolder, expanded = false) fun updatePhantomRestart() { val modeChanged = PhantomModeSetting.saved(this) != testPhantomMode val urlChanged = (WalletReturnUrlSetting.saved(this) ?: "") != (testWalletReturnUrl ?: "") restartCollapsible.set(modeChanged || urlChanged) } body.addView( SegmentedControl( ui, listOf("Not set", "In-app", "Redirect"), modes.indexOf(PhantomModeSetting.saved(this)).coerceAtLeast(0), ) { i -> PhantomModeSetting.save(this, modes[i]) settingsSummary.text = settingsSummaryText() // The saved mode only takes effect on the next launch. updatePhantomRestart() }, ) body.addView(restartHolder) body.addView(ui.text("Wallet return URL", 13f, Palette.textSecondary, Weight.MEDIUM), ui.lp(top = 16, bottom = 8)) val returnUrlField = ui.input( hint = "https://your-app.example/phantom-return", initial = WalletReturnUrlSetting.saved(this) ?: "", mono = true, ) returnUrlField.doAfterTextChanged { text -> val value = text?.toString()?.trim() WalletReturnUrlSetting.save(this, value?.takeIf { it.isNotBlank() }) updatePhantomRestart() } body.addView(returnUrlField) body.addView(ui.text("Open wallet links externally", 13f, Palette.textSecondary, Weight.MEDIUM), ui.lp(top = 16, bottom = 8)) body.addView( SegmentedControl(ui, listOf("On", "Off"), if (openWalletLinksExternally) 0 else 1) { i -> openWalletLinksExternally = i == 0 }, ) val developerTools = ActionButton(ui, ActionButton.Kind.SECONDARY, "Developer tools") developerTools.setOnClickListener { startActivity(Intent(this, HarnessActivity::class.java).putExtra(HarnessContract.EXTRA_BASE_URL, hostedPageUrl)) } body.addView(developerTools, ui.lp(top = 20)) val bodyCollapsible = Collapsible(ui, body, expanded = false) card.addView(headerRow) card.addView(body) headerRow.setOnClickListener { val open = !bodyCollapsible.isExpanded bodyCollapsible.set(open) chevron.animate().rotation(if (open) 270f else 90f) .setDuration(Motion.STANDARD).setInterpolator(Motion.decelerate).start() } return card } // ── Wallet list ─────────────────────────────────────────────────────────── private fun buildListScreen(): LinearLayout { val screen = ui.vertical() flowTabs = SegmentedControl(ui, listOf("Headless", "Redirect", "Embedded", "Meta Embedded"), flowTab) { i -> flowTab = i renderRows(animate = true) } screen.addView(flowTabs) flowDescription = ui.text("", 13f, Palette.textSecondary) screen.addView(flowDescription, ui.lp(top = 12)) searchInput = ui.input("Search wallets, e.g. Trust or Bitget").apply { contentDescription = "wallet-search" addTextChangedListener(object : android.text.TextWatcher { override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) = Unit override fun afterTextChanged(s: android.text.Editable?) = renderRows(animate = false) }) } screen.addView(searchInput, ui.lp(top = 14)) rowsContainer = ui.vertical() screen.addView(rowsContainer, ui.lp(top = 14)) return screen } private fun rows(): List<WalletChainRow> = rowsFor(all.filter { it.featured }) private fun rowsFor(wallets: List<Wallet>): List<WalletChainRow> = wallets.flatMap { wallet -> chains(wallet).map { WalletChainRow(wallet, it) } } private fun searchQuery(): String = searchInput.text.toString().trim().lowercase() /** Featured wallets until the user types; then the whole catalogue the * engine sent, matched on name or key, so any wallet can be tried without * changing the engine's featured list. */ private fun headlessRows(): List<WalletChainRow> { val query = searchQuery() if (query.isEmpty()) return rows() val matches = all.filter { wallet -> val matchesName = wallet.name.lowercase().contains(query) val matchesKey = wallet.key.lowercase().contains(query) (matchesName || matchesKey) && chains(wallet).isNotEmpty() } return rowsFor(matches.take(SEARCH_RESULT_LIMIT)) } /** The engine's own chains, plus a synthetic "evm" for a wallet whose EVM * surface only exists inside its own in-app browser (Phantom), which * therefore never appears in [Wallet.chains]. */ private fun chains(wallet: Wallet): List<String> = wallet.chains + if (offersInAppBrowserEvm(wallet)) listOf("evm") else emptyList() /** * Scoped to Phantom on purpose, and NOT derived from "has an in-app-browser * template" — a template only means the wallet can open a URL in its own * browser; it says nothing about which chains that browser injects a * provider for. The evidence for Phantom specifically is * `phantomevm.injectedConfig.windowLocations: ["phantom.ethereum"]`. * * Redirect mode has no Phantom EVM: that row is the relay bridge's. */ private fun offersInAppBrowserEvm(wallet: Wallet): Boolean = testPhantomMode != "redirect" && wallet.key.lowercase() == "phantom" && wallet.inAppBrowser != null && !wallet.chains.contains("evm") private fun renderList() = renderRows(animate = false) private fun renderRows(animate: Boolean) { flowDescription.text = when (flowTab) { 0 -> "FireblocksHeadlessConnect.connect — the hidden WebView engine, no UI. A wallet or chain " + "with no headless path reports FallbackRequired instead of connecting." 1 -> "FireblocksConnect.present — the hosted flow opens in a Chrome Custom Tab and redirects " + "back to the app through its URL scheme." 2 -> "WebView — the hosted page renders inside the app. The app only listens for the " + "$scheme://wallet-callback redirect, then swaps the page for the connected screen." else -> "Meta WebView — the same embedded page, with the navigation policy of Meta's own " + "WebView: http(s) links, wallet universal links included, always load inside it." } searchInput.visibility = if (flowTab == 0 && all.isNotEmpty()) View.VISIBLE else View.GONE applyEmbeddedLayout() val showsEmbedded = flowTab == 2 val showsMetaEmbedded = flowTab == 3 if (!showsEmbedded) stopEmbedded() if (!showsMetaEmbedded) stopMetaEmbedded() if (showsEmbedded) { renderEmbedded(animate) return } if (showsMetaEmbedded) { renderMetaEmbedded(animate) return } rowsContainer.removeAllViews() val items = mutableListOf<View>() listError?.let { message -> items += errorNotice(message) } fun walletRows(flow: Flow) { val searching = flow == Flow.HIDDEN_WEBVIEW && searchQuery().isNotEmpty() val rows = if (flow == Flow.HIDDEN_WEBVIEW) headlessRows() else rows() if (rows.isEmpty()) { val message = if (searching) "No wallet matches \"${searchQuery()}\"." else "No wallets reported by the catalogue." items += ui.text(message, 14f, Palette.textSecondary) } rows.forEach { row -> val id = rowId(flow, row) items += listRow(row.wallet.name, row.wallet.name, chainLabel(row.chain), id) { connect(row, flow, id) } } } when { all.isEmpty() -> repeat(4) { items += skeletonRow() } flowTab == 0 -> walletRows(Flow.HIDDEN_WEBVIEW) else -> { items += sectionHeader("No wallet preselected", "The web app's own wallet picker runs inside the tab.") items += listRow("Web", "Open Authenticate Webview", null, BARE_ROW_ID) { openBareAuthWebview() } items += sectionHeader("Wallet preselected", "?wallet=&chain= jumps straight to one wallet and chain.") walletRows(Flow.AUTH_WEBVIEW) } } items.forEach { rowsContainer.addView(it, ui.lp(bottom = 10)) } if (animate) ui.enter(items) } private fun errorNotice(message: String) = ui.text(message, 13f, Palette.error).apply { background = ui.rounded(Palette.errorSoft, 14) setPadding(ui.dp(14), ui.dp(12), ui.dp(14), ui.dp(12)) } // ── Embedded ────────────────────────────────────────────────────────────── private val embeddedMode get() = (flowTab == 2 || flowTab == 3) && connectedWallet == null /** Header, settings and tabs stay put; the web view takes the rest of the * height, so the outer scroll is off while it is showing. */ private fun applyEmbeddedLayout() { val fill = embeddedMode scroll.scrollingEnabled = !fill listOf(stage, listScreen, rowsContainer).forEach { view -> (view.layoutParams as LinearLayout.LayoutParams).apply { height = if (fill) 0 else WRAP_CONTENT weight = if (fill) 1f else 0f } view.requestLayout() } } private fun renderEmbedded(animate: Boolean) { if (embeddedView == null) { rowsContainer.removeAllViews() val notice = errorNotice("").apply { visibility = View.GONE } val card = EmbeddedConnectView( activity = this, ui = ui, hostedPageUrl = hostedPageUrl, scheme = scheme, environmentId = environmentId, locale = testLocale, theme = testTheme, phantomMode = testPhantomMode, openWalletLinksExternally = { openWalletLinksExternally }, takeFakeRedirect = { pendingFakeRedirect.also { pendingFakeRedirect = null } }, ) { result -> when (result) { is FireblocksConnectResult.Success -> showConnected(result.wallet) is FireblocksConnectResult.Cancelled -> showEmbeddedError("cancelled") is FireblocksConnectResult.Error -> showEmbeddedError(result.code ?: result.reason) } } rowsContainer.addView(notice, ui.lp(bottom = 10)) rowsContainer.addView(card, ui.lp(height = 0, weight = 1f)) embeddedNotice = notice embeddedView = card if (animate) ui.enter(listOf(card)) } } private fun renderMetaEmbedded(animate: Boolean) { if (metaEmbeddedView == null) { rowsContainer.removeAllViews() val notice = errorNotice("").apply { visibility = View.GONE } val card = MetaEmbeddedConnectView( activity = this, ui = ui, hostedPageUrl = hostedPageUrl, scheme = scheme, environmentId = environmentId, locale = testLocale, theme = testTheme, phantomMode = testPhantomMode, takeFakeRedirect = { pendingFakeRedirect.also { pendingFakeRedirect = null } }, ) { result -> when (result) { is FireblocksConnectResult.Success -> showConnected(result.wallet) is FireblocksConnectResult.Cancelled -> showMetaEmbeddedError("cancelled") is FireblocksConnectResult.Error -> showMetaEmbeddedError(result.code ?: result.reason) } } rowsContainer.addView(notice, ui.lp(bottom = 10)) rowsContainer.addView(card, ui.lp(height = 0, weight = 1f)) metaEmbeddedNotice = notice metaEmbeddedView = card if (animate) ui.enter(listOf(card)) } } private fun showMetaEmbeddedError(reason: String) { metaEmbeddedNotice?.apply { text = "Couldn't connect ($reason)." visibility = View.VISIBLE } } private fun showEmbeddedError(reason: String) { embeddedNotice?.apply { text = "Couldn't connect ($reason)." visibility = View.VISIBLE } } private fun stopEmbedded() { embeddedView?.destroy() embeddedView = null embeddedNotice = null } private fun stopMetaEmbedded() { metaEmbeddedView?.destroy() metaEmbeddedView = null metaEmbeddedNotice = null } private fun sectionHeader(title: String, caption: String): View = ui.vertical().apply { setPadding(ui.dp(2), ui.dp(8), 0, ui.dp(2)) addView(ui.text(title, 15f, weight = Weight.BOLD)) addView(ui.text(caption, 13f, Palette.textSecondary), ui.lp(top = 3)) } private fun listRow(avatarName: String, title: String, chain: String?, id: String, onTap: () -> Unit): View { val connecting = connectingRowId == id val outcome = rowOutcomes[id] val idle = connectingRowId == null val row = ui.horizontal().apply { background = ui.rippleOver( ui.rounded(Palette.surface, 16, if (connecting) Palette.primary else Palette.border, if (connecting) 2 else 1), 16, ) setPadding(ui.dp(14), ui.dp(14), ui.dp(14), ui.dp(14)) minimumHeight = ui.dp(68) isEnabled = idle alpha = if (idle || connecting) 1f else 0.55f isClickable = true setOnClickListener { onTap() } } ui.pressable(row, 0.98f) val avatar = ui.avatar(avatarName, 40) (avatar.layoutParams as LinearLayout.LayoutParams).rightMargin = ui.dp(14) row.addView(avatar) val titles = ui.vertical() val titleRow = ui.horizontal() titleRow.addView(ui.text(title, 16f, weight = Weight.MEDIUM)) if (chain != null) { titleRow.addView(ui.pill(chain, Palette.textSecondary, Palette.track), ui.lp(width = WRAP_CONTENT, start = 8)) } titles.addView(titleRow) if (outcome != null) { titles.addView( ui.text(outcome.text, 12f, if (outcome.isExpected) Palette.success else Palette.warning, Weight.MEDIUM), ui.lp(top = 4), ) } row.addView(titles, ui.lp(width = 0, weight = 1f)) if (connecting) { row.addView( ProgressBar(this, null, android.R.attr.progressBarStyleSmall).apply { indeterminateTintList = android.content.res.ColorStateList.valueOf(Palette.primary) }, LinearLayout.LayoutParams(ui.dp(22), ui.dp(22)), ) } else { row.addView(ui.text("›", 24f, Palette.hint)) } return row } /** Placeholder rows that breathe while the engine is still reporting its wallet list. */ private fun skeletonRow(): View { val row = ui.horizontal().apply { background = ui.rounded(Palette.surface, 16, Palette.border) setPadding(ui.dp(14), ui.dp(14), ui.dp(14), ui.dp(14)) minimumHeight = ui.dp(68) } row.addView( View(this).apply { background = ui.rounded(Palette.track, 20) }, LinearLayout.LayoutParams(ui.dp(40), ui.dp(40)).apply { rightMargin = ui.dp(14) }, ) val bars = ui.vertical() bars.addView(View(this).apply { background = ui.rounded(Palette.track, 5) }, ui.lp(width = ui.dp(140), height = ui.dp(12))) bars.addView(View(this).apply { background = ui.rounded(Palette.track, 5) }, ui.lp(width = ui.dp(90), height = ui.dp(10), top = 8)) row.addView(bars) val pulse = ObjectAnimator.ofFloat(row, View.ALPHA, 0.45f, 1f).apply { duration = 900 repeatCount = ValueAnimator.INFINITE repeatMode = ValueAnimator.REVERSE start() } row.addOnAttachStateChangeListener(object : View.OnAttachStateChangeListener { override fun onViewAttachedToWindow(v: View) {} override fun onViewDetachedFromWindow(v: View) { pulse.cancel() } }) return row } private fun rowId(flow: Flow, row: WalletChainRow) = "$flow-${row.id}" private fun openBareAuthWebview() { listError = null connectingRowId = BARE_ROW_ID renderList() FireblocksConnect.present(this, hostedPageUrl, scheme, environmentId, testLocale, testTheme, testPhantomMode) { result -> runOnUiThread { connectingRowId = null when (result) { is FireblocksConnectResult.Success -> showConnected(result.wallet) is FireblocksConnectResult.Cancelled -> renderList() is FireblocksConnectResult.Error -> { listError = "Couldn't connect (${result.code ?: result.reason})." renderList() } } } } } private fun connect(row: WalletChainRow, flow: Flow, id: String) { listError = null rowOutcomes.remove(id) connectingRowId = id renderList() when (flow) { Flow.AUTH_WEBVIEW -> FireblocksConnect.present( this, hostedUrl(row.wallet.key, row.chain), scheme, environmentId, testLocale, testTheme, testPhantomMode, ) { result -> runOnUiThread { connectingRowId = null when (result) { is FireblocksConnectResult.Success -> showConnected(result.wallet) is FireblocksConnectResult.Cancelled -> renderList() is FireblocksConnectResult.Error -> { rowOutcomes[id] = RowOutcome("Failed (${result.code ?: result.reason})", false) renderList() } } } } Flow.HIDDEN_WEBVIEW -> FireblocksHeadlessConnect.connect(this, row.wallet.key, row.chain) { result -> runOnUiThread { connectingRowId = null when (result) { is FireblocksHeadlessConnect.Result.Success -> showConnected(result.wallet, headless = true) is FireblocksHeadlessConnect.Result.FallbackRequired -> { val expected = row.id in EXPECTED_FALLBACK rowOutcomes[id] = RowOutcome( if (expected) "Fallback required (expected)" else "Fallback required (unexpected)", expected, ) renderList() } is FireblocksHeadlessConnect.Result.Failure -> { rowOutcomes[id] = RowOutcome("Failed (${result.code})", false) renderList() } } } } } } /** [FireblocksConnect.present] appends redirect_uri, nonce, embedded and * environmentId itself, so only the preselection goes here. */ private fun hostedUrl(wallet: String, chain: String): String = Uri.parse(hostedPageUrl).buildUpon() .appendQueryParameter("wallet", wallet) // "solana-testmode" is a headless-engine option; the visible flow only knows real chains. .appendQueryParameter("chain", if (chain == "solana-testmode") "solana" else chain) .build() .toString() // "solana-testmode" (Phantom redirect mode only): the same Solana connection, // but the session binds to devnet, for a Phantom app in Testnet Mode. private fun chainLabel(chain: String) = when (chain) { "evm" -> "EVM" "solana" -> "SVM" "solana-testmode" -> "SVM · Testnet Mode" "bitcoin" -> "BTC" else -> chain.uppercase() } // ── Screen switching ────────────────────────────────────────────────────── private fun showConnected(wallet: WalletConnection, headless: Boolean = false) { connectingRowId = null connectedWallet = wallet connectedHeadlessly = headless // A session-bound network (Phantom's redirect protocol) is the only // network this wallet will sign for — follow it. The toggle is // replaced by a read-only note for such connections. wallet.network?.let { solNetwork = it } renderConnected() settingsCollapsible.set(false) applyEmbeddedLayout() swap(listScreen, connectedScreen) { connectedWallet != null } listScreen.postDelayed({ if (connectedWallet != null) { stopEmbedded() stopMetaEmbedded() } }, Motion.QUICK) } private fun disconnect() { connectedWallet = null connectedHeadlessly = false renderList() settingsCollapsible.set(true) swap(connectedScreen, listScreen) { connectedWallet == null } } /** The outgoing screen leaves quickly on an accelerate curve; the incoming * one rises in, staggered, on a decelerate curve. */ private fun swap(from: View, to: View, stillWanted: () -> Boolean) { from.animate().cancel() from.animate().alpha(0f).translationY(-ui.dpf(8f)) .setDuration(Motion.QUICK).setInterpolator(Motion.accelerate) .withEndAction { if (stillWanted()) from.visibility = View.GONE from.alpha = 1f from.translationY = 0f } .start() to.animate().cancel() to.alpha = 1f to.translationY = 0f to.visibility = View.VISIBLE scroll.scrollTo(0, 0) ui.enter((to as LinearLayout).let { g -> (0 until g.childCount).map { g.getChildAt(it) } }) } // ── Connected ───────────────────────────────────────────────────────────── private fun renderConnected() { val wallet = connectedWallet ?: return connectedScreen.removeAllViews() connectedScreen.addView(walletCard(wallet), ui.lp(bottom = 14)) if (wallet.params.isNotEmpty()) connectedScreen.addView(redirectParamsCard(wallet.params), ui.lp(bottom = 14)) // Network comes first, before anything else. Two cases: // - session-bound network (Phantom's redirect protocol, // wallet.network != null): the session decides what the wallet // will sign for — show it read-only, no choice to offer (the // engine rejects a send on the other network anyway; reconnect // with the other picker option to switch). // - no binding (other Solana wallets): free toggle, and everything // below (send, transfer) uses that choice. if (wallet.chain.lowercase() == "solana") { connectedScreen.addView( if (wallet.network != null) solanaNetworkLocked(wallet.network) else solanaNetworkToggle(), ui.lp(bottom = 14), ) } val panels = mutableListOf<Pair<String, View>>() panels += "Sign" to signPanel(wallet) panels += "Send" to if (wallet.chain.lowercase() == "solana") solanaSendPanel() else evmSendPanel() if (wallet.walletBrowserUrl == null || wallet.walletKey == null) { panels += "Transfer" to transferPanel(wallet) } if (connectedHeadlessly) panels += "Accounts" to walletAccountsPanel() panels += "Fund" to fundPanel(wallet) val host = FrameLayout(this) panels.forEachIndexed { i, (_, panel) -> panel.visibility = if (i == 0) View.VISIBLE else View.GONE host.addView(panel, FrameLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT)) } var current = 0 val tabs = SegmentedControl(ui, panels.map { it.first }, 0) { index -> val old = panels[current].second val new = panels[index].second val dir = if (index > current) 1f else -1f current = index old.animate().cancel() old.animate().alpha(0f).translationX(-dir * ui.dpf(16f)) .setDuration(Motion.QUICK).setInterpolator(Motion.accelerate) .withEndAction { if (old !== panels[current].second) old.visibility = View.GONE old.alpha = 1f old.translationX = 0f } .start() new.animate().cancel() new.visibility = View.VISIBLE new.alpha = 0f new.translationX = dir * ui.dpf(16f) new.animate().alpha(1f).translationX(0f).setStartDelay(60) .setDuration(Motion.STANDARD).setInterpolator(Motion.decelerate).start() } connectedScreen.addView(tabs, ui.lp(bottom = 14)) connectedScreen.addView(host) } private fun redirectParamsCard(params: Map<String, String>): View { val card = ui.card(padding = 0) val chevron = ui.text("›", 24f, Palette.textSecondary).apply { rotation = 90f } val headerRow = ui.horizontal().apply { setPadding(ui.dp(18), ui.dp(16), ui.dp(18), ui.dp(16)) background = ui.rippleOver(ui.rounded(0x00FFFFFF, 18), 18) isClickable = true val titles = ui.vertical().apply { addView(ui.text("Redirect params", 16f, weight = Weight.MEDIUM)) addView(ui.text("${params.size} returned by the auth webview", 13f, Palette.textSecondary), ui.lp(top = 3)) } addView(titles, ui.lp(width = 0, weight = 1f)) addView(chevron) } val body = ui.vertical().apply { setPadding(ui.dp(18), 0, ui.dp(18), ui.dp(18)) } params.entries.forEachIndexed { i, (name, value) -> body.addView(ui.text(name, 12f, Palette.textSecondary, Weight.MEDIUM), ui.lp(top = if (i == 0) 0 else 12)) body.addView( ui.text(value.ifEmpty { "(empty)" }, 13f, mono = true).apply { setTextIsSelectable(true) }, ui.lp(top = 3), ) } val bodyCollapsible = Collapsible(ui, body, expanded = false) card.addView(headerRow) card.addView(body) headerRow.setOnClickListener { val open = !bodyCollapsible.isExpanded bodyCollapsible.set(open) chevron.animate().rotation(if (open) 270f else 90f) .setDuration(Motion.STANDARD).setInterpolator(Motion.decelerate).start() } return card } private fun walletCard(wallet: WalletConnection): View { val card = ui.card() val top = ui.horizontal() val avatar = ui.avatar(wallet.walletName, 48) (avatar.layoutParams as LinearLayout.LayoutParams).rightMargin = ui.dp(14) top.addView(avatar) val titles = ui.vertical() val nameRow = ui.horizontal() nameRow.addView(ui.text(wallet.walletName, 19f, weight = Weight.BOLD)) nameRow.addView( ui.pill(chainLabel(wallet.chain.lowercase()), Palette.primary, Palette.primarySoft), ui.lp(width = WRAP_CONTENT, start = 8), ) titles.addView(nameRow) val shortAddress = shortenAddress(wallet.address) val addressRow = ui.horizontal().apply { setPadding(0, ui.dp(8), ui.dp(12), ui.dp(2)) isClickable = true } addressRow.addView(ui.text(shortAddress, 14f, Palette.textSecondary, mono = true)) val copyLabel = ui.text("Copy", 13f, Palette.primary, Weight.MEDIUM) addressRow.addView(copyLabel, ui.lp(width = WRAP_CONTENT, start = 10)) addressRow.setOnClickListener { ui.copyToClipboard("address", wallet.address) copyLabel.text = "Copied" copyLabel.postDelayed({ copyLabel.text = "Copy" }, 1400) } titles.addView(addressRow) top.addView(titles, ui.lp(width = 0, weight = 1f)) card.addView(top) card.addView( ActionButton(ui, ActionButton.Kind.SECONDARY, "Disconnect wallet").apply { setOnClickListener { FireblocksHeadlessConnect.cancel() disconnect() } }, ui.lp(top = 16), ) return card } /// Solana send: a native SOL transfer. This app only picks /// network/recipient/amount — the ENGINE builds the actual transaction /// (fetches a recent blockhash from the chosen cluster, adds a System /// Program transfer instruction; see `resolveSolanaTx` in /// `src/headless.ts`). `network` only picks which cluster THIS APP asks /// the engine to build against — the connected wallet (e.g. Phantom) /// broadcasts on whatever cluster IT is configured for, so a mismatch /// fails with something like "blockhash not found". private fun solanaNetworkToggle(): View { val card = ui.card(padding = 14) card.addView(ui.text("Solana network", 13f, Palette.textSecondary, Weight.MEDIUM), ui.lp(bottom = 8)) card.addView( SegmentedControl(ui, listOf("Mainnet", "Devnet"), if (solNetwork == "devnet") 1 else 0) { i -> solNetwork = if (i == 1) "devnet" else "mainnet-beta" }, ) return card } /// Read-only replacement for [solanaNetworkToggle] when the wallet /// session is BOUND to a network (Phantom's redirect protocol): the /// session decides what the wallet will sign for, so there's no choice /// to offer — switching means reconnecting with the other picker option /// in the wallet list. private fun solanaNetworkLocked(network: String): View = ui.text( "Network locked to ${if (network == "devnet") "Devnet" else "Mainnet"} — chosen at connect. " + "Reconnect to switch.", 13f, Palette.primary, ).apply { background = ui.rounded(Palette.primarySoft, 14) setPadding(ui.dp(14), ui.dp(12), ui.dp(14), ui.dp(12)) } // ── Action panels ───────────────────────────────────────────────────────── private fun panelCard(title: String, description: String): LinearLayout = ui.card().apply { addView(ui.text(title, 18f, weight = Weight.BOLD)) addView(ui.text(description, 14f, Palette.textSecondary), ui.lp(top = 4, bottom = 6)) } private fun label(text: String) = ui.text(text, 13f, Palette.textSecondary, Weight.MEDIUM) private fun shortenAddress(address: String) = if (address.length > 12) "${address.take(6)}…${address.takeLast(4)}" else address private fun walletAccountsPanel(): View { val card = panelCard( "Wallet accounts", "Lists the accounts the engine currently holds.", ) val button = ActionButton(ui, ActionButton.Kind.PRIMARY, "Get wallet accounts") val list = ui.vertical() val result = ResultView(ui) card.addView(button, ui.lp(top = 16)) card.addView(list, ui.lp(top = 14)) card.addView(result, ui.lp(top = 14)) button.setOnClickListener { result.clear() list.removeAllViews() button.setLoading(true, "Loading…") FireblocksHeadlessConnect.getWalletAccounts { outcome -> runOnUiThread { button.setLoading(false) when (outcome) { is WalletAccountsResult.Success -> showWalletAccounts(list, outcome.accounts) is WalletAccountsResult.Failure -> result.error("[${outcome.code}] ${outcome.message}") } } } } return card } private fun formatLastSelected(date: Date?): String { if (date == null) return "never" val format = SimpleDateFormat("yyyy-MM-dd HH:mm 'UTC'", Locale.US) format.timeZone = TimeZone.getTimeZone("UTC") return format.format(date) } private fun showWalletAccounts(list: LinearLayout, accounts: List<WalletAccount>) { list.addView(ui.text("${accounts.size} account(s)", 14f, weight = Weight.BOLD)) if (accounts.isEmpty()) { list.addView( ui.text("No wallet accounts known to the engine.", 14f, Palette.textSecondary), ui.lp(top = 8), ) } for (account in accounts) { val rows = listOf( "Chain" to account.chain, "Provider" to account.walletProviderKey, "ID" to account.id, "Last selected" to formatLastSelected(account.lastSelectedAt), ) val accountCard = ui.vertical().apply { background = ui.rounded(Palette.bg, 12, Palette.border) setPadding(ui.dp(12), ui.dp(12), ui.dp(12), ui.dp(12)) } accountCard.addView(ui.text(shortenAddress(account.address), 15f, weight = Weight.BOLD, mono = true)) for ((label, value) in rows) { val row = ui.horizontal() row.addView(ui.text(label, 13f, Palette.textSecondary, Weight.MEDIUM), ui.lp(width = WRAP_CONTENT, end = 8)) row.addView(ui.text(value, 13f, mono = true), ui.lp(width = 0, weight = 1f)) accountCard.addView(row, ui.lp(top = 6)) } list.addView(accountCard, ui.lp(top = 12)) } } private fun signPanel(wallet: WalletConnection): View { val card = panelCard("Sign a message", "Signs the message below with the connected wallet. Nothing is sent on chain.") val button = ActionButton(ui, ActionButton.Kind.PRIMARY, "Sign message") val result = ResultView(ui) val defaultMessage = "Fireblocks Android sample sign test — ${System.currentTimeMillis()}" val messageField = ui.input("Message to sign", defaultMessage, Ui.InputKind.ADDRESS) card.addView(ui.field("Message", messageField), ui.lp(top = 12)) card.addView(button, ui.lp(top = 16)) card.addView(result, ui.lp(top = 14)) button.setOnClickListener { result.clear() val message = messageField.text.toString() if (message.isBlank()) { result.validation("Enter a message to sign.") return@setOnClickListener } button.setLoading(true, "Waiting for wallet…") val done = { signature: String?, error: String? -> runOnUiThread { button.setLoading(false) if (signature != null) { result.success("Message signed", signature, signature) } else if (error != null) { result.error(error) } } } // A connection made inside the WALLET's own browser (Phantom on // EVM) has to be signed there too — that's the only place its // injected provider exists; neither the headless engine nor the // Custom Tab flow can see it. val template = wallet.walletBrowserUrl val walletKey = wallet.walletKey if (template != null && walletKey != null) { FireblocksWalletBrowser.signMessage( context = this@MainActivity, hostedPageUrl = hostedPageUrl, scheme = scheme, walletBrowserUrl = template, walletKey = walletKey, message = message, expectedAddress = wallet.address, environmentId = environmentId, locale = testLocale, theme = testTheme, phantomMode = testPhantomMode, ) { r -> when (r) { is FireblocksSignResult.Success -> done(r.signature, null) is FireblocksSignResult.Cancelled -> done(null, null) is FireblocksSignResult.Error -> done(null, "[${r.code ?: "unknown"}] ${r.reason}") } } return@setOnClickListener } FireblocksHeadlessConnect.sign(message) { r -> when (r) { is SignResult.Success -> done(r.signature, null) is SignResult.Failure -> done(null, "[${r.code}] ${r.message}") } } } return card } /** Circle's native USDC (6 decimals) per network id as typed in the Network field. */ private val usdcByNetwork = mapOf( "1" to "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", "11155111" to "0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238", "84532" to "0x036CbD53842c5426634e7929541eC2318f3dCF7e", "137" to "0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359", "80002" to "0x41E94Eb019C0762f9Bfcf9Fb1E58725BfB0e7582", "mainnet-beta" to "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", "devnet" to "4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU", ) private val usdcDecimals = 6 private val evmNetworks = listOf( Preset("Ethereum", "1"), Preset("Sepolia", "11155111"), Preset("Base Sepolia", "84532"), Preset("Polygon", "137"), Preset("Polygon Amoy", "80002"), ) /** Chips that fill [input] with a preset, and follow it when the user types a matching value. */ private fun presetChips(presets: List<Preset>, input: EditText): View { val chips = ChipGroup(ui, presets.map { it.label }, presets.indexOfFirst { it.value == input.text.toString().trim() }.takeIf { it >= 0 }) { i -> input.setText(presets[i].value) input.setSelection(input.text.length) } input.doAfterTextChanged { text -> val value = text.toString().trim() chips.select(presets.indexOfFirst { it.value == value }.takeIf { it >= 0 }) } return chips.view } /// EVM send: a plain JSON tx object — no chain SDK needed to build it, /// unlike Solana below. private fun evmSendPanel(): View { val card = panelCard("Send a transaction", "A native or ERC-20 transfer, signed and broadcast by the connected wallet.") val chainIdField = ui.input("e.g. 1", "1", Ui.InputKind.INTEGER) card.addView(label("Network"), ui.lp(top = 12, bottom = 8)) card.addView(presetChips(evmNetworks, chainIdField)) card.addView(ui.field("Chain ID", chainIdField), ui.lp(top = 12)) // Asset — native token, or a custom ERC-20 by contract address (e.g. // a token not worth curating a chain-id table for, like B3). No RPC // call backs this app, so decimals/symbol are typed in rather than // looked up — see the caution label below the fields. card.addView(label("Asset"), ui.lp(top = 16, bottom = 8)) val customTokenContainer = ui.vertical() val customTokenAddressField = ui.input("0x…", kind = Ui.InputKind.ADDRESS, mono = true) val customTokenSymbolField = ui.input("e.g. B3", kind = Ui.InputKind.CAPS) val customTokenDecimalsField = ui.input("18", "18", Ui.InputKind.INTEGER) customTokenContainer.addView(ui.field("Token contract address", customTokenAddressField), ui.lp(top = 14)) val tokenRow = ui.horizontal().apply { gravity = Gravity.TOP } tokenRow.addView(ui.field("Symbol", customTokenSymbolField), ui.lp(width = 0, weight = 1f, end = 10)) tokenRow.addView(ui.field("Decimals", customTokenDecimalsField), ui.lp(width = 0, weight = 1f)) customTokenContainer.addView(tokenRow, ui.lp(top = 14)) customTokenContainer.addView( ui.text( "This app makes no RPC call to verify decimals against the token contract — wrong " + "decimals sends the wrong amount. Double-check on a block explorer before sending.", 12f, Palette.warning, ).apply { background = ui.rounded(Palette.warningSoft, 12) setPadding(ui.dp(12), ui.dp(10), ui.dp(12), ui.dp(10)) }, ui.lp(top = 12), ) val amountLabel = label("Amount (native token)") lateinit var assetSeg: SegmentedControl fun refreshAmountLabel() { amountLabel.text = if (assetSeg.index == 1) { val symbol = customTokenSymbolField.text.toString().trim() "Amount (${symbol.ifEmpty { "TOKEN" }.uppercase()})" } else { "Amount (native token)" } } lateinit var customCollapsible: Collapsible assetSeg = SegmentedControl(ui, listOf("Native", "Custom token"), 0) { i -> customCollapsible.set(i == 1) refreshAmountLabel() } card.addView(assetSeg) card.addView(customTokenContainer) customCollapsible = Collapsible(ui, customTokenContainer, expanded = false) customTokenSymbolField.doAfterTextChanged { refreshAmountLabel() } val toField = ui.input("0x…", "0xc0ffee254729296a45a3885639AC7E10F9d54979", Ui.InputKind.ADDRESS, mono = true) card.addView(ui.field("Recipient", toField), ui.lp(top = 16)) val amountField = ui.input("0.001", kind = Ui.InputKind.DECIMAL) card.addView(amountLabel, ui.lp(top = 16, bottom = 6)) card.addView(amountField) val result = ResultView(ui) val sendButton = ActionButton(ui, ActionButton.Kind.PRIMARY, "Review & send") card.addView(sendButton, ui.lp(top = 20)) card.addView(result, ui.lp(top = 14)) sendButton.setOnClickListener { refreshAmountLabel() result.clear() val chainId = chainIdField.text.toString().trim().toIntOrNull() val recipient = toField.text.toString().trim() val isCustom = assetSeg.index == 1 val tokenAddress = customTokenAddressField.text.toString().trim() val decimals = if (isCustom) customTokenDecimalsField.text.toString().trim().toIntOrNull() else 18 val units = decimals?.let { parseUnits(amountField.text.toString(), it) } val validRecipient = recipient.matches(Regex("^0x[0-9a-fA-F]{40}$")) val validToken = !isCustom || tokenAddress.matches(Regex("^0x[0-9a-fA-F]{40}$")) if (chainId == null || !validRecipient || decimals == null || units == null || !validToken) { result.validation( if (isCustom) { "Enter a valid chain ID, token contract address, recipient (0x + 40 hex " + "chars), decimals, and amount." } else { "Enter a valid chain ID, recipient (0x + 40 hex chars), and amount." }, ) return@setOnClickListener } // The `to`/`value`/`data` this send needs: a plain native transfer, // or an ERC-20 `transfer(address,uint256)` call against the token // contract when a custom asset is selected. val to = if (isCustom) tokenAddress else recipient val value = if (isCustom) "0x0" else "0x" + units.toString(16) val data = if (isCustom) erc20TransferCalldata(recipient, units) else "0x" val symbol = if (isCustom) customTokenSymbolField.text.toString().trim().ifEmpty { "TOKEN" }.uppercase() else "native" val summary = mutableListOf("Network" to "Chain $chainId", "To" to recipient, "Amount" to "${amountField.text.toString().trim()} $symbol") if (isCustom) summary.add(2, "Token contract" to tokenAddress) ui.reviewSheet( this, "Review transaction", summary, "This sends a REAL transaction on chain $chainId and spends real gas from the connected wallet. " + "This cannot be undone.", "Send", ) { sendButton.setLoading(true, "Sending…") val done = { txHash: String?, error: String? -> runOnUiThread { sendButton.setLoading(false) if (txHash != null) { result.success("Transaction sent", txHash, txHash) } else if (error != null) { result.error(error) } } } // Same reasoning as the sign button's wallet-browser branch: // the wallet only exposes this account inside its own // browser, so the send has to be confirmed there. val connected = connectedWallet val template = connected?.walletBrowserUrl val walletKey = connected?.walletKey if (connected != null && template != null && walletKey != null) { FireblocksWalletBrowser.sendTransaction( context = this@MainActivity, hostedPageUrl = hostedPageUrl, scheme = scheme, walletBrowserUrl = template, walletKey = walletKey, to = to, chainId = "0x" + chainId.toString(16), expectedAddress = connected.address, value = value, data = data, environmentId = environmentId, locale = testLocale, theme = testTheme, phantomMode = testPhantomMode, ) { r -> when (r) { is FireblocksSendResult.Success -> done(r.txHash, null) is FireblocksSendResult.Cancelled -> done(null, null) is FireblocksSendResult.Error -> done(null, "[${r.code ?: "unknown"}] ${r.reason}") } } return@reviewSheet } val transaction = org.json.JSONObject() .put("to", to) .put("value", value) .put("data", data) .put("chainId", "0x" + chainId.toString(16)) .toString() FireblocksHeadlessConnect.sendTransaction(transaction) { r -> when (r) { is SendResult.Success -> done(r.txHash, null) is SendResult.Failure -> done(null, "[${r.code}] ${r.message}") } } } } return card } private fun solanaSendPanel(): View { val card = panelCard("Send SOL", "A native SOL transfer. The engine builds the transaction on the network chosen above.") val toField = ui.input("Base58 address", kind = Ui.InputKind.ADDRESS, mono = true) card.addView(ui.field("Recipient", toField), ui.lp(top = 12)) val amountField = ui.input("0.01", kind = Ui.InputKind.DECIMAL) card.addView(ui.field("Amount (SOL)", amountField), ui.lp(top = 16)) card.addView( ui.text( "Make sure the connected wallet is also set to the same network — this app can't switch it for you.", 12f, Palette.textSecondary, ), ui.lp(top = 10), ) val result = ResultView(ui) val sendButton = ActionButton(ui, ActionButton.Kind.PRIMARY, "Review & send") card.addView(sendButton, ui.lp(top = 20)) card.addView(result, ui.lp(top = 14)) sendButton.setOnClickListener { result.clear() val to = toField.text.toString().trim() val lamports = parseUnits(amountField.text.toString(), 9) if (!to.matches(Regex("^[1-9A-HJ-NP-Za-km-z]{32,44}$")) || lamports == null) { result.validation("Enter a valid Solana recipient address and amount.") return@setOnClickListener } val network = solNetwork val networkName = if (network == "mainnet-beta") "Mainnet" else "Devnet" ui.reviewSheet( this, "Review transaction", listOf("Network" to "Solana $networkName", "To" to to, "Amount" to "${amountField.text.toString().trim()} SOL"), "This sends a REAL SOL transfer on Solana $networkName and spends real SOL for network fees " + "from the connected wallet. This cannot be undone.", "Send", ) { sendButton.setLoading(true, "Sending…") val transaction = org.json.JSONObject() .put("to", to) .put("lamports", lamports.toString()) .put("network", network) .toString() FireblocksHeadlessConnect.sendTransaction(transaction) { r -> runOnUiThread { sendButton.setLoading(false) when (r) { is SendResult.Success -> result.success("Transaction sent", r.txHash, r.txHash) is SendResult.Failure -> result.error("[${r.code}] ${r.message}") } } } } } return card } /// transferAmount: a display-unit amount — the engine builds and validates /// everything, so nothing here is parsed beyond what the call signature needs. private fun transferPanel(wallet: WalletConnection): View { val card = panelCard( "Transfer amount", "A display-unit amount — no transaction to build. The engine validates it and picks the asset.", ) val recipientField = ui.input("Recipient address", kind = Ui.InputKind.ADDRESS, mono = true) card.addView(ui.field("Recipient", recipientField), ui.lp(top = 12)) val amountField = ui.input("0.01", kind = Ui.InputKind.DECIMAL) card.addView(ui.field("Amount", amountField), ui.lp(top = 16)) val networkIdField = ui.input("Wallet default", kind = Ui.InputKind.TEXT) val presets = when (wallet.chain.lowercase()) { "evm" -> listOf(Preset("Wallet default", "")) + listOf("Sepolia", "Base Sepolia", "Polygon Amoy", "Polygon", "Ethereum") .map { name -> evmNetworks.first { it.label == name } } "solana" -> listOf(Preset("Wallet default", ""), Preset("Mainnet", "mainnet-beta"), Preset("Devnet", "devnet")) else -> emptyList() } card.addView(label("Network (optional)"), ui.lp(top = 16, bottom = 8)) if (presets.isNotEmpty()) card.addView(presetChips(presets, networkIdField)) card.addView( ui.field("Network ID", networkIdField, "EVM chainId, or mainnet-beta / devnet. Blank uses the wallet's active network."), ui.lp(top = if (presets.isNotEmpty()) 12 else 0), ) card.addView(label("Asset"), ui.lp(top = 16, bottom = 8)) val tokenContainer = ui.vertical() val tokenAddressField = ui.input("Token contract or mint address", kind = Ui.InputKind.ADDRESS, mono = true) val tokenDecimalsField = ui.input("e.g. 6", kind = Ui.InputKind.INTEGER) tokenContainer.addView(ui.field("Token address", tokenAddressField), ui.lp(top = 14)) tokenContainer.addView(ui.field("Token decimals", tokenDecimalsField), ui.lp(top = 14)) lateinit var tokenCollapsible: Collapsible val assetSeg = SegmentedControl(ui, listOf("Native", "Token", "USDC"), 0) { i -> tokenCollapsible.set(i == 1) } card.addView(assetSeg) card.addView(tokenContainer) tokenCollapsible = Collapsible(ui, tokenContainer, expanded = false) val result = ResultView(ui) val transferButton = ActionButton(ui, ActionButton.Kind.PRIMARY, "Review & transfer") card.addView(transferButton, ui.lp(top = 20)) card.addView(result, ui.lp(top = 14)) transferButton.setOnClickListener { result.clear() val recipient = recipientField.text.toString().trim() val amount = amountField.text.toString().trim() val networkId = networkIdField.text.toString().trim().ifEmpty { null } val useToken = assetSeg.index == 1 val useUsdc = assetSeg.index == 2 val usdcAddress = if (useUsdc) usdcByNetwork[networkId] else null val tokenAddress = when { useToken -> tokenAddressField.text.toString().trim() useUsdc -> usdcAddress.orEmpty() else -> "" } val tokenDecimals = if (useUsdc) usdcDecimals else tokenDecimalsField.text.toString().trim().toIntOrNull() val inputError = when { recipient.isEmpty() -> "Enter a recipient." amount.isEmpty() -> "Enter an amount." useUsdc && usdcAddress == null -> "Pick a network with a known USDC (Ethereum, Sepolia, Base Sepolia, Polygon, Polygon Amoy, Solana mainnet/devnet), or use Token." useToken && tokenAddress.isEmpty() -> "Enter the token's address, or switch the asset to Native." tokenAddress.isNotEmpty() && tokenDecimals == null -> "Enter the token's decimals (a whole number)." else -> null } if (inputError != null) { result.validation(inputError) return@setOnClickListener } val token = if (tokenAddress.isNotEmpty() && tokenDecimals != null) { TransferToken(tokenAddress, tokenDecimals) } else { null } val summary = mutableListOf( "Network" to (networkId ?: "Wallet's active network"), "To" to recipient, "Amount" to when { useUsdc -> "$amount USDC" token != null -> "$amount (token, $tokenDecimals decimals)" else -> "$amount (native)" }, ) if (token != null) summary.add(2, "Token" to tokenAddress) ui.reviewSheet( this, "Review transfer", summary, "This sends $amount to the recipient as a REAL transaction from the connected wallet. " + "This cannot be undone.", "Send", ) { transferButton.setLoading(true, "Sending…") FireblocksHeadlessConnect.transferAmount( from = wallet.address, amount = amount, recipient = recipient, networkId = networkId, token = token, ) { r -> runOnUiThread { transferButton.setLoading(false) when (r) { is SendResult.Success -> result.success("Transfer sent", r.txHash, r.txHash) is SendResult.Failure -> result.error("[${r.code}] ${r.message}") } } } } } return card } /** "Fund from Coinbase": opens the hosted page's ?intent=fundFromExchange * flow in a Custom Tab. Needs no connected wallet and no signature — the * user signs in to the exchange and the exchange sends the funds. The * sample targets the connected wallet's address purely because that's the * address on screen. See [FireblocksConnect.fundFromExchange] for why * there's no headless path. */ private fun fundPanel(wallet: WalletConnection): View { val card = panelCard( "Fund from Coinbase", "Opens Coinbase in a Custom Tab; the exchange sends the funds to this wallet's address.", ) // Left blank on purpose: a prefilled currency narrows the hosted // page's balance picker down to just that currency (see its // preferredSources()) — fine for an integrator who already knows // what they want, but it means this sample would only ever show // USDC unless the field is cleared first. Empty shows every balance. val currencyField = ui.input("e.g. USDC", kind = Ui.InputKind.CAPS) card.addView( ui.field("Currency (optional)", currencyField, "Leave blank to see every balance."), ui.lp(top = 12), ) val amountField = ui.input("e.g. 10", kind = Ui.InputKind.DECIMAL) card.addView(ui.field("Amount", amountField), ui.lp(top = 16)) val result = ResultView(ui) val button = ActionButton(ui, ActionButton.Kind.PRIMARY, "Fund from Coinbase") card.addView(button, ui.lp(top = 20)) card.addView(result, ui.lp(top = 14)) button.setOnClickListener { result.clear() button.setLoading(true, "Waiting for Coinbase…") FireblocksConnect.fundFromExchange( context = this, hostedPageUrl = hostedPageUrl, scheme = scheme, to = wallet.address, currency = currencyField.text.toString().trim(), amount = amountField.text.toString().trim(), environmentId = environmentId, locale = testLocale, theme = testTheme, ) { r -> runOnUiThread { button.setLoading(false) when (r) { is FireblocksFundResult.Success -> { // The id is the exchange's, not a tx hash — label it // so nobody pastes it into a block explorer. result.success( "Coinbase transfer started", "${r.transferId}\n${r.amount} ${r.currency}" + (r.status?.let { " · $it" } ?: "") + "\nExchange id, not an on-chain hash.", r.transferId, ) } is FireblocksFundResult.Cancelled -> Unit is FireblocksFundResult.Error -> result.error("[${r.code ?: "unknown"}] ${r.reason}") } } } } return card } /// Parses a decimal-string amount (e.g. "10.5") into the smallest unit for /// a token with [decimals] decimal places, as a [BigInteger] — no /// floating point, so precision never gets lost the way `Double` would /// with large amounts. Returns `null` for empty/malformed input, too many /// fractional digits, or a zero amount. Mirrors `_parseUnits` in the /// Flutter sample's `example_screen.dart`. private fun parseUnits(input: String, decimals: Int): BigInteger? { val trimmed = input.trim() if (trimmed.isEmpty() || !Regex("^\\d+(\\.\\d+)?$").matches(trimmed)) return null val parts = trimmed.split(".") val whole = parts[0] val frac = if (parts.size > 1) parts[1] else "" if (frac.length > decimals) return null val value = (whole + frac.padEnd(decimals, '0')).toBigIntegerOrNull() ?: return null return if (value == BigInteger.ZERO) null else value } /// Encodes an ERC-20 `transfer(address,uint256)` call: 4-byte selector /// (`0xa9059cbb`) + the recipient left-padded to 32 bytes + the amount /// left-padded to 32 bytes. Mirrors `_erc20TransferCalldata` in the /// Flutter sample's `example_screen.dart`. private fun erc20TransferCalldata(recipient: String, amount: BigInteger): String { val addressWord = recipient.removePrefix("0x").lowercase().padStart(64, '0') val amountWord = amount.toString(16).padStart(64, '0') return "0xa9059cbb$addressWord$amountWord" }}/** The demo's saved Phantom mode. Read once per process: the hidden engine keeps * the mode it first loaded with until the app restarts. */private object PhantomModeSetting { private const val KEY = "phantomMode" private var atLaunch: String? = null private var read = false fun atLaunch(context: Context): String? { if (!read) { atLaunch = saved(context) read = true } return atLaunch } fun saved(context: Context): String? = prefs(context).getString(KEY, null) fun save(context: Context, mode: String?) = prefs(context).edit().putString(KEY, mode).apply() private fun prefs(context: Context) = context.getSharedPreferences("demo", Context.MODE_PRIVATE)}/** The demo's saved Wallet return URL, same read-once semantics as * [PhantomModeSetting]. */private object WalletReturnUrlSetting { private const val KEY = "walletReturnUrl" private var atLaunch: String? = null private var read = false fun atLaunch(context: Context): String? { if (!read) { atLaunch = saved(context) read = true } return atLaunch } fun saved(context: Context): String? = prefs(context).getString(KEY, null) fun save(context: Context, url: String?) = prefs(context).edit().putString(KEY, url).apply() private fun prefs(context: Context) = context.getSharedPreferences("demo", Context.MODE_PRIVATE)}/** A [ScrollView] that can be locked, for a screen whose content fills the viewport and scrolls itself. */private class LockableScrollView(context: Context) : ScrollView(context) { var scrollingEnabled = true override fun onInterceptTouchEvent(ev: MotionEvent) = scrollingEnabled && super.onInterceptTouchEvent(ev) override fun onTouchEvent(ev: MotionEvent) = scrollingEnabled && super.onTouchEvent(ev)}
9. Connect Phantom
Connect Phantom on EVM or Solana with the same call as any other wallet: FireblocksHeadlessConnect.connect(this, "phantom", "evm"), or "solana" as the chain. Phantom has no WalletConnect entry in Dynamic’s wallet book. In the default in-appPhantom mode, the engine bridges through Phantom’s own in-app browser:
The engine mints a WalletConnect pairing and sends a deeplink that opens your hosted page inside Phantom.
The page approves the pairing with Phantom’s injected provider, and the engine receives the connection over the WalletConnect relay.
Phantom’s “Return to app” button opens <scheme>://phantom-headless with no payload. FireblocksHeadlessConnect.handleReturnURL (called from FireblocksRedirectActivity) consumes it, and your connect callback receives the result from the engine.
No connection data comes back through your URL scheme. The engine offers a chain only when your Dynamic environment has a network enabled for it, and it fails with timeout if Phantom does not approve within 60 seconds.
Phantom modes
Set FireblocksHeadlessConnect.phantomMode before prewarm() to choose how the engine connects Phantom:
in-app (default) uses the WalletConnect bridge described above. It works on EVM and Solana but only connects; sign and send calls return fallback_required.
redirect uses Phantom’s encrypted deeplinks on Solana only. Phantom returns to your app after the connect and after every signature, and handleReturnURL passes the response to the engine. This mode works only through the headless engine, not the visible flows.
Return Phantom to an https link
In redirect mode, Phantom returns to <scheme>://phantom-headless by default. To use your app’s https App Link instead, set walletReturnUrl before prewarm() and forward the incoming link to handleReturnURL:
MainActivity.kt
FireblocksHeadlessConnect.phantomMode = "redirect"FireblocksHeadlessConnect.walletReturnUrl = "https://your-app.com/phantom-return"FireblocksHeadlessConnect.prewarm(this)// in the activity that owns the App Linkintent?.data?.let { FireblocksHeadlessConnect.handleReturnURL(it) }
The URL must use https, or the engine falls back to the custom scheme. handleReturnURL and the engine accept a returning link only when its origin and path match walletReturnUrl.
10. Use a wallet’s own browser (Phantom on EVM)
Phantom injects its EVM provider (window.phantom.ethereum) only inside its own in-app browser. To sign or send with it, open your hosted page inside Phantom’s browser: connect there, then reopen the same browser for each sign or send.Each operation is one round trip: Phantom comes to the foreground with your page in it, the user approves, and the result arrives on <scheme>://wallet-browser.
The engine reports each wallet’s in-app-browser template in the wallets bridge message as inAppBrowser. The template contains {{encodedDappURI}}, and you replace every occurrence (Phantom’s uses it twice). A template is not a chain: it only means the wallet can open a URL in its own browser, so you decide per wallet which chains that browser serves.
package com.fireblocks.connectimport android.content.ActivityNotFoundExceptionimport android.content.Contextimport android.content.Intentimport android.net.Uriimport android.os.Handlerimport android.os.Looperimport android.util.Logimport java.security.SecureRandom/** * Drives the hosted visible flow **inside a wallet's own in-app browser**. * * ## Why this exists (and why it isn't [FireblocksConnect]) * * [FireblocksConnect] opens the hosted page in a Chrome Custom Tab — a system * browser. That covers every wallet reachable by WalletConnect, a deeplink, or * an SDK (Base Account). It cannot cover a wallet whose only mobile surface for * a given chain is the provider it injects into its OWN browser, because that * provider isn't there in a Custom Tab. * * Phantom on EVM is exactly that case, and it's why "Phantom EVM" never worked: * no `phantom*` entry in Dynamic's wallet book has a `walletConnect` block, and * `phantomevm` carries no mobile deeplink at all — its only surface is * `window.phantom.ethereum`, injected inside Phantom's in-app browser (see * `classifyChain`'s doc comment in `src/utils/chain`). So the page has to be * opened THERE, and the result handed back over this app's URL scheme. * * ## Mechanics * * 1. Build the hosted-page URL (`?wallet=…&chain=evm`, or an * `?intent=signMessage|sendTx` variant) with * `redirect_uri=<scheme>://[CALLBACK_HOST]` and a fresh nonce. * 2. Wrap it in the wallet's in-app-browser template (`{{encodedDappURI}}`, * replaced everywhere — Phantom's uses it twice) and hand it to the OS with * `ACTION_VIEW`. The template comes from the engine's wallet catalogue * ([FireblocksHeadlessConnect.Wallet.inAppBrowser]), i.e. from Dynamic's * wallet book — never hard-coded here. * 3. The wallet opens its browser on the page; the user connects/signs with the * injected provider; the page redirects to `<scheme>://[CALLBACK_HOST]`, * which [FireblocksRedirectActivity] catches and routes here. * * The callback host differs from the Custom Tab flow's `wallet-callback` on * purpose: a return from the wallet's app must not be able to complete (or * steal) an in-flight Custom Tab request, and vice versa. * * ## Caveats worth knowing before shipping this * * - Step 2 hands an `https` app link to the OS. It reaches the wallet only if * the wallet's app links are verified for that domain; otherwise it can land * in Chrome, where nothing is injected and the page correctly reports that * the wallet has no path for this chain. That message in a browser that ISN'T * the wallet means the hand-off went to the wrong app, not that the wallet * can't do it. * - Whether a wallet's browser honours a custom-scheme navigation is the * wallet's choice. The hosted page always ALSO renders a "Return to the app" * anchor for custom-scheme targets (a real tap is the reliable path where a * programmatic navigation is ignored), so the user has a way back either way. * - Nothing here is silent: the wallet app comes to the foreground with a web * page in it, plus the wallet's own approval prompt. * * Single in-flight request at a time (the callback carries no request id beyond * its nonce). Held statically, like [FireblocksConnect]; a production app should * prefer a ViewModel so it survives process death. */object FireblocksWalletBrowser { const val CALLBACK_HOST = "wallet-browser" /** * How long to wait for the return URL before giving up. The user is in * another app for this whole window (open, connect, approve, come back), so * this is generous by design; it exists so an abandoned flow can't leave a * callback pending for the process lifetime. */ private const val TIMEOUT_MS = 5 * 60 * 1000L private const val TAG = "FbWalletBrowser" private sealed class Pending { abstract val nonce: String class Connect( override val nonce: String, val walletKey: String, val walletBrowserUrl: String, val chain: String, val onResult: (FireblocksConnectResult) -> Unit, ) : Pending() class Sign( override val nonce: String, val onResult: (FireblocksSignResult) -> Unit, ) : Pending() class Send( override val nonce: String, val onResult: (FireblocksSendResult) -> Unit, ) : Pending() } private var pending: Pending? = null private val handler = Handler(Looper.getMainLooper()) private var timeout: Runnable? = null /** * Connect [walletKey] on [chain] inside the wallet's own browser. * * @param walletBrowserUrl the wallet's in-app-browser template, from * [FireblocksHeadlessConnect.Wallet.inAppBrowser]. * @param locale UI locale for the hosted page — e.g. `"en_US"`, `"es_LA"`. * `null`/blank omits the param. * @param theme UI theme for the hosted page — `"light"` or `"dark"`. * `null`/blank omits the param. * @param phantomMode How the hosted page connects Phantom — `"in-app"` or * `"redirect"`. `null`/blank omits the param. * * The resulting [WalletConnection] carries [WalletConnection.walletBrowserUrl] * and [WalletConnection.walletKey] so later sign/send calls can be routed * back into the same browser — the account lives with that injected provider * and nowhere else. */ fun connect( context: Context, hostedPageUrl: String, scheme: String, walletBrowserUrl: String, walletKey: String, chain: String = "evm", environmentId: String? = null, locale: String? = null, theme: String? = null, phantomMode: String? = null, onResult: (FireblocksConnectResult) -> Unit, ) { val nonce = randomNonce() val pageUrl = buildPageUrl( hostedPageUrl, scheme, nonce, environmentId, locale, theme, phantomMode, mapOf("wallet" to walletKey, "chain" to chain), ) arm(Pending.Connect(nonce, walletKey, walletBrowserUrl, chain, onResult)) { onResult(FireblocksConnectResult.Cancelled) } if (!open(context, walletBrowserUrl, pageUrl)) { clear() onResult(FireblocksConnectResult.Error("could not open the wallet app — is it installed?")) } } /** * Sign [message] with a wallet connected through [connect]. * * [expectedAddress] is REQUIRED and checked by the page itself: it connects * again inside the wallet's browser before signing, and without this it * would sign with whatever account happens to connect. * * @param locale UI locale for the hosted page — e.g. `"en_US"`, `"es_LA"`. * `null`/blank omits the param. * @param theme UI theme for the hosted page — `"light"` or `"dark"`. * `null`/blank omits the param. * @param phantomMode Same as [connect]'s. */ fun signMessage( context: Context, hostedPageUrl: String, scheme: String, walletBrowserUrl: String, walletKey: String, message: String, expectedAddress: String, environmentId: String? = null, locale: String? = null, theme: String? = null, phantomMode: String? = null, onResult: (FireblocksSignResult) -> Unit, ) { val nonce = randomNonce() val pageUrl = buildPageUrl( hostedPageUrl, scheme, nonce, environmentId, locale, theme, phantomMode, mapOf( "intent" to "signMessage", "walletKey" to walletKey, "message" to message, "expectedAddress" to expectedAddress, ), ) arm(Pending.Sign(nonce, onResult)) { onResult(FireblocksSignResult.Cancelled) } if (!open(context, walletBrowserUrl, pageUrl)) { clear() onResult(FireblocksSignResult.Error("could not open the wallet app — is it installed?")) } } /** * Send an EVM transaction with a wallet connected through [connect]. * [to] / [chainId] / [value] / [data] / [gasLimit] are `0x`-prefixed hex, * same contract as [FireblocksConnect.sendTransaction]. The wallet signs AND * broadcasts: a success is already on-chain. * * @param locale UI locale for the hosted page — e.g. `"en_US"`, `"es_LA"`. * `null`/blank omits the param. * @param theme UI theme for the hosted page — `"light"` or `"dark"`. * `null`/blank omits the param. * @param phantomMode Same as [connect]'s. */ fun sendTransaction( context: Context, hostedPageUrl: String, scheme: String, walletBrowserUrl: String, walletKey: String, to: String, chainId: String, expectedAddress: String, value: String = "0x0", data: String = "0x", gasLimit: String? = null, environmentId: String? = null, locale: String? = null, theme: String? = null, phantomMode: String? = null, onResult: (FireblocksSendResult) -> Unit, ) { val nonce = randomNonce() val params = buildMap { put("intent", "sendTx") put("walletKey", walletKey) put("to", to) put("value", value) put("data", data) put("chainId", chainId) put("expectedAddress", expectedAddress) gasLimit?.takeIf { it.isNotBlank() }?.let { put("gasLimit", it) } } val pageUrl = buildPageUrl(hostedPageUrl, scheme, nonce, environmentId, locale, theme, phantomMode, params) arm(Pending.Send(nonce, onResult)) { onResult(FireblocksSendResult.Cancelled) } if (!open(context, walletBrowserUrl, pageUrl)) { clear() onResult(FireblocksSendResult.Error("could not open the wallet app — is it installed?")) } } /** Abandon the in-flight request (e.g. the user navigated away in the app). */ fun cancel() { val inFlight = pending ?: return clear() when (inFlight) { is Pending.Connect -> inFlight.onResult(FireblocksConnectResult.Cancelled) is Pending.Sign -> inFlight.onResult(FireblocksSignResult.Cancelled) is Pending.Send -> inFlight.onResult(FireblocksSendResult.Cancelled) } } /** * Called by [FireblocksRedirectActivity]. Returns `true` when the URL was * this flow's callback (consumed, whether or not a request was waiting), so * the activity can fall through to the Custom Tab flows for anything else. */ internal fun handleRedirect(uri: Uri): Boolean { if (!uri.host.equals(CALLBACK_HOST, ignoreCase = true)) return false val inFlight = pending ?: run { Log.d(TAG, "callback with no request in flight: $uri") return true } // A stale callback (an old page re-opened in the wallet's browser) must // not resolve the request that IS in flight: drop it and keep waiting, // rather than failing the live request with a nonce mismatch. if (uri.getQueryParameter("nonce") != inFlight.nonce) { Log.d(TAG, "dropped callback with mismatched nonce") return true } clear() when (inFlight) { is Pending.Connect -> { val address = uri.getQueryParameter("address").orEmpty() if (address.isEmpty()) { inFlight.onResult(FireblocksConnectResult.Error("malformed result")) } else { inFlight.onResult( FireblocksConnectResult.Success( WalletConnection( address = address, chain = uri.getQueryParameter("chain") ?: inFlight.chain, walletName = uri.getQueryParameter("walletName").orEmpty(), walletImage = uri.getQueryParameter("walletImage").orEmpty(), sessionId = "", walletKey = inFlight.walletKey, walletBrowserUrl = inFlight.walletBrowserUrl, networkId = uri.getQueryParameter("networkId")?.takeIf { it.isNotEmpty() }, ) ) ) } } is Pending.Sign -> { if (uri.getQueryParameter("error") == "1") { val message = uri.getQueryParameter("message").orEmpty() inFlight.onResult( FireblocksSignResult.Error( message.ifEmpty { "sign failed" }, uri.getQueryParameter("code") ?: "unknown", ) ) } else { val signature = uri.getQueryParameter("signature").orEmpty() if (signature.isEmpty()) { inFlight.onResult(FireblocksSignResult.Error("malformed result")) } else { inFlight.onResult(FireblocksSignResult.Success(signature)) } } } is Pending.Send -> { if (uri.getQueryParameter("error") == "1") { val message = uri.getQueryParameter("message").orEmpty() inFlight.onResult( FireblocksSendResult.Error( message.ifEmpty { "send failed" }, uri.getQueryParameter("code") ?: "unknown", ) ) } else { val txHash = uri.getQueryParameter("txHash").orEmpty() if (txHash.isEmpty()) { inFlight.onResult(FireblocksSendResult.Error("malformed result")) } else { inFlight.onResult(FireblocksSendResult.Success(txHash)) } } } } return true } // ── Private ────────────────────────────────────────────────────────────── /** Replace whatever was waiting (see the object's docs) and arm the timeout. */ private fun arm(next: Pending, onTimeout: () -> Unit) { cancel() pending = next val runnable = Runnable { // Only if this very request is still the one waiting. if (pending === next) { clear() onTimeout() } } timeout = runnable handler.postDelayed(runnable, TIMEOUT_MS) } private fun clear() { pending = null timeout?.let(handler::removeCallbacks) timeout = null } /** Expand the template and hand it to the OS. `false` = nothing took it. */ private fun open(context: Context, walletBrowserUrl: String, pageUrl: String): Boolean { // Some templates (Phantom's) use the placeholder more than once — as // both the browse target and the `ref` — so replace every occurrence. // Uri.encode matches JavaScript's encodeURIComponent allow-list, which // is what the template expects. val target = walletBrowserUrl.replace("{{encodedDappURI}}", Uri.encode(pageUrl)) return try { context.startActivity( Intent(Intent.ACTION_VIEW, Uri.parse(target)) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) ) true } catch (e: ActivityNotFoundException) { Log.w(TAG, "no app handled $target", e) false } } private fun buildPageUrl( hostedPageUrl: String, scheme: String, nonce: String, environmentId: String?, locale: String? = null, theme: String? = null, phantomMode: String? = null, params: Map<String, String>, ): String { val builder = Uri.parse(hostedPageUrl).buildUpon() params.forEach { (key, value) -> builder.appendQueryParameter(key, value) } builder.appendQueryParameter("redirect_uri", "$scheme://$CALLBACK_HOST") builder.appendQueryParameter("nonce", nonce) // The page runs inside a wallet's WebView here — say so explicitly // rather than leaving it to user-agent guessing (see `getEnvInfo` in // `src/env.ts`): among other things this stops it offering a deeplink // connector that would bounce out of that browser. builder.appendQueryParameter("embedded", "1") environmentId?.takeIf { it.isNotBlank() } ?.let { builder.appendQueryParameter("environmentId", it) } locale?.takeIf { it.isNotBlank() } ?.let { builder.appendQueryParameter("locale", it) } theme?.takeIf { it.isNotBlank() } ?.let { builder.appendQueryParameter("theme", it) } phantomMode?.takeIf { it.isNotBlank() } ?.let { builder.appendQueryParameter("phantomMode", it) } return builder.build().toString() } /** Cryptographically-random nonce (CSRF correlation; not a secret). */ private fun randomNonce(): String { val bytes = ByteArray(16) SecureRandom().nextBytes(bytes) return bytes.joinToString("") { "%02x".format(it) } }}
Carry the two extra fields
Add the template to FireblocksHeadlessConnect.Wallet and remember it on the connection, or sign and send fall back to the engine.
data class Wallet( // … /** The wallet's own in-app-browser template, or null if it has none. */ val inAppBrowser: String? = null,)data class WalletConnection( // … /** Set when the connection was made inside the wallet's browser. */ val walletBrowserUrl: String? = null,)
Register the callback host
Add a third host to the FireblocksRedirectActivity intent-filter and route it before the Custom Tab flows, which all share wallet-callback.
intent?.data?.let { uri -> if (!FireblocksHeadlessConnect.handleReturnURL(uri) && !FireblocksWalletBrowser.handleRedirect(uri) ) { FireblocksConnect.handleRedirect(uri) }}
Offer the option only for Phantom
Do not derive EVM support from the presence of a template. Phantom’s template comes from its Sui wallet-book entry, so a template on its own says nothing about EVM. The evidence for Phantom specifically is phantomevm.injectedConfig.windowLocations: ["phantom.ethereum"], an EIP-1193 provider inside its browser.
MainActivity.kt
private fun offersInAppBrowserEvm(wallet: Wallet): Boolean = wallet.key.lowercase() == "phantom" && wallet.inAppBrowser != null && !wallet.chains.contains("evm")private fun chains(wallet: Wallet): List<String> = wallet.chains + if (offersInAppBrowserEvm(wallet)) listOf("evm") else emptyList()
Show it as its own chain row with “Opens in the wallet’s own browser” underneath. The current engine already lists evm in Phantom’s chains and connects it headlessly (Connect Phantom), so the !wallet.chains.contains("evm") guard keeps the synthetic row from doubling it: it only appears for engines that predate the headless bridge, or if you want the row to route into the wallet-browser connect below instead, which is what signing needs. A headless Phantom connection is connect-only.
Connect, sign, and send
MainActivity.kt
// connect: the synthetic picker value routes hereval template = wallet.inAppBrowser ?: returnFireblocksWalletBrowser.connect( context = this, hostedPageUrl = hostedPageUrl, scheme = scheme, walletBrowserUrl = template, walletKey = wallet.key,) { result -> runOnUiThread { when (result) { is FireblocksConnectResult.Success -> showConnected(result.wallet) is FireblocksConnectResult.Cancelled -> renderList() is FireblocksConnectResult.Error -> fail(result.reason) } }}// sign and send: reopen the SAME browserconnection.walletBrowserUrl?.let { browserUrl -> FireblocksWalletBrowser.signMessage( context = this, hostedPageUrl = hostedPageUrl, scheme = scheme, walletBrowserUrl = browserUrl, walletKey = connection.walletKey!!, message = "Hello from Android", expectedAddress = connection.address, // the page refuses a mismatch ) { result -> /* Success / Cancelled / Error */ } FireblocksWalletBrowser.sendTransaction( context = this, hostedPageUrl = hostedPageUrl, scheme = scheme, walletBrowserUrl = browserUrl, walletKey = connection.walletKey!!, to = "0xRecipientAddress", chainId = "0x1", expectedAddress = connection.address, value = "0x2386f26fc10000", // 0.01 ETH, hex wei ) { result -> /* Success / Cancelled / Error */ }}
What travels on the URL
Parameter
Value
wallet and chain=evm
connect, or intent=signMessage / intent=sendTx with walletKey
redirect_uri
<scheme>://wallet-browser
nonce
random per attempt, verified on return, mismatches dropped
embedded=1
the page is inside a wallet web view, so it must not offer a connector that bounces out of it
environmentId
optional Dynamic environment ID
The callback carries address and chain (connect), signature (sign), or txHash (send), or error=1&code=&message=, always with the nonce echoed back. A send is already broadcast when the hash arrives. One request is in flight at a time, a new one supersedes the previous, and an abandoned one times out after five minutes.
Phantom pitfalls
Keep the template on the connection. Sign and send must reopen the same browser, because the account exists nowhere else. Losing the stored template sends the request to the engine, which reports no wallet connected.
Use a separate callback host.wallet-callback is claimed by the visible flow, so a link arriving from Phantom would be dropped or complete an unrelated request.
Watch where the template lands on Android. The template is an https app link and reaches Phantom only if its app links are verified. Otherwise Android can hand it to Chrome, where nothing is injected and the page correctly reports no EVM path. That message in a browser that is not Phantom means the hand-off went to the wrong app.
Offer the return anchor. The page renders a “Return to the app” link for browsers that ignore a programmatic redirect.
11. The bridge (for reference)
Identical to iOS.networkId is the CAIP-2 id of the network the wallet is on. It is not network, the Phantom Solana session cluster. See Network fields.