> ## Documentation Index
> Fetch the complete documentation index at: https://second.tech/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Run delegated refreshes from background tasks

> Wake your mobile wallet app every few hours, run one delegated maintenance pass per wake, and store the mnemonic so background tasks can read it.

iOS and Android suspend your wallet app shortly after the user leaves it. Its VTXOs still fall due for refresh on their own schedule.

## Wake the app every few hours

Send a background push from your server to every device about every 4 hours. The wallet app decides locally what is due, so your server never needs the user's VTXOs.

The first pass submits a delegated refresh, and a later pass completes it ([complete each refresh on a later wake](#complete-each-refresh-on-a-later-wake)). At this cadence, both passes run well inside the mainnet default refresh window of 144 blocks, about 24 hours.

> [tab] iOS
>
> Send a [background notification](https://developer.apple.com/documentation/usernotifications/pushing-background-updates-to-your-app), which launches or resumes your app in the background without showing anything:
>
> 1. In Xcode, add the **Push Notifications** capability.
> 2. Add the **Background Modes** capability and select **Remote notifications**.
> 3. Call `registerForRemoteNotifications()` at every launch.
> 4. Send the device token that iOS returns to your server.
> 5. From your server, send a payload whose `aps` dictionary holds only `content-available`, with the headers below.
> 6. Run the pass from `application(_:didReceiveRemoteNotification:fetchCompletionHandler:)`.
>
> ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> { "aps": { "content-available": 1 } }
> ```
>
> ```text theme={"theme":{"light":"github-light","dark":"github-dark"}}
> apns-push-type: background
> apns-priority: 5
> apns-topic: com.example.wallet
> ```
>
> * **Priority 5 only:** APNs treats priority 10 as an error for a background push. It applies 10 when the header is missing.
> * **Bundle ID as the topic:** A background push must carry your app's bundle ID in `apns-topic`.
> * **Best-effort delivery:** iOS can delay, group, throttle, or drop background pushes ([catch devices that stop waking](#catch-devices-that-stop-waking) covers the fallback).
> * **Expo push service:** Send iOS devices only `data` with `contentAvailable: true` and `priority: "normal"`. The service defaults iOS to high priority, which maps to APNs priority 10.

> [tab] Android
>
> Send an FCM data message at [normal priority](https://firebase.google.com/docs/cloud-messaging/android-message-priority), the default, and hand the pass to WorkManager when it arrives:
>
> 1. Add the `firebase_messaging_installation_id_enabled` metadata, set to `true`, to your `AndroidManifest.xml`.
> 2. Send the Firebase Installation ID (FID) to your server each time Firebase calls `onRegistered()`.
> 3. From your server, send the message with a `data` payload, no `notification` payload, and the `android` settings below.
> 4. In your `FirebaseMessagingService.onMessageReceived`, enqueue a WorkManager request that runs the pass and requires a network connection. The handler itself gets only several seconds.
>
> ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
> {
>   "message": {
>     "fid": "<Firebase Installation ID>",
>     "data": { "type": "maintenance" },
>     "android": { "collapse_key": "maintenance" }
>   }
> }
> ```
>
> * **Normal priority, not high:** Android reserves high priority for messages that show a notification. FCM can downgrade high-priority messages that never lead to one.
> * **Delivery waits out Doze:** On a device in Doze, Android delivers the message at the next maintenance window, or as soon as the user wakes the device.
> * **One message per wake:** With a `collapse_key`, FCM sends only the latest message of the group when delivery resumes on a device that was asleep.

If you run no push server, fall back to an OS scheduler, which wakes the app on the system's schedule:

* **iOS:** Enable the `fetch` background mode, list the task identifier in `BGTaskSchedulerPermittedIdentifiers`, and submit a `BGAppRefreshTaskRequest`. iOS picks the launch time and gives the task up to 30 seconds. `earliestBeginDate` is only a lower bound. The wait can be many hours.
* **Android:** Enqueue periodic WorkManager work. The minimum interval is 15 minutes. While the device is in Doze, the work waits for a maintenance window.

Ask for a pass about every 4 hours. On iOS, submit the next request from each run with `earliestBeginDate` 4 hours ahead. On Android, set a 4-hour interval.

## Run one pass per wake

Run these steps from every wake handler:

1. Return early if a pass is already running in your app process. An in-memory flag that the pass sets and clears is enough.

2. Reuse the wallet if your app process already has it open. Bark allows one open wallet per data directory. A second `Wallet.open` on the same directory fails at once, from the same process or another one.

3. Otherwise, read the mnemonic from secure storage ([store the mnemonic](#store-the-mnemonic-so-background-tasks-can-read-it) covers the setting its entry needs).

4. Open the wallet with these arguments:

   * **`runDaemon: false`:** The bark library's background daemon joins rounds interactively, which needs the process alive for the whole round. Until the daemon runs delegated refreshes itself, your app runs the delegated pass below on each wake.
   * **`createIfNotExists: false`:** A wake that finds no wallet data then fails instead of creating a new wallet.
   * **The same `Config` and on-chain wallet as your foreground code:** Your foreground code reuses this instance when the user opens the app while the process is alive. Opened without the on-chain wallet, the instance cannot fund exits. A different `vtxoRefreshExpiryThreshold` changes which VTXOs the pass refreshes.

5. If `hasPendingExits()` returns true, call `progressExits()` first. It needs no Ark server, so a live exit keeps moving even when the server is unreachable.

6. Read `nextRoundStartTime()`. If the last pass saw the same value, call only `sync()`, which completes pending refreshes without submitting new ones.

7. Otherwise, call `maintenanceDelegated()` (`Wallet::maintenance_delegated()` in Rust). It syncs the wallet's off-chain state, completes earlier delegated refreshes that are ready, and submits the VTXOs that are due. When something is due, it returns as soon as the Ark server accepts the participation, without waiting for the round.

8. Report the outcome to your server ([catch devices that stop waking](#catch-devices-that-stop-waking) covers what the server does with it).

9. Call the completion handler for a background push, `setTaskCompleted(success:)` for a `BGAppRefreshTask`, or return from the worker on Android.

In React Native, put the pass in one function. Call it from your wake handler, for example, a task you define at module scope and register with `Notifications.registerTaskAsync` from `expo-notifications`:

```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
import { Wallet, WalletOpenArgs, type WalletLike } from '@secondts/bark-react-native';

// network, config, onchain, datadir, readMnemonic, and reportPassOutcome are your app's own.
let wallet: WalletLike | undefined; // shared with your foreground code
let passRunning = false;
let lastPassRound = 0n; // persist it if a wake can start a fresh process

export async function runMaintenancePass(): Promise<void> {
  if (passRunning) return;
  passRunning = true;
  const errors: string[] = [];
  try {
    if (!wallet) {
      wallet = await Wallet.open(
        network,
        await readMnemonic(),
        config,
        WalletOpenArgs.create({ datadir, onchain, runDaemon: false, createIfNotExists: false }),
      );
    }
    try {
      // Exits first: they need no Ark server, so they progress even when it is down.
      if (await wallet.hasPendingExits()) await wallet.progressExits(undefined);
    } catch (e) {
      errors.push(String(e));
    }
    const nextRound = await wallet.nextRoundStartTime();
    if (nextRound === lastPassRound) {
      await wallet.sync(); // a pass already ran before this round
    } else {
      await wallet.maintenanceDelegated();
      lastPassRound = nextRound;
    }
  } catch (e) {
    errors.push(String(e));
  } finally {
    passRunning = false;
  }
  await reportPassOutcome({ ok: errors.length === 0, errors });
}
```

* **Run at most one pass per round:** A second pass before the same round submits the waiting VTXOs again. The new participation replaces the waiting one at the current price. The replaced refresh movement ends `failed` ([plan for the deadline the user still has to meet](https://second.tech/docs/patterns/delegated-cosigner.md#plan-for-the-deadline-the-user-still-has-to-meet) covers replacement). Step 6 guards against it by comparing `nextRoundStartTime()` with the value the last pass saw.
* **Stay within the iOS time limit:** iOS terminates an app that has not called the completion handler within 30 seconds. Call it before then, even if the pass has not returned. With `expo-notifications`, iOS gets the result when your task returns, so return from the task before then. Add no other sync call to the pass, since `maintenanceDelegated()` already syncs.
* **Run the pass on foreground opens too:** Call the same function when the app comes to the foreground, so one flag covers both paths. To try an interactive refresh, call `maintenance()` before that function, and only while the app stays in the foreground. When a VTXO is due, `maintenance()` waits for the next round to start, up to an hour on Second's Ark server. It then takes part in that round until it ends, which an app the OS suspends cannot finish. Run the delegated pass after it even when it throws. If the OS suspends the app first, the pass on the next wake is the fallback.
* **Stop the background daemon when the app leaves the foreground:** If your foreground code runs the bark library's background daemon, call `stopDaemon()` when the app moves to the background and `runDaemon()` when it returns. While the daemon runs, do not also call `maintenance()`, since the daemon already joins each round with the VTXOs that are due. A wake that reuses the wallet then runs only the delegated pass, never an interactive round it cannot finish. There are two exceptions. The pass can still join an interactive refresh your foreground code left pending. A `maintenance()` call still waiting for its round joins that round if it starts during the wake. Do this until the daemon runs delegated refreshes itself.

## Complete each refresh on a later wake

A delegated refresh needs at least two passes. The first submits it. A later pass completes it once the round transaction has the confirmations set by `roundTxRequiredConfirmations` in `Config`, 1 by default (`round_tx_required_confirmations` in Rust). The wallet app signs the forfeits only then. A pass after the round but before that confirmation only locks the inputs.

Second's Ark server runs a [round](https://second.tech/docs/learn/rounds.md) every hour. With a wake every 4 hours, the round transaction usually has its confirmation by the next wake. Each pass then completes the refresh the previous pass submitted and submits what is due next.

![Diagram of three wakes of Alice's wallet app 4 hours apart, with hourly rounds between them, each refresh submitted at one wake and completed at the next](https://mintcdn.com/second-0659a37d/Gcjn5Ak6i6HjTioT/images/background-refresh-wake-cycle.svg?fit=max\&auto=format\&n=Gcjn5Ak6i6HjTioT\&q=85\&s=7dfdff463de69b71229a0a590a4cd32d)

With a wake every 4 hours, each wake completes the refresh the previous wake submitted and submits what is due next

* **Complete it before the old VTXOs expire:** The completing pass has to run while an emergency exit on the old VTXOs could still confirm before they expire ([plan for the deadline the user still has to meet](https://second.tech/docs/patterns/delegated-cosigner.md#plan-for-the-deadline-the-user-still-has-to-meet)).
* **Complete a scheduled refresh the same way:** A [scheduled delegated refresh](https://second.tech/docs/patterns/refresh-options.md#schedule-a-delegated-refresh-ahead-of-time) enters the first round after the chain tip reaches its scheduled height. A pass completes it once that round's transaction confirms, as above.
* **Show it as in progress:** `pendingRoundStates()` lists the participation as `delegated-pending` (a `RoundFlowKind` case in the native SDK bindings) until a pass completes it. Show the refresh as in progress, not finished, for that time. If it is still `delegated-pending` when the old VTXOs are close to expiry, start an emergency exit on them ([plan for the deadline the user still has to meet](https://second.tech/docs/patterns/delegated-cosigner.md#plan-for-the-deadline-the-user-still-has-to-meet) covers when).

## Store the mnemonic so background tasks can read it

Every pass that opens the wallet has to read the mnemonic, because a public key is not enough. A delegated refresh carries one Schnorr attestation per input VTXO, made with that VTXO's own key, which derives from the mnemonic. A scheduled delegated refresh, signed in the foreground, covers a single future refresh ([plan for the deadline the user still has to meet](https://second.tech/docs/patterns/delegated-cosigner.md#plan-for-the-deadline-the-user-still-has-to-meet) covers what one participation buys).

For most wallet apps, store the mnemonic where only your app can read it, with no prompt or password required for a read. [Mnemonic storage](https://second.tech/docs/patterns/mnemonic-storage.md) gives the settings and code for each platform. On iOS, the default keychain class, `kSecAttrAccessibleWhenUnlocked`, blocks reads whenever the screen is locked, which is when most background wakes arrive. Set the after-first-unlock class instead. Your app can still show a biometric prompt in its UI wherever you want, since that prompt does not depend on how you store the entry.

A wake that fires after a restart, before the user unlocks the device once, can't read the entry on either platform. Treat it as a missed pass.

> [!WARNING]
>
> **An auth-bound mnemonic stops background refreshes**
>
> A mnemonic that needs a biometric prompt or a password on each read makes every background pass that opens the wallet fail. The task cannot show a prompt, so it never signs or submits the refresh. If the user then stops opening the app, their VTXOs expire and the Ark server can sweep them ([expired VTXOs](https://second.tech/docs/patterns/expired-vtxos.md) covers what your app can still recover).

If your product does not allow a background-readable mnemonic, use one of two foreground alternatives:

* **Visible push notification:** Send one before a refresh is due and prompt the user to open the app. A per-use biometric prompt works fine in the foreground.
* **Scheduled delegated refreshes:** Register the participation during a foreground session for a future block height ([schedule a delegated refresh](https://second.tech/docs/patterns/refresh-options.md#schedule-a-delegated-refresh-ahead-of-time)).

Both depend on the user opening the app.

## Weigh availability against lock-screen protection

A background-readable mnemonic gives up lock-screen protection to get unattended maintenance:

* **What you give up:** After the first unlock, the entry is open to any code running in your app's context, so the lock screen no longer protects it.
* **What you get:** Maintenance that runs unattended, which keeps VTXOs from expiring while the app stays closed.
* **Grant the minimum that works:** The after-first-unlock class is enough for background tasks. Never reach for the deprecated always-accessible class.
* **Require biometrics for user actions:** Put sends, mnemonic reveal, and settings changes behind a per-use prompt. Only the background read path bypasses it.

Storage is separate from the refresh trust model. A delegated refresh also means trusting the Ark server for as long as the user holds its new VTXO ([delegated co-signer](https://second.tech/docs/patterns/delegated-cosigner.md) covers that decision).

## Catch devices that stop waking

On some devices, your wallet app stops running passes, whatever your server sends. Give those users a way back before their VTXOs expire:

* **Schedule a local notification as the floor:** Set it for half your refresh threshold before the first VTXO expiry, about 12 hours at the mainnet default. Working passes complete a refresh at least one wake, about 4 hours, before that point, so the notification fires only when passes stop or fall behind. Have it ask the user to open the app. Reschedule it after every pass.
* **Count the inputs of a delegated round:** Read `getFirstExpiringVtxoBlockheight()` and the lowest `expiryHeight` among the VTXOs that `pendingRoundInputVtxos()` returns. Use whichever expiry comes first. Convert heights to a time from the current chain tip at about 10 minutes per block ([expose the next refresh deadline](https://second.tech/docs/patterns/maintenance.md#expose-the-next-refresh-deadline) covers the height helpers).
* **Alert from your server when reports stop:** A device that has not reported a pass for half your refresh threshold, 12 hours at the mainnet default, may hold a VTXO halfway through its refresh window. Send it a visible notification asking the user to open the app.
* **Ask for notification permission during setup:** On iOS and on Android 13 and later, neither notification shows unless your app has notification permission. Request it when the user creates or restores the wallet.
* **Leave the refresh window wide:** Do not lower the threshold on mobile ([tune the refresh policy](https://second.tech/docs/patterns/maintenance.md#tune-the-refresh-policy)). At the mainnet default of 144 blocks, about 24 hours, a VTXO that falls due still gets about six wakes before it expires. A few missed wakes then cost nothing.

Passes stop in these cases:

* **Force-quit on iOS:** An app the user swiped away in the App Switcher gets no background push until the user opens it again or restarts the device.
* **Force stop on Android:** An app the user force-stopped gets no FCM message, visible or silent, until the user opens it again. The system also clears its scheduled jobs and alarms, so neither notification above reaches it.
* **Rarely opened apps on Android:** Android limits the background jobs and network access of apps the user rarely opens ([App Standby Buckets](https://developer.android.com/topic/performance/appstandby)).
* **Low Power Mode on iOS:** Low Power Mode turns off Background App Refresh. Apple counts that setting and the device's power state among the factors that decide whether a background push arrives.
* **Before the first unlock:** After a restart, no pass can read the mnemonic until the user unlocks the device once ([store the mnemonic](#store-the-mnemonic-so-background-tasks-can-read-it) covers why).

> [accordion] How Bark Wallet does it
>
> Bark Wallet runs in a browser, where no background wake exists. The web version (WASM) keeps a worker loop running while a tab is open and submits its refreshes as delegated participations. A refresh submitted before the tab closed completes on the next open. While a tab is open, the bark library's background daemon can also join a round interactively for the VTXOs its maintenance selection finds due. The installed version leaves background upkeep to the `barkd` daemon ([maintenance](https://second.tech/docs/patterns/maintenance.md) covers both).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.