---
title: "Spend and sell virtual currency in flows"
description: "Build two flows for an iOS app with virtual currency: users spend currency with native buttons in one flow, and buy more in the other when their balance is too low."
---

> **AI agents**: to search Adapty docs faster and with fewer tokens, install the Adapty skills: `npx adapty skills install --yes`

Follow this recipe to combine flows with virtual currency in your iOS app. The recipe shows how to:

- Show the currency balance in a flow, and keep it current while the flow is open.
- Spend currency when a user taps a native button in a flow, and show a spinner while the spend runs.
- Show users how much more currency they need.
- Offer currency packs and a subscription in a flow.
- Close one flow and open another from your app code.

Because the packs and the subscription are in a flow, you can change them without an app release, and [A/B test](ab-tests) them. The A/B test report counts the purchases. Spends don't appear in it: your backend sends them to Adapty with no link to the test.

By the end of this recipe, you have two flows for a game. In the out-of-energy flow, players spend diamonds on energy. In the top-up flow, they buy diamonds. The same steps work for any app where users spend virtual currency, such as credits per AI generation or coins per drama episode. In your app, replace the energy options and the diamonds with your own options and currency. The finished example works as follows:

1. A player runs out of energy, and your app code opens the out-of-energy flow. The player sees the diamond balance and two buttons, one per option: an energy refill for 10 diamonds, and an hour of unlimited energy for 30.
2. The player taps a button, and your app code calls your backend to spend the diamonds. While the spend runs, the player sees a spinner in the button.
3. If the spend goes through, the player sees a checkmark. Your app code closes the flow, and the game gives the player the energy.
4. If the balance is too low, your app code closes the out-of-energy flow and opens the top-up flow. The player sees how many more diamonds they need, and buys a diamond pack or the subscription.
5. After the purchase, your app code opens the out-of-energy flow again. The player sees the new balance, and taps a button to spend diamonds.

## Before you start

- Have users sign in, so that they [keep their balance](virtual-currency-balance#balances-profiles-and-devices) on every device and after a reinstall. When a user signs in, [identify the user](identifying-users) in your app code with a customer user ID. Your backend needs this ID to identify the user to Adapty.
- To show the balance and the buttons in the flows, update your app to Adapty iOS SDK 4.4 or later.
- Set up your app to [fetch](get-pb-paywalls) and [display](ios-present-paywalls) flows.
- Set up a backend that calls the server-side API with your [secret API key](ss-authorization). Keep the key on your backend: anyone with the key can add diamonds to any balance.
- In App Store Connect, [create a consumable product](app-store-products) for each diamond pack, and an auto-renewable subscription. Then [add each product to Adapty](create-product).
- [Create a virtual currency](create-virtual-currency) with the code `DIAMONDS`. [Link](create-virtual-currency#link-products) each product to `DIAMONDS`, and set how many diamonds Adapty adds to the balance:
  - **Diamond pack**: The **Credit amount**, for each purchase.
  - **Subscription**: The **Credit per cycle**, for each billing period. When a user starts a free trial, Adapty only adds the **Credit on trial start**.

  Set each of the three values to at least 30 diamonds, the price of an hour of unlimited energy. With these values, every purchase in the top-up flow covers the missing diamonds.

## 1. Build the flow where players spend diamonds

In the Flow & Paywall Builder, create the out-of-energy flow. Add the flow to a [placement](placements) with the ID `out_of_energy`. When a player runs out of energy, the code in step 2 opens the flow from this placement.

To give players a way to close the flow without a spend, add a [**Close** button](basic-paywall-screen#3-add-the-close-button).

### Show the diamond balance

To show the diamond balance, use a [custom element](flow-custom-elements): an element where users see a native view from your app code. When your app code changes the balance while the flow is open, such as after a spend, users see the new balance.

1. [Add a custom element](flow-custom-elements#add-and-configure) to the screen, and enter its **Type** and **ID**:
   - **Type**: `currency_balance`.
   - **ID**: `diamonds`.

   The code in [step 2](#create-the-balance-view) matches the balance view to the custom element by this Type and ID.

   <ZoomImage id="vc-top-up-custom-element.webp" width="700px" alt="Custom element settings in the Flow & Paywall Builder, with currency_balance in the Type field, diamonds in the ID field, and an Icon inside the Diamond balance layer" />

2. Inside the custom element, add a diamond [**Icon**](custom-media#icon). In app versions without the balance view, users see the icon as the [fallback](flow-custom-elements#set-fallback-content).

### Add buttons for an energy refill and unlimited energy

To show a spinner and then a checkmark in the button that users tap, add both buttons as custom elements. Users see neither a spinner nor a checkmark in a builder button with a [custom action](onboarding-actions#what-custom-actions-cant-do). A custom action is one-way: your app code can't return the result of the spend to the flow. The text and look of the buttons come from your app code. To change the text or look, [release an app update](flow-custom-elements#what-changes-require-an-app-release).

1. [Add a custom element](flow-custom-elements#add-and-configure) for the energy refill, and enter its **Type** and **ID**:
   - **Type**: `spend_button`.
   - **ID**: `energy_refill`.
2. Add a second custom element for unlimited energy, with the same Type and the ID `unlimited_energy`.

   The code in [step 2](#connect-the-buttons-to-your-backend) matches one button view to both custom elements by their Type. The code reads the option of each button from its ID.

   <ZoomImage id="vc-top-up-spend-button.webp" width="700px" alt="Custom element settings in the Flow & Paywall Builder, with spend_button in the Type field and unlimited_energy in the ID field" />

3. Lower the **Fixed** height of each custom element from 200 to the height that the button needs.
4. Inside each custom element, add a text element, and enter the words for its option:
   - Energy refill: "Update the game to refill energy."
   - Unlimited energy: "Update the game to get unlimited energy."

   In app versions without the button view, users see this text as the [fallback](flow-custom-elements#set-fallback-content), with no button to tap.

## 2. Spend diamonds when a player taps a button

In this step, you write the backend code and the app code for the out-of-energy flow. After this step, players with enough diamonds can spend them in the flow.

### Spend diamonds from your backend

When a player taps a button in the out-of-energy flow, your app code calls your backend to spend diamonds on the option of that button. Your app code can't send the spend to Adapty, because the request needs your secret API key. Your backend calls [Create virtual currency transaction](api-adapty/operations/createVirtualCurrencyTransaction) with a negative `amount`, as in the [Virtual currency quickstart](virtual-currency-quickstart) tutorial. Send the spend without a balance request first: Adapty verifies the balance as part of the spend.

Keep the cost of each option on your backend: 10 diamonds for an energy refill, and 30 for an hour of unlimited energy. Your app code only sends the option to your backend, so a modified version of your app can't lower the cost.

```bash title="Spend diamonds"
curl -X POST https://api.adapty.io/api/v2/server-side-api/vc/transactions/ \
  -H "Authorization: Api-Key {your secret key}" \
  -H "adapty-customer-user-id: player-42" \
  -H "Idempotency-Key: 5221577a-8b4c-419a-a0f5-028e4598b265" \
  -H "Content-Type: application/json" \
  -d '{
        "items": [{"currency_code": "DIAMONDS", "amount": -30}],
        "operation": "spend",
        "feature": "unlimited_energy",
        "customer_placement_id": "out_of_energy",
        "reference_id": "energy_order_7781"
      }'
```

The request identifies the spend, the player, and the option:

- **`Idempotency-Key`**: A UUID v4 that your app code creates for each new spend, to protect the user from being debited multiple times for the same transaction. If you need to retry a transaction (for example, due to a network failure), reuse the key from the original transaction. The key stays valid for 1 hour. Once a transaction with the key succeeds, later requests with that key return the original transaction and don't change the balance.
- **`adapty-customer-user-id`**: The customer user ID of the signed-in user. In your backend, read it from the sign-in session.
- **`feature`**: A [label](virtual-currencies#feature) for the option, such as `unlimited_energy`. With this label, you can see what each spend was for in the [event history](virtual-currency-balance#review-balance-changes-in-the-event-history) of the player.

Two optional fields help you trace a spend later. Both appear in the [transaction details](virtual-currency-balance#transaction-details) of the event history:

- **`customer_placement_id`**: The ID of the screen in your app where the spend happened. With it, you can see which screen each spend came from. In this recipe, use the placement ID of the out-of-energy flow, `out_of_energy`.
- **`reference_id`**: The ID of the related record in your backend, such as the energy order that the spend pays for. With it, your support team can match a spend to what the user received.

If the spend goes through, give the player the energy from your backend: Adapty keeps the diamond balance, not the energy. Give the energy once per `transaction_id` of the response, because a retry with the same `Idempotency-Key` returns the original transaction. The `balances` array of the response includes the `available` value of `DIAMONDS`: the diamonds that the player can spend now. Return this value to your app code.

If the balance can't cover the cost, the request fails with HTTP status 400 and doesn't change the balance. To detect this error, compare `error_code` with `insufficient_balance`. Then calculate how many diamonds the player needs: read the balance with [List virtual currency balances](api-adapty/operations/listVirtualCurrencyBalances), and subtract the `available` value of `DIAMONDS` from the cost. Return the result and the `available` value to your app code.

If the result is 0 or less, Adapty added diamonds to the balance after the spend failed, such as for a subscription renewal. In this case, retry the request with the same `Idempotency-Key`, and return the result of the retry instead. Adapty doesn't keep the key of a failed spend, so it accepts the second request.

When the first request with the same `Idempotency-Key` is still in progress, the retry fails with HTTP status 409 and the `idempotency_in_flight` error code. Wait for the number of seconds in the `Retry-After` header of the response, and retry the request with the same key.

Spend requests from all your users count toward one limit: by default, 600 requests per minute for your app. A request over the limit fails with HTTP status 429 and the `rate_limited` error code. If you expect more spend requests at peak times, ask support which [rate limit](ss-authorization#rate-limits) applies to your app.

On your backend, add an endpoint for the balance: call List virtual currency balances, and return the `available` value of `DIAMONDS`. The app code in this recipe calls this endpoint before the out-of-energy flow opens, and after a purchase.

:::tip
When you [turn on credit expiration](create-virtual-currency#link-products) for the subscription, remind users to spend their credits in time. The `expiry.expiring` array of [List virtual currency balances](api-adapty/operations/listVirtualCurrencyBalances) lists how many credits expire and when. Show the soonest amount in a flow with a [custom tag](flow-custom-tags), such as "30 diamonds expire in 2 days".
:::

### Create the balance view

Create a model for the diamond balance, and a SwiftUI view for the `currency_balance` custom element. The code later in this step and in step 4 sets the balance in the model from the responses of your backend. The view observes the model, so it redraws when the balance changes:

```swift showLineNumbers title="Swift"
import Combine
import SwiftUI

// The diamond balance that your app keeps up to date
@MainActor
final class DiamondWallet: ObservableObject {
    @Published var balance: Int? // nil until your backend returns a balance
}

struct DiamondBalanceView: View {
    @ObservedObject var wallet: DiamondWallet

    var body: some View {
        Label(wallet.balance?.formatted() ?? "—", systemImage: "diamond.fill")
    }
}
```

`DiamondBalanceView` uses the system text color, which turns white when the device is in dark mode. A flow keeps its light colors unless you [add a dark theme](paywall-dark-mode#add-a-dark-theme) to it. If your flows have no dark theme, set a fixed text color in the view, such as `.foregroundStyle(.black)`.

To display the view in both flows, return it from your [app-wide resolver](ios-flow-custom-elements#set-an-app-wide-resolver), which matches each custom element to a view by its Type and ID. Add a `wallet` property of the `DiamondWallet` type, and a case that returns `DiamondBalanceView` for the `currency_balance` Type and the `diamonds` ID. The highlighted lines show what to add. If your app has no app-wide resolver yet, copy the whole code:

```swift showLineNumbers title="Swift" {5,13-14}
import AdaptyUIBuilder
import SwiftUI

struct CustomElementsResolver: AdaptyUICustomElementsResolver {
    let wallet: DiamondWallet

    func view(
        forType type: String,
        id: String,
        context: AdaptyUICustomElementContext
    ) -> AnyView? {
        switch type {
        case "currency_balance" where id == "diamonds":
            return AnyView(DiamondBalanceView(wallet: wallet))
        // the other cases of your resolver
        default:
            return nil
        }
    }
}
```

Create the resolver with a `DiamondWallet`, and set it as the app-wide resolver. Call `AdaptyUI.setCustomElementsResolver(_:)` once, such as at app launch:

```swift showLineNumbers title="Swift"
import AdaptyUI

@MainActor let diamondWallet = DiamondWallet()

// keep this instance: a resolver for one flow can reuse it
@MainActor let customElementsResolver = CustomElementsResolver(wallet: diamondWallet)

// at app launch, such as in application(_:didFinishLaunchingWithOptions:)
AdaptyUI.setCustomElementsResolver(customElementsResolver)
```

### Create the button view

Create one SwiftUI view for both buttons. The view receives the button text, and a closure that spends the diamonds and returns `true` when the spend goes through. While the spend runs, players see a spinner in the button, and the button ignores more taps. After the spend goes through, players see a checkmark:

```swift showLineNumbers title="Swift"
import SwiftUI

struct SpendButton: View {
    let title: String
    let spend: @MainActor () async -> Bool // true when the spend goes through

    @State private var phase = Phase.ready
    private enum Phase { case ready, spending, done }

    var body: some View {
        Button {
            guard phase == .ready else { return } // ignore more taps while the spend runs
            phase = .spending
            // a Task keeps running when the flow closes and this view disappears
            Task {
                phase = await spend() ? .done : .ready
            }
        } label: {
            Group {
                switch phase {
                case .ready: Text(title)
                case .spending: ProgressView().tint(.white) // white on the filled button
                case .done: Image(systemName: "checkmark")
                }
            }
            .frame(maxWidth: .infinity) // the full width of the custom element
        }
        .buttonStyle(.borderedProminent)
    }
}
```

### Connect the buttons to your backend

Create an enum for the two options. As the raw value of each option, use the ID of its custom element:

```swift showLineNumbers title="Swift"
// the options to spend diamonds on, with the IDs of their custom elements
enum EnergyOption: String {
    case energyRefill = "energy_refill"
    case unlimitedEnergy = "unlimited_energy"

    // keep the numbers equal to the costs on your backend
    var title: String {
        switch self {
        case .energyRefill: return "Energy refill · 10 ◆"
        case .unlimitedEnergy: return "Unlimited energy for 1 hour · 30 ◆"
        }
    }
}
```

The following code is for UIKit. In the view controller that opens the out-of-energy flow, add a method that spends diamonds on an option. The method sends the option to your backend, and sets the balance in `diamondWallet` from the response. Then the method does one of the following:

- **The spend goes through**: The method returns `true`, and players see the checkmark in the button. After one second, the code closes the flow.
- **The balance is too low**: The method calls `openTopUpFlow`, the function that [opens the top-up flow](#open-the-top-up-flow-when-a-player-doesnt-have-enough-diamonds).

```swift showLineNumbers title="Swift"
private var outOfEnergyFlow: AdaptyFlowController? // set when the out-of-energy flow opens

// true when the spend goes through
func spendDiamonds(on option: EnergyOption) async -> Bool {
    do {
        // the client of your backend: your backend sends the spend to Adapty
        let result = try await GameBackend.shared.spendDiamonds(
            on: option.rawValue,
            idempotencyKey: UUID() // a new key for each spend; UUID() creates a version 4 UUID
        )
        switch result {
        case let .spent(available):
            diamondWallet.balance = available
            // your backend gave the player the energy: show it in the game
            Task {
                try? await Task.sleep(for: .seconds(1)) // players see the checkmark first
                outOfEnergyFlow?.dismiss(animated: true)
            }
            return true
        case let .insufficientBalance(diamondsNeeded, available):
            diamondWallet.balance = available
            await openTopUpFlow(diamondsNeeded: diamondsNeeded)
            return false
        }
    } catch {
        // handle the error
        return false
    }
}
```

Then write a resolver for the out-of-energy flow. For each custom element with the `spend_button` Type, the resolver reads the option from the ID, and returns a `SpendButton` that calls the spend method. A resolver that you [attach to a flow](ios-flow-custom-elements#attach-a-resolver-to-one-flow) replaces the app-wide resolver in that flow. To show the balance in the out-of-energy flow, this resolver calls the app-wide resolver:

```swift showLineNumbers title="Swift"
import AdaptyUIBuilder
import SwiftUI

struct OutOfEnergyResolver: AdaptyUICustomElementsResolver {
    let spend: @MainActor (EnergyOption) async -> Bool // the spend method of your view controller
    let appWideResolver: any AdaptyUICustomElementsResolver

    func view(
        forType type: String,
        id: String,
        context: AdaptyUICustomElementContext
    ) -> AnyView? {
        // the ID tells the buttons apart: energy_refill or unlimited_energy
        if type == "spend_button", let option = EnergyOption(rawValue: id) {
            return AnyView(SpendButton(title: option.title) { await spend(option) })
        }
        // other custom elements, such as the balance: the views of the app-wide resolver
        return appWideResolver.view(forType: type, id: id, context: context)
    }
}
```

### Open the out-of-energy flow from your app code

When a player runs out of energy, open the out-of-energy flow with the following function. The function asks your backend for the balance first, so that players see it when the flow opens. Then the function attaches `OutOfEnergyResolver` to the flow, and keeps the flow controller in `outOfEnergyFlow`. With this reference, `spendDiamonds` can close the flow:

```swift showLineNumbers title="Swift"
// call when a player runs out of energy
func openOutOfEnergyFlow() async {
    // the balance that players see when the flow opens; without it, players see a dash
    if let available = try? await GameBackend.shared.diamondBalance() {
        diamondWallet.balance = available
    }
    do {
        let flow = try await Adapty.getFlow(placementId: "out_of_energy")
        let flowConfiguration = try await AdaptyUI.getFlowConfiguration(
            forFlow: flow,
            customElementsResolver: OutOfEnergyResolver(
                spend: { [weak self] option in
                    await self?.spendDiamonds(on: option) ?? false
                },
                appWideResolver: customElementsResolver // the instance that you set app-wide
            )
        )
        let flowController = try AdaptyUI.flowController(
            with: flowConfiguration,
            delegate: self
        )
        outOfEnergyFlow = flowController
        present(flowController, animated: true)
    } catch {
        // handle the error
    }
}
```

As the delegate of the out-of-energy flow, the view controller must also implement the [delegate methods](ios-handling-events#handling-events-in-uikit) for purchases and restores. For `didFinishPurchase`, use the code from [step 4](#open-the-out-of-energy-flow-again-after-a-purchase).

In SwiftUI, attach `OutOfEnergyResolver` when you fetch the flow configuration. In the `spend` closure of the resolver, call your spend method. Present the flow configuration with the `.flow` modifier, and use its closures instead of the delegate methods. The closures receive no view controller. To close the flow, set `isPresented` to `false`.

## 3. Build the flow where players buy diamonds

In the Flow & Paywall Builder, create the top-up flow. Add the flow to a [placement](placements) with the ID `out_of_diamonds`. When the balance is too low for a spend, the code in step 4 opens the flow from this placement.

To show a different top-up flow depending on the balance, add an [audience](audience) with a [segment by virtual currency balance](segments#virtual-currency-balance) to the `out_of_diamonds` placement. For example, show a separate flow to users with 0 diamonds. Adapty reads the balance each time your app code fetches the flow, so a spend or a purchase can change the flow that the user sees next.

To show the diamond balance in this flow too, [add a custom element](flow-custom-elements#add-and-configure) with the same Type and ID as in the out-of-energy flow: `currency_balance` and `diamonds`. Inside the custom element, add the diamond **Icon** as the fallback. Players see the same balance view in both flows, and you don't need to add code for it.

### Show how many diamonds the player needs

To tell players how many more diamonds they need, use a [custom tag](flow-custom-tags): a placeholder that you insert into a text element. The code in step 4 passes the number to the tag once, when it opens the flow. The words around the number stay in the builder, where you can edit and translate them.

1. [Create a custom tag](flow-custom-tags#create-a-custom-tag) named `diamonds_needed`, and enter a dash (`—`) in its **Initial value** field. If your app code passes no number for the tag, players see the dash.
2. Add a text element with the words "You need more diamonds". After "need", [insert the `diamonds_needed` custom tag](flow-custom-tags#add-a-custom-tag-to-a-text-element).

   <ZoomImage id="vc-top-up-custom-tag.webp" width="700px" alt="A text element with the content “You need diamonds_needed more diamonds”, and the dash of the custom tag on the canvas" />

### Add diamond packs and a subscription

1. Add a [**Products** element](paywall-product-block#add-a-product-group) with the diamond packs. To start the purchase of a pack when a player taps its card, attach the [**Purchase** action to each card](paywall-product-block#trigger-purchase-from-a-product-card).
2. To offer the subscription on the same screen as the packs, add a [purchase button](paywall-product-block#add-a-purchase-button). In the **Purchase** action of the button, select the subscription from the **Product** dropdown. In the button text, insert the [`prod_price` and `prod_billing_period`](onboarding-variables#product-variables) variables of the subscription.
3. In a text element of each card, type how many diamonds the player receives, such as "500 diamonds". Add a text element for the subscription, and type how many diamonds the player receives for each billing period, such as "300 diamonds every month". Keep each number equal to the **Credit amount** or **Credit per cycle** of the product: no [product variable](onboarding-variables#product-variables) holds this number. If the name of each pack in the app store already includes the number, such as "500 Diamonds", insert the `prod_title` variable instead.
4. To give players a way to close the flow without a purchase, add a [**Close** button](basic-paywall-screen#3-add-the-close-button). Add the [footer links](basic-paywall-screen#9-add-footer-links): app stores require the Terms of Use and Privacy Policy links wherever players can buy a subscription.

<ZoomImage id="vc-top-up-screen.webp" width="300px" alt="The finished top-up flow in the Flow & Paywall Builder, with the diamond icon in place of the balance, the text “You need — more diamonds”, three diamond packs with prices, and the purchase button of the subscription" />

## 4. Close one flow and open the other

After this step, players without enough diamonds can buy more in the top-up flow, and then spend them. In this recipe, one view controller is the delegate of both flows. To tell the flows apart in a delegate method, compare the `controller.flowPlacementId` property with the placement ID of each flow. In SwiftUI, present the top-up flow with a second `.flow` modifier, and open one flow from the `didDisappear` closure of the other.

### Open the top-up flow when a player doesn't have enough diamonds

The following function passes the number of missing diamonds to the `diamonds_needed` tag, and opens the top-up flow. A view controller presents one flow at a time, so the function first closes the out-of-energy flow, and then opens the top-up flow:

```swift showLineNumbers title="Swift"
func openTopUpFlow(diamondsNeeded: Int) async {
    // with no value, players see the Initial value of the tag
    let tags = diamondsNeeded > 0 ? ["diamonds_needed": diamondsNeeded.formatted()] : [:]
    do {
        let flow = try await Adapty.getFlow(placementId: "out_of_diamonds")
        let flowConfiguration = try await AdaptyUI.getFlowConfiguration(
            forFlow: flow,
            tagResolver: tags
        )
        let flowController = try AdaptyUI.flowController(
            with: flowConfiguration,
            delegate: self
        )
        // a view controller presents one flow at a time
        outOfEnergyFlow?.dismiss(animated: true) {
            self.present(flowController, animated: true)
        }
    } catch {
        // handle the error
    }
}
```

### Open the out-of-energy flow again after a purchase

When a player buys a pack or the subscription in the top-up flow, Adapty usually adds the diamonds to the balance first. Then the Adapty SDK calls `didFinishPurchase`, but doesn't close the flow. In this method, the following code asks your backend for the new balance, closes the top-up flow, and opens the out-of-energy flow again. The player sees the new balance there, and taps a button to spend diamonds. Don't spend diamonds right after the purchase: the player may no longer want the energy.

```swift showLineNumbers title="Swift"
func flowController(
    _ controller: AdaptyFlowController,
    didFinishPurchase product: AdaptyPaywallProduct,
    purchaseResult: AdaptyPurchaseResult
) {
    // canceled or pending: the flow stays open
    guard purchaseResult.isPurchaseSuccess,
          controller.flowPlacementId == "out_of_diamonds" // the top-up flow
    else { return }
    Task {
        let balanceBefore = diamondWallet.balance ?? 0
        if let available = try? await GameBackend.shared.diamondBalance() {
            diamondWallet.balance = available
        }
        let diamondsArrived = (diamondWallet.balance ?? 0) > balanceBefore
        controller.dismiss(animated: true) {
            if diamondsArrived {
                Task { await self.openOutOfEnergyFlow() } // the player taps a button again
            } else {
                // Adapty adds the diamonds later: tell the player in your own UI
            }
        }
    }
}
```

When the player cancels the purchase, or when the purchase is pending, the code leaves the top-up flow open. The Adapty SDK also calls `didFinishPurchase` in these cases, but the balance stays the same.

When a purchase succeeds but the balance from your backend stays the same, the code closes the top-up flow and doesn't open the out-of-energy flow. In either flow, the player would see the old balance right after the purchase. The balance stays the same when the Adapty SDK can't validate the purchase with Adapty right away. Adapty adds the diamonds later, when the Adapty SDK sends the purchase to Adapty again, such as at the next app launch. Until then, tell the player in your own UI that the diamonds are on the way.

Don't add diamonds from your backend when a user buys a product [linked to `DIAMONDS`](create-virtual-currency#link-products): Adapty adds these diamonds, and the user would receive them twice.

## 5. Test on a device

The Flow & Paywall Builder can't run your app code, so on its canvas, you only see the fallbacks of the custom elements.

To see the diamonds from purchases, test with a [sandbox account](test-purchases-in-sandbox). In the sandbox, a subscription renews every few minutes, and Adapty adds diamonds at each renewal. With a StoreKit configuration file in Xcode, the Adapty SDK doesn't validate purchases with Adapty, and Adapty adds no diamonds.

To test the recipe:

1. [Publish both flows](builder-save-publish). To see the latest published versions instead of cached ones, register the device as a [test device](test-devices).
2. Run your app with the recipe code, and sign in as a player with no diamonds. Run out of energy in the game. Verify that the out-of-energy flow opens with a balance of 0.
3. Tap the unlimited energy button. Verify that a spinner appears in the button, and then the top-up flow opens with the text "You need 30 more diamonds".
4. Buy a diamond pack. Verify that the out-of-energy flow opens again with the new balance.
5. Tap the energy refill button. Verify that a checkmark appears in the button, the flow closes, and the game gives the player an energy refill.
6. In the Adapty Dashboard, open the profile of the player. [Debit the balance](virtual-currency-balance#adjust-a-balance-manually) to less than 10 with the **Adjustment** operation. Run out of energy again, tap the energy refill button, and buy the subscription in the top-up flow. Verify that the out-of-energy flow opens again with the new balance.
7. Tap the unlimited energy button. Verify that a checkmark appears in the button, the flow closes, and the game gives the player unlimited energy.
8. In the [event history](virtual-currency-balance#review-balance-changes-in-the-event-history) of the player, verify the following entries:

- **Virtual currency credited**: For each purchase or renewal that adds diamonds.
- **Virtual currency debited**: For each spend that goes through, with the `energy_refill` or `unlimited_energy` label. Adapty names this entry after the `spend` operation. Without `operation`, Adapty names it **Virtual currency transaction**.
- **Virtual currency adjusted**: For each manual debit with the **Adjustment** operation, such as the one in step 6.
- **Virtual currency expired**: For subscription diamonds that expire unspent.

To find out why a fallback appears instead of the balance or a button, follow the [steps to test custom elements](ios-flow-custom-elements#test-on-a-device).