Buy Dew through Google Play in the Google Play version

The Google Play edition (the gplay build type) now builds its native code
with GOOGLE_PLAY and adds Kryon's Play Billing (its gplay sources from the
Kryon package and billing 9.1); the direct and F-Droid builds carry no
Google billing. Top up lists Entity's Dew packs at Google Play's price in the
buyer's currency once Play answers. Breeze sends each purchase to the node
with its own signed-in request through entity/dew_play, and Play forgets it
only after the node has credited the Dew. The Play edition's Top up shows no
Monero address or other coins, and running out of Dew no longer names
Monero. The old payment bridge stubs are gone.

Kryon and Entity move to their Play Billing commits; liboqs stays pinned.
This commit is contained in:
waozi committed 2026-10-27 18:06:54 -03:00
1 parent 72c80cc0f6
commit 955fe51d17
24 files changed
+492 -225

No files matched your search

+16
View File
@@ -22,6 +22,8 @@ if (verificationInstance && gradle.startParameter.taskNames.any {
}
def buildingAndroidBundle = gradle.startParameter.taskNames.any { it.toLowerCase().contains("bundle") }
def kryonDirOverride = (project.findProperty('kryon.dir') ?: System.getenv("KRYON_DIR") ?: '').toString()
// The same Kryon checkout CMake builds with; a relative path starts at the repository.
def kryonDir = rootProject.file('..').toPath().resolve(kryonDirOverride ?: 'build/packages/kryon').toFile()
android {
useLibrary 'android.test.runner', false
@@ -106,6 +108,12 @@ android {
initWith release
signingConfig releaseSigning
matchingFallbacks = ['release']
// Native code sees GOOGLE_PLAY and sells Dew through Play Billing.
externalNativeBuild {
cmake {
arguments '-DAPP_EDITION=gplay'
}
}
buildConfigField "boolean", "GPLAY", "true"
buildConfigField "boolean", "SELF_UPDATE", "false"
buildConfigField "String", "UPDATE_FEED", '""'
@@ -143,6 +151,10 @@ android {
}
}
// Kryon's Play Billing (kryon/play_billing finds it through the
// activity's class loader); other editions carry no Google billing.
sourceSets.gplay.java.srcDir new File(kryonDir, 'templates/droid/droid/app/src/gplay/java')
dependenciesInfo {
includeInApk = false
}
@@ -267,6 +279,10 @@ dependencies {
implementation 'com.google.zxing:core:3.3.0'
gplayImplementation platform('com.google.firebase:firebase-bom:34.18.0')
gplayImplementation 'com.google.firebase:firebase-messaging'
gplayImplementation 'com.android.billingclient:billing:9.1.0'
// Billing's AndroidX libraries mix Kotlin 1.6 and 1.8 standard
// libraries; one Kotlin version keeps their classes from colliding.
gplayImplementation platform('org.jetbrains.kotlin:kotlin-bom:1.8.22')
// Play services still request Fragment 1.1.0, which Google Play reports
// as an outdated SDK; resolve it to a current release instead.
constraints {
+3 -1
View File
@@ -5,7 +5,9 @@
# Native code looks these up by class or method name through JNI/reflection.
-keep class xyz.waozi.inbe.ShareHelper { *; }
-keep class xyz.waozi.inbe.GplayPushBridge { *; }
-keep class xyz.waozi.inbe.GplayPaymentBridge { *; }
-keep class org.kryonlabs.play.PlayBilling {
public static java.lang.String call(android.app.Activity, java.lang.String);
}
# Manifest and platform callback entrypoints must keep their public shape.
-keep class xyz.waozi.inbe.FcmPushService { *; }
@@ -1,21 +0,0 @@
package xyz.waozi.inbe;
import android.widget.Toast;
final class GplayPaymentBridge {
private GplayPaymentBridge() {}
static String channel() {
return "disabled";
}
static void purchaseTokens(final MainActivity activity, final String productId,
final String accountId, final String authToken) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(activity, "Token purchases are not available in this build.", Toast.LENGTH_LONG).show();
}
});
}
}
+6
View File
@@ -98,6 +98,12 @@ if(CMAKE_BUILD_TYPE STREQUAL "Debug")
list(APPEND APP_ZIRAN_DEFINES --define ANDROID_DEBUG)
string(APPEND APP_ZIRAN_CHECK_DEFINES " ANDROID_DEBUG")
endif()
# The Google Play edition (build.gradle's gplay type) buys Dew through Play
# Billing (entity/dew_play).
if(APP_EDITION STREQUAL "gplay")
list(APPEND APP_ZIRAN_DEFINES --define GOOGLE_PLAY)
string(APPEND APP_ZIRAN_CHECK_DEFINES " GOOGLE_PLAY")
endif()
if(ANDROID_ABI STREQUAL "arm64-v8a")
set(APP_ZIRAN_ARCH __aarch64__)
elseif(ANDROID_ABI STREQUAL "armeabi-v7a")
@@ -1079,18 +1079,6 @@ public class MainActivity extends NativeActivity {
PushBridge.disable(this);
}
public String paymentChannel() {
return PaymentBridge.channel();
}
public boolean dewAvailable() {
return !BuildConfig.GPLAY;
}
public void purchaseTokens(final String productId, final String accountId, final String authToken) {
PaymentBridge.purchaseTokens(this, productId, accountId, authToken);
}
private RadioPlayer radioPlayer;
private volatile boolean radioBackgroundActive;
private volatile boolean sessionWakeLockRequested;
@@ -1,127 +0,0 @@
package xyz.waozi.inbe;
import android.widget.Toast;
import java.lang.reflect.Method;
import org.json.JSONObject;
final class PaymentBridge {
private static final String DAOCHI_BASE_URL = "https://api.waozi.xyz";
private PaymentBridge() {}
static String channel() {
String gplayChannel = gplayChannel();
if (gplayChannel != null) {
return gplayChannel;
}
return "monero";
}
static void purchaseTokens(final MainActivity activity, final String productId,
final String accountId, final String authToken) {
if (purchaseGplayTokens(activity, productId, accountId, authToken)) {
return;
}
new Thread(new Runnable() {
@Override
public void run() {
try {
String body = "{\"app_id\":\"inbe\",\"product_id\":\"" + jsonEscape(productId) + "\"}";
String response = SyncNetwork.httpRequest("PAYMENTS", "POST",
DAOCHI_BASE_URL + "/api/v1/tokens/purchases/monero/invoices",
body, authHeaders(authToken));
final Invoice invoice = parseInvoice(response);
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
if (invoice.ok) {
Toast.makeText(activity,
"Send " + invoice.atomicAmount + " atomic XMR to " + invoice.address,
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(activity, invoice.message, Toast.LENGTH_LONG).show();
}
}
});
} catch (Exception e) {
showToast(activity, "Monero invoice failed");
}
}
}, "monero-token-invoice").start();
}
private static String gplayChannel() {
try {
Method method = Class.forName("xyz.waozi.inbe.GplayPaymentBridge").getDeclaredMethod("channel");
method.setAccessible(true);
return (String) method.invoke(null);
} catch (ClassNotFoundException e) {
return null;
} catch (Exception e) {
return "disabled";
}
}
private static boolean purchaseGplayTokens(MainActivity activity, String productId,
String accountId, String authToken) {
try {
Method method = Class.forName("xyz.waozi.inbe.GplayPaymentBridge").getDeclaredMethod(
"purchaseTokens", MainActivity.class, String.class, String.class, String.class);
method.setAccessible(true);
method.invoke(null, activity, productId, accountId, authToken);
return true;
} catch (ClassNotFoundException e) {
return false;
} catch (Exception e) {
showToast(activity, "Token purchases are not available in this build.");
return true;
}
}
private static String[] authHeaders(String authToken) {
return new String[] {
"Content-Type: application/json",
"Authorization: Bearer " + (authToken != null ? authToken : "")
};
}
private static Invoice parseInvoice(String response) throws Exception {
int newline = response.indexOf('\n');
int status = newline > 0 ? Integer.parseInt(response.substring(0, newline).trim()) : 0;
String body = newline >= 0 ? response.substring(newline + 1) : "";
if (status < 200 || status >= 300) {
return new Invoice(false, "Monero invoice unavailable", "", 0);
}
JSONObject json = new JSONObject(body);
return new Invoice(true, "", json.optString("address", ""),
json.optLong("atomic_amount", 0));
}
private static void showToast(final MainActivity activity, final String message) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(activity, message, Toast.LENGTH_LONG).show();
}
});
}
private static String jsonEscape(String value) {
if (value == null) return "";
return value.replace("\\", "\\\\").replace("\"", "\\\"");
}
private static final class Invoice {
final boolean ok;
final String message;
final String address;
final long atomicAmount;
Invoice(boolean ok, String message, String address, long atomicAmount) {
this.ok = ok;
this.message = message;
this.address = address;
this.atomicAmount = atomicAmount;
}
}
}
+25 -1
View File
@@ -5143,7 +5143,7 @@ Dobít
---
[profile_dew_funds]
Nedostatek Dew. Nejprve dobij přes Monero.
Nedostatek Dew. Nejprve si dobij.
---
[profile_dew_retry]
@@ -5211,6 +5211,30 @@ Získávám tvou adresu Monero…
Adresu Monero se nepodařilo získat. Zkus to znovu.
---
[profile_dew_play_pack]
Koupit %s Dew
---
[profile_dew_play_loading]
Načítám ceny z Google Play…
---
[profile_dew_play_unavailable]
Nákupy přes Google Play teď nejsou k dispozici.
---
[profile_dew_play_verifying]
Připisuji Dew z tvého nákupu na Google Play…
---
[profile_dew_play_credited]
Dew bylo připsáno.
---
[profile_dew_play_failed]
Google Play platbu přijal, ale Dew zatím nešlo připsat. Zkusí se to znovu automaticky.
---
[profile_dew_topup_send]
Pošli Monero na tuto adresu. Dew se objeví po %d potvrzeních.
---
+25 -1
View File
@@ -5137,7 +5137,7 @@ Aufladen
---
[profile_dew_funds]
Nicht genug Dew. Lade zuerst mit Monero auf.
Nicht genug Dew. Lade zuerst auf.
---
[profile_dew_retry]
@@ -5205,6 +5205,30 @@ Deine Monero-Adresse wird abgerufen…
Die Monero-Adresse konnte nicht abgerufen werden. Versuche es erneut.
---
[profile_dew_play_pack]
%s Dew kaufen
---
[profile_dew_play_loading]
Google-Play-Preise werden geladen…
---
[profile_dew_play_unavailable]
Käufe über Google Play sind gerade nicht verfügbar.
---
[profile_dew_play_verifying]
Das Dew aus deinem Google-Play-Kauf wird gutgeschrieben…
---
[profile_dew_play_credited]
Dein Dew wurde gutgeschrieben.
---
[profile_dew_play_failed]
Google Play hat die Zahlung erhalten, aber das Dew konnte noch nicht gutgeschrieben werden. Es wird automatisch erneut versucht.
---
[profile_dew_topup_send]
Sende Monero an diese Adresse. Dew erscheint nach %d Bestätigungen.
---
+25 -1
View File
@@ -5161,7 +5161,7 @@ Top up
---
[profile_dew_funds]
Not enough Dew. Top up with Monero first.
Not enough Dew. Top up first.
---
[profile_dew_retry]
@@ -5229,6 +5229,30 @@ Getting your Monero address…
Could not get your Monero address. Try again.
---
[profile_dew_play_pack]
Buy %s Dew
---
[profile_dew_play_loading]
Loading Google Play prices…
---
[profile_dew_play_unavailable]
Google Play purchases are not available right now.
---
[profile_dew_play_verifying]
Adding the Dew from your Google Play purchase…
---
[profile_dew_play_credited]
Your Dew has been added.
---
[profile_dew_play_failed]
Google Play took the payment, but the Dew could not be added yet. It tries again automatically.
---
[profile_dew_topup_send]
Send Monero to this address. Dew appears after %d confirmations.
---
+25 -1
View File
@@ -5137,7 +5137,7 @@ Recargar
---
[profile_dew_funds]
No tienes suficiente Dew. Recarga primero con Monero.
No tienes suficiente Dew. Recarga primero.
---
[profile_dew_retry]
@@ -5205,6 +5205,30 @@ Obteniendo tu dirección de Monero…
No se pudo obtener tu dirección de Monero. Inténtalo de nuevo.
---
[profile_dew_play_pack]
Comprar %s Dew
---
[profile_dew_play_loading]
Cargando precios de Google Play…
---
[profile_dew_play_unavailable]
Las compras de Google Play no están disponibles en este momento.
---
[profile_dew_play_verifying]
Añadiendo el Dew de tu compra en Google Play…
---
[profile_dew_play_credited]
Tu Dew se ha añadido.
---
[profile_dew_play_failed]
Google Play recibió el pago, pero el Dew aún no se pudo añadir. Se volverá a intentar automáticamente.
---
[profile_dew_topup_send]
Envía Monero a esta dirección. Dew aparece tras %d confirmaciones.
---
+25 -1
View File
@@ -5125,7 +5125,7 @@ Recharger
---
[profile_dew_funds]
Dew insuffisant. Rechargez d’abord avec Monero.
Dew insuffisant. Rechargez d’abord.
---
[profile_dew_retry]
@@ -5193,6 +5193,30 @@ Récupération de votre adresse Monero…
Impossible de récupérer votre adresse Monero. Réessayez.
---
[profile_dew_play_pack]
Acheter %s Dew
---
[profile_dew_play_loading]
Chargement des prix Google Play…
---
[profile_dew_play_unavailable]
Les achats Google Play ne sont pas disponibles pour le moment.
---
[profile_dew_play_verifying]
Ajout des Dew de votre achat Google Play…
---
[profile_dew_play_credited]
Vos Dew ont été ajoutés.
---
[profile_dew_play_failed]
Google Play a reçu le paiement, mais les Dew n’ont pas encore pu être ajoutés. Une nouvelle tentative aura lieu automatiquement.
---
[profile_dew_topup_send]
Envoyez des Monero à cette adresse. Les Dew apparaissent après %d confirmations.
---
+25 -1
View File
@@ -5126,7 +5126,7 @@ Isi saldo
---
[profile_dew_funds]
Dew tidak cukup. Isi terlebih dahulu dengan Monero.
Dew tidak cukup. Isi saldo terlebih dahulu.
---
[profile_dew_retry]
@@ -5194,6 +5194,30 @@ Mengambil alamat Monero…
Alamat Monero tidak dapat diambil. Coba lagi.
---
[profile_dew_play_pack]
Beli %s Dew
---
[profile_dew_play_loading]
Memuat harga Google Play…
---
[profile_dew_play_unavailable]
Pembelian Google Play sedang tidak tersedia.
---
[profile_dew_play_verifying]
Menambahkan Dew dari pembelian Google Play Anda…
---
[profile_dew_play_credited]
Dew Anda telah ditambahkan.
---
[profile_dew_play_failed]
Google Play sudah menerima pembayaran, tetapi Dew belum dapat ditambahkan. Akan dicoba lagi secara otomatis.
---
[profile_dew_topup_send]
Kirim Monero ke alamat ini. Dew muncul setelah %d konfirmasi.
---
+25 -1
View File
@@ -5126,7 +5126,7 @@ Ricarica
---
[profile_dew_funds]
Dew insufficiente. Ricarica prima con Monero.
Dew insufficiente. Ricarica prima.
---
[profile_dew_retry]
@@ -5194,6 +5194,30 @@ Recupero del tuo indirizzo Monero…
Impossibile recuperare il tuo indirizzo Monero. Riprova.
---
[profile_dew_play_pack]
Acquista %s Dew
---
[profile_dew_play_loading]
Caricamento dei prezzi di Google Play…
---
[profile_dew_play_unavailable]
Gli acquisti con Google Play non sono disponibili al momento.
---
[profile_dew_play_verifying]
Aggiunta dei Dew dal tuo acquisto su Google Play…
---
[profile_dew_play_credited]
I tuoi Dew sono stati aggiunti.
---
[profile_dew_play_failed]
Google Play ha ricevuto il pagamento, ma non è stato ancora possibile aggiungere i Dew. Verrà riprovato automaticamente.
---
[profile_dew_topup_send]
Invia Monero a questo indirizzo. Dew appare dopo %d conferme.
---
+25 -1
View File
@@ -5122,7 +5122,7 @@ Dewで前払いします。プランが自動で更新されることはあり
---
[profile_dew_funds]
Dewが不足しています。先にMoneroでチャージしてください。
Dewが不足しています。先にチャージしてください。
---
[profile_dew_retry]
@@ -5190,6 +5190,30 @@ Moneroアドレスを取得しています…
Moneroアドレスを取得できませんでした。もう一度お試しください。
---
[profile_dew_play_pack]
%s Dewを購入
---
[profile_dew_play_loading]
Google Playの価格を読み込んでいます…
---
[profile_dew_play_unavailable]
現在、Google Playでの購入はご利用いただけません。
---
[profile_dew_play_verifying]
Google Playでの購入分のDewを追加しています…
---
[profile_dew_play_credited]
Dewが追加されました。
---
[profile_dew_play_failed]
Google Playでの支払いは完了しましたが、まだDewを追加できませんでした。自動的に再試行します。
---
[profile_dew_topup_send]
このアドレスにMoneroを送金してください。%d回の承認後にDewが反映されます。
---
+25 -1
View File
@@ -5132,7 +5132,7 @@ Dew로 미리 결제합니다. 요금제는 자동으로 갱신되지 않습니
---
[profile_dew_funds]
Dew가 부족해요. 먼저 Monero로 충전하세요.
Dew가 부족해요. 먼저 충전하세요.
---
[profile_dew_retry]
@@ -5200,6 +5200,30 @@ Monero 주소를 가져오는 중…
Monero 주소를 가져오지 못했습니다. 다시 시도하세요.
---
[profile_dew_play_pack]
%s Dew 구매
---
[profile_dew_play_loading]
Google Play 가격을 불러오는 중…
---
[profile_dew_play_unavailable]
지금은 Google Play 구매를 사용할 수 없어요.
---
[profile_dew_play_verifying]
Google Play 구매로 받은 Dew를 추가하는 중…
---
[profile_dew_play_credited]
Dew가 추가되었어요.
---
[profile_dew_play_failed]
Google Play에서 결제가 완료되었지만 아직 Dew를 추가하지 못했어요. 자동으로 다시 시도해요.
---
[profile_dew_topup_send]
이 주소로 Monero를 보내세요. %d번 확인 후 Dew가 표시됩니다.
---
+25 -1
View File
@@ -5135,7 +5135,7 @@ Recarregar
---
[profile_dew_funds]
Dew insuficiente. Adicione Dew com Monero primeiro.
Dew insuficiente. Recarregue primeiro.
---
[profile_dew_retry]
@@ -5203,6 +5203,30 @@ Obtendo seu endereço Monero…
Não foi possível obter seu endereço Monero. Tente novamente.
---
[profile_dew_play_pack]
Comprar %s Dew
---
[profile_dew_play_loading]
Carregando preços do Google Play…
---
[profile_dew_play_unavailable]
As compras pelo Google Play não estão disponíveis no momento.
---
[profile_dew_play_verifying]
Adicionando o Dew da sua compra no Google Play…
---
[profile_dew_play_credited]
Seu Dew foi adicionado.
---
[profile_dew_play_failed]
O Google Play recebeu o pagamento, mas o Dew ainda não pôde ser adicionado. Uma nova tentativa será feita automaticamente.
---
[profile_dew_topup_send]
Envie Monero para este endereço. Dew aparece após %d confirmações.
---
+25 -1
View File
@@ -5131,7 +5131,7 @@ Lumi остаётся без сети, пока вы не примете её у
---
[profile_dew_funds]
Недостаточно Dew. Сначала пополни баланс через Monero.
Недостаточно Dew. Сначала пополни баланс.
---
[profile_dew_retry]
@@ -5199,6 +5199,30 @@ Lumi остаётся без сети, пока вы не примете её у
Не удалось получить адрес Monero. Попробуй ещё раз.
---
[profile_dew_play_pack]
Купить %s Dew
---
[profile_dew_play_loading]
Загружаем цены Google Play…
---
[profile_dew_play_unavailable]
Покупки через Google Play сейчас недоступны.
---
[profile_dew_play_verifying]
Зачисляем Dew за твою покупку в Google Play…
---
[profile_dew_play_credited]
Dew зачислены.
---
[profile_dew_play_failed]
Google Play принял оплату, но Dew пока не удалось зачислить. Попробуем снова автоматически.
---
[profile_dew_topup_send]
Отправь Monero на этот адрес. Dew появится после %d подтверждений.
---
+25 -1
View File
@@ -5137,7 +5137,7 @@ Dew余额
---
[profile_dew_funds]
Dew不足,请先使用Monero充值。
Dew不足,请先充值。
---
[profile_dew_retry]
@@ -5205,6 +5205,30 @@ Dew不足,请先使用Monero充值。
无法获取你的Monero地址。请重试。
---
[profile_dew_play_pack]
购买 %s Dew
---
[profile_dew_play_loading]
正在加载Google Play价格…
---
[profile_dew_play_unavailable]
Google Play购买目前不可用。
---
[profile_dew_play_verifying]
正在添加你在Google Play购买的Dew…
---
[profile_dew_play_credited]
你的Dew已添加。
---
[profile_dew_play_failed]
Google Play已收到付款,但暂时无法添加Dew。系统会自动重试。
---
[profile_dew_topup_send]
将Monero发送到此地址。%d次确认后Dew即会到账。
---
+2
View File
@@ -11,6 +11,7 @@
#import, file "route_types.zi";
#import, file "exercise_types.zi";
#import, file "../platform/environment.zi";
#import, file "../platform/dew_payment.zi";
#import "android_device"
#import, file "../platform/android/graphics_context.zi";
#import, file "fonts.zi";
@@ -352,6 +353,7 @@ app_init :: (vapp: *void) {
app.break_sounds_enabled = 0
}
data_init()
DewPaymentStart()
TelegramAccountFlowStart()
if !AppsStart(app) {
TraceLog(LOG_ERROR, "APP: required Lists, Habits or Practice bundle failed validation")
+13 -26
View File
@@ -1,34 +1,21 @@
// Dew works in every build: the balance, storage plans, practice unlocks and
// app rewards are paid in Dew. Only topping Dew up with Monero is left out of
// the Play build, whose activity reports it.
#if #defined(ANDROID_BUILD) {
#import "android_jni"
}
// Dew works in every edition: the balance, storage plans, practice unlocks
// and app rewards are paid in Dew. The direct and F-Droid editions top Dew up
// with Monero; the Google Play edition (the GOOGLE_PLAY define) sells Dew
// packs through Google Play (entity/dew_play) once Play Billing answers.
#import "entity/dew_play"
dew_channel_known: bool;
dew_channel_available: bool;
dew_play: DewPlay;
// Called once at start, before the first frame asks for Dew.
DewPaymentStart :: () {
dew_play.enabled = DewPlayEdition()
}
DewAvailable :: () -> bool { return true }
DewTopUpAvailable :: () -> bool {
#if #defined(ANDROID_BUILD) {
if !dew_channel_known {
session: AndroidJniSession
if AndroidJniAttachCurrent(*session) == 0 {
return false
}
method := AndroidJniMethod(*session, "dewAvailable", "()Z")
if method != null {
dew_channel_available = session.env.functions.CallBooleanMethodA(
session.env, session.activity, method, null) != 0
if session.env.functions.ExceptionCheck(session.env) != 0 {
dew_channel_available = false
}
}
AndroidJniDetachCurrent(*session)
dew_channel_known = true
}
return dew_channel_available
if dew_play.enabled {
return dew_play.available
}
return true
}
+76 -4
View File
@@ -19,6 +19,8 @@
#import "segmented_control_widget"
#import "layout"
#import "tree"
#import "kryon/play_billing"
#import "entity/dew_play"
#import, file "../storage/dew.zi";
#import, file "../storage/sync_async.zi";
#import, file "../storage/sync_node_storage.zi";
@@ -169,7 +171,8 @@ ProfileDewContent :: (app: *InnerBreeze, x: s32, y: *s32, width: s32,
unused AppCopyText("—", value[:])
}
busy := dew_operation.active
// Top-ups belong to the balance they fill; the Play build sells no Dew.
// Top-ups belong to the balance they fill; the Google Play edition
// shows its button once Google Play answers.
if dew_account.known && DewReady() && DewTopUpAvailable() {
label := LocaleText("profile_dew_topup")
button_w := AppTextWidth(label, AppFontSize()) + AppScale(32)
@@ -494,11 +497,76 @@ ProfileTopUpAddressText :: (output: []u8) {
}
}
// What the Google Play window says under its Dew packs, or "".
ProfileTopUpPlayNotice :: (billing: *PlayBillingState, shown: s32) -> string {
status := TextUntilNul(dew_play.status[:])
if status == "verifying" {
return LocaleText("profile_dew_play_verifying")
}
if status == "credited" {
return LocaleText("profile_dew_play_credited")
}
if status == "failed" {
return LocaleText("profile_dew_play_failed")
}
if shown > 0 {
return ""
}
error := TextUntilNul(billing.error[:])
if error != "" && error != "cancelled" {
return LocaleText("profile_dew_play_unavailable")
}
return LocaleText("profile_dew_play_loading")
}
// The Google Play edition sells Dew packs at Google Play's price in the
// buyer's currency. Play's own sheet takes the payment, and the Dew arrives
// once the node has credited the purchase (entity/dew_play).
ProfileTopUpPlayContent :: (app: *InnerBreeze, x: s32, y: *s32, width: s32, draw: bool) {
billing: PlayBillingState
unused PlayBillingRead(TextUntilNul(dew_play.state[:]), *billing)
busy := dew_operation.active || TextUntilNul(dew_play.status[:]) == "verifying"
packs: [4]string = .["dew_100", "dew_500", "dew_1000", "dew_5000"]
shown: s32 = 0
for pack: packs {
product: *PlayBillingProduct = null
for index: cast(s32)0..7 {
if index >= billing.product_count {
break
}
candidate := *billing.products[index]
if TextUntilNul(candidate.id[:]) == pack {
product = candidate
}
}
if product == null {
continue
}
label: [96]u8
arguments: [1]FormatArg = .[FormatArg.{.text = pack[4:], .is_text = true}]
unused FormatTemplate(LocaleText("profile_dew_play_pack"), arguments[:], label[:])
price := TextUntilNul(product.price[:])
if ProfileDewButton(app, TextUntilNul(label[:]), x, y, width, busy, draw, price) {
unused DewPlayBuy(*dew_play, pack)
}
shown += 1
}
notice := ProfileTopUpPlayNotice(*billing, shown)
if notice != "" {
ProfileDewText(app, notice, x, y, width, AppSmallFontSize(), draw)
}
}
// Topping up is the one place Dew shows its money value: the balance's
// worth and the node's exchange rate.
// worth and the node's exchange rate, or Google Play's prices.
ProfileTopUpContent :: (app: *InnerBreeze, x: s32, y: *s32, width: s32, draw: bool) {
line: [384]u8
ProfileDewFormatDew(dew_account.balance, LocaleText("profile_dew_balance_line"), line[:])
if dew_play.enabled {
ProfileDewText(app, TextUntilNul(line[:]), x, y, width, AppSmallFontSize(), draw)
ProfileTopUpPlayContent(app, x, y, width, draw)
return
}
DewAppendWorth(dew_account.balance, line[:])
ProfileDewText(app, TextUntilNul(line[:]), x, y, width, AppSmallFontSize(), draw)
if ProfileDewExchangeText(line[:]) {
@@ -590,8 +658,12 @@ ProfileTopUpContent :: (app: *InnerBreeze, x: s32, y: *s32, width: s32, draw: bo
}
ProfileTopUpModalDraw :: (app: *InnerBreeze) {
ProfileTopUpPump()
DewRatesRefresh()
// Monero needs this account's address and the node's rates; Google Play
// has its own prices.
if !dew_play.enabled {
ProfileTopUpPump()
DewRatesRefresh()
}
width := app.ui.view_width - AppScale(32)
if width > AppScale(480) {
width = AppScale(480)
+18 -1
View File
@@ -2,6 +2,7 @@
// payment confirmations and expiry; a device never grants itself credit.
#import "auth"
#import "entity/dew_model"
#import "entity/dew_play"
#import "json_scan"
#import "text_buffer"
#import "byte_text_linux"
@@ -15,6 +16,7 @@ Clock :: #import "date_time";
#import, file "sync_nodes.zi";
#import, file "sync_node_storage.zi";
#import, file "../platform/network_transport.zi";
#import, file "../platform/dew_payment.zi";
#import, file "../app/text_buffers.zi";
DewNow :: () -> s64 {
@@ -25,6 +27,7 @@ DewRead :: 1
DewUpgrade :: 2
DewAddress :: 3
DewGift :: 4
DewPlayCredit :: 5
// Where a gift to a friend stands, for the window that sends it.
DewGiftNone :: 0
@@ -156,7 +159,7 @@ DewBegin :: (action: s32, path: string, body: string) -> bool {
dew_response = .{}
dew_action = action
method := "GET"
if action == DewUpgrade || action == DewGift {
if action == DewUpgrade || action == DewGift || action == DewPlayCredit {
method = "POST"
}
if !BeginStoredRequest(*dew_operation, DewNode, NetworkTransport(*dew_transfer),
@@ -330,6 +333,8 @@ DewTick :: (visible: bool, now: float64) {
if !DewParseAddress(json) {
dew_notice = "profile_dew_error"
}
} else if dew_action == DewPlayCredit {
refresh_soon = DewPlayVerified(*dew_play, true, dew_operation.request.status, json)
} else {
received: DewAccount
if DewParseAccount(json, TextUntilNul(dew_identity[:]), *received) {
@@ -358,6 +363,9 @@ DewTick :: (visible: bool, now: float64) {
dew_notice = "profile_dew_error"
}
}
} else if dew_action == DewPlayCredit {
refresh_soon = DewPlayVerified(*dew_play, false, dew_operation.request.status,
TextUntilNul(dew_response[:]))
} else if dew_action == DewGift {
status := dew_operation.request.status
if status == 402 {
@@ -395,6 +403,15 @@ DewTick :: (visible: bool, now: float64) {
dew_gift_retry_at = now + 15.0
return
}
// A Google Play purchase goes to the node next; Play keeps it until the
// node has credited its Dew.
if DewPlayTick(*dew_play, DewReady() && !dew_operation.active) {
if !DewBegin(DewPlayCredit, DEW_PLAY_VERIFY_PATH, TextUntilNul(dew_play.body[:])) {
// Offline: the purchase waits and goes again later.
unused DewPlayVerified(*dew_play, false, 0, "")
}
return
}
// One read soon after launch keeps the balance current before Profile
// opens; a few background tries, then only while Profile shows it.
background := !dew_account_fresh && dew_background_reads < 3
+37
View File
@@ -1,4 +1,5 @@
#import "entity/dew_model"
#import "entity/dew_play"
// Real account keys, authentication and persistence; only HTTP is synthetic.
#import, file "../src/storage/dew.zi";
#import, file "../src/storage/practice_unlocks.zi";
@@ -21,6 +22,7 @@
#import, file "../src/storage/sync_state.zi";
#import, file "../src/storage/storage_settings.zi";
#import, file "../src/app/text_buffers.zi";
#import, file "../src/platform/dew_payment.zi";
owner: AccountKeys;
response_status: s32 = 200;
@@ -40,6 +42,9 @@ gift_balance: s64;
// Answers a gift as if for another request, which settles nothing.
gift_reply_foreign: bool;
last_gift_body: [256]u8;
play_requests: s32;
last_play_body: [512]u8;
TestPlayPurchase :: "{\"ready\":true,\"package\":\"xyz.waozi.inbe\",\"error\":\"\",\"products\":[],\"purchases\":[{\"product\":\"dew_500\",\"token\":\"abcdefghijklmnop.Token-1_2\",\"order\":\"GPA.1\"}]}"
TestFriend :: "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
TestAddress :: "8aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
@@ -125,6 +130,12 @@ FakeStart :: (context: *void, request: HttpRequest, output: []u8) -> bool {
check_true("unlocks are read with an authenticated GET", request.method == "GET" && request.body.count == 0)
return AppCopyText("{\"unlocks\":[{\"product\":\"inbe.practice.taichi\",\"receipt_id\":\"r1\",\"created_at\":1}],\"products\":[{\"product\":\"inbe.practice.taichi\",\"price_units\":1000000,\"regular_price_units\":10000000,\"trial_until\":1807801200}]}", output)
}
if request.url == "https://api.waozi.xyz/api/v1/tokens/purchases/google/verify" {
play_requests += 1
check_true("Google Play purchases are sent with an authenticated POST", request.method == "POST")
unused AppCopyText(request.body, last_play_body[:])
return AppCopyText("{\"credited\":true}", output)
}
if request.url == "https://api.waozi.xyz/api/v1/tokens/gifts" {
gift_requests += 1
check_true("gifts are sent with an authenticated POST", request.method == "POST")
@@ -422,6 +433,32 @@ Check :: () -> s32 {
Finish()
check_true("a refused request is not repeated", dew_gift_notice == "dew_gift_failed" && dew_gift_attempt[0] == cast(u8)0)
response_status = 200
// The Google Play edition sends each purchase Play lists to the node, and
// Play forgets it only once the node has credited its Dew.
check_true("other editions sell no Dew through Google Play", !dew_play.enabled && DewTopUpAvailable())
dew_play.enabled = true
check_true("the Play edition tops up once Google Play answers", !DewTopUpAvailable())
unused AppCopyText(TestPlayPurchase, dew_play.state[:])
response_status = 503
DewTick(false, 200.0)
check_true("a Google Play purchase goes to the node", dew_operation.active && dew_action == DewPlayCredit)
Finish()
check_int("one Google Play verify request", play_requests, 1)
check_true("the verify request names the package, pack and token", TextUntilNul(last_play_body[:]) ==
"{\"app_id\":\"entity\",\"package_name\":\"xyz.waozi.inbe\",\"product_id\":\"dew_500\",\"purchase_token\":\"abcdefghijklmnop.Token-1_2\"}")
check_true("an uncredited purchase stays with Play and waits", TextUntilNul(dew_play.status[:]) == "failed" &&
dew_play.wait > 0 && dew_play.state[0] == #char "{" && !dew_operation.active)
DewTick(false, 201.0)
check_true("the waiting purchase is not sent at once", !dew_operation.active && play_requests == 1)
response_status = 200
dew_play.wait = 1
DewTick(false, 202.0)
Finish()
check_int("the purchase is sent again", play_requests, 2)
check_true("a credited purchase is done", TextUntilNul(dew_play.status[:]) == "credited" &&
dew_play.state[0] == cast(u8)0 && !dew_operation.active)
dew_play = .{}
storage_set_setting_text("sync_public_id", "another-account")
DewContext()
check_true("account change clears the old balance", !dew_account.known && dew_address[0] == cast(u8)0)
+21 -21
View File
@@ -18,17 +18,9 @@
"ref": "master",
"url": "https://github.com/ziranlang/qrcode.git"
},
{
"commit": "ca637d08b0d6b54ab6bb56bbfd9a25d7fb70f56c",
"dependencies": {"daochi_client": "p9972fcdd2d5ba999", "kryon": "p78e3cb7d22b3e56c", "monocypher": "p809b4d31a48625a3", "qrcode": "p0dfa70137405b096"},
"id": "p52862c0351d05875",
"name": "Entity",
"ref": "master",
"url": "https://github.com/waozixyz/entity.git"
},
{
"commit": "1cb9df183089a77c8a16448a556186f30b261a98",
"dependencies": {"kryon": "p78e3cb7d22b3e56c"},
"dependencies": {"kryon": "p974af619ca377b85"},
"id": "p1b13dda539ed2a39",
"name": "Kss",
"ref": "master",
@@ -36,7 +28,7 @@
},
{
"commit": "bad2caaa84ef3eae61e40c99bf572d2b060d0ca2",
"dependencies": {"kryon": "p78e3cb7d22b3e56c"},
"dependencies": {"kryon": "p974af619ca377b85"},
"id": "p20eb23d3e6db3711",
"name": "Game2D",
"ref": "master",
@@ -44,7 +36,7 @@
},
{
"commit": "b1e4ed4b0f7283e2b7a8ae7740f283d5729b3b04",
"dependencies": {"crypto": "pc23fbf455e97614d", "kryon": "p78e3cb7d22b3e56c"},
"dependencies": {"crypto": "pc23fbf455e97614d", "kryon": "p974af619ca377b85"},
"id": "p4158fd507db6061e",
"name": "Apps",
"ref": "b1e4ed4b0f7283e2b7a8ae7740f283d5729b3b04",
@@ -76,14 +68,6 @@
"ref": "master",
"url": "https://github.com/ziranlang/oqs.git"
},
{
"commit": "1fd45c1fea2e76e69cac0e09f774e6f63ed75eff",
"dependencies": {"raylib": "p5a77c9c35110e925"},
"id": "p78e3cb7d22b3e56c",
"name": "kryon",
"ref": "master",
"url": "https://github.com/kryonlabs/kryon.git"
},
{
"commit": "f5f0a19a5dc6c14a49adb3cd63ea79a60f6ba77b",
"dependencies": {},
@@ -102,6 +86,14 @@
"source": true,
"url": "https://github.com/waozixyz/practices.git"
},
{
"commit": "3fad22341997f7c58ed1b11b1e88217358e51af5",
"dependencies": {"raylib": "p5a77c9c35110e925"},
"id": "p974af619ca377b85",
"name": "kryon",
"ref": "master",
"url": "https://github.com/kryonlabs/kryon.git"
},
{
"commit": "25d9f649c43a8de44a5fea602d2835e33e6ca999",
"dependencies": {"crypto": "pc23fbf455e97614d", "oqs": "p7098ac9cd92f7e5f"},
@@ -112,7 +104,7 @@
},
{
"commit": "3f888653b6b97010163d824c4cc72476be3214f3",
"dependencies": {"kryon": "p78e3cb7d22b3e56c"},
"dependencies": {"kryon": "p974af619ca377b85"},
"id": "pab5377a2950368a2",
"name": "plot",
"ref": "master",
@@ -126,6 +118,14 @@
"ref": "master",
"url": "https://github.com/ziranlang/crypto.git"
},
{
"commit": "224a08fe845cc277255af68b7c3c27ecfa0f2cc0",
"dependencies": {"daochi_client": "p9972fcdd2d5ba999", "kryon": "p974af619ca377b85", "monocypher": "p809b4d31a48625a3", "qrcode": "p0dfa70137405b096"},
"id": "pd2e439f031fa79fe",
"name": "Entity",
"ref": "master",
"url": "https://github.com/waozixyz/entity.git"
},
{
"commit": "9ef1a3a130450d603abd029772422abd40cfcde0",
"dependencies": {},
@@ -154,7 +154,7 @@
}
],
"root": {
"dependencies": {"apps": "p4158fd507db6061e", "crypto": "pc23fbf455e97614d", "curl": "pd4bcd11b7d623073", "daochi_client": "p9972fcdd2d5ba999", "entity": "p52862c0351d05875", "game2d": "p20eb23d3e6db3711", "kryon": "p78e3cb7d22b3e56c", "kss": "p1b13dda539ed2a39", "liboqs": "p4b0a50b49959e674", "mingcute": "pe1027b9d16704793", "monocypher": "p809b4d31a48625a3", "oqs": "p7098ac9cd92f7e5f", "plot": "pab5377a2950368a2", "practices": "p9079dde0fcc11248", "qrcode": "p0dfa70137405b096", "rini": "p09fa77e94b0dfc6c", "sqlite": "peaa43c4b7ef72edf"},
"dependencies": {"apps": "p4158fd507db6061e", "crypto": "pc23fbf455e97614d", "curl": "pd4bcd11b7d623073", "daochi_client": "p9972fcdd2d5ba999", "entity": "pd2e439f031fa79fe", "game2d": "p20eb23d3e6db3711", "kryon": "p974af619ca377b85", "kss": "p1b13dda539ed2a39", "liboqs": "p4b0a50b49959e674", "mingcute": "pe1027b9d16704793", "monocypher": "p809b4d31a48625a3", "oqs": "p7098ac9cd92f7e5f", "plot": "pab5377a2950368a2", "practices": "p9079dde0fcc11248", "qrcode": "p0dfa70137405b096", "rini": "p09fa77e94b0dfc6c", "sqlite": "peaa43c4b7ef72edf"},
"name": "Inbe"
},
"toolchain": {