Compare commits

..
Author SHA1 Message Date
Siddarth Kumar 09845eb4c9 chore: bump release version for Fdroid 2024-11-15 12:03:28 +07:00
Icaro Motta e9eda15bef Update app metadata for Status 2.31.0 in F-Droid (#21606)
- Assets were compressed from Figma exports.
- Locale for Ukrainian fixed: from `uk` to `uk-UA` according to official reference https://android.googlesource.com/platform/frameworks/base/+/master/core/res/res/values/locale_config.xml.
- Titles for each locale are now translated.

Fixes https://github.com/status-im/status-mobile/issues/21605
2024-11-12 15:49:28 -03:00
Lungu Cristian 838c85cd20 Fix "Failed to get dApps" error when a session expired (#21531)
* fix: pass the topic instead of entire session

* chore: added logs for future debugging
2024-10-30 12:00:22 -03:00
Brian Sztamfater e8ff0c80a7 feat(swap): add metrics for swaps (#21485)
Signed-off-by: Brian Sztamfater <brian@status.im>
2024-10-30 06:29:41 -03:00
Parvesh Monu 0c5faec5d2 fix No tabs are available in the app on Graphene OS (#21520) 2024-10-30 06:29:41 -03:00
Siddarth Kumar 701fa1a268 chore(deps)_: use gradle plugin to get deps (#21502)
related issue : https://github.com/status-im/status-mobile/issues/15447

This commit makes use of https://github.com/gradle/github-dependency-graph-gradle-plugin to generate deps so that we may get rid of the AWK script that parses `gradle` output to figure out `gradle` dependencies.

credits to Vedran for doing initial research on this dependency generator plugin.

We still miss a few dependencies and are not completely able to get rid of the hack list step just yet.

I also moved `react-native-share` out of  `pluginManagement ` block in `android/settings.gradle` because it does not belong there.
2024-10-30 06:29:41 -03:00
Parvesh Monu 73be7cd784 fix Error when creating an account on e2e build (#21496) 2024-10-29 07:25:03 -03:00
Mohamed Javid e457cfbf5e fix(wallet-settings)_: Icon color in missing keypair section (#21498)
This commit fixes the icon color in the missing keypair section

Signed-off-by: Mohamed Javid <19339952+smohamedjavid@users.noreply.github.com>
2024-10-28 13:40:46 -03:00
Mohamed Javid 4e8e1b6fa7 fix(wallet)_: token supported networks (#21451)
This commit 
- fixes the networks/chains supported by the token based on the token list fetched from status-go instead of relying on the balance-per-chain map as status-go returns balance for chains only if there is a positive balance
- adds supported-networks key to token data map for network details

Signed-off-by: Mohamed Javid <19339952+smohamedjavid@users.noreply.github.com>
2024-10-28 13:40:46 -03:00
Icaro Motta 92e81e1e0b chore: Bump status-go
https://github.com/status-im/status-go/compare/39511298...635f19e3
2024-10-23 12:58:23 -03:00
Sean Hagstrom acbaa01cb3 chore: refactor screens definitions and add more navigation events for screens (#21328)
This change refactors the navigation-screens namespace to organise each screen definition into a group based on the app features. It also adds some metrics tracking to all the of the screens defined in the navigation-screens namespace. 

Additionally, in this change we've introduced a new build configuration for shadow-cljs which allows us to conditionally include code for certain shadow-cljs builds. In this case, we've decided to only exclude the metrics re-frame interceptor from being required when running the component-tests build. This is due to a complication with the metrics interceptor depending on the navigation-screens namespace, which would eventually require many other third-party dependencies that do not have mocks defined for the component tests. To avoid defining more mocks, we've avoided requiring the metrics interceptor for now.
2024-10-23 12:58:23 -03:00
Mohsen dffbe3430e [#21439] fix: close swap flow after confirmation (#21466)
Signed-off-by: Brian Sztamfater <brian@status.im>
2024-10-23 12:58:23 -03:00
Icaro Motta e8ccd19631 feat(onboarding): Present Terms to users upgrading from v1 or those who need to accept updated Terms (#21487)
Cherry-pick https://github.com/status-im/status-mobile/commit/d45eb5ec20ae7757cd99554920e466eabac0bfb1.

Fixes https://github.com/status-im/status-mobile/issues/21113

Related status-go PR: https://github.com/status-im/status-go/pull/5977
2024-10-23 12:58:23 -03:00
Siddarth Kumar 7146f9dd07 chore(ci)_: bump universal apk size limit to 125MB (#21486) (#21488) 2024-10-23 15:48:10 +05:30
Icaro Motta f8a1712b56 Bump status-go version to release/3.4.x 2024-10-22 17:18:30 -03:00
Icaro Motta b1901a2610 Bump release to 2.31.0 2024-10-22 17:18:30 -03:00
Volodymyr Kozieiev 2d71a15de7 collectible metrics (#21280) 2024-10-22 17:18:30 -03:00
Mohamed Javid fa42a1b977 fix(wallet)_: Activity tab is selected on navigating back from the swap flow (#21474)
This commit fixes activity tab is selected when navigating back from the swap flow

Signed-off-by: Mohamed Javid <19339952+smohamedjavid@users.noreply.github.com>
2024-10-22 17:18:30 -03:00
Lungu Cristian 697e300f47 Fix networks on select asset screen (#21403)
* fix: filter tokens by balance on select asset

* feat: added network-list-with-positive-balance

* fix: swaps error when using networks with balance

* fix: hide send/bridge/swap when no token balance
2024-10-22 17:18:30 -03:00
Andrey Bocharnikov 01801e5881 fix: client should pass a list with "Symbol" and without "ChainID-" prefix to wallet_fetchMarketValues, wallet_fetchPrices (#21453)
Signed-off-by: Brian Sztamfater <brian@status.im>
2024-10-22 17:18:30 -03:00
338 changed files with 5977 additions and 5727 deletions
+1
View File
@@ -1,5 +1,6 @@
CACHED_WEBVIEWS_ENABLED=1
DEBUG_WEBVIEW=1
DEFAULT_NETWORK=mainnet_rpc
DEV_BUILD=1
ETHEREUM_DEV_CLUSTER=1
EXTENSIONS=0
+3 -2
View File
@@ -1,4 +1,5 @@
DEBUG_WEBVIEW=1
DEFAULT_NETWORK=goerli_rpc
ETHEREUM_DEV_CLUSTER=1
EXTENSIONS=0
FLEET=status.staging
@@ -21,8 +22,8 @@ KEYCARD_TEST_MENU=1
QR_READ_TEST_MENU=1
ENABLE_ROOT_ALERT=0
APN_TOPIC=im.status.ethereum.pr
VERIFY_TRANSACTION_CHAIN_ID=11155111
VERIFY_ENS_CHAIN_ID=11155111
VERIFY_TRANSACTION_CHAIN_ID=5
VERIFY_ENS_CHAIN_ID=5
TEST_STATEOFUS=1
DATABASE_MANAGEMENT_ENABLED=1
COMMUNITIES_ENABLED=1
+3 -2
View File
@@ -1,5 +1,6 @@
CACHED_WEBVIEWS_ENABLED=1
DEBUG_WEBVIEW=1
DEFAULT_NETWORK=goerli_rpc
ETHEREUM_DEV_CLUSTER=1
EXTENSIONS=0
GROUP_CHATS_ENABLED=1
@@ -20,8 +21,8 @@ KEYCARD_TEST_MENU=0
ENABLE_ROOT_ALERT=1
DISABLE_WALLET_ON_MOBILE_NETWORK=1
APN_TOPIC=im.status.ethereum.pr
VERIFY_TRANSACTION_CHAIN_ID=11155111
VERIFY_ENS_CHAIN_ID=11155111
VERIFY_TRANSACTION_CHAIN_ID=5
VERIFY_ENS_CHAIN_ID=5
TEST_STATEOFUS=1
BLANK_PREVIEW=0
DATABASE_MANAGEMENT_ENABLED=1
+1
View File
@@ -1,4 +1,5 @@
DEBUG_WEBVIEW=1
DEFAULT_NETWORK=mainnet_rpc
ETHEREUM_DEV_CLUSTER=1
EXTENSIONS=0
GROUP_CHATS_ENABLED=1
+1
View File
@@ -1,4 +1,5 @@
DEBUG_WEBVIEW=0
DEFAULT_NETWORK=mainnet_rpc
ETHEREUM_DEV_CLUSTER=0
EXTENSIONS=0
GROUP_CHATS_ENABLED=1
+1 -1
View File
@@ -2,7 +2,7 @@
name: Bug Report
about: Bug Report
title: ''
type: 'Bug'
labels: ['bug', ':1234: low prio']
assignees: ''
---
-3
View File
@@ -1,3 +0,0 @@
[submodule "legal-docs"]
path = legal-docs
url = https://github.com/status-im/status-software-legal-documents.git
+1 -3
View File
@@ -1,8 +1,6 @@
{
"ignore_dirs": [
"android/build",
"target",
".clj-kondo",
".shadow-cljs"
"target"
]
}
+1 -1
View File
@@ -1 +1 @@
2.30.0
2.31.1
+1 -1
View File
@@ -92,7 +92,7 @@ For particular example it was failed on `Recover access(password:qwerty, keycard
Not all features of the app could be covered by e2e at the moment:
- Colours or place of an element on UI.
- Real ETH/token transactions. Thats the main reason we have separate .apk build for automation needs - it defaults to Sepolia network. Also it has enabled keycard test menu, ENS names and chat commands are also on Sepolia network (the same in PR builds, but not in nightlies / release)
- Real ETH/token transactions. Thats the main reason we have separate .apk build for automation needs - it defaults to Goerli network. Also it has enabled keycard test menu, ENS names and chat commands are also on Goerli network (the same in PR builds, but not in nightlies / release)
- Autologin/Biometric related actions (autologin available when device meets certain conditions like the it has set unlock password and device is not rooted: all emulators are rooted in SauceLabs)
## Brief flow for test to be automated
-61
View File
@@ -1,61 +0,0 @@
## What is Status Backend Server
Status Backend Server is a http server that runs status-go, it exposed endpoints come from [mobile/status.go](https://github.com/status-im/status-go/blob/master/mobile/status.go) so that you can call them through http requests. It brings the following benefits:
- When verifying changes made in status-go, you only need to run these commands once (unless modifying Kotlin/Objective-C code):
- `make clean && make run-clojure`
- `make run-android` or `make run-ios`
This avoids repeatedly rebuilding and saves development time.
- Debug status-go while running status mobile app
## Solution to use Status Backend Server for mobile development
`StatusBackendClient` is the entry point to use Status Backend Server. We need always to call `status-im.setup.status-backend-client/init` whether `STATUS_BACKEND_SERVER_ENABLED` is `1` or not. If it's not enabled, the invocation to functions in `native-module.core` will be delegated to built-in status-go library, otherwise it will be delegated to status-go running in status-backend server. Currently, all functions has usages in `native-module.core` should be supported delegated to.
NOTE: not all the native functions used `StatusBackendClient`, only the corresponding functions in `native-module.core` has usages should be supported delegated to ATM.
related [PR](https://github.com/status-im/status-mobile/pull/21550)
## Usage
### Add environment variables to your local machine:
```shell
# enable using status backend server or not, otherwise it will use built-in status-go library
export STATUS_BACKEND_SERVER_ENABLED=1
#The host should contain an IP address and a port separated by a colon.
#The port comes from your running status backend server.
#If you run it by PORT=60000 make run-status-backend , then host will likely be 127.0.0.1:60000
export STATUS_BACKEND_SERVER_HOST="127.0.0.1:60000"
export STATUS_BACKEND_SERVER_ROOT_DATA_DIR="/path/to/your/root/data/dir"
```
You need to change `STATUS_BACKEND_SERVER_ROOT_DATA_DIR` to your preferred directory and ensure it exists, it should be in absolute path.
All the db files and log files(requests.log/geth.log) and keystore files etc will be stored in this directory.
### Start the status backend server:
```shell
PORT=60000 make run-status-backend
```
MAKE SURE the status-backend is checked out to a revision that's at least compatible with the revision in status-mobile/status-go-version.json before starting the server.
For the Android simulator, you need to reverse the port:
```shell
adb reverse tcp:60000 tcp:60000
```
However, there is restriction when use adb reverse, we use random port for media server. So I'd suggest use "10.0.2.2:60000" as `STATUS_BACKEND_SERVER_HOST`.
### Debug status-go using IDEA
Assume you've already set up the development environment for status-go, open status-go project use IDEA, run `make generate` with terminal in the status-go project root directory to ensure all the generated files are up to date, then open `cmd/status-backend/main.go` file, navigate to function `main()`, click the green play button on the left of `main()`, choose `Modify Run Configuration`, in `Program arguments` section, add `--address=localhost:60000 --media-https=false`, then click `OK`, finally click the green play button on the left of `main()` again and choose `Debug ...`.
Basically, you don't have to run `make generate` again and again, just run it once at the beginning. So you can re-run and debug it faster!
## Known Android simulator issues
- Issue#1: Android simulator may not display images due to TLS certificate validation issues with the image server
- solution: use http instead of https for media server with set env: `export STATUS_BACKEND_SERVER_MEDIA_SERVER_ENABLE_TLS=0`, you also need to set env variable `STATUS_BACKEND_SERVER_IMAGE_SERVER_URI_PREFIX` to "http://10.0.2.2:" so that `image_server.cljs` can work, and to make `/accountInitials` work, you need to copy `Inter-Medium.ttf` to your host machine from the android simulator, let's say you store it in `/Users/mac/Downloads/Inter-Medium.ttf`, then you need to update `get-font-file-ready` manually in `image_server.cljs` to return the correct path so that status backend server can access it.
- Issue#2: exportUnencryptedDatabaseV2/import-multiaccount does not work for android, probably cause of tech debt, I found it during creating the draft PR.
- Issue#3: unable to invoke `multiaccounts_storeIdentityImage` to change avatar image.
- The reason is that we path the absolute path of the image to the backend server, but the image file is stored in the android simulator. the backend server cannot access it as it runs in the host machine.
If you're using ios simulator, you can skip above issues!
## Details for issue#1 if you're interested
- we use `react-native-fast-image` which use okhttpclient behind
- we were using custom cert for https
- we fetch the custom cert through endpoint `ImageServerTLSCert`
- we fetched it through built-in status-go before, now we need to fetch it through status backend server
- we expect `OkHttpClientProvider.setOkHttpClientFactory(StatusOkHttpClientFactory())` to be invoked early(will trigger fetching wrong custom cert via built-in status-go since StatusBackendClient is not initialised yet!) in `MainApplication.kt` before executing clojure code, otherwise we will get black screen after `make run-android` . After deep research, I found there's no way to update the cert okhttpclient used to the correct one return from status backend server
+1 -8
View File
@@ -29,8 +29,6 @@
#import <Security/Security.h>
#import <react/config/ReactNativeConfig.h>
#import "StatusBackendClient.h"
//TODO: properly import the framework
extern "C" NSString* StatusgoImageServerTLSCert();
@@ -190,12 +188,7 @@ didReceiveNotificationResponse:(UNNotificationResponse *)response
NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge;
__block NSURLCredential *credential = nil;
NSString *pemCert = [StatusBackendClient executeStatusGoRequestWithResult:@"ImageServerTLSCert"
body:@""
statusgoFunction:^NSString *{
return StatusgoImageServerTLSCert();
}];
NSString *pemCert = StatusgoImageServerTLSCert();
pemCert = [pemCert stringByReplacingOccurrencesOfString:@"-----BEGIN CERTIFICATE-----\n" withString:@""];
pemCert = [pemCert stringByReplacingOccurrencesOfString:@"\n-----END CERTIFICATE-----" withString:@""];
NSData *derCert = [[NSData alloc] initWithBase64EncodedString:pemCert options:NSDataBase64DecodingIgnoreUnknownCharacters];
Submodule legal-docs deleted from 3943b281b0
@@ -24,23 +24,25 @@ class AccountManager(private val reactContext: ReactApplicationContext) : ReactC
@ReactMethod
fun createAccountAndLogin(createAccountRequest: String) {
Log.d(TAG, "createAccountAndLogin")
StatusBackendClient.executeStatusGoRequest(
endpoint = "CreateAccountAndLogin",
requestBody = createAccountRequest,
statusgoFunction = { Statusgo.createAccountAndLogin(createAccountRequest) }
)
val result = Statusgo.createAccountAndLogin(createAccountRequest)
if (result.startsWith("{\"error\":\"\"")) {
Log.d(TAG, "createAccountAndLogin success: $result")
Log.d(TAG, "Geth node started")
} else {
Log.e(TAG, "createAccountAndLogin failed: $result")
}
}
@ReactMethod
fun restoreAccountAndLogin(restoreAccountRequest: String) {
Log.d(TAG, "restoreAccountAndLogin")
StatusBackendClient.executeStatusGoRequest(
endpoint = "RestoreAccountAndLogin",
requestBody = restoreAccountRequest,
statusgoFunction = { Statusgo.restoreAccountAndLogin(restoreAccountRequest) }
)
val result = Statusgo.restoreAccountAndLogin(restoreAccountRequest)
if (result.startsWith("{\"error\":\"\"")) {
Log.d(TAG, "restoreAccountAndLogin success: $result")
Log.d(TAG, "Geth node started")
} else {
Log.e(TAG, "restoreAccountAndLogin failed: $result")
}
}
private fun updateConfig(jsonConfigString: String, absRootDirPath: String, keystoreDirPath: String): String {
@@ -171,7 +173,12 @@ class AccountManager(private val reactContext: ReactApplicationContext) : ReactC
accountsData,
chatKey
)
utils.handleStatusGoResponse(result, "saveAccountAndLoginWithKeycard")
if (result.startsWith("{\"error\":\"\"")) {
Log.d(TAG, "saveAccountAndLoginWithKeycard result: $result")
Log.d(TAG, "Geth node started")
} else {
Log.e(TAG, "saveAccountAndLoginWithKeycard failed: $result")
}
} catch (e: JSONException) {
Log.e(TAG, "JSON conversion failed: ${e.message}")
}
@@ -182,7 +189,11 @@ class AccountManager(private val reactContext: ReactApplicationContext) : ReactC
Log.d(TAG, "loginWithKeycard")
utils.migrateKeyStoreDir(accountData, password)
val result = Statusgo.loginWithKeycard(accountData, password, chatKey, nodeConfigJSON)
utils.handleStatusGoResponse(result, "loginWithKeycard")
if (result.startsWith("{\"error\":\"\"")) {
Log.d(TAG, "LoginWithKeycard result: $result")
} else {
Log.e(TAG, "LoginWithKeycard failed: $result")
}
}
@ReactMethod
@@ -190,17 +201,22 @@ class AccountManager(private val reactContext: ReactApplicationContext) : ReactC
Log.d(TAG, "loginWithConfig")
utils.migrateKeyStoreDir(accountData, password)
val result = Statusgo.loginWithConfig(accountData, password, configJSON)
utils.handleStatusGoResponse(result, "loginWithConfig")
if (result.startsWith("{\"error\":\"\"")) {
Log.d(TAG, "LoginWithConfig result: $result")
} else {
Log.e(TAG, "LoginWithConfig failed: $result")
}
}
@ReactMethod
fun loginAccount(request: String) {
Log.d(TAG, "loginAccount")
StatusBackendClient.executeStatusGoRequest(
endpoint = "LoginAccount",
requestBody = request,
statusgoFunction = { Statusgo.loginAccount(request) }
)
val result = Statusgo.loginAccount(request)
if (result.startsWith("{\"error\":\"\"")) {
Log.d(TAG, "loginAccount result: $result")
} else {
Log.e(TAG, "loginAccount failed: $result")
}
}
@ReactMethod
@@ -208,31 +224,16 @@ class AccountManager(private val reactContext: ReactApplicationContext) : ReactC
val absRootDirPath = utils.getNoBackupDirectory()
val newKeystoreDir = utils.pathCombine(absRootDirPath, "keystore")
val jsonParams = JSONObject()
jsonParams.put("keyStoreDir", newKeystoreDir)
jsonParams.put("address", address)
jsonParams.put("password", password)
StatusBackendClient.executeStatusGoRequestWithCallback(
endpoint = "VerifyAccountPasswordV2",
requestBody = jsonParams.toString(),
statusgoFunction = { Statusgo.verifyAccountPasswordV2(jsonParams.toString()) },
utils.executeRunnableStatusGoMethod(
{ Statusgo.verifyAccountPassword(newKeystoreDir, address, password) },
callback
)
}
@ReactMethod
fun verifyDatabasePassword(keyUID: String, password: String, callback: Callback) {
val jsonParams = JSONObject()
jsonParams.put("keyUID", keyUID)
jsonParams.put("password", password)
val jsonString = jsonParams.toString()
StatusBackendClient.executeStatusGoRequestWithCallback(
endpoint = "VerifyDatabasePasswordV2",
requestBody = jsonString,
statusgoFunction = { Statusgo.verifyDatabasePasswordV2(jsonString) },
utils.executeRunnableStatusGoMethod(
{ Statusgo.verifyDatabasePassword(keyUID, password) },
callback
)
}
@@ -248,136 +249,79 @@ class AccountManager(private val reactContext: ReactApplicationContext) : ReactC
@ReactMethod
private fun initializeApplication(request: String, callback: Callback) {
Log.d(TAG, "initializeApplication")
StatusBackendClient.executeStatusGoRequestWithCallback(
"InitializeApplication",
request,
{ Statusgo.initializeApplication(request) },
callback
)
Log.d(TAG, "[Initializing application $request")
utils.executeRunnableStatusGoMethod({ Statusgo.initializeApplication(request) }, callback)
}
@ReactMethod
private fun acceptTerms(callback: Callback) {
Log.d(TAG, "acceptTerms")
StatusBackendClient.executeStatusGoRequestWithCallback(
"AcceptTerms",
"",
{ Statusgo.acceptTerms() },
callback
)
utils.executeRunnableStatusGoMethod({ Statusgo.acceptTerms() }, callback)
}
@ReactMethod
fun logout() {
Log.d(TAG, "logout")
StatusBackendClient.executeStatusGoRequest(
endpoint = "Logout",
requestBody = "",
statusgoFunction = { Statusgo.logout() }
)
val runnable = Runnable {
val result = Statusgo.logout()
if (result.startsWith("{\"error\":\"\"")) {
Log.d(TAG, "Logout result: $result")
} else {
Log.e(TAG, "Logout failed: $result")
}
}
StatusThreadPoolExecutor.getInstance().execute(runnable)
}
@ReactMethod
fun multiAccountStoreAccount(json: String, callback: Callback) {
StatusBackendClient.executeStatusGoRequestWithCallback(
endpoint = "MultiAccountStoreAccount",
requestBody = json,
statusgoFunction = { Statusgo.multiAccountStoreAccount(json) },
callback = callback
)
utils.executeRunnableStatusGoMethod({ Statusgo.multiAccountStoreAccount(json) }, callback)
}
@ReactMethod
fun multiAccountLoadAccount(json: String, callback: Callback) {
StatusBackendClient.executeStatusGoRequestWithCallback(
endpoint = "MultiAccountLoadAccount",
requestBody = json,
statusgoFunction = { Statusgo.multiAccountLoadAccount(json) },
callback = callback
)
utils.executeRunnableStatusGoMethod({ Statusgo.multiAccountLoadAccount(json) }, callback)
}
@ReactMethod
fun multiAccountDeriveAddresses(json: String, callback: Callback) {
StatusBackendClient.executeStatusGoRequestWithCallback(
endpoint = "MultiAccountDeriveAddresses",
requestBody = json,
statusgoFunction = { Statusgo.multiAccountDeriveAddresses(json) },
callback = callback
)
utils.executeRunnableStatusGoMethod({ Statusgo.multiAccountDeriveAddresses(json) }, callback)
}
@ReactMethod
fun multiAccountGenerateAndDeriveAddresses(json: String, callback: Callback) {
StatusBackendClient.executeStatusGoRequestWithCallback(
endpoint = "MultiAccountGenerateAndDeriveAddresses",
requestBody = json,
statusgoFunction = { Statusgo.multiAccountGenerateAndDeriveAddresses(json) },
callback = callback
)
utils.executeRunnableStatusGoMethod({ Statusgo.multiAccountGenerateAndDeriveAddresses(json) }, callback)
}
@ReactMethod
fun multiAccountStoreDerived(json: String, callback: Callback) {
StatusBackendClient.executeStatusGoRequestWithCallback(
endpoint = "MultiAccountStoreDerivedAccounts",
requestBody = json,
statusgoFunction = { Statusgo.multiAccountStoreDerivedAccounts(json) },
callback = callback
)
utils.executeRunnableStatusGoMethod({ Statusgo.multiAccountStoreDerivedAccounts(json) }, callback)
}
@ReactMethod
fun multiAccountImportMnemonic(json: String, callback: Callback) {
StatusBackendClient.executeStatusGoRequestWithCallback(
endpoint = "MultiAccountImportMnemonic",
requestBody = json,
statusgoFunction = { Statusgo.multiAccountImportMnemonic(json) },
callback = callback
)
utils.executeRunnableStatusGoMethod({ Statusgo.multiAccountImportMnemonic(json) }, callback)
}
@ReactMethod
fun multiAccountImportPrivateKey(json: String, callback: Callback) {
StatusBackendClient.executeStatusGoRequestWithCallback(
endpoint = "MultiAccountImportPrivateKey",
requestBody = json,
statusgoFunction = { Statusgo.multiAccountImportPrivateKey(json) },
callback = callback
)
utils.executeRunnableStatusGoMethod({ Statusgo.multiAccountImportPrivateKey(json) }, callback)
}
@ReactMethod
fun deleteMultiaccount(keyUID: String, callback: Callback) {
val keyStoreDir = utils.getKeyStorePath(keyUID)
val params = JSONObject().apply {
put("keyUID", keyUID)
put("keyStoreDir", keyStoreDir)
}
val jsonString = params.toString()
StatusBackendClient.executeStatusGoRequestWithCallback(
endpoint = "DeleteMultiaccountV2",
requestBody = jsonString,
statusgoFunction = { Statusgo.deleteMultiaccountV2(jsonString) },
callback
)
utils.executeRunnableStatusGoMethod({ Statusgo.deleteMultiaccount(keyUID, keyStoreDir) }, callback)
}
@ReactMethod
fun getRandomMnemonic(callback: Callback) {
StatusBackendClient.executeStatusGoRequestWithCallback(
"GetRandomMnemonic",
"",
{ Statusgo.getRandomMnemonic() },
callback
)
utils.executeRunnableStatusGoMethod({ Statusgo.getRandomMnemonic() }, callback)
}
@ReactMethod
fun createAccountFromMnemonicAndDeriveAccountsForPaths(mnemonic: String, callback: Callback) {
StatusBackendClient.executeStatusGoRequestWithCallback(
"CreateAccountFromMnemonicAndDeriveAccountsForPaths",
mnemonic,
utils.executeRunnableStatusGoMethod(
{ Statusgo.createAccountFromMnemonicAndDeriveAccountsForPaths(mnemonic) },
callback
)
@@ -385,12 +329,7 @@ class AccountManager(private val reactContext: ReactApplicationContext) : ReactC
@ReactMethod
fun createAccountFromPrivateKey(json: String, callback: Callback) {
StatusBackendClient.executeStatusGoRequestWithCallback(
endpoint = "CreateAccountFromPrivateKey",
requestBody = json,
statusgoFunction = { Statusgo.createAccountFromPrivateKey(json) },
callback = callback
)
utils.executeRunnableStatusGoMethod({ Statusgo.createAccountFromPrivateKey(json) }, callback)
}
companion object {
@@ -9,8 +9,6 @@ import com.facebook.react.bridge.ReactContextBaseJavaModule
import com.facebook.react.bridge.ReactMethod
import statusgo.Statusgo
import java.io.File
import org.json.JSONObject
import org.json.JSONException
class DatabaseManager(private val reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) {
@@ -19,43 +17,22 @@ class DatabaseManager(private val reactContext: ReactApplicationContext) : React
override fun getName() = "DatabaseManager"
private fun getExportDBFile(): File {
StatusBackendClient.getInstance()?.let {
if (it.serverEnabled) {
return File(it.rootDataDir, exportDBFileName)
}
}
val pubDirectory = reactContext.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
return File(pubDirectory, exportDBFileName)
}
@ReactMethod
fun exportUnencryptedDatabase(accountData: String, password: String, callback: Callback) {
Log.d(TAG, "exportUnencryptedDatabase")
Log.d(TAG, "login")
val newFile = getExportDBFile()
utils.migrateKeyStoreDir(accountData, password)
try {
val accountJson = JSONObject(accountData)
val params = JSONObject().apply {
put("account", accountJson)
put("password", password)
put("databasePath", newFile.absolutePath)
}
val jsonParams = params.toString()
StatusBackendClient.executeStatusGoRequestWithCallback(
endpoint = "ExportUnencryptedDatabaseV2",
requestBody = jsonParams,
statusgoFunction = { Statusgo.exportUnencryptedDatabaseV2(jsonParams) },
callback = null
)
callback.invoke(newFile.absolutePath)
} catch (e: JSONException) {
Log.e(TAG, "Error parsing account data: ${e.message}")
val result = Statusgo.exportUnencryptedDatabase(accountData, password, newFile.absolutePath)
if (result.startsWith("{\"error\":\"\"")) {
Log.d(TAG, "Login result: $result")
} else {
Log.e(TAG, "Login failed: $result")
}
}
@@ -66,25 +43,11 @@ class DatabaseManager(private val reactContext: ReactApplicationContext) : React
val newFile = getExportDBFile()
utils.migrateKeyStoreDir(accountData, password)
try {
val accountJson = JSONObject(accountData)
val params = JSONObject().apply {
put("account", accountJson)
put("password", password)
put("databasePath", newFile.absolutePath)
}
val jsonParams = params.toString()
StatusBackendClient.executeStatusGoRequest(
endpoint = "ImportUnencryptedDatabaseV2",
requestBody = jsonParams,
statusgoFunction = { Statusgo.importUnencryptedDatabaseV2(jsonParams) }
)
} catch (e: JSONException) {
Log.e(TAG, "Error parsing account data: ${e.message}")
val result = Statusgo.importUnencryptedDatabase(accountData, password, newFile.absolutePath)
if (result.startsWith("{\"error\":\"\"")) {
Log.d(TAG, "import result: $result")
} else {
Log.e(TAG, "import failed: $result")
}
}
@@ -7,7 +7,6 @@ import com.facebook.react.bridge.Callback;
import android.util.Log;
import statusgo.Statusgo;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.function.Function;
import android.app.Activity;
import android.view.WindowManager;
@@ -40,151 +39,67 @@ public class EncryptionUtils extends ReactContextBaseJavaModule {
final String commonKeydir = this.utils.pathCombine(this.utils.getNoBackupDirectory(), "/keystore");
final String keydir = this.utils.pathCombine(commonKeydir, keyUID);
StatusBackendClient.executeStatusGoRequestWithCallback(
"InitKeystore",
keydir,
() -> Statusgo.initKeystore(keydir),
callback
);
this.utils.executeRunnableStatusGoMethod(() -> Statusgo.initKeystore(keydir), callback);
}
@ReactMethod
public void reEncryptDbAndKeystore(final String keyUID, final String password, final String newPassword, final Callback callback) throws JSONException {
JSONObject params = new JSONObject();
params.put("keyUID", keyUID);
params.put("oldPassword", password);
params.put("newPassword", newPassword);
String jsonParams = params.toString();
StatusBackendClient.executeStatusGoRequestWithCallback(
"ChangeDatabasePasswordV2",
jsonParams,
() -> Statusgo.changeDatabasePasswordV2(jsonParams),
callback
);
this.utils.executeRunnableStatusGoMethod(() -> Statusgo.changeDatabasePassword(keyUID, password, newPassword), callback);
}
@ReactMethod
public void convertToKeycardAccount(final String keyUID, final String accountData, final String options, final String keycardUID, final String password,
final String newPassword, final Callback callback) throws JSONException {
final String keyStoreDir = this.utils.getKeyStorePath(keyUID);
JSONObject params = new JSONObject();
params.put("keyUID", keyUID);
params.put("account", new JSONObject(accountData));
params.put("settings", new JSONObject(options));
params.put("keycardUID", keycardUID);
params.put("oldPassword", password);
params.put("newPassword", newPassword);
final String jsonParams = params.toString();
StatusBackendClient.executeStatusGoRequest(
"InitKeystore",
keyStoreDir,
() -> Statusgo.initKeystore(keyStoreDir)
);
StatusBackendClient.executeStatusGoRequestWithCallback(
"ConvertToKeycardAccountV2",
jsonParams,
() -> Statusgo.convertToKeycardAccountV2(jsonParams),
callback
);
this.utils.executeRunnableStatusGoMethod(() -> {
Statusgo.initKeystore(keyStoreDir);
return Statusgo.convertToKeycardAccount(accountData, options, keycardUID, password, newPassword);
}, callback);
}
@ReactMethod(isBlockingSynchronousMethod = true)
public String encodeTransfer(final String to, final String value) {
try {
JSONObject params = new JSONObject();
params.put("to", to);
params.put("value", value);
String jsonParams = params.toString();
return StatusBackendClient.executeStatusGoRequestWithResult(
"EncodeTransferV2",
jsonParams,
() -> Statusgo.encodeTransferV2(jsonParams)
);
} catch (JSONException e) {
Log.e(TAG, "Error creating JSON for encodeTransfer: " + e.getMessage());
return null;
}
return Statusgo.encodeTransfer(to, value);
}
@ReactMethod(isBlockingSynchronousMethod = true)
public String encodeFunctionCall(final String method, final String paramsJSON) {
try {
JSONObject params = new JSONObject();
params.put("method", method);
params.put("paramsJSON", new JSONObject(paramsJSON));
String jsonString = params.toString();
return StatusBackendClient.executeStatusGoRequestWithResult(
"EncodeFunctionCallV2",
jsonString,
() -> Statusgo.encodeFunctionCallV2(jsonString)
);
} catch (JSONException e) {
Log.e(TAG, "Error creating JSON for encodeFunctionCall: " + e.getMessage());
return null;
}
return Statusgo.encodeFunctionCall(method, paramsJSON);
}
@ReactMethod(isBlockingSynchronousMethod = true)
public String decodeParameters(final String decodeParamJSON) {
return StatusBackendClient.executeStatusGoRequestWithResult(
"DecodeParameters",
decodeParamJSON,
() -> Statusgo.decodeParameters(decodeParamJSON)
);
return Statusgo.decodeParameters(decodeParamJSON);
}
@ReactMethod(isBlockingSynchronousMethod = true)
public String hexToNumber(final String hex) {
return StatusBackendClient.executeStatusGoRequestWithResult(
"HexToNumber",
hex,
() -> Statusgo.hexToNumber(hex)
);
return Statusgo.hexToNumber(hex);
}
@ReactMethod(isBlockingSynchronousMethod = true)
public String numberToHex(final String numString) {
return StatusBackendClient.executeStatusGoRequestWithResult(
"NumberToHex",
numString,
() -> Statusgo.numberToHex(numString)
);
return Statusgo.numberToHex(numString);
}
@ReactMethod(isBlockingSynchronousMethod = true)
public String sha3(final String str) {
return StatusBackendClient.executeStatusGoRequestWithResult(
"Sha3",
str,
() -> Statusgo.sha3(str)
);
return Statusgo.sha3(str);
}
@ReactMethod(isBlockingSynchronousMethod = true)
public String utf8ToHex(final String str) {
return StatusBackendClient.executeStatusGoRequestWithResult(
"Utf8ToHex",
str,
() -> Statusgo.utf8ToHex(str)
);
return Statusgo.utf8ToHex(str);
}
@ReactMethod(isBlockingSynchronousMethod = true)
public String hexToUtf8(final String str) {
return StatusBackendClient.executeStatusGoRequestWithResult(
"HexToUtf8",
str,
() -> Statusgo.hexToUtf8(str)
);
return Statusgo.hexToUtf8(str);
}
@ReactMethod(isBlockingSynchronousMethod = true)
public String serializeLegacyKey(final String publicKey) {
return StatusBackendClient.executeStatusGoRequestWithResult(
"SerializeLegacyKey",
publicKey,
() -> Statusgo.serializeLegacyKey(publicKey)
);
return Statusgo.serializeLegacyKey(publicKey);
}
@ReactMethod
@@ -215,46 +130,22 @@ public class EncryptionUtils extends ReactContextBaseJavaModule {
@ReactMethod
public void hashTransaction(final String txArgsJSON, final Callback callback) throws JSONException {
StatusBackendClient.executeStatusGoRequestWithCallback(
"HashTransaction",
txArgsJSON,
() -> Statusgo.hashTransaction(txArgsJSON),
callback
);
this.utils.executeRunnableStatusGoMethod(() -> Statusgo.hashTransaction(txArgsJSON), callback);
}
@ReactMethod
public void hashMessage(final String message, final Callback callback) throws JSONException {
StatusBackendClient.executeStatusGoRequestWithCallback(
"HashMessage",
message,
() -> Statusgo.hashMessage(message),
callback
);
this.utils.executeRunnableStatusGoMethod(() -> Statusgo.hashMessage(message), callback);
}
@ReactMethod
public void multiformatDeserializePublicKey(final String multiCodecKey, final String base58btc, final Callback callback) throws JSONException {
JSONObject params = new JSONObject();
params.put("key", multiCodecKey);
params.put("outBase", base58btc);
String jsonParams = params.toString();
StatusBackendClient.executeStatusGoRequestWithCallback(
"MultiformatDeserializePublicKeyV2",
jsonParams,
() -> Statusgo.multiformatDeserializePublicKeyV2(jsonParams),
callback
);
this.utils.executeRunnableStatusGoMethod(() -> Statusgo.multiformatDeserializePublicKey(multiCodecKey,base58btc), callback);
}
@ReactMethod
public void deserializeAndCompressKey(final String desktopKey, final Callback callback) throws JSONException {
StatusBackendClient.executeStatusGoRequestWithCallback(
"DeserializeAndCompressKey",
desktopKey,
() -> Statusgo.deserializeAndCompressKey(desktopKey),
callback
);
this.utils.executeRunnableStatusGoMethod(() -> Statusgo.deserializeAndCompressKey(desktopKey), callback);
}
@ReactMethod
@@ -269,12 +160,7 @@ public class EncryptionUtils extends ReactContextBaseJavaModule {
@ReactMethod
public void signMessage(final String rpcParams, final Callback callback) throws JSONException {
StatusBackendClient.executeStatusGoRequestWithCallback(
"SignMessage",
rpcParams,
() -> Statusgo.signMessage(rpcParams),
callback
);
this.utils.executeRunnableStatusGoMethod(() -> Statusgo.signMessage(rpcParams), callback);
}
@ReactMethod
@@ -206,12 +206,7 @@ class LogManager(private val reactContext: ReactApplicationContext) : ReactConte
put("LogRequestFile", getRequestLogFile().absolutePath)
}
val config = jsonConfig.toString()
StatusBackendClient.executeStatusGoRequestWithCallback(
endpoint = "InitLogging",
requestBody = config,
statusgoFunction = { Statusgo.initLogging(config) },
callback = callback
)
utils.executeRunnableStatusGoMethod({ Statusgo.initLogging(config) }, callback)
}
@ReactMethod(isBlockingSynchronousMethod = true)
@@ -16,12 +16,7 @@ class NetworkManager(private val reactContext: ReactApplicationContext) : ReactC
@ReactMethod
fun startSearchForLocalPairingPeers(callback: Callback) {
StatusBackendClient.executeStatusGoRequestWithCallback(
endpoint = "StartSearchForLocalPairingPeers",
requestBody = "",
statusgoFunction = { Statusgo.startSearchForLocalPairingPeers() },
callback = callback
)
utils.executeRunnableStatusGoMethod({ Statusgo.startSearchForLocalPairingPeers() }, callback)
}
@ReactMethod
@@ -31,85 +26,48 @@ class NetworkManager(private val reactContext: ReactApplicationContext) : ReactC
val keyUID = senderConfig.getString("keyUID")
val keyStorePath = utils.getKeyStorePath(keyUID)
senderConfig.put("keystorePath", keyStorePath)
val jsonString = jsonConfig.toString()
StatusBackendClient.executeStatusGoRequestWithCallback(
endpoint = "GetConnectionStringForBootstrappingAnotherDevice",
requestBody = jsonString,
statusgoFunction = { Statusgo.getConnectionStringForBootstrappingAnotherDevice(jsonString) },
utils.executeRunnableStatusGoMethod(
{ Statusgo.getConnectionStringForBootstrappingAnotherDevice(jsonConfig.toString()) },
callback
)
}
@ReactMethod
fun inputConnectionStringForBootstrapping(connectionString: String, configJSON: String, callback: Callback) {
val receiverClientConfig = JSONObject(configJSON)
val params = JSONObject().apply {
put("connectionString", connectionString)
put("receiverClientConfig", receiverClientConfig)
}
val jsonString = params.toString()
StatusBackendClient.executeStatusGoRequestWithCallback(
endpoint = "InputConnectionStringForBootstrappingV2",
requestBody = jsonString,
statusgoFunction = { Statusgo.inputConnectionStringForBootstrappingV2(jsonString) },
val jsonConfig = JSONObject(configJSON)
utils.executeRunnableStatusGoMethod(
{ Statusgo.inputConnectionStringForBootstrapping(connectionString, jsonConfig.toString()) },
callback
)
}
@ReactMethod
fun sendTransactionWithSignature(txArgsJSON: String, signature: String, callback: Callback) {
StatusBackendClient.executeStatusGoRequestWithCallback(
endpoint = "SendTransactionWithSignature",
requestBody = txArgsJSON,
statusgoFunction = { Statusgo.sendTransactionWithSignature(txArgsJSON, signature) },
utils.executeRunnableStatusGoMethod(
{ Statusgo.sendTransactionWithSignature(txArgsJSON, signature) },
callback
)
}
@ReactMethod
fun sendTransaction(txArgsJSON: String, password: String, callback: Callback) {
val jsonParams = JSONObject().apply {
put("txArgs", JSONObject(txArgsJSON))
put("password", password)
}
val jsonString = jsonParams.toString()
StatusBackendClient.executeStatusGoRequestWithCallback(
endpoint = "SendTransactionV2",
requestBody = jsonString,
statusgoFunction = { Statusgo.sendTransactionV2(jsonString) },
callback
)
utils.executeRunnableStatusGoMethod({ Statusgo.sendTransaction(txArgsJSON, password) }, callback)
}
@ReactMethod
fun callRPC(payload: String, callback: Callback) {
StatusBackendClient.executeStatusGoRequestWithCallback(
endpoint = "CallRPC",
requestBody = payload,
statusgoFunction = { Statusgo.callRPC(payload) },
callback = callback
)
utils.executeRunnableStatusGoMethod({ Statusgo.callRPC(payload) }, callback)
}
@ReactMethod
fun callPrivateRPC(payload: String, callback: Callback) {
StatusBackendClient.executeStatusGoRequestWithCallback(
endpoint = "CallPrivateRPC",
requestBody = payload,
statusgoFunction = { Statusgo.callPrivateRPC(payload) },
callback = callback
)
utils.executeRunnableStatusGoMethod({ Statusgo.callPrivateRPC(payload) }, callback)
}
@ReactMethod
fun recover(rpcParams: String, callback: Callback) {
StatusBackendClient.executeStatusGoRequestWithCallback(
endpoint = "Recover",
requestBody = rpcParams,
statusgoFunction = { Statusgo.recover(rpcParams) },
callback
)
utils.executeRunnableStatusGoMethod({ Statusgo.recover(rpcParams) }, callback)
}
@ReactMethod
@@ -119,33 +77,22 @@ class NetworkManager(private val reactContext: ReactApplicationContext) : ReactC
val keyUID = senderConfig.getString("loggedInKeyUid")
val keyStorePath = utils.getKeyStorePath(keyUID)
senderConfig.put("keystorePath", keyStorePath)
val jsonString = jsonConfig.toString()
StatusBackendClient.executeStatusGoRequestWithCallback(
endpoint = "GetConnectionStringForExportingKeypairsKeystores",
requestBody = jsonString,
statusgoFunction = { Statusgo.getConnectionStringForExportingKeypairsKeystores(jsonString) },
callback = callback
)
utils.executeRunnableStatusGoMethod(
{ Statusgo.getConnectionStringForExportingKeypairsKeystores(jsonConfig.toString()) },
callback)
}
@ReactMethod
fun inputConnectionStringForImportingKeypairsKeystores(connectionString: String, configJSON: String, callback: Callback) {
val keystoreFilesReceiverClientConfig = JSONObject(configJSON)
val receiverConfig = keystoreFilesReceiverClientConfig.getJSONObject("receiverConfig")
val jsonConfig = JSONObject(configJSON)
val receiverConfig = jsonConfig.getJSONObject("receiverConfig")
val keyStorePath = utils.pathCombine(utils.getNoBackupDirectory(), "/keystore")
receiverConfig.put("keystorePath", keyStorePath)
val params = JSONObject().apply {
put("connectionString", connectionString)
put("keystoreFilesReceiverClientConfig", keystoreFilesReceiverClientConfig)
}
val jsonString = params.toString()
StatusBackendClient.executeStatusGoRequestWithCallback(
endpoint = "InputConnectionStringForImportingKeypairsKeystoresV2",
requestBody = jsonString,
statusgoFunction = { Statusgo.inputConnectionStringForImportingKeypairsKeystoresV2(jsonString) },
callback = callback
utils.executeRunnableStatusGoMethod(
{ Statusgo.inputConnectionStringForImportingKeypairsKeystores(connectionString, jsonConfig.toString()) },
callback
)
}
}
@@ -1,209 +0,0 @@
package im.status.ethereum.module
import android.util.Log
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import okhttp3.WebSocket
import okhttp3.WebSocketListener
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactContextBaseJavaModule
import com.facebook.react.bridge.ReactMethod
import com.facebook.react.bridge.Callback
import java.net.SocketException
import java.net.SocketTimeoutException
import java.util.concurrent.TimeUnit
class StatusBackendClient(private val reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) {
companion object {
private const val TAG = "StatusBackendClient"
private val JSON = "application/json; charset=utf-8".toMediaType()
private const val TIMEOUT_SECONDS = 30L
@Volatile private var instance: StatusBackendClient? = null
private lateinit var utils: Utils
fun getInstance(): StatusBackendClient? = instance
@JvmStatic
fun executeStatusGoRequest(
endpoint: String,
requestBody: String,
statusgoFunction: () -> String
) {
val statusBackendClient = getInstance()
if (statusBackendClient?.serverEnabled == true) {
val result = statusBackendClient.request(endpoint, requestBody)
result.onSuccess { response ->
utils.handleStatusGoResponse(response, endpoint)
}.onFailure { error ->
Log.e(TAG, "request to $endpoint failed", error)
}
} else {
val result = statusgoFunction()
utils.handleStatusGoResponse(result, endpoint)
}
}
@JvmStatic
fun executeStatusGoRequestWithCallback(
endpoint: String,
requestBody: String,
statusgoFunction: () -> String,
callback: Callback?
) {
val statusBackendClient = getInstance()
if (statusBackendClient?.serverEnabled == true) {
val runnable = Runnable {
val result = statusBackendClient.request(endpoint, requestBody)
result.onSuccess { response ->
callback?.invoke(response)
}.onFailure { error ->
Log.e(TAG, "request to $endpoint failed", error)
callback?.invoke(false)
}
}
StatusThreadPoolExecutor.getInstance().execute(runnable)
} else {
utils.executeRunnableStatusGoMethod(statusgoFunction, callback)
}
}
@JvmStatic
fun executeStatusGoRequestWithResult(
endpoint: String,
requestBody: String,
statusgoFunction: () -> String
): String {
val statusBackendClient = getInstance()
return if (statusBackendClient?.serverEnabled == true) {
val result = statusBackendClient.request(endpoint, requestBody)
result.getOrElse { error ->
Log.e(TAG, "request to $endpoint failed", error)
""
}
} else {
statusgoFunction()
}
}
}
init {
instance = this
utils = Utils(reactContext)
}
override fun getName(): String = "StatusBackendClient"
private val httpClient = OkHttpClient.Builder()
.connectTimeout(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.writeTimeout(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.readTimeout(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.retryOnConnectionFailure(true)
.build()
private val wsClient = OkHttpClient.Builder()
.retryOnConnectionFailure(true)
.build()
private var webSocket: WebSocket? = null
@Volatile var serverEnabled = false
@Volatile private var statusGoEndpoint: String? = null
@Volatile private var signalEndpoint: String? = null
@Volatile var rootDataDir: String? = null
@ReactMethod
fun configStatusBackendServer(
serverEnabled: Boolean,
statusGoEndpoint: String,
signalEndpoint: String,
rootDataDir: String
) {
configure(serverEnabled, statusGoEndpoint, signalEndpoint, rootDataDir)
}
private fun configure(
serverEnabled: Boolean,
statusGoEndpoint: String,
signalEndpoint: String,
rootDataDir: String
) {
Log.d(TAG, "configure: serverEnabled=$serverEnabled, statusGoEndpoint=$statusGoEndpoint, " +
"signalEndpoint=$signalEndpoint, rootDataDir=$rootDataDir")
this.serverEnabled = serverEnabled
if (serverEnabled) {
this.statusGoEndpoint = statusGoEndpoint
this.signalEndpoint = signalEndpoint
this.rootDataDir = rootDataDir
connectWebSocket()
} else {
disconnectWebSocket()
this.statusGoEndpoint = null
this.signalEndpoint = null
this.rootDataDir = null
}
}
private fun connectWebSocket() {
if (!serverEnabled || signalEndpoint == null) {
return
}
val request = Request.Builder()
.url("$signalEndpoint")
.build()
webSocket = wsClient.newWebSocket(request, object : WebSocketListener() {
override fun onMessage(webSocket: WebSocket, text: String) {
StatusModule.getInstance()?.handleSignal(text)
}
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
Log.e(TAG, "WebSocket error: ${t.message}")
}
})
}
private fun disconnectWebSocket() {
webSocket?.cancel()
webSocket = null
}
fun request(endpoint: String, body: String): Result<String> {
if (!serverEnabled || statusGoEndpoint == null) {
return Result.failure(IllegalStateException("Status backend server is not enabled"))
}
val fullUrl = "$statusGoEndpoint$endpoint"
return try {
val request = Request.Builder()
.url(fullUrl)
.post(body.toRequestBody(JSON))
.build()
httpClient.newCall(request).execute().use { response ->
val responseBody = response.body?.string() ?: ""
if (response.isSuccessful) {
Log.d(TAG, "Request to $endpoint succeeded: $responseBody")
Result.success(responseBody)
} else {
val errorMsg = "Request failed with code ${response.code}: $responseBody"
Log.e(TAG, "Request to $endpoint failed: $errorMsg")
Result.failure(Exception(errorMsg))
}
}
} catch (e: Exception) {
when (e) {
is SocketTimeoutException -> Log.e(TAG, "Request to $endpoint timed out", e)
is SocketException -> Log.e(TAG, "Socket error for $endpoint", e)
else -> Log.e(TAG, "Request to $endpoint failed with exception", e)
}
Result.failure(e)
}
}
}
@@ -9,17 +9,12 @@ import statusgo.SignalHandler
import statusgo.Statusgo
import org.json.JSONException
import android.view.WindowManager
import org.json.JSONObject
class StatusModule(private val reactContext: ReactApplicationContext, private val rootedDevice: Boolean) : ReactContextBaseJavaModule(reactContext), LifecycleEventListener, SignalHandler {
companion object {
private const val TAG = "StatusModule"
private var module: StatusModule? = null
fun getInstance(): StatusModule? {
return module
}
}
private val utils: Utils = Utils(reactContext)
@@ -61,97 +56,45 @@ class StatusModule(private val reactContext: ReactApplicationContext, private va
@ReactMethod
fun connectionChange(type: String, isExpensive: Boolean) {
Log.d(TAG, "ConnectionChange: $type, is expensive $isExpensive")
val params = JSONObject().apply {
put("type", type)
put("expensive", isExpensive)
}
val jsonString = params.toString()
StatusBackendClient.executeStatusGoRequest(
endpoint = "ConnectionChangeV2",
requestBody = jsonString,
statusgoFunction = { Statusgo.connectionChangeV2(jsonString) }
)
Statusgo.connectionChange(type, if (isExpensive) 1 else 0)
}
@ReactMethod
fun appStateChange(state: String) {
Log.d(TAG, "AppStateChange: $state")
val params = JSONObject().apply {
put("state", state)
}
val jsonString = params.toString()
StatusBackendClient.executeStatusGoRequest(
endpoint = "AppStateChangeV2",
requestBody = jsonString,
statusgoFunction = { Statusgo.appStateChangeV2(jsonString) }
)
fun appStateChange(type: String) {
Log.d(TAG, "AppStateChange: $type")
Statusgo.appStateChange(type)
}
@ReactMethod
fun startLocalNotifications() {
Log.d(TAG, "startLocalNotifications")
StatusBackendClient.executeStatusGoRequest(
endpoint = "StartLocalNotifications",
requestBody = "",
statusgoFunction = { Statusgo.startLocalNotifications() }
)
Statusgo.startLocalNotifications()
}
@ReactMethod
fun getNodeConfig(callback: Callback) {
StatusBackendClient.executeStatusGoRequestWithCallback(
endpoint = "GetNodeConfig",
requestBody = "",
statusgoFunction = { Statusgo.getNodeConfig() },
callback = callback
)
utils.executeRunnableStatusGoMethod({ Statusgo.getNodeConfig() }, callback)
}
@ReactMethod
fun addCentralizedMetric(request: String, callback: Callback) {
StatusBackendClient.executeStatusGoRequestWithCallback(
endpoint = "AddCentralizedMetric",
requestBody = request,
statusgoFunction = { Statusgo.addCentralizedMetric(request) },
callback
)
utils.executeRunnableStatusGoMethod({ Statusgo.addCentralizedMetric(request) }, callback)
}
@ReactMethod
fun toggleCentralizedMetrics(request: String, callback: Callback) {
StatusBackendClient.executeStatusGoRequestWithCallback(
endpoint = "ToggleCentralizedMetrics",
requestBody = request,
statusgoFunction = { Statusgo.toggleCentralizedMetrics(request) },
callback
)
utils.executeRunnableStatusGoMethod({ Statusgo.toggleCentralizedMetrics(request) }, callback)
}
@ReactMethod
fun deleteImportedKey(keyUID: String, address: String, password: String, callback: Callback) {
val keyStoreDir = utils.getKeyStorePath(keyUID)
val params = JSONObject().apply {
put("address", address)
put("password", password)
put("keyStoreDir", keyStoreDir)
}
val jsonString = params.toString()
StatusBackendClient.executeStatusGoRequestWithCallback(
endpoint = "DeleteImportedKeyV2",
requestBody = jsonString,
statusgoFunction = { Statusgo.deleteImportedKeyV2(jsonString) },
callback
)
utils.executeRunnableStatusGoMethod({ Statusgo.deleteImportedKey(address, password, keyStoreDir) }, callback)
}
@ReactMethod(isBlockingSynchronousMethod = true)
fun fleets(): String {
return StatusBackendClient.executeStatusGoRequestWithResult(
endpoint = "Fleets",
requestBody = "",
statusgoFunction = { Statusgo.fleets() }
)
return Statusgo.fleets()
}
override fun getConstants(): Map<String, Any>? {
@@ -9,12 +9,7 @@ import statusgo.Statusgo
class StatusPackage(private val rootedDevice: Boolean) : ReactPackage {
companion object {
fun getImageTLSCert(): String =
StatusBackendClient.executeStatusGoRequestWithResult(
endpoint = "ImageServerTLSCert",
requestBody = "",
statusgoFunction = { Statusgo.imageServerTLSCert() }
)
fun getImageTLSCert(): String = Statusgo.imageServerTLSCert()
}
override fun createNativeModules(reactContext: ReactApplicationContext): List<NativeModule> {
@@ -31,7 +26,6 @@ class StatusPackage(private val rootedDevice: Boolean) : ReactPackage {
add(NetworkManager(reactContext))
add(MailManager(reactContext))
add(RNSelectableTextInputModule(reactContext))
add(StatusBackendClient(reactContext))
}
return modules
@@ -25,11 +25,6 @@ class Utils(private val reactContext: ReactApplicationContext) : ReactContextBas
}
fun getNoBackupDirectory(): String {
StatusBackendClient.getInstance()?.let { client ->
if (client.serverEnabled && client.rootDataDir != null) {
return client.rootDataDir!!
}
}
return reactContext.noBackupFilesDir.absolutePath
}
@@ -39,11 +34,6 @@ class Utils(private val reactContext: ReactApplicationContext) : ReactContextBas
}
fun getPublicStorageDirectory(): File? {
StatusBackendClient.getInstance()?.let { client ->
if (client.serverEnabled && client.rootDataDir != null) {
return File(client.rootDataDir!!)
}
}
// Environment.getExternalStoragePublicDirectory doesn't work as expected on Android Q
// https://developer.android.com/reference/android/os/Environment#getExternalStoragePublicDirectory(java.lang.String)
return reactContext.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
@@ -79,22 +69,8 @@ class Utils(private val reactContext: ReactApplicationContext) : ReactContextBas
val keydirFile = File(keydir)
if (!keydirFile.exists() || keydirFile.list().isEmpty()) {
Log.d(TAG, "migrateKeyStoreDir")
val jsonParams = JSONObject()
jsonParams.put("account", JSONObject(accountData)) // Remove 'new' keyword
jsonParams.put("password", password)
jsonParams.put("oldDir", commonKeydir)
jsonParams.put("newDir", keydir)
StatusBackendClient.executeStatusGoRequest(
endpoint = "MigrateKeyStoreDirV2",
requestBody = jsonParams.toString(),
statusgoFunction = { Statusgo.migrateKeyStoreDirV2(jsonParams.toString()) }
)
StatusBackendClient.executeStatusGoRequest(
endpoint = "InitKeystore",
requestBody = keydir,
statusgoFunction = { Statusgo.initKeystore(keydir) }
)
Statusgo.migrateKeyStoreDir(accountData, password, commonKeydir, keydir)
Statusgo.initKeystore(keydir)
}
} catch (e: JSONException) {
Log.e(TAG, "JSON conversion failed: ${e.message}")
@@ -123,15 +99,15 @@ class Utils(private val reactContext: ReactApplicationContext) : ReactContextBas
return false
}
fun executeRunnableStatusGoMethod(method: Supplier<String>, callback: Callback?) {
fun executeRunnableStatusGoMethod(method: Supplier<String>, callback: Callback) {
if (!checkAvailability()) {
callback?.invoke(false)
callback.invoke(false)
return
}
val runnableTask = Runnable {
val res = method.get()
callback?.invoke(res)
callback.invoke(res)
}
StatusThreadPoolExecutor.getInstance().execute(runnableTask)
@@ -139,15 +115,7 @@ class Utils(private val reactContext: ReactApplicationContext) : ReactContextBas
@ReactMethod
fun validateMnemonic(seed: String, callback: Callback) {
val jsonParams = JSONObject()
jsonParams.put("mnemonic", seed)
val jsonString = jsonParams.toString()
StatusBackendClient.executeStatusGoRequestWithCallback(
endpoint = "ValidateMnemonicV2",
requestBody = jsonString,
statusgoFunction = { Statusgo.validateMnemonicV2(jsonString) },
callback
)
executeRunnableStatusGoMethod({ Statusgo.validateMnemonic(seed) }, callback)
}
fun is24Hour(): Boolean {
@@ -156,29 +124,17 @@ class Utils(private val reactContext: ReactApplicationContext) : ReactContextBas
@ReactMethod(isBlockingSynchronousMethod = true)
fun checkAddressChecksum(address: String): String {
return StatusBackendClient.executeStatusGoRequestWithResult(
endpoint = "CheckAddressChecksum",
requestBody = address,
statusgoFunction = { Statusgo.checkAddressChecksum(address) }
)
return Statusgo.checkAddressChecksum(address)
}
@ReactMethod(isBlockingSynchronousMethod = true)
fun isAddress(address: String): String {
return StatusBackendClient.executeStatusGoRequestWithResult(
endpoint = "IsAddress",
requestBody = address,
statusgoFunction = { Statusgo.isAddress(address) }
)
return Statusgo.isAddress(address)
}
@ReactMethod(isBlockingSynchronousMethod = true)
fun toChecksumAddress(address: String): String {
return StatusBackendClient.executeStatusGoRequestWithResult(
endpoint = "ToChecksumAddress",
requestBody = address,
statusgoFunction = { Statusgo.toChecksumAddress(address) }
)
return Statusgo.toChecksumAddress(address)
}
fun readableArrayToStringArray(r: ReadableArray): Array<String> {
@@ -194,19 +150,6 @@ class Utils(private val reactContext: ReactApplicationContext) : ReactContextBas
@ReactMethod(isBlockingSynchronousMethod = true)
fun validateConnectionString(connectionString: String): String {
return StatusBackendClient.executeStatusGoRequestWithResult(
endpoint = "ValidateConnectionString",
requestBody = connectionString,
statusgoFunction = { Statusgo.validateConnectionString(connectionString) }
)
}
fun handleStatusGoResponse(response: String, source: String) {
//TODO(frank) we should remove sensitive data from the response
if (response.startsWith("{\"error\":\"\"")) {
Log.d(TAG, "$source success: $response")
} else {
Log.e(TAG, "$source failed: $response")
}
return Statusgo.validateConnectionString(connectionString)
}
}
@@ -870,11 +870,7 @@ public class PushNotificationHelper {
public void start() {
Log.e(LOG_TAG, "Starting Foreground Service");
Intent serviceIntent = new Intent(context, ForegroundService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(serviceIntent);
} else {
context.startService(serviceIntent);
}
context.startService(serviceIntent);
this.registerBroadcastReceiver();
}
@@ -3,7 +3,6 @@
#import "React/RCTEventDispatcher.h"
#import "Statusgo.h"
#import "Utils.h"
#import "StatusBackendClient.h"
@implementation AccountManager
@@ -13,29 +12,23 @@ RCT_EXPORT_METHOD(createAccountAndLogin:(NSString *)request) {
#if DEBUG
NSLog(@"createAccountAndLogin() method called");
#endif
[StatusBackendClient executeStatusGoRequest:@"CreateAccountAndLogin"
body:request
statusgoFunction:^NSString *{
return StatusgoCreateAccountAndLogin(request);
}];
StatusgoCreateAccountAndLogin(request);
}
RCT_EXPORT_METHOD(restoreAccountAndLogin:(NSString *)request) {
#if DEBUG
NSLog(@"restoreAccountAndLogin() method called");
#endif
[StatusBackendClient executeStatusGoRequest:@"RestoreAccountAndLogin"
body:request
statusgoFunction:^NSString *{
return StatusgoRestoreAccountAndLogin(request);
}];
StatusgoRestoreAccountAndLogin(request);
}
-(NSString *) prepareDirAndUpdateConfig:(NSString *)config
withKeyUID:(NSString *)keyUID {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error = nil;
NSURL *rootUrl =[Utils getRootUrl];
NSURL *rootUrl =[[fileManager
URLsForDirectory:NSLibraryDirectory inDomains:NSUserDomainMask]
lastObject];
NSURL *absTestnetFolderName = [rootUrl URLByAppendingPathComponent:@"ethereum/testnet"];
if (![fileManager fileExistsAtPath:absTestnetFolderName.path])
@@ -109,24 +102,8 @@ RCT_EXPORT_METHOD(deleteMultiaccount:(NSString *)keyUID
NSLog(@"DeleteMultiaccount() method called");
#endif
NSURL *multiaccountKeystoreDir = [Utils getKeyStoreDirForKeyUID:keyUID];
NSDictionary *params = @{
@"keyUID": keyUID,
@"keyStoreDir": multiaccountKeystoreDir.path
};
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:0 error:&error];
if (error) {
NSLog(@"Error creating JSON: %@", error);
return;
}
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
[StatusBackendClient executeStatusGoRequestWithCallback:@"DeleteMultiaccountV2"
body:jsonString
statusgoFunction:^NSString *{
return StatusgoDeleteMultiaccountV2(jsonString);
}
callback:callback];
NSString *result = StatusgoDeleteMultiaccount(keyUID, multiaccountKeystoreDir.path);
callback(@[result]);
}
RCT_EXPORT_METHOD(prepareDirAndUpdateConfig:(NSString *)keyUID
@@ -186,69 +163,36 @@ RCT_EXPORT_METHOD(loginWithConfig:(NSString *)accountData
RCT_EXPORT_METHOD(loginAccount:(NSString *)request) {
#if DEBUG
NSLog(@"loginAccount() method called");
NSLog(@"LoginAccount() method called");
#endif
[StatusBackendClient executeStatusGoRequest:@"LoginAccount"
body:request
statusgoFunction:^NSString *{
return StatusgoLoginAccount(request);
}];
NSString *result = StatusgoLoginAccount(request);
NSLog(@"%@", result);
}
RCT_EXPORT_METHOD(verify:(NSString *)address
password:(NSString *)password
callback:(RCTResponseSenderBlock)callback) {
#if DEBUG
NSLog(@"VerifyAccountPasswordV2() method called");
NSLog(@"VerifyAccountPassword() method called");
#endif
NSURL *rootUrl = [Utils getRootUrl];
NSString *keystorePath = [rootUrl.path stringByAppendingPathComponent:@"keystore"];
NSDictionary *params = @{
@"keyStoreDir": keystorePath,
@"address": address,
@"password": password
};
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:0 error:&error];
if (error) {
NSLog(@"Error creating JSON: %@", error);
return;
}
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
[StatusBackendClient executeStatusGoRequestWithCallback:@"VerifyAccountPasswordV2"
body:jsonString
statusgoFunction:^NSString *{
return StatusgoVerifyAccountPasswordV2(jsonString);
}
callback:callback];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *rootUrl =[[fileManager
URLsForDirectory:NSLibraryDirectory inDomains:NSUserDomainMask]
lastObject];
NSURL *absKeystoreUrl = [rootUrl URLByAppendingPathComponent:@"keystore"];
NSString *result = StatusgoVerifyAccountPassword(absKeystoreUrl.path, address, password);
callback(@[result]);
}
RCT_EXPORT_METHOD(verifyDatabasePassword:(NSString *)keyUID
password:(NSString *)password
callback:(RCTResponseSenderBlock)callback) {
#if DEBUG
NSLog(@"VerifyDatabasePasswordV2() method called");
NSLog(@"VerifyDatabasePassword() method called");
#endif
NSDictionary *params = @{
@"keyUID": keyUID,
@"password": password
};
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:0 error:&error];
if (error) {
NSLog(@"Error creating JSON: %@", error);
return;
}
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
[StatusBackendClient executeStatusGoRequestWithCallback:@"VerifyDatabasePasswordV2"
body:jsonString
statusgoFunction:^NSString *{
return StatusgoVerifyDatabasePasswordV2(jsonString);
}
callback:callback];
NSString *result = StatusgoVerifyDatabasePassword(keyUID, password);
callback(@[result]);
}
RCT_EXPORT_METHOD(initializeApplication:(NSString *)request
@@ -256,173 +200,62 @@ RCT_EXPORT_METHOD(initializeApplication:(NSString *)request
#if DEBUG
NSLog(@"initializeApplication() method called");
#endif
[StatusBackendClient executeStatusGoRequestWithCallback:@"InitializeApplication"
body:request
statusgoFunction:^NSString *{
return StatusgoInitializeApplication(request);
}
callback:callback];
NSString *result = StatusgoInitializeApplication(request);
callback(@[result]);
}
RCT_EXPORT_METHOD(acceptTerms:(RCTResponseSenderBlock)callback) {
#if DEBUG
NSLog(@"acceptTerms() method called");
#endif
[StatusBackendClient executeStatusGoRequestWithCallback:@"AcceptTerms"
body:@""
statusgoFunction:^NSString *{
return StatusgoAcceptTerms();
}
callback:callback];
NSString *result = StatusgoAcceptTerms();
callback(@[result]);
}
RCT_EXPORT_METHOD(openAccounts:(RCTResponseSenderBlock)callback) {
#if DEBUG
NSLog(@"OpenAccounts() method called");
#endif
NSURL *rootUrl =[Utils getRootUrl];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *rootUrl =[[fileManager
URLsForDirectory:NSLibraryDirectory inDomains:NSUserDomainMask]
lastObject];
NSString *result = StatusgoOpenAccounts(rootUrl.path);
callback(@[result]);
}
RCT_EXPORT_METHOD(logout) {
#if DEBUG
NSLog(@"Logout() method called");
NSLog(@"Logout() method called");
#endif
[StatusBackendClient executeStatusGoRequest:@"Logout"
body:@""
statusgoFunction:^NSString *{
return StatusgoLogout();
}];
}
NSString *result = StatusgoLogout();
RCT_EXPORT_METHOD(multiAccountStoreAccount:(NSString *)json
callback:(RCTResponseSenderBlock)callback) {
#if DEBUG
NSLog(@"MultiAccountStoreAccount() method called");
#endif
[StatusBackendClient executeStatusGoRequestWithCallback:@"MultiAccountStoreAccount"
body:json
statusgoFunction:^NSString *{
return StatusgoMultiAccountStoreAccount(json);
}
callback:callback];
}
RCT_EXPORT_METHOD(multiAccountLoadAccount:(NSString *)json
callback:(RCTResponseSenderBlock)callback) {
#if DEBUG
NSLog(@"MultiAccountLoadAccount() method called");
#endif
[StatusBackendClient executeStatusGoRequestWithCallback:@"MultiAccountLoadAccount"
body:json
statusgoFunction:^NSString *{
return StatusgoMultiAccountLoadAccount(json);
}
callback:callback];
}
RCT_EXPORT_METHOD(multiAccountDeriveAddresses:(NSString *)json
callback:(RCTResponseSenderBlock)callback) {
#if DEBUG
NSLog(@"multiAccountDeriveAddresses() method called");
#endif
[StatusBackendClient executeStatusGoRequestWithCallback:@"MultiAccountDeriveAddresses"
body:json
statusgoFunction:^NSString *{
return StatusgoMultiAccountDeriveAddresses(json);
}
callback:callback];
}
RCT_EXPORT_METHOD(multiAccountGenerateAndDeriveAddresses:(NSString *)json
callback:(RCTResponseSenderBlock)callback) {
#if DEBUG
NSLog(@"MultiAccountGenerateAndDeriveAddresses() method called");
#endif
[StatusBackendClient executeStatusGoRequestWithCallback:@"MultiAccountGenerateAndDeriveAddresses"
body:json
statusgoFunction:^NSString *{
return StatusgoMultiAccountGenerateAndDeriveAddresses(json);
}
callback:callback];
}
RCT_EXPORT_METHOD(multiAccountStoreDerived:(NSString *)json
callback:(RCTResponseSenderBlock)callback) {
#if DEBUG
NSLog(@"MultiAccountStoreDerived() method called");
#endif
[StatusBackendClient executeStatusGoRequestWithCallback:@"MultiAccountStoreDerivedAccounts"
body:json
statusgoFunction:^NSString *{
return StatusgoMultiAccountStoreDerivedAccounts(json);
}
callback:callback];
}
RCT_EXPORT_METHOD(multiAccountImportMnemonic:(NSString *)json
callback:(RCTResponseSenderBlock)callback) {
#if DEBUG
NSLog(@"MultiAccountImportMnemonic() method called");
#endif
[StatusBackendClient executeStatusGoRequestWithCallback:@"MultiAccountImportMnemonic"
body:json
statusgoFunction:^NSString *{
return StatusgoMultiAccountImportMnemonic(json);
}
callback:callback];
}
RCT_EXPORT_METHOD(multiAccountImportPrivateKey:(NSString *)json
callback:(RCTResponseSenderBlock)callback) {
#if DEBUG
NSLog(@"MultiAccountImportPrivateKey() method called");
#endif
[StatusBackendClient executeStatusGoRequestWithCallback:@"MultiAccountImportPrivateKey"
body:json
statusgoFunction:^NSString *{
return StatusgoMultiAccountImportPrivateKey(json);
}
callback:callback];
NSLog(@"%@", result);
}
RCT_EXPORT_METHOD(getRandomMnemonic:(RCTResponseSenderBlock)callback) {
#if DEBUG
NSLog(@"GetRandomMnemonic() method called");
#endif
[StatusBackendClient executeStatusGoRequestWithCallback:@"GetRandomMnemonic"
body:@""
statusgoFunction:^NSString *{
return StatusgoGetRandomMnemonic();
}
callback:callback];
NSString *result = StatusgoGetRandomMnemonic();
callback(@[result]);
}
RCT_EXPORT_METHOD(createAccountFromMnemonicAndDeriveAccountsForPaths:(NSString *)mnemonic
callback:(RCTResponseSenderBlock)callback) {
RCT_EXPORT_METHOD(createAccountFromMnemonicAndDeriveAccountsForPaths:(NSString *)mnemonic callback:(RCTResponseSenderBlock)callback) {
#if DEBUG
NSLog(@"createAccountFromMnemonicAndDeriveAccountsForPaths() method called");
#endif
[StatusBackendClient executeStatusGoRequestWithCallback:@"CreateAccountFromMnemonicAndDeriveAccountsForPaths"
body:mnemonic
statusgoFunction:^NSString *{
return StatusgoCreateAccountFromMnemonicAndDeriveAccountsForPaths(mnemonic);
}
callback:callback];
NSString *result = StatusgoCreateAccountFromMnemonicAndDeriveAccountsForPaths(mnemonic);
callback(@[result]);
}
RCT_EXPORT_METHOD(createAccountFromPrivateKey:(NSString *)json
callback:(RCTResponseSenderBlock)callback) {
RCT_EXPORT_METHOD(createAccountFromPrivateKey:(NSString *)configJSON callback:(RCTResponseSenderBlock)callback) {
#if DEBUG
NSLog(@"createAccountFromPrivateKey() method called");
#endif
[StatusBackendClient executeStatusGoRequestWithCallback:@"CreateAccountFromPrivateKey"
body:json
statusgoFunction:^NSString *{
return StatusgoCreateAccountFromPrivateKey(json);
}
callback:callback];
NSString *result = StatusgoCreateAccountFromPrivateKey(configJSON);
callback(@[result]);
}
@end
@@ -3,7 +3,7 @@
#import "React/RCTEventDispatcher.h"
#import "Statusgo.h"
#import "Utils.h"
#import "StatusBackendClient.h"
@implementation DatabaseManager
RCT_EXPORT_MODULE();
@@ -16,31 +16,8 @@ RCT_EXPORT_METHOD(exportUnencryptedDatabase:(NSString *)accountData
#endif
NSString *filePath = [Utils getExportDbFilePath];
NSDictionary *params = @{
@"account": [NSJSONSerialization JSONObjectWithData:[accountData dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil],
@"password": password,
@"databasePath": filePath
};
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:0 error:&error];
if (error) {
NSLog(@"Error creating JSON: %@", [error localizedDescription]);
callback(@[filePath]);
return;
}
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
[StatusBackendClient executeStatusGoRequestWithCallback:@"ExportUnencryptedDatabaseV2"
body:jsonString
statusgoFunction:^NSString *{
return StatusgoExportUnencryptedDatabaseV2(jsonString);
}
callback:nil];
StatusgoExportUnencryptedDatabase(accountData, password, filePath);
callback(@[filePath]);
}
@@ -49,31 +26,7 @@ RCT_EXPORT_METHOD(importUnencryptedDatabase:(NSString *)accountData
#if DEBUG
NSLog(@"importUnencryptedDatabase() method called");
#endif
NSString *filePath = [Utils getExportDbFilePath];
[Utils migrateKeystore:accountData password:password];
NSDictionary *params = @{
@"account": [NSJSONSerialization JSONObjectWithData:[accountData dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil],
@"password": password,
@"databasePath": filePath
};
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:0 error:&error];
if (error) {
NSLog(@"Error creating JSON: %@", [error localizedDescription]);
return;
}
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
[StatusBackendClient executeStatusGoRequest:@"ImportUnencryptedDatabaseV2"
body:jsonString
statusgoFunction:^NSString *{
return StatusgoImportUnencryptedDatabaseV2(jsonString);
}];
"";
}
@@ -3,7 +3,6 @@
#import "React/RCTEventDispatcher.h"
#import "Statusgo.h"
#import "Utils.h"
#import "StatusBackendClient.h"
@implementation EncryptionUtils
@@ -16,14 +15,21 @@ RCT_EXPORT_METHOD(initKeystore:(NSString *)keyUID
#if DEBUG
NSLog(@"initKeystore() method called");
#endif
NSURL *multiaccountKeystoreDir = [Utils getKeyStoreDirForKeyUID:keyUID];
[StatusBackendClient executeStatusGoRequestWithCallback:@"InitKeystore"
body:multiaccountKeystoreDir.path
statusgoFunction:^NSString *{
return StatusgoInitKeystore(multiaccountKeystoreDir.path);
}
callback:callback];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *rootUrl =[[fileManager
URLsForDirectory:NSLibraryDirectory inDomains:NSUserDomainMask]
lastObject];
NSURL *commonKeystoreDir = [rootUrl URLByAppendingPathComponent:@"keystore"];
NSURL *keystoreDir = [commonKeystoreDir URLByAppendingPathComponent:keyUID];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
^(void)
{
NSString *res = StatusgoInitKeystore(keystoreDir.path);
NSLog(@"InitKeyStore result %@", res);
callback(@[]);
});
}
RCT_EXPORT_METHOD(reEncryptDbAndKeystore:(NSString *)keyUID
@@ -33,26 +39,9 @@ RCT_EXPORT_METHOD(reEncryptDbAndKeystore:(NSString *)keyUID
#if DEBUG
NSLog(@"reEncryptDbAndKeystore() method called");
#endif
// Construct params into JSON string
NSDictionary *params = @{
@"keyUID": keyUID,
@"oldPassword": currentPassword,
@"newPassword": newPassword
};
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:0 error:&error];
if (error) {
NSLog(@"Error creating JSON: %@", error);
return;
}
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
[StatusBackendClient executeStatusGoRequestWithCallback:@"ChangeDatabasePasswordV2"
body:jsonString
statusgoFunction:^NSString *{
return StatusgoChangeDatabasePasswordV2(jsonString);
}
callback:callback];
// changes password and re-encrypts keystore
NSString *result = StatusgoChangeDatabasePassword(keyUID, currentPassword, newPassword);
callback(@[result]);
}
RCT_EXPORT_METHOD(convertToKeycardAccount:(NSString *)keyUID
@@ -66,141 +55,47 @@ RCT_EXPORT_METHOD(convertToKeycardAccount:(NSString *)keyUID
NSLog(@"convertToKeycardAccount() method called");
#endif
NSURL *multiaccountKeystoreDir = [Utils getKeyStoreDirForKeyUID:keyUID];
// First initialize keystore
[StatusBackendClient executeStatusGoRequest:@"InitKeystore"
body:multiaccountKeystoreDir.path
statusgoFunction:^NSString *{
return StatusgoInitKeystore(multiaccountKeystoreDir.path);
}];
// Prepare parameters for conversion
NSDictionary *params = @{
@"keyUID": keyUID,
@"account": [NSJSONSerialization JSONObjectWithData:[accountData dataUsingEncoding:NSUTF8StringEncoding]
options:0
error:nil],
@"settings": [NSJSONSerialization JSONObjectWithData:[settings dataUsingEncoding:NSUTF8StringEncoding]
options:0
error:nil],
@"keycardUID": keycardUID,
@"oldPassword": currentPassword,
@"newPassword": newPassword
};
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:0 error:&error];
if (error) {
NSLog(@"Error creating JSON: %@", [error localizedDescription]);
return;
}
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
[StatusBackendClient executeStatusGoRequestWithCallback:@"ConvertToKeycardAccountV2"
body:jsonString
statusgoFunction:^NSString *{
return StatusgoConvertToKeycardAccountV2(jsonString);
}
callback:callback];
StatusgoInitKeystore(multiaccountKeystoreDir.path);
NSString *result = StatusgoConvertToKeycardAccount(accountData, settings, keycardUID, currentPassword, newPassword);
callback(@[result]);
}
RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(encodeTransfer:(NSString *)to
value:(NSString *)value) {
NSDictionary *params = @{
@"to": to,
@"value": value
};
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:0 error:&error];
if (error) {
NSLog(@"Error creating JSON: %@", [error localizedDescription]);
return nil;
}
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
return [StatusBackendClient executeStatusGoRequestWithResult:@"EncodeTransferV2"
body:jsonString
statusgoFunction:^NSString *{
return StatusgoEncodeTransferV2(jsonString);
}];
value:(NSString *)value) {
return StatusgoEncodeTransfer(to,value);
}
RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(encodeFunctionCall:(NSString *)method
paramsJSON:(NSString *)paramsJSON) {
NSDictionary *params = @{
@"method": method,
@"paramsJSON": paramsJSON
};
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:0 error:&error];
if (error) {
NSLog(@"Error creating JSON: %@", [error localizedDescription]);
return nil;
}
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
return [StatusBackendClient executeStatusGoRequestWithResult:@"EncodeFunctionCallV2"
body:jsonString
statusgoFunction:^NSString *{
return StatusgoEncodeFunctionCallV2(jsonString);
}];
paramsJSON:(NSString *)paramsJSON) {
return StatusgoEncodeFunctionCall(method,paramsJSON);
}
RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(decodeParameters:(NSString *)decodeParamJSON) {
return [StatusBackendClient executeStatusGoRequestWithResult:@"DecodeParameters"
body:decodeParamJSON
statusgoFunction:^NSString *{
return StatusgoDecodeParameters(decodeParamJSON);
}];
return StatusgoDecodeParameters(decodeParamJSON);
}
RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(hexToNumber:(NSString *)hex) {
return [StatusBackendClient executeStatusGoRequestWithResult:@"HexToNumber"
body:hex
statusgoFunction:^NSString *{
return StatusgoHexToNumber(hex);
}];
return StatusgoHexToNumber(hex);
}
RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(numberToHex:(NSString *)numString) {
return [StatusBackendClient executeStatusGoRequestWithResult:@"NumberToHex"
body:numString
statusgoFunction:^NSString *{
return StatusgoNumberToHex(numString);
}];
return StatusgoNumberToHex(numString);
}
RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(sha3:(NSString *)str) {
return [StatusBackendClient executeStatusGoRequestWithResult:@"Sha3"
body:str
statusgoFunction:^NSString *{
return StatusgoSha3(str);
}];
return StatusgoSha3(str);
}
RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(utf8ToHex:(NSString *)str) {
return [StatusBackendClient executeStatusGoRequestWithResult:@"Utf8ToHex"
body:str
statusgoFunction:^NSString *{
return StatusgoUtf8ToHex(str);
}];
return StatusgoUtf8ToHex(str);
}
RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(hexToUtf8:(NSString *)str) {
return [StatusBackendClient executeStatusGoRequestWithResult:@"HexToUtf8"
body:str
statusgoFunction:^NSString *{
return StatusgoHexToUtf8(str);
}];
return StatusgoHexToUtf8(str);
}
RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(serializeLegacyKey:(NSString *)str) {
return [StatusBackendClient executeStatusGoRequestWithResult:@"SerializeLegacyKey"
body:str
statusgoFunction:^NSString *{
return StatusgoSerializeLegacyKey(str);
}];
return StatusgoSerializeLegacyKey(str);
}
RCT_EXPORT_METHOD(setBlankPreviewFlag:(BOOL *)newValue)
@@ -215,14 +110,10 @@ RCT_EXPORT_METHOD(setBlankPreviewFlag:(BOOL *)newValue)
RCT_EXPORT_METHOD(hashTransaction:(NSString *)txArgsJSON
callback:(RCTResponseSenderBlock)callback) {
#if DEBUG
NSLog(@"hashTransaction() method called");
NSLog(@"HashTransaction() method called");
#endif
[StatusBackendClient executeStatusGoRequestWithCallback:@"HashTransaction"
body:txArgsJSON
statusgoFunction:^NSString *{
return StatusgoHashTransaction(txArgsJSON);
}
callback:callback];
NSString *result = StatusgoHashTransaction(txArgsJSON);
callback(@[result]);
}
RCT_EXPORT_METHOD(hashMessage:(NSString *)message
@@ -230,12 +121,8 @@ RCT_EXPORT_METHOD(hashMessage:(NSString *)message
#if DEBUG
NSLog(@"hashMessage() method called");
#endif
[StatusBackendClient executeStatusGoRequestWithCallback:@"HashMessage"
body:message
statusgoFunction:^NSString *{
return StatusgoHashMessage(message);
}
callback:callback];
NSString *result = StatusgoHashMessage(message);
callback(@[result]);
}
RCT_EXPORT_METHOD(localPairingPreflightOutboundCheck:(RCTResponseSenderBlock)callback) {
@@ -249,34 +136,14 @@ RCT_EXPORT_METHOD(localPairingPreflightOutboundCheck:(RCTResponseSenderBlock)cal
RCT_EXPORT_METHOD(multiformatDeserializePublicKey:(NSString *)multiCodecKey
base58btc:(NSString *)base58btc
callback:(RCTResponseSenderBlock)callback) {
NSDictionary *params = @{
@"key": multiCodecKey,
@"outBase": base58btc
};
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:0 error:&error];
if (error) {
NSLog(@"Error creating JSON: %@", error);
return;
}
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
[StatusBackendClient executeStatusGoRequestWithCallback:@"MultiformatDeserializePublicKeyV2"
body:jsonString
statusgoFunction:^NSString *{
return StatusgoMultiformatDeserializePublicKeyV2(jsonString);
}
callback:callback];
NSString *result = StatusgoMultiformatDeserializePublicKey(multiCodecKey,base58btc);
callback(@[result]);
}
RCT_EXPORT_METHOD(deserializeAndCompressKey:(NSString *)desktopKey
callback:(RCTResponseSenderBlock)callback) {
[StatusBackendClient executeStatusGoRequestWithCallback:@"DeserializeAndCompressKey"
body:desktopKey
statusgoFunction:^NSString *{
return StatusgoDeserializeAndCompressKey(desktopKey);
}
callback:callback];
NSString *result = StatusgoDeserializeAndCompressKey(desktopKey);
callback(@[result]);
}
RCT_EXPORT_METHOD(hashTypedData:(NSString *)data
@@ -299,14 +166,13 @@ RCT_EXPORT_METHOD(hashTypedDataV4:(NSString *)data
#pragma mark - SignMessage
RCT_EXPORT_METHOD(signMessage:(NSString *)rpcParams
callback:(RCTResponseSenderBlock)callback) {
[StatusBackendClient executeStatusGoRequestWithCallback:@"SignMessage"
body:rpcParams
statusgoFunction:^NSString *{
return StatusgoSignMessage(rpcParams);
}
callback:callback];
RCT_EXPORT_METHOD(signMessage:(NSString *)message
callback:(RCTResponseSenderBlock)callback) {
#if DEBUG
NSLog(@"SignMessage() method called");
#endif
NSString *result = StatusgoSignMessage(message);
callback(@[result]);
}
#pragma mark - SignTypedData
@@ -4,7 +4,6 @@
#import "Statusgo.h"
#import "Utils.h"
#import "SSZipArchive.h"
#import "StatusBackendClient.h"
@implementation LogManager
@@ -15,12 +14,15 @@ RCT_EXPORT_MODULE();
RCT_EXPORT_METHOD(sendLogs:(NSString *)dbJson
jsLogs:(NSString *)jsLogs
callback:(RCTResponseSenderBlock)callback) {
// TODO: Implement SendLogs for iOS
#if DEBUG
NSLog(@"SendLogs() method called");
NSLog(@"SendLogs() method called, not implemented");
#endif
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error = nil;
NSURL *rootUrl =[Utils getRootUrl];
NSURL *rootUrl =[[fileManager
URLsForDirectory:NSLibraryDirectory inDomains:NSUserDomainMask]
lastObject];
NSURL *zipFile = [rootUrl URLByAppendingPathComponent:@"logs.zip"];
[fileManager removeItemAtPath:zipFile.path error:nil];
@@ -32,6 +34,25 @@ RCT_EXPORT_METHOD(sendLogs:(NSString *)dbJson
NSURL *dbFile = [logsFolderName URLByAppendingPathComponent:@"db.json"];
NSURL *jsLogsFile = [logsFolderName URLByAppendingPathComponent:@"Status.log"];
#if DEBUG
NSString *networkDirPath = @"ethereum/mainnet_rpc_dev";
#else
NSString *networkDirPath = @"ethereum/mainnet_rpc";
#endif
#if DEBUG
NSString *goerliNetworkDirPath = @"ethereum/goerli_rpc_dev";
#else
NSString *goerliNetworkDirPath = @"ethereum/goerli_rpc";
#endif
NSURL *networkDir = [rootUrl URLByAppendingPathComponent:networkDirPath];
NSURL *originalGethLogsFile = [networkDir URLByAppendingPathComponent:@"geth.log"];
NSURL *gethLogsFile = [logsFolderName URLByAppendingPathComponent:@"mainnet_geth.log"];
NSURL *goerliNetworkDir = [rootUrl URLByAppendingPathComponent:goerliNetworkDirPath];
NSURL *goerliGethLogsFile = [goerliNetworkDir URLByAppendingPathComponent:@"geth.log"];
NSURL *goerliLogsFile = [logsFolderName URLByAppendingPathComponent:@"goerli_geth.log"];
NSURL *mainGethLogsFile = [rootUrl URLByAppendingPathComponent:@"geth.log"];
NSURL *mainLogsFile = [logsFolderName URLByAppendingPathComponent:@"geth.log"];
@@ -41,6 +62,10 @@ RCT_EXPORT_METHOD(sendLogs:(NSString *)dbJson
[dbJson writeToFile:dbFile.path atomically:YES encoding:NSUTF8StringEncoding error:nil];
[jsLogs writeToFile:jsLogsFile.path atomically:YES encoding:NSUTF8StringEncoding error:nil];
//NSString* gethLogs = StatusgoExportNodeLogs();
//[gethLogs writeToFile:gethLogsFile.path atomically:YES encoding:NSUTF8StringEncoding error:nil];
[fileManager copyItemAtPath:originalGethLogsFile.path toPath:gethLogsFile.path error:nil];
[fileManager copyItemAtPath:goerliGethLogsFile.path toPath:goerliLogsFile.path error:nil];
[fileManager copyItemAtPath:mainGethLogsFile.path toPath:mainLogsFile.path error:nil];
if ([fileManager fileExistsAtPath:requestsLogFile.path]) {
@@ -63,36 +88,37 @@ RCT_EXPORT_METHOD(initLogging:(BOOL)enabled
NSString *logFilePath = [logDirectory stringByAppendingPathComponent:@"geth.log"];
NSString *logRequestFilePath = [logDirectory stringByAppendingPathComponent:@"requests.log"];
NSDictionary *config = @{
@"Enabled": @(enabled),
@"MobileSystem": @(mobileSystem),
@"Level": logLevel,
@"File": logFilePath,
@"LogRequestGo": @(logRequestGo),
@"LogRequestFile": logRequestFilePath
};
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:config options:0 error:&error];
NSMutableDictionary *jsonConfig = [NSMutableDictionary dictionary];
jsonConfig[@"Enabled"] = @(enabled);
jsonConfig[@"MobileSystem"] = @(mobileSystem);
jsonConfig[@"Level"] = logLevel;
jsonConfig[@"File"] = logFilePath;
jsonConfig[@"LogRequestGo"] = @(logRequestGo);
jsonConfig[@"LogRequestFile"] = logRequestFilePath;
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonConfig options:0 error:&error];
if (error) {
NSLog(@"Error creating JSON: %@", [error localizedDescription]);
// Handle JSON serialization error
callback(@[error.localizedDescription]);
return;
}
NSString *configJson = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
[StatusBackendClient executeStatusGoRequestWithCallback:@"InitLogging"
body:configJson
statusgoFunction:^NSString *{
return StatusgoInitLogging(configJson);
}
callback:callback];
NSString *config = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
// Call your native logging initialization method here
NSString *initResult = StatusgoInitLogging(config);
callback(@[initResult]);
}
RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(logFileDirectory) {
NSURL *rootUrl = [Utils getRootUrl];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *rootUrl =[[fileManager
URLsForDirectory:NSLibraryDirectory inDomains:NSUserDomainMask]
lastObject];
return rootUrl.path;
}
@end
@@ -3,18 +3,14 @@
#import "React/RCTEventDispatcher.h"
#import "Statusgo.h"
#import "Utils.h"
#import "StatusBackendClient.h"
@implementation NetworkManager
RCT_EXPORT_MODULE();
RCT_EXPORT_METHOD(startSearchForLocalPairingPeers:(RCTResponseSenderBlock)callback) {
[StatusBackendClient executeStatusGoRequestWithCallback:@"StartSearchForLocalPairingPeers"
body:@""
statusgoFunction:^NSString *{
return StatusgoStartSearchForLocalPairingPeers();
}
callback:callback];
NSString *result = StatusgoStartSearchForLocalPairingPeers();
callback(@[result]);
}
RCT_EXPORT_METHOD(getConnectionStringForBootstrappingAnotherDevice:(NSString *)configJSON
@@ -23,11 +19,6 @@ RCT_EXPORT_METHOD(getConnectionStringForBootstrappingAnotherDevice:(NSString *)c
NSData *configData = [configJSON dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSMutableDictionary *configDict = [NSJSONSerialization JSONObjectWithData:configData options:NSJSONReadingMutableContainers error:&error];
if (error) {
NSLog(@"Error parsing JSON: %@", error);
return;
}
NSMutableDictionary *senderConfig = configDict[@"senderConfig"];
NSString *keyUID = senderConfig[@"keyUID"];
NSURL *multiaccountKeystoreDir = [Utils getKeyStoreDirForKeyUID:keyUID];
@@ -36,43 +27,16 @@ RCT_EXPORT_METHOD(getConnectionStringForBootstrappingAnotherDevice:(NSString *)c
[senderConfig setValue:keystoreDir forKey:@"keystorePath"];
NSString *modifiedConfigJSON = [Utils jsonStringWithPrettyPrint:NO fromDictionary:configDict];
[StatusBackendClient executeStatusGoRequestWithCallback:@"GetConnectionStringForBootstrappingAnotherDevice"
body:modifiedConfigJSON
statusgoFunction:^NSString *{
return StatusgoGetConnectionStringForBootstrappingAnotherDevice(modifiedConfigJSON);
}
callback:callback];
NSString *result = StatusgoGetConnectionStringForBootstrappingAnotherDevice(modifiedConfigJSON);
callback(@[result]);
}
RCT_EXPORT_METHOD(inputConnectionStringForBootstrapping:(NSString *)cs
configJSON:(NSString *)configJSON
callback:(RCTResponseSenderBlock)callback) {
NSData *configData = [configJSON dataUsingEncoding:NSUTF8StringEncoding];
NSError *jsonError;
NSDictionary *configDict = [NSJSONSerialization JSONObjectWithData:configData options:0 error:&jsonError];
if (jsonError) {
NSLog(@"Error parsing JSON: %@", jsonError);
return;
}
NSDictionary *params = @{
@"connectionString": cs,
@"receiverClientConfig": configDict
};
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:0 error:&error];
if (error) {
NSLog(@"Error creating JSON: %@", error);
return;
}
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
[StatusBackendClient executeStatusGoRequestWithCallback:@"InputConnectionStringForBootstrappingV2"
body:jsonString
statusgoFunction:^NSString *{
return StatusgoInputConnectionStringForBootstrappingV2(jsonString);
}
callback:callback];
NSString *result = StatusgoInputConnectionStringForBootstrapping(cs, configJSON);
callback(@[result]);
}
RCT_EXPORT_METHOD(sendTransactionWithSignature:(NSString *)txArgsJSON
@@ -81,12 +45,8 @@ RCT_EXPORT_METHOD(sendTransactionWithSignature:(NSString *)txArgsJSON
#if DEBUG
NSLog(@"sendTransactionWithSignature() method called");
#endif
[StatusBackendClient executeStatusGoRequestWithCallback:@"SendTransactionWithSignature"
body:txArgsJSON
statusgoFunction:^NSString *{
return StatusgoSendTransactionWithSignature(txArgsJSON, signature);
}
callback:callback];
NSString *result = StatusgoSendTransactionWithSignature(txArgsJSON, signature);
callback(@[result]);
}
#pragma mark - SendTransaction
@@ -95,53 +55,30 @@ RCT_EXPORT_METHOD(sendTransaction:(NSString *)txArgsJSON
password:(NSString *)password
callback:(RCTResponseSenderBlock)callback) {
#if DEBUG
NSLog(@"SendTransactionV2() method called");
NSLog(@"SendTransaction() method called");
#endif
NSData *txArgsData = [txArgsJSON dataUsingEncoding:NSUTF8StringEncoding];
NSError *jsonError;
NSDictionary *txArgsDict = [NSJSONSerialization JSONObjectWithData:txArgsData options:0 error:&jsonError];
if (jsonError) {
NSLog(@"Error parsing JSON: %@", jsonError);
return;
}
NSDictionary *params = @{
@"txArgs": txArgsDict,
@"password": password
};
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:0 error:&error];
if (error) {
NSLog(@"Error creating JSON: %@", error);
return;
}
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
[StatusBackendClient executeStatusGoRequestWithCallback:@"SendTransactionV2"
body:jsonString
statusgoFunction:^NSString *{
return StatusgoSendTransactionV2(jsonString);
}
callback:callback];
NSString *result = StatusgoSendTransaction(txArgsJSON, password);
callback(@[result]);
}
RCT_EXPORT_METHOD(callRPC:(NSString *)payload
callback:(RCTResponseSenderBlock)callback) {
[StatusBackendClient executeStatusGoRequestWithCallback:@"CallRPC"
body:payload
statusgoFunction:^NSString *{
return StatusgoCallRPC(payload);
}
callback:callback];
dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSString *result = StatusgoCallRPC(payload);
dispatch_async(dispatch_get_main_queue(), ^{
callback(@[result]);
});
});
}
RCT_EXPORT_METHOD(callPrivateRPC:(NSString *)payload
callback:(RCTResponseSenderBlock)callback) {
[StatusBackendClient executeStatusGoRequestWithCallback:@"CallPrivateRPC"
body:payload
statusgoFunction:^NSString *{
return StatusgoCallPrivateRPC(payload);
}
callback:callback];
dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSString *result = StatusgoCallPrivateRPC(payload);
dispatch_async(dispatch_get_main_queue(), ^{
callback(@[result]);
});
});
}
#pragma mark - Recover
@@ -151,12 +88,8 @@ RCT_EXPORT_METHOD(recover:(NSString *)message
#if DEBUG
NSLog(@"Recover() method called");
#endif
[StatusBackendClient executeStatusGoRequestWithCallback:@"Recover"
body:message
statusgoFunction:^NSString *{
return StatusgoRecover(message);
}
callback:callback];
NSString *result = StatusgoRecover(message);
callback(@[result]);
}
RCT_EXPORT_METHOD(getConnectionStringForExportingKeypairsKeystores:(NSString *)configJSON
@@ -173,12 +106,8 @@ RCT_EXPORT_METHOD(getConnectionStringForExportingKeypairsKeystores:(NSString *)c
[senderConfig setValue:keystoreDir forKey:@"keystorePath"];
NSString *modifiedConfigJSON = [Utils jsonStringWithPrettyPrint:NO fromDictionary:configDict];
[StatusBackendClient executeStatusGoRequestWithCallback:@"GetConnectionStringForExportingKeypairsKeystores"
body:modifiedConfigJSON
statusgoFunction:^NSString *{
return StatusgoGetConnectionStringForExportingKeypairsKeystores(modifiedConfigJSON);
}
callback:callback];
NSString *result = StatusgoGetConnectionStringForExportingKeypairsKeystores(modifiedConfigJSON);
callback(@[result]);
}
RCT_EXPORT_METHOD(inputConnectionStringForImportingKeypairsKeystores:(NSString *)cs
@@ -190,25 +119,14 @@ RCT_EXPORT_METHOD(inputConnectionStringForImportingKeypairsKeystores:(NSString *
NSMutableDictionary *configDict = [NSJSONSerialization JSONObjectWithData:configData options:NSJSONReadingMutableContainers error:&error];
NSMutableDictionary *receiverConfig = configDict[@"receiverConfig"];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *rootUrl =[Utils getRootUrl];
NSURL *rootUrl =[[fileManager URLsForDirectory:NSLibraryDirectory inDomains:NSUserDomainMask] lastObject];
NSURL *multiaccountKeystoreDir = [rootUrl URLByAppendingPathComponent:@"keystore"];
NSString *keystoreDir = multiaccountKeystoreDir.path;
[receiverConfig setValue:keystoreDir forKey:@"keystorePath"];
NSString *modifiedConfigJSON = [Utils jsonStringWithPrettyPrint:NO fromDictionary:configDict];
NSDictionary *params = @{
@"connectionString": cs,
@"keystoreFilesReceiverClientConfig": modifiedConfigJSON
};
NSString *paramsJSON = [Utils jsonStringWithPrettyPrint:NO fromDictionary:params];
[StatusBackendClient executeStatusGoRequestWithCallback:@"InputConnectionStringForImportingKeypairsKeystoresV2"
body:paramsJSON
statusgoFunction:^NSString *{
return StatusgoInputConnectionStringForImportingKeypairsKeystoresV2(paramsJSON);
}
callback:callback];
NSString *result = StatusgoInputConnectionStringForImportingKeypairsKeystores(cs, modifiedConfigJSON);
callback(@[result]);
}
@end
@@ -5,6 +5,5 @@
#import "RCTLog.h"
@interface Status : NSObject <RCTBridgeModule, StatusgoSignalHandler>
+ (Status *)sharedInstance;
- (void)handleSignal:(NSString *)signal;
@end
@@ -2,22 +2,13 @@
#import "React/RCTBridge.h"
#import "React/RCTEventDispatcher.h"
#import "Statusgo.h"
#import "StatusBackendClient.h"
#import "Utils.h"
static RCTBridge *bridge;
@implementation Status
+ (Status *)sharedInstance {
static Status *sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[self alloc] init];
});
return sharedInstance;
}
- (instancetype)init {
self = [super init];
if (!self) {
@@ -82,17 +73,74 @@ RCT_EXPORT_METHOD(deleteImportedKey:(NSString *)keyUID
password:(NSString *)password
callback:(RCTResponseSenderBlock)callback) {
#if DEBUG
NSLog(@"DeleteImportedKeyV2() method called");
NSLog(@"DeleteImportedKey() method called");
#endif
NSURL *multiaccountKeystoreDir = [Utils getKeyStoreDirForKeyUID:keyUID];
NSString *jsonParams = [NSString stringWithFormat:@"{\"address\":\"%@\",\"password\":\"%@\",\"keyStoreDir\":\"%@\"}",
address, password, multiaccountKeystoreDir.path];
[StatusBackendClient executeStatusGoRequestWithCallback:@"DeleteImportedKeyV2"
body:jsonParams
statusgoFunction:^NSString *{
return StatusgoDeleteImportedKeyV2(jsonParams);
}
callback:callback];
NSString *result = StatusgoDeleteImportedKey(address, password, multiaccountKeystoreDir.path);
callback(@[result]);
}
RCT_EXPORT_METHOD(multiAccountGenerateAndDeriveAddresses:(NSString *)json
callback:(RCTResponseSenderBlock)callback) {
#if DEBUG
NSLog(@"MultiAccountGenerateAndDeriveAddresses() method called");
#endif
NSString *result = StatusgoMultiAccountGenerateAndDeriveAddresses(json);
callback(@[result]);
}
RCT_EXPORT_METHOD(multiAccountStoreAccount:(NSString *)json
callback:(RCTResponseSenderBlock)callback) {
#if DEBUG
NSLog(@"MultiAccountStoreAccount() method called");
#endif
NSString *result = StatusgoMultiAccountStoreAccount(json);
callback(@[result]);
}
RCT_EXPORT_METHOD(multiAccountLoadAccount:(NSString *)json
callback:(RCTResponseSenderBlock)callback) {
#if DEBUG
NSLog(@"MultiAccountLoadAccount() method called");
#endif
NSString *result = StatusgoMultiAccountLoadAccount(json);
callback(@[result]);
}
RCT_EXPORT_METHOD(multiAccountStoreDerived:(NSString *)json
callback:(RCTResponseSenderBlock)callback) {
#if DEBUG
NSLog(@"MultiAccountStoreDerived() method called");
#endif
NSString *result = StatusgoMultiAccountStoreDerivedAccounts(json);
callback(@[result]);
}
RCT_EXPORT_METHOD(multiAccountImportPrivateKey:(NSString *)json
callback:(RCTResponseSenderBlock)callback) {
#if DEBUG
NSLog(@"MultiAccountImportPrivateKey() method called");
#endif
NSString *result = StatusgoMultiAccountImportPrivateKey(json);
callback(@[result]);
}
RCT_EXPORT_METHOD(multiAccountImportMnemonic:(NSString *)json
callback:(RCTResponseSenderBlock)callback) {
#if DEBUG
NSLog(@"MultiAccountImportMnemonic() method called");
#endif
NSString *result = StatusgoMultiAccountImportMnemonic(json);
callback(@[result]);
}
RCT_EXPORT_METHOD(multiAccountDeriveAddresses:(NSString *)json
callback:(RCTResponseSenderBlock)callback) {
#if DEBUG
NSLog(@"MultiAccountDeriveAddresses() method called");
#endif
NSString *result = StatusgoMultiAccountDeriveAddresses(json);
callback(@[result]);
}
#pragma mark - GetNodeConfig
@@ -101,20 +149,12 @@ RCT_EXPORT_METHOD(getNodeConfig:(RCTResponseSenderBlock)callback) {
#if DEBUG
NSLog(@"GetNodeConfig() method called");
#endif
[StatusBackendClient executeStatusGoRequestWithCallback:@"GetNodeConfig"
body:@""
statusgoFunction:^NSString *{
return StatusgoGetNodeConfig();
}
callback:callback];
NSString *result = StatusgoGetNodeConfig();
callback(@[result]);
}
RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(fleets) {
return [StatusBackendClient executeStatusGoRequestWithResult:@"Fleets"
body:@""
statusgoFunction:^NSString *{
return StatusgoFleets();
}];
return StatusgoFleets();
}
RCT_EXPORT_METHOD(closeApplication) {
@@ -126,55 +166,14 @@ RCT_EXPORT_METHOD(connectionChange:(NSString *)type
#if DEBUG
NSLog(@"ConnectionChange() method called");
#endif
NSDictionary *params = @{
@"type": type,
@"expensive": @(isExpensive)
};
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params
options:0
error:&error];
if (error) {
NSLog(@"Error creating JSON: %@", error);
return;
}
if (jsonData) {
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
[StatusBackendClient executeStatusGoRequest:@"ConnectionChangeV2"
body:jsonString
statusgoFunction:^NSString *{
return StatusgoConnectionChangeV2(jsonString);
}];
} else {
NSLog(@"Failed to create JSON data");
}
StatusgoConnectionChange(type, isExpensive ? 1 : 0);
}
RCT_EXPORT_METHOD(appStateChange:(NSString *)state) {
RCT_EXPORT_METHOD(appStateChange:(NSString *)type) {
#if DEBUG
NSLog(@"AppStateChange() method called");
#endif
NSDictionary *params = @{@"state": state};
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params
options:0
error:&error];
if (error) {
NSLog(@"Error creating JSON: %@", error);
return;
}
if (jsonData) {
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
[StatusBackendClient executeStatusGoRequest:@"AppStateChangeV2"
body:jsonString
statusgoFunction:^NSString *{
return StatusgoAppStateChangeV2(jsonString);
}];
} else {
NSLog(@"Failed to create JSON data");
}
StatusgoAppStateChange(type);
}
RCT_EXPORT_METHOD(addCentralizedMetric:(NSString *)request
@@ -182,12 +181,8 @@ RCT_EXPORT_METHOD(addCentralizedMetric:(NSString *)request
#if DEBUG
NSLog(@"addCentralizedMetric() method called");
#endif
[StatusBackendClient executeStatusGoRequestWithCallback:@"AddCentralizedMetric"
body:request
statusgoFunction:^NSString *{
return StatusgoAddCentralizedMetric(request);
}
callback:callback];
NSString *result = StatusgoAddCentralizedMetric(request);
callback(@[result]);
}
RCT_EXPORT_METHOD(toggleCentralizedMetrics:(NSString *)request
@@ -195,23 +190,15 @@ RCT_EXPORT_METHOD(toggleCentralizedMetrics:(NSString *)request
#if DEBUG
NSLog(@"toggleCentralizedMetrics() method called");
#endif
[StatusBackendClient executeStatusGoRequestWithCallback:@"ToggleCentralizedMetrics"
body:request
statusgoFunction:^NSString *{
return StatusgoToggleCentralizedMetrics(request);
}
callback:callback];
NSString *result = StatusgoToggleCentralizedMetrics(request);
callback(@[result]);
}
RCT_EXPORT_METHOD(startLocalNotifications) {
#if DEBUG
NSLog(@"StartLocalNotifications() method called");
#endif
[StatusBackendClient executeStatusGoRequest:@"StartLocalNotifications"
body:@""
statusgoFunction:^NSString *{
return StatusgoStartLocalNotifications();
}];
StatusgoStartLocalNotifications();
}
#pragma mark - deviceinfo
@@ -1,31 +0,0 @@
#import <Foundation/Foundation.h>
#import <React/RCTBridgeModule.h>
@interface StatusBackendClient : NSObject <RCTBridgeModule>
@property (nonatomic) BOOL serverEnabled;
@property (nonatomic, strong) NSString *statusGoEndpoint;
@property (nonatomic, strong) NSString *signalEndpoint;
@property (nonatomic, strong) NSString *rootDataDir;
@property (nonatomic, strong) NSURLSessionWebSocketTask *webSocket;
// Add sharedInstance class method declaration
+ (instancetype)sharedInstance;
- (void)request:(NSString *)endpoint
body:(NSString *)body
callback:(void (^)(NSString *response, NSError *error))callback;
+ (void)executeStatusGoRequest:(NSString *)endpoint
body:(NSString *)body
statusgoFunction:(NSString * (^)(void))statusgoFunction;
+ (void)executeStatusGoRequestWithCallback:(NSString *)endpoint
body:(NSString *)body
statusgoFunction:(NSString * (^)(void))statusgoFunction
callback:(RCTResponseSenderBlock)callback;
+ (NSString *)executeStatusGoRequestWithResult:(NSString *)endpoint
body:(NSString *)body
statusgoFunction:(NSString * (^)(void))statusgoFunction;
@end
@@ -1,246 +0,0 @@
#import "StatusBackendClient.h"
#import "RCTStatus.h"
#import "Utils.h"
@implementation StatusBackendClient {
NSURLSessionWebSocketTask *_webSocket;
BOOL _serverEnabled;
NSString *_statusGoEndpoint;
NSString *_signalEndpoint;
NSString *_rootDataDir;
}
RCT_EXPORT_MODULE();
+ (BOOL)requiresMainQueueSetup {
return YES;
}
+ (instancetype)allocWithZone:(NSZone *)zone {
static StatusBackendClient *sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [super allocWithZone:zone];
});
return sharedInstance;
}
+ (instancetype)sharedInstance {
return [[self alloc] init];
}
- (instancetype)init {
static StatusBackendClient *sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [super init];
if (sharedInstance) {
sharedInstance->_serverEnabled = NO;
sharedInstance->_statusGoEndpoint = nil;
sharedInstance->_signalEndpoint = nil;
sharedInstance->_rootDataDir = nil;
sharedInstance->_webSocket = nil;
}
});
return sharedInstance;
}
- (id)copyWithZone:(NSZone *)zone {
return self;
}
- (BOOL)serverEnabled {
return _serverEnabled;
}
- (NSString *)statusGoEndpoint {
return _statusGoEndpoint;
}
- (NSString *)signalEndpoint {
return _signalEndpoint;
}
- (NSString *)rootDataDir {
return _rootDataDir;
}
- (void)connectWebSocket {
if (!self.serverEnabled || !self.signalEndpoint) {
return;
}
NSString *fullUrl = [NSString stringWithFormat:@"%@", self.signalEndpoint];
NSURL *url = [NSURL URLWithString:fullUrl];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
self.webSocket = [session webSocketTaskWithURL:url];
[self.webSocket resume];
[self receiveMessage];
}
- (void)receiveMessage {
__weak typeof(self) weakSelf = self;
[self.webSocket receiveMessageWithCompletionHandler:^(NSURLSessionWebSocketMessage *message, NSError *error) {
__strong typeof(weakSelf) strongSelf = weakSelf;
if (!strongSelf || !strongSelf.webSocket) {
return;
}
if (error) {
NSLog(@"WebSocket error: %@", error);
// Attempt to reconnect after error
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[strongSelf connectWebSocket];
});
return;
}
if (message) {
if (message.type == NSURLSessionWebSocketMessageTypeString && message.string) {
[[Status sharedInstance] handleSignal:message.string];
}
// Continue receiving messages only if the connection is still active
if (strongSelf.webSocket) {
[strongSelf receiveMessage];
}
}
}];
}
- (void)disconnectWebSocket {
if (self.webSocket) {
[self.webSocket cancel];
self.webSocket = nil;
}
}
- (void)request:(NSString *)endpoint
body:(NSString *)body
callback:(void (^)(NSString *response, NSError *error))callback {
NSString *fullUrlString = [NSString stringWithFormat:@"%@%@", self.statusGoEndpoint, endpoint];
NSURL *url = [NSURL URLWithString:fullUrlString];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
request.HTTPMethod = @"POST";
[request setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
NSData *bodyData = [body dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody = bodyData;
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(@"request error: %@", error);
callback(nil, error);
return;
}
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
callback(responseString, nil);
}];
[task resume];
}
RCT_EXPORT_METHOD(configStatusBackendServer:(BOOL)serverEnabled
statusGoEndpoint:(NSString *)statusGoEndpoint
signalEndpoint:(NSString *)signalEndpoint
rootDataDir:(NSString *)rootDataDir) {
[self configureWithEnabled:serverEnabled
statusGoEndpoint:statusGoEndpoint
signalEndpoint:signalEndpoint
rootDataDir:rootDataDir];
}
- (void)configureWithEnabled:(BOOL)serverEnabled
statusGoEndpoint:(NSString *)statusGoEndpoint
signalEndpoint:(NSString *)signalEndpoint
rootDataDir:(NSString *)rootDataDir {
_serverEnabled = serverEnabled;
if (serverEnabled) {
_statusGoEndpoint = statusGoEndpoint;
_signalEndpoint = signalEndpoint;
_rootDataDir = rootDataDir;
[self connectWebSocket];
} else {
[self disconnectWebSocket];
_statusGoEndpoint = nil;
_signalEndpoint = nil;
_rootDataDir = nil;
}
}
+ (void)executeStatusGoRequest:(NSString *)endpoint
body:(NSString *)body
statusgoFunction:(NSString * (^)(void))statusgoFunction {
StatusBackendClient *client = [StatusBackendClient sharedInstance];
if (client.serverEnabled) {
[client request:endpoint body:body callback:^(NSString *response, NSError *error) {
[Utils handleStatusGoResponse:response source:endpoint error:error];
}];
} else {
NSString *result = statusgoFunction();
[Utils handleStatusGoResponse:result source:endpoint error:nil];
}
}
+ (void)executeStatusGoRequestWithCallback:(NSString *)endpoint
body:(NSString *)body
statusgoFunction:(NSString * (^)(void))statusgoFunction
callback:(RCTResponseSenderBlock)callback {
StatusBackendClient *client = [StatusBackendClient sharedInstance];
if (client.serverEnabled) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[client request:endpoint body:body callback:^(NSString *response, NSError *error) {
if (error) {
NSLog(@"request to %@ failed: %@", endpoint, error);
if (callback) {
callback(@[@(NO)]);
}
} else {
if (callback) {
callback(@[response]);
}
}
}];
});
} else {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSString *result = statusgoFunction();
if (callback) {
callback(@[result]);
}
});
}
}
+ (NSString *)executeStatusGoRequestWithResult:(NSString *)endpoint
body:(NSString *)body
statusgoFunction:(NSString * (^)(void))statusgoFunction {
StatusBackendClient *client = [StatusBackendClient sharedInstance];
if (client.serverEnabled) {
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
__block NSString *resultString = @"";
[client request:endpoint body:body callback:^(NSString *response, NSError *error) {
if (error) {
NSLog(@"request to %@ failed: %@", endpoint, error);
resultString = @"";
} else {
resultString = response;
}
dispatch_semaphore_signal(semaphore);
}];
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
return resultString;
} else {
return statusgoFunction();
}
}
@end
@@ -6,13 +6,11 @@
@interface Utils : NSObject <RCTBridgeModule>
+ (NSURL *)getRootUrl;
+ (NSString *)jsonStringWithPrettyPrint:(BOOL)prettyPrint fromDictionary:(NSDictionary *)dictionary;
+ (NSString *)jsonStringWithPrettyPrint:(BOOL)prettyPrint fromArray:(NSArray *)array;
+ (NSURL *)getKeyStoreDirForKeyUID:(NSString *)keyUID;
+ (NSString *)getExportDbFilePath;
+ (NSString *)getKeyUID:(NSString *)jsonString;
+ (void)migrateKeystore:(NSString *)accountData password:(NSString *)password;
+ (void)handleStatusGoResponse:(NSString *)response source:(NSString *)source error:(NSError *)error;
@end
@@ -3,28 +3,11 @@
#import "React/RCTEventDispatcher.h"
#import "Statusgo.h"
#import "Utils.h"
#import "StatusBackendClient.h"
@implementation Utils
RCT_EXPORT_MODULE();
#pragma mark - Private Methods
+ (NSURL *)getRootUrl {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *rootUrl;
StatusBackendClient *client = [StatusBackendClient sharedInstance];
if (client.serverEnabled && client.rootDataDir) {
rootUrl = [NSURL fileURLWithPath:client.rootDataDir];
} else {
rootUrl = [[fileManager URLsForDirectory:NSLibraryDirectory inDomains:NSUserDomainMask] lastObject];
}
return rootUrl;
}
+ (NSString *)jsonStringWithPrettyPrint:(BOOL)prettyPrint fromDictionary:(NSDictionary *)dictionary {
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary
@@ -55,7 +38,7 @@ RCT_EXPORT_MODULE();
+ (NSURL *)getKeyStoreDirForKeyUID:(NSString *)keyUID {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *rootUrl = [self getRootUrl];
NSURL *rootUrl = [[fileManager URLsForDirectory:NSLibraryDirectory inDomains:NSUserDomainMask] lastObject];
NSURL *oldKeystoreDir = [rootUrl URLByAppendingPathComponent:@"keystore"];
NSURL *multiaccountKeystoreDir = [oldKeystoreDir URLByAppendingPathComponent:keyUID];
@@ -74,11 +57,6 @@ RCT_EXPORT_MODULE();
}
+ (NSString *) getExportDbFilePath {
StatusBackendClient *client = [StatusBackendClient sharedInstance];
if (client.serverEnabled && client.rootDataDir) {
return [client.rootDataDir stringByAppendingPathComponent:@"export.db"];
}
NSString *filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"export.db"];
NSFileManager *fileManager = [NSFileManager defaultManager];
@@ -92,36 +70,17 @@ RCT_EXPORT_MODULE();
+ (void) migrateKeystore:(NSString *)accountData
password:(NSString *)password {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *rootUrl =[self getRootUrl];
NSURL *rootUrl =[[fileManager
URLsForDirectory:NSLibraryDirectory inDomains:NSUserDomainMask]
lastObject];
NSData *jsonData = [accountData dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSDictionary *accountJson = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
if (error) {
NSLog(@"Error parsing accountData: %@", error);
return;
}
NSString *keyUID = [self getKeyUID:accountData];
NSURL *keyUID = [self getKeyStoreDirForKeyUID:accountData];
NSURL *oldKeystoreDir = [rootUrl URLByAppendingPathComponent:@"keystore"];
NSURL *multiaccountKeystoreDir = [self getKeyStoreDirForKeyUID:keyUID];
NSURL *multiaccountKeystoreDir = [self getKeyStoreDirForKeyUID:keyUID.path];
NSArray *keys = [fileManager contentsOfDirectoryAtPath:multiaccountKeystoreDir.path error:nil];
if (keys.count == 0) {
NSDictionary *params = @{
@"account": accountJson,
@"password": password,
@"oldDir": oldKeystoreDir.path,
@"newDir": multiaccountKeystoreDir.path
};
NSData *paramsJsonData = [NSJSONSerialization dataWithJSONObject:params options:0 error:&error];
if (error) {
NSLog(@"Error creating params JSON: %@", error);
return;
}
NSString *jsonString = [[NSString alloc] initWithData:paramsJsonData encoding:NSUTF8StringEncoding];
NSString *migrationResult = StatusgoMigrateKeyStoreDirV2(jsonString);
NSString *migrationResult = StatusgoMigrateKeyStoreDir(accountData, password, oldKeystoreDir.path, multiaccountKeystoreDir.path);
NSLog(@"keystore migration result %@", migrationResult);
NSString *initKeystoreResult = StatusgoInitKeystore(multiaccountKeystoreDir.path);
@@ -130,19 +89,18 @@ RCT_EXPORT_MODULE();
}
RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(backupDisabledDataDir) {
StatusBackendClient *client = [StatusBackendClient sharedInstance];
if (client.serverEnabled && client.rootDataDir) {
return client.rootDataDir;
}
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *rootUrl = [Utils getRootUrl];
NSURL *rootUrl =[[fileManager
URLsForDirectory:NSLibraryDirectory inDomains:NSUserDomainMask]
lastObject];
return rootUrl.path;
}
RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(keystoreDir) {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *rootUrl =[Utils getRootUrl];
NSURL *rootUrl =[[fileManager
URLsForDirectory:NSLibraryDirectory inDomains:NSUserDomainMask]
lastObject];
NSURL *commonKeystoreDir = [rootUrl URLByAppendingPathComponent:@"keystore"];
@@ -152,17 +110,9 @@ RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(keystoreDir) {
RCT_EXPORT_METHOD(validateMnemonic:(NSString *)seed
callback:(RCTResponseSenderBlock)callback) {
#if DEBUG
NSLog(@"validateMnemonicV2() method called");
NSLog(@"validateMnemonic() method called");
#endif
NSDictionary *params = @{@"mnemonic": seed};
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:0 error:&error];
if (error) {
NSLog(@"Error creating JSON: %@", error);
return;
}
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSString *result = StatusgoValidateMnemonicV2(jsonString);
NSString *result = StatusgoValidateMnemonic(seed);
callback(@[result]);
}
@@ -182,17 +132,4 @@ RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(validateConnectionString:(NSString *)cs)
return StatusgoValidateConnectionString(cs);
}
+ (void)handleStatusGoResponse:(NSString *)response source:(NSString *)source error:(NSError *)error {
if (error) {
NSLog(@"%@ failed: %@", source, error);
return;
}
if ([response hasPrefix:@"{\"error\":\"\""]) {
NSLog(@"%@ success: %@", source, response);
} else {
NSLog(@"%@ failed: %@", source, response);
}
}
@end
+5
View File
@@ -44,6 +44,11 @@ in {
doCheck = false;
});
# Downgrade watchman in attempt to fix "too many files open issue"
watchman = callPackage ./pkgs/watchman {
inherit (super.darwin.apple_sdk.frameworks) CoreServices;
autoconf = super.buildPackages.autoconf269;
};
# Package version adjustments
nodejs = super.nodejs_20;
+23
View File
@@ -0,0 +1,23 @@
# Issue
`watchman` was upgraded significantly during the last nixpkgs upgrade (`4.9.0` (Aug 16, 2017) to `2023.01.30.00` - 6 years between):
- https://github.com/status-im/status-mobile/pull/14944
- https://github.com/status-im/nixpkgs/commit/4e9c02bcc709fe1737a746add0e8e0109133d808
Probably causing developers to have "too many files open" issue:
https://github.com/status-im/status-mobile/issues/16341
```
Error: A non-recoverable condition has triggered. Watchman needs your help!
The triggering condition was at timestamp=1687286390: opendir(/Users/javid/Projects/status-mobile/node_modules/metro-core/node_modules/jest-regex-util/build) -> Too many open files
All requests will continue to fail with this message until you resolve
the underlying problem. You will find more information on fixing this at
https://facebook.github.io/watchman/docs/troubleshooting.html#poison-opendir
```
# Fix
This is an attempt to fix the issue by downgrading the watchman
# Upgrade
When upgrading in the future, please read the comments:
https://github.com/status-im/status-mobile/issues/16341
+48
View File
@@ -0,0 +1,48 @@
{ stdenv, lib, config, fetchFromGitHub, autoconf, automake, pcre
, libtool, pkg-config, openssl
, confFile ? config.watchman.confFile or null
, withApple ? stdenv.isDarwin, CoreServices
}:
stdenv.mkDerivation rec {
pname = "watchman";
version = "4.9.0";
src = fetchFromGitHub {
owner = "facebook";
repo = "watchman";
rev = "v${version}";
sha256 = "0fdaj5pmicm6j17d5q7px800m5rmam1a400x3hv1iiifnmhgnkal";
};
nativeBuildInputs = [ autoconf automake pkg-config libtool ];
buildInputs = [ pcre openssl ]
#++ lib.optionals withApple [ CoreServices ];
++ lib.optionals stdenv.isDarwin [ CoreServices ];
configureFlags = [
"--enable-lenient"
"--enable-conffile=${if confFile == null then "no" else confFile}"
"--with-pcre=yes"
# For security considerations re: --disable-statedir, see:
# https://github.com/facebook/watchman/issues/178
"--disable-statedir"
];
prePatch = ''
patchShebangs .
'';
preConfigure = ''
./autogen.sh
'';
meta = with lib; {
description = "Watches files and takes action when they change";
homepage = "https://facebook.github.io/watchman";
maintainers = with maintainers; [ cstrahan ];
platforms = with platforms; linux ++ darwin;
license = licenses.asl20;
};
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 810 B

After

Width:  |  Height:  |  Size: 673 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 KiB

After

Width:  |  Height:  |  Size: 1001 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 69 KiB

+3
View File
@@ -32,9 +32,12 @@ trap "rm -vf ${SECRETS_FILE_PATH}" EXIT ERR INT QUIT
# Names of variables containing secrets to save in env file.
SECRETS_ENV_VARS=(
'ALCHEMY_ETHEREUM_MAINNET_TOKEN'
'ALCHEMY_ETHEREUM_GOERLI_TOKEN'
'ALCHEMY_ETHEREUM_SEPOLIA_TOKEN'
'ALCHEMY_ARBITRUM_GOERLI_TOKEN'
'ALCHEMY_ARBITRUM_MAINNET_TOKEN'
'ALCHEMY_ARBITRUM_SEPOLIA_TOKEN'
'ALCHEMY_OPTIMISM_GOERLI_TOKEN'
'ALCHEMY_OPTIMISM_MAINNET_TOKEN'
'ALCHEMY_OPTIMISM_SEPOLIA_TOKEN'
'RARIBLE_MAINNET_API_KEY'
+1 -2
View File
@@ -9,8 +9,7 @@ if test -n "$INVALID_CHANGES"; then
exit 1
fi
# Add exception for status-im.config in the utils package check
INVALID_CHANGES2=$(grep -E -r '(status-im\.)' --include '*.cljs' --include '*.clj' './src/utils' | grep -v 'status-im.config')
INVALID_CHANGES2=$(grep -E -r '(status-im\.)' --include '*.cljs' --include '*.clj' './src/utils')
if test -n "$INVALID_CHANGES2"; then
echo "WARNING: status-im are not allowed in utils package"
+56 -55
View File
@@ -51,61 +51,56 @@
;; the target files (a.k.a hot reload). When false, you can manually
;; reload by calling `shadow.cljs.devtools.api/watch-compile-all!`.
:devtools {:autobuild #shadow/env ["SHADOW_AUTOBUILD_ENABLED" :default true :as :bool]}
:dev
{:devtools {:before-load-async status-im.setup.hot-reload/before-reload
:after-load-async status-im.setup.hot-reload/reload
:build-notify status-im.setup.hot-reload/build-notify
:preloads [;; The official recommendation is to
;; load the debugger preload first.
flow-storm.api
re-frisk-remote.preload
status-im.setup.schema-preload
;; In order to use component test helpers in the REPL we need to
;; preload namespaces that are not normally required by
;; production code, such as @testing-library/react-native.
test-helpers.component]}
:closure-defines
{status-im.config/POKT_TOKEN #shadow/env "POKT_TOKEN"
status-im.config/INFURA_TOKEN #shadow/env "INFURA_TOKEN"
status-im.config/STATUS_BUILD_PROXY_USER #shadow/env "STATUS_BUILD_PROXY_USER"
status-im.config/STATUS_BUILD_PROXY_PASSWORD #shadow/env "STATUS_BUILD_PROXY_PASSWORD"
status-im.config/STATUS_BACKEND_SERVER_ENABLED #shadow/env "STATUS_BACKEND_SERVER_ENABLED"
status-im.config/STATUS_BACKEND_SERVER_HOST #shadow/env "STATUS_BACKEND_SERVER_HOST"
status-im.config/STATUS_BACKEND_SERVER_MEDIA_SERVER_ENABLE_TLS
#shadow/env "STATUS_BACKEND_SERVER_MEDIA_SERVER_ENABLE_TLS"
status-im.config/STATUS_BACKEND_SERVER_IMAGE_SERVER_URI_PREFIX
#shadow/env "STATUS_BACKEND_SERVER_IMAGE_SERVER_URI_PREFIX"
status-im.config/STATUS_BACKEND_SERVER_ROOT_DATA_DIR #shadow/env
"STATUS_BACKEND_SERVER_ROOT_DATA_DIR"
status-im.config/MIXPANEL_APP_ID #shadow/env "MIXPANEL_APP_ID"
status-im.config/MIXPANEL_TOKEN #shadow/env "MIXPANEL_TOKEN"
status-im.config/OPENSEA_API_KEY #shadow/env "OPENSEA_API_KEY"
status-im.config/RARIBLE_MAINNET_API_KEY #shadow/env "RARIBLE_MAINNET_API_KEY"
status-im.config/RARIBLE_TESTNET_API_KEY #shadow/env "RARIBLE_TESTNET_API_KEY"
status-im.config/ALCHEMY_ETHEREUM_MAINNET_TOKEN #shadow/env "ALCHEMY_ETHEREUM_MAINNET_TOKEN"
status-im.config/ALCHEMY_ETHEREUM_SEPOLIA_TOKEN #shadow/env "ALCHEMY_ETHEREUM_SEPOLIA_TOKEN"
status-im.config/ALCHEMY_ARBITRUM_MAINNET_TOKEN #shadow/env "ALCHEMY_ARBITRUM_MAINNET_TOKEN"
status-im.config/ALCHEMY_ARBITRUM_SEPOLIA_TOKEN #shadow/env "ALCHEMY_ARBITRUM_SEPOLIA_TOKEN"
status-im.config/ALCHEMY_OPTIMISM_MAINNET_TOKEN #shadow/env "ALCHEMY_OPTIMISM_MAINNET_TOKEN"
status-im.config/ALCHEMY_OPTIMISM_SEPOLIA_TOKEN #shadow/env "ALCHEMY_OPTIMISM_SEPOLIA_TOKEN"}
:compiler-options {:output-feature-set :es5
;; We disable `:fn-deprecated` warnings because we
;; are managing deprecation via clj-kondo and we
;; don't want the terminal output to be littered
;; with warnings on every code reload.
:warnings {:fn-deprecated false}
:closure-defines {re-frame.trace/trace-enabled? true}
:source-map false
;; This seems to be necessary while using the REPL,
;; otherwise sometimes you'll get weird errors when
;; instrumenting functions.
:static-fns false
:infer-externs true
:reader-features #{:mobile}}
;; if you want to use a real device, set your local ip
;; in the SHADOW_HOST env variable to make sure that
;; it will use the right interface
:local-ip #shadow/env "SHADOW_HOST"}
:dev {:devtools {:before-load-async status-im.setup.hot-reload/before-reload
:after-load-async status-im.setup.hot-reload/reload
:build-notify status-im.setup.hot-reload/build-notify
:preloads [;; The official recommendation is to
;; load the debugger preload first.
flow-storm.api
re-frisk-remote.preload
status-im.setup.schema-preload
;; In order to use component test helpers in the REPL we
;; need to preload namespaces that are not normally required
;; by production code, such as
;; @testing-library/react-native.
test-helpers.component]}
:closure-defines
{status-im.config/POKT_TOKEN #shadow/env "POKT_TOKEN"
status-im.config/INFURA_TOKEN #shadow/env "INFURA_TOKEN"
status-im.config/STATUS_BUILD_PROXY_USER #shadow/env "STATUS_BUILD_PROXY_USER"
status-im.config/STATUS_BUILD_PROXY_PASSWORD #shadow/env "STATUS_BUILD_PROXY_PASSWORD"
status-im.config/MIXPANEL_APP_ID #shadow/env "MIXPANEL_APP_ID"
status-im.config/MIXPANEL_TOKEN #shadow/env "MIXPANEL_TOKEN"
status-im.config/OPENSEA_API_KEY #shadow/env "OPENSEA_API_KEY"
status-im.config/RARIBLE_MAINNET_API_KEY #shadow/env "RARIBLE_MAINNET_API_KEY"
status-im.config/RARIBLE_TESTNET_API_KEY #shadow/env "RARIBLE_TESTNET_API_KEY"
status-im.config/ALCHEMY_ETHEREUM_MAINNET_TOKEN #shadow/env "ALCHEMY_ETHEREUM_MAINNET_TOKEN"
status-im.config/ALCHEMY_ETHEREUM_GOERLI_TOKEN #shadow/env "ALCHEMY_ETHEREUM_GOERLI_TOKEN"
status-im.config/ALCHEMY_ETHEREUM_SEPOLIA_TOKEN #shadow/env "ALCHEMY_ETHEREUM_SEPOLIA_TOKEN"
status-im.config/ALCHEMY_ARBITRUM_MAINNET_TOKEN #shadow/env "ALCHEMY_ARBITRUM_MAINNET_TOKEN"
status-im.config/ALCHEMY_ARBITRUM_GOERLI_TOKEN #shadow/env "ALCHEMY_ARBITRUM_GOERLI_TOKEN"
status-im.config/ALCHEMY_ARBITRUM_SEPOLIA_TOKEN #shadow/env "ALCHEMY_ARBITRUM_SEPOLIA_TOKEN"
status-im.config/ALCHEMY_OPTIMISM_MAINNET_TOKEN #shadow/env "ALCHEMY_OPTIMISM_MAINNET_TOKEN"
status-im.config/ALCHEMY_OPTIMISM_GOERLI_TOKEN #shadow/env "ALCHEMY_OPTIMISM_GOERLI_TOKEN"
status-im.config/ALCHEMY_OPTIMISM_SEPOLIA_TOKEN #shadow/env "ALCHEMY_OPTIMISM_SEPOLIA_TOKEN"}
:compiler-options {:output-feature-set :es5
;; We disable `:fn-deprecated` warnings because we
;; are managing deprecation via clj-kondo and we
;; don't want the terminal output to be littered
;; with warnings on every code reload.
:warnings {:fn-deprecated false}
:closure-defines {re-frame.trace/trace-enabled? true}
:source-map false
;; This seems to be necessary while using the REPL,
;; otherwise sometimes you'll get weird errors when
;; instrumenting functions.
:static-fns false
:infer-externs true
:reader-features #{:mobile}}
;; if you want to use a real device, set your local ip
;; in the SHADOW_HOST env variable to make sure that
;; it will use the right interface
:local-ip #shadow/env "SHADOW_HOST"}
:chunks {:fleets legacy.status-im.fleet.default-fleet/default-fleets}
:release
{:closure-defines
@@ -119,10 +114,13 @@
status-im.config/RARIBLE_MAINNET_API_KEY #shadow/env "RARIBLE_MAINNET_API_KEY"
status-im.config/RARIBLE_TESTNET_API_KEY #shadow/env "RARIBLE_TESTNET_API_KEY"
status-im.config/ALCHEMY_ETHEREUM_MAINNET_TOKEN #shadow/env "ALCHEMY_ETHEREUM_MAINNET_TOKEN"
status-im.config/ALCHEMY_ETHEREUM_GOERLI_TOKEN #shadow/env "ALCHEMY_ETHEREUM_GOERLI_TOKEN"
status-im.config/ALCHEMY_ETHEREUM_SEPOLIA_TOKEN #shadow/env "ALCHEMY_ETHEREUM_SEPOLIA_TOKEN"
status-im.config/ALCHEMY_ARBITRUM_MAINNET_TOKEN #shadow/env "ALCHEMY_ARBITRUM_MAINNET_TOKEN"
status-im.config/ALCHEMY_ARBITRUM_GOERLI_TOKEN #shadow/env "ALCHEMY_ARBITRUM_GOERLI_TOKEN"
status-im.config/ALCHEMY_ARBITRUM_SEPOLIA_TOKEN #shadow/env "ALCHEMY_ARBITRUM_SEPOLIA_TOKEN"
status-im.config/ALCHEMY_OPTIMISM_MAINNET_TOKEN #shadow/env "ALCHEMY_OPTIMISM_MAINNET_TOKEN"
status-im.config/ALCHEMY_OPTIMISM_GOERLI_TOKEN #shadow/env "ALCHEMY_OPTIMISM_GOERLI_TOKEN"
status-im.config/ALCHEMY_OPTIMISM_SEPOLIA_TOKEN #shadow/env "ALCHEMY_OPTIMISM_SEPOLIA_TOKEN"}
:compiler-options {:output-feature-set :es6
;;disable for android build as there
@@ -160,10 +158,13 @@
status-im.config/RARIBLE_MAINNET_API_KEY #shadow/env "RARIBLE_MAINNET_API_KEY"
status-im.config/RARIBLE_TESTNET_API_KEY #shadow/env "RARIBLE_TESTNET_API_KEY"
status-im.config/ALCHEMY_ETHEREUM_MAINNET_TOKEN #shadow/env "ALCHEMY_ETHEREUM_MAINNET_TOKEN"
status-im.config/ALCHEMY_ETHEREUM_GOERLI_TOKEN #shadow/env "ALCHEMY_ETHEREUM_GOERLI_TOKEN"
status-im.config/ALCHEMY_ETHEREUM_SEPOLIA_TOKEN #shadow/env "ALCHEMY_ETHEREUM_SEPOLIA_TOKEN"
status-im.config/ALCHEMY_ARBITRUM_MAINNET_TOKEN #shadow/env "ALCHEMY_ARBITRUM_MAINNET_TOKEN"
status-im.config/ALCHEMY_ARBITRUM_GOERLI_TOKEN #shadow/env "ALCHEMY_ARBITRUM_GOERLI_TOKEN"
status-im.config/ALCHEMY_ARBITRUM_SEPOLIA_TOKEN #shadow/env "ALCHEMY_ARBITRUM_SEPOLIA_TOKEN"
status-im.config/ALCHEMY_OPTIMISM_MAINNET_TOKEN #shadow/env "ALCHEMY_OPTIMISM_MAINNET_TOKEN"
status-im.config/ALCHEMY_OPTIMISM_GOERLI_TOKEN #shadow/env "ALCHEMY_OPTIMISM_GOERLI_TOKEN"
status-im.config/ALCHEMY_OPTIMISM_SEPOLIA_TOKEN #shadow/env "ALCHEMY_OPTIMISM_SEPOLIA_TOKEN"
status-im.config/WALLET_CONNECT_PROJECT_ID #shadow/env "WALLET_CONNECT_PROJECT_ID"}
:compiler-options
@@ -10,3 +10,40 @@ export function scrollDownButtonOpacity(chatListScrollY, isComposerFocused, wind
}
});
}
export function jumpToButtonOpacity(scrollDownButtonOpacity, isComposerFocused) {
return useDerivedValue(function () {
'worklet';
return withTiming(scrollDownButtonOpacity.value == 1 || isComposerFocused.value ? 0 : 1);
});
}
export function jumpToButtonPosition(scrollDownButtonOpacity, isComposerFocused) {
return useDerivedValue(function () {
'worklet';
return withTiming(scrollDownButtonOpacity.value == 1 || isComposerFocused.value ? 35 : 0);
});
}
export function composerContainerOpacity(isComposerFocused, isEmptyInput, emptyOpacity) {
return useDerivedValue(function () {
'worklet';
return isEmptyInput.value && !isComposerFocused.value
? withDelay(300, withTiming(emptyOpacity, { duration: 0 }))
: 1;
});
}
export function blurContainerElevation(isComposerFocused, isEmptyInput) {
return useDerivedValue(function () {
'worklet';
return isEmptyInput.value && !isComposerFocused.value ? 10 : 0;
});
}
export function composerElevation(isComposerFocused, isEmptyInput) {
return useDerivedValue(function () {
'worklet';
return isEmptyInput.value && !isComposerFocused.value ? 0 : 10;
});
}
+37 -2
View File
@@ -1,12 +1,47 @@
import { useDerivedValue, withTiming } from 'react-native-reanimated';
import * as constants from './constants';
export function bottomTabIconColor(stackId, selectedStackId, selectedTabColor, defaultColor) {
export function bottomTabIconColor(
stackId,
selectedStackId,
homeStackState,
passThrough,
selectedTabColor,
defaultColor,
passThroughColor,
) {
return useDerivedValue(function () {
'worklet';
if (selectedStackId.value == stackId) {
var homeStackStateValue = homeStackState.value;
if (
selectedStackId.value == stackId &&
(homeStackStateValue == constants.OPEN_WITH_ANIMATION || homeStackStateValue == constants.OPEN_WITHOUT_ANIMATION)
) {
return selectedTabColor;
} else if (passThrough.value) {
return passThroughColor;
} else {
return defaultColor;
}
});
}
export function bottomTabsHeight(homeStackState, height, extendedHeight) {
return useDerivedValue(function () {
'worklet';
switch (homeStackState.value) {
case constants.OPEN_WITH_ANIMATION:
return withTiming(extendedHeight, constants.LINEAR_EASING);
break;
case constants.CLOSE_WITH_ANIMATION:
return withTiming(height, constants.LINEAR_EASING);
break;
case constants.OPEN_WITHOUT_ANIMATION:
return extendedHeight;
break;
case constants.CLOSE_WITHOUT_ANIMATION:
return height;
break;
}
});
}
+29
View File
@@ -0,0 +1,29 @@
import { Easing } from 'react-native-reanimated';
// Home Stack States
export const CLOSE_WITHOUT_ANIMATION = 0;
export const OPEN_WITHOUT_ANIMATION = 1;
export const CLOSE_WITH_ANIMATION = 2;
export const OPEN_WITH_ANIMATION = 3;
// Floating Screen States
export const CLOSE_SCREEN_WITHOUT_ANIMATION = 0;
export const OPEN_SCREEN_WITHOUT_ANIMATION = 1;
export const CLOSE_SCREEN_WITH_SHELL_ANIMATION = 2;
export const OPEN_SCREEN_WITH_SHELL_ANIMATION = 3;
export const CLOSE_SCREEN_WITH_SLIDE_TO_RIGHT_ANIMATION = 4;
export const OPEN_SCREEN_WITH_SLIDE_FROM_RIGHT_ANIMATION = 5;
export const CLOSE_SCREEN_WITH_SLIDE_TO_BOTTOM_ANIMATION = 6;
export const OPEN_SCREEN_WITH_SLIDE_FROM_BOTTOM_ANIMATION = 7;
export const SHELL_ANIMATION_TIME = 200;
export const LINEAR_EASING = {
duration: SHELL_ANIMATION_TIME,
easing: Easing.bezier(0, 0, 1, 1),
};
export const EASE_OUT_EASING = {
duration: SHELL_ANIMATION_TIME,
easing: Easing.bezier(0, 0, 0.58, 1),
};
+180
View File
@@ -0,0 +1,180 @@
import { useDerivedValue, withTiming, withSequence, withDelay, Easing, runOnJS } from 'react-native-reanimated';
import * as constants from './constants';
// Derived Values
export function screenLeft(screenState, screenWidth, switcherCardLeftPosition) {
return useDerivedValue(function () {
'worklet';
switch (screenState.value) {
case constants.CLOSE_SCREEN_WITHOUT_ANIMATION:
return screenWidth;
case constants.OPEN_SCREEN_WITHOUT_ANIMATION:
// Note - don't use return 0; its not working in ios
// https://github.com/software-mansion/react-native-reanimated/issues/3296#issuecomment-1573900172
return withSequence(withTiming(-1, { duration: 0 }), withTiming(0, { duration: 0 }));
case constants.CLOSE_SCREEN_WITH_SHELL_ANIMATION:
return withSequence(
withTiming(switcherCardLeftPosition, constants.EASE_OUT_EASING),
withTiming(screenWidth, { duration: 0 }),
);
case constants.OPEN_SCREEN_WITH_SHELL_ANIMATION:
return withTiming(0, constants.EASE_OUT_EASING);
case constants.CLOSE_SCREEN_WITH_SLIDE_TO_RIGHT_ANIMATION:
return withTiming(screenWidth, constants.EASE_OUT_EASING);
case constants.OPEN_SCREEN_WITH_SLIDE_FROM_RIGHT_ANIMATION:
return withTiming(0, constants.EASE_OUT_EASING);
case constants.CLOSE_SCREEN_WITH_SLIDE_TO_BOTTOM_ANIMATION:
return withDelay(constants.SHELL_ANIMATION_TIME, withTiming(screenWidth, { duration: 0 }));
case constants.OPEN_SCREEN_WITH_SLIDE_FROM_BOTTOM_ANIMATION:
return 0;
default:
return screenWidth;
}
});
}
export function screenTop(screenState, screenHeight, switcherCardTopPosition) {
return useDerivedValue(function () {
'worklet';
switch (screenState.value) {
case constants.CLOSE_SCREEN_WITHOUT_ANIMATION:
return screenHeight;
case constants.OPEN_SCREEN_WITHOUT_ANIMATION:
return withSequence(withTiming(-1, { duration: 0 }), withTiming(0, { duration: 0 }));
case constants.CLOSE_SCREEN_WITH_SHELL_ANIMATION:
return withSequence(
withTiming(switcherCardTopPosition, constants.EASE_OUT_EASING),
withTiming(screenHeight, { duration: 0 }),
);
case constants.OPEN_SCREEN_WITH_SHELL_ANIMATION:
return withTiming(0, constants.EASE_OUT_EASING);
case constants.CLOSE_SCREEN_WITH_SLIDE_TO_RIGHT_ANIMATION:
return withDelay(constants.SHELL_ANIMATION_TIME, withTiming(screenHeight, { duration: 0 }));
case constants.OPEN_SCREEN_WITH_SLIDE_FROM_RIGHT_ANIMATION:
return 0;
case constants.CLOSE_SCREEN_WITH_SLIDE_TO_BOTTOM_ANIMATION:
return withTiming(screenHeight, constants.EASE_OUT_EASING);
case constants.OPEN_SCREEN_WITH_SLIDE_FROM_BOTTOM_ANIMATION:
return withTiming(0, constants.EASE_OUT_EASING);
default:
return screenHeight;
}
});
}
export function screenWidth(screenState, screenWidth, switcherCardSize) {
return useDerivedValue(function () {
'worklet';
switch (screenState.value) {
case constants.CLOSE_SCREEN_WITH_SHELL_ANIMATION:
return withTiming(switcherCardSize, constants.EASE_OUT_EASING);
case constants.OPEN_SCREEN_WITH_SHELL_ANIMATION:
return withSequence(
withTiming(switcherCardSize, { duration: 0 }),
withTiming(screenWidth, constants.EASE_OUT_EASING),
);
default:
return screenWidth;
}
});
}
export function screenHeight(screenState, screenHeight, switcherCardSize) {
return useDerivedValue(function () {
'worklet';
switch (screenState.value) {
case constants.CLOSE_SCREEN_WITH_SHELL_ANIMATION:
return withTiming(switcherCardSize, constants.EASE_OUT_EASING);
case constants.OPEN_SCREEN_WITH_SHELL_ANIMATION:
return withSequence(
withTiming(switcherCardSize, { duration: 0 }),
withTiming(screenHeight, constants.EASE_OUT_EASING),
);
default:
return screenHeight;
}
});
}
export function screenZIndex(screenState) {
return useDerivedValue(function () {
'worklet';
switch (screenState.value) {
case constants.CLOSE_SCREEN_WITH_SHELL_ANIMATION:
case constants.CLOSE_SCREEN_WITH_SLIDE_TO_RIGHT_ANIMATION:
case constants.CLOSE_SCREEN_WITH_SLIDE_TO_BOTTOM_ANIMATION:
return withDelay(constants.SHELL_ANIMATION_TIME, withTiming(-1, { duration: 0 }));
case constants.CLOSE_SCREEN_WITHOUT_ANIMATION:
return -1;
default:
return 1;
}
});
}
export function screenBorderRadius(screenState) {
return useDerivedValue(function () {
'worklet';
switch (screenState.value) {
case constants.OPEN_SCREEN_WITH_SHELL_ANIMATION:
return withDelay(constants.SHELL_ANIMATION_TIME, withTiming(0, { duration: 0 }));
case constants.OPEN_SCREEN_WITH_SLIDE_FROM_RIGHT_ANIMATION:
case constants.OPEN_SCREEN_WITH_SLIDE_FROM_BOTTOM_ANIMATION:
case constants.OPEN_SCREEN_WITHOUT_ANIMATION:
return 0;
case constants.CLOSE_SCREEN_WITH_SLIDE_TO_RIGHT_ANIMATION:
case constants.CLOSE_SCREEN_WITH_SLIDE_TO_BOTTOM_ANIMATION:
return withDelay(constants.SHELL_ANIMATION_TIME, withTiming(20, { duration: 0 }));
case constants.CLOSE_SCREEN_WITHOUT_ANIMATION:
case constants.CLOSE_SCREEN_WITH_SHELL_ANIMATION:
return 20;
}
});
}
export function screenGestureOnUpdate(screenLeft) {
return function (event) {
'worklet';
const absoluteX = event.absoluteX;
if (absoluteX !== null) {
screenLeft.value = event.absoluteX;
}
};
}
export function screenGestureOnEnd(data) {
return function (event) {
'worklet';
const {
'screen-left': screenLeft,
'screen-state': screenState,
'screen-width': screenWidth,
'left-velocity': leftVelocity,
'right-velocity': rightVelocity,
'screen-closed-callback': screenClosedCallback,
} = data;
const absoluteX = event.absoluteX ?? 0;
const velocityX = event.velocityX ?? 0;
const closeScreen = velocityX > rightVelocity || (velocityX > leftVelocity && absoluteX >= screenWidth / 2);
// Velocity (points/sec) = Distance/time
var animationVelocity = (screenWidth * 1000) / constants.SHELL_ANIMATION_TIME;
if (Math.abs(velocityX) > animationVelocity) {
animationVelocity = velocityX; // Faster fling
}
const newDistance = closeScreen ? screenWidth - absoluteX : absoluteX;
const animationTime = (newDistance * 1000) / animationVelocity;
screenLeft.value = withTiming(closeScreen ? screenWidth : 0, {
duration: animationTime,
easing: Easing.bezier(0, 0, 0.58, 1),
});
if (closeScreen) {
runOnJS(screenClosedCallback)(animationTime);
}
};
}
+97
View File
@@ -1,4 +1,5 @@
import { useDerivedValue, withTiming, withSequence, withDelay } from 'react-native-reanimated';
import * as constants from './constants';
// Derived values for each stack (communities, chat, wallet, browser)
export function stackOpacity(stackId, selectedStackId) {
@@ -14,3 +15,99 @@ export function stackZIndex(stackId, selectedStackId) {
return selectedStackId.value == stackId ? 10 : 9;
});
}
// Derived values for home stack (container)
export function homeStackOpacity(homeStackState) {
return useDerivedValue(function () {
'worklet';
switch (homeStackState.value) {
case constants.OPEN_WITH_ANIMATION:
return withTiming(1, constants.LINEAR_EASING);
case constants.CLOSE_WITH_ANIMATION:
return withTiming(0, constants.LINEAR_EASING);
case constants.OPEN_WITHOUT_ANIMATION:
return 1;
case constants.CLOSE_WITHOUT_ANIMATION:
return 0;
}
});
}
export function homeStackTop(homeStackState, top) {
return useDerivedValue(function () {
'worklet';
switch (homeStackState.value) {
case constants.OPEN_WITH_ANIMATION:
return withTiming(0, constants.LINEAR_EASING);
case constants.CLOSE_WITH_ANIMATION:
return withTiming(top, constants.LINEAR_EASING);
case constants.OPEN_WITHOUT_ANIMATION:
return 0;
case constants.CLOSE_WITHOUT_ANIMATION:
return top;
}
});
}
export function homeStackLeft(selectedStackId, animateHomeStackLeft, homeStackState, left) {
return useDerivedValue(function () {
'worklet';
if (animateHomeStackLeft.value) {
var leftValue = left[selectedStackId.value];
switch (homeStackState.value) {
case constants.OPEN_WITH_ANIMATION:
return withSequence(withTiming(leftValue, { duration: 0 }), withTiming(0, constants.LINEAR_EASING));
case constants.CLOSE_WITH_ANIMATION:
return withTiming(leftValue, constants.LINEAR_EASING);
case constants.OPEN_WITHOUT_ANIMATION:
return 0;
case constants.CLOSE_WITHOUT_ANIMATION:
return leftValue;
}
} else {
return 0;
}
});
}
export function homeStackPointer(homeStackState) {
return useDerivedValue(function () {
'worklet';
var homeStackStateValue = homeStackState.value;
return homeStackStateValue == constants.OPEN_WITH_ANIMATION ||
homeStackStateValue == constants.OPEN_WITHOUT_ANIMATION
? 'auto'
: 'none';
});
}
export function homeStackScale(homeStackState, minimizeScale) {
return useDerivedValue(function () {
'worklet';
switch (homeStackState.value) {
case constants.OPEN_WITH_ANIMATION:
return withTiming(1, constants.LINEAR_EASING);
case constants.CLOSE_WITH_ANIMATION:
return withTiming(minimizeScale, constants.LINEAR_EASING);
case constants.OPEN_WITHOUT_ANIMATION:
return 1;
case constants.CLOSE_WITHOUT_ANIMATION:
return minimizeScale;
}
});
}
export function homeStackBorderRadius(homeStackState) {
return useDerivedValue(function () {
'worklet';
switch (homeStackState.value) {
case constants.OPEN_WITH_ANIMATION:
return withDelay(constants.SHELL_ANIMATION_TIME, withTiming(0, { duration: 0 }));
case constants.CLOSE_WITH_ANIMATION:
case constants.CLOSE_WITHOUT_ANIMATION:
return 20;
case constants.OPEN_WITHOUT_ANIMATION:
return 0;
}
});
}
+12 -10
View File
@@ -3,7 +3,8 @@
["react-native" :as rn]
["react-native-status-keycard" :default status-keycard]
[react-native.platform :as platform]
[taoensso.timbre :as log]))
[taoensso.timbre :as log]
[utils.address :as address]))
(defonce event-emitter
(if platform/ios?
@@ -93,14 +94,22 @@
[{:keys [on-success on-failure]}]
(.. status-keycard
(getApplicationInfo)
(then on-success)
(then (fn [response]
(let [info (-> response
(js->clj :keywordize-keys true)
(update :key-uid address/normalized-hex))]
(on-success info))))
(catch on-failure)))
(defn factory-reset
[{:keys [on-success on-failure]}]
(.. status-keycard
(factoryReset)
(then on-success)
(then (fn [response]
(let [info (-> response
(js->clj :keywordize-keys true)
(update :key-uid address/normalized-hex))]
(on-success info))))
(catch on-failure)))
(defn install-applet
@@ -146,13 +155,6 @@
(then on-success)
(catch on-failure)))
(defn save-mnemonic
[{:keys [mnemonic pin on-success on-failure]}]
(.. status-keycard
(saveMnemonic mnemonic pin)
(then on-success)
(catch on-failure)))
(defn unblock-pin
[{:keys [puk new-pin on-success on-failure]}]
(when (and new-pin puk)
+12 -12
View File
@@ -306,13 +306,13 @@
{:dispatch [:universal-links/handle-url normalized-url]}
(if config/show-not-implemented-features?
(rf/merge cofx
{:db (assoc db
:browser/options
{:browser-id (:browser-id browser)}
:browser/screen-id :browser)
:dispatch-n [[:shell/change-tab :browser-stack]]}
{:db (assoc db
:browser/options
{:browser-id (:browser-id browser)}
:browser/screen-id :browser)}
(navigation/pop-to-root :shell-stack)
(chat.events/close-chat (:current-chat-id db))
(navigation/change-tab :browser-stack)
(update-browser browser)
(resolve-url nil))
{:linking/open-url url}))))
@@ -323,20 +323,20 @@
[{:keys [db] :as cofx} browser-id]
(let [browser (get-in db [:browser/browsers browser-id])]
(rf/merge cofx
{:db (assoc db
:browser/options
{:browser-id browser-id}
:browser/screen-id :browser)
:dispatch-n [[:shell/change-tab :browser-stack]]}
{:db (assoc db
:browser/options
{:browser-id browser-id}
:browser/screen-id :browser)}
(update-browser browser)
(navigation/change-tab :browser-stack)
(resolve-url nil))))
(rf/defn open-browser-tabs
{:events [:browser.ui/open-browser-tabs]}
[{:keys [db] :as cofx}]
(rf/merge cofx
{:db (assoc db :browser/screen-id :browser-tabs)
:dispatch-n [[:shell/change-tab :browser-stack]]}))
{:db (assoc db :browser/screen-id :browser-tabs)}
(navigation/change-tab :browser-stack)))
(rf/defn web3-error-callback
{:events [:browser.dapp/transaction-on-error]}
@@ -0,0 +1,44 @@
(ns legacy.status-im.data-store.switcher-cards
(:require
[clojure.set :as set]
[clojure.walk :as walk]
[re-frame.core :as re-frame]
[status-im.common.json-rpc.events :as json-rpc]
[taoensso.timbre :as log]
[utils.re-frame :as rf]))
(defn <-rpc
[switcher-cards]
(walk/postwalk-replace
{:cardId :card-id
:screenId :screen-id}
switcher-cards))
(defn rpc->
[switcher-card]
(set/rename-keys switcher-card
{:card-id :cardId
:screen-id :screenId}))
(rf/defn upsert-switcher-card-rpc
[_ switcher-card]
{:json-rpc/call [{:method "wakuext_upsertSwitcherCard"
:params [(rpc-> switcher-card)]
:on-success #()
:on-error #()}]})
(rf/defn delete-switcher-card-rpc
[_ card-id]
{:json-rpc/call [{:method "wakuext_deleteSwitcherCard"
:params [card-id]
:on-success #()
:on-error #()}]})
(re-frame/reg-fx :switcher-cards/fetch
(fn []
(json-rpc/call {:method "wakuext_switcherCards"
:params []
:on-success #(rf/dispatch
[:shell/switcher-cards-loaded
(:switcherCards ^js %)])
:on-error #(log/error "Failed to fetch switcher cards" %)})))
+2 -2
View File
@@ -20,9 +20,9 @@
{:mainnet {:name "Ether"
:symbol :ETH
:decimals 18}
:sepolia {:name "Sepolia Ether"
:goerli {:name "Goerli Ether"
:symbol :ETH
:symbol-display :ETH
:symbol-display :ETHgo
:decimals 18}
:xdai {:name "xDAI"
:symbol :ETH
@@ -15,12 +15,12 @@
(def etherscan-supported?
#{(chain/chain-keyword->chain-id :mainnet)
(chain/chain-keyword->chain-id :sepolia)})
(chain/chain-keyword->chain-id :goerli)})
(def binance-mainnet-chain-id (chain/chain-keyword->chain-id :bsc))
(def binance-testnet-chain-id (chain/chain-keyword->chain-id :bsc-testnet))
(def network->subdomain {11155111 "sepolia"})
(def network->subdomain {5 "goerli"})
(defn get-transaction-details-url
[chain-id tx-hash]
+5 -2
View File
@@ -6,11 +6,13 @@
legacy.status-im.browser.permissions
legacy.status-im.chat.models.loading
legacy.status-im.data-store.chats
legacy.status-im.data-store.switcher-cards
legacy.status-im.data-store.visibility-status-updates
legacy.status-im.fleet.core
legacy.status-im.group-chats.core
legacy.status-im.log-level.core
legacy.status-im.multiaccounts.login.core
legacy.status-im.multiaccounts.logout.core
[legacy.status-im.multiaccounts.model :as multiaccounts.model]
legacy.status-im.multiaccounts.update.core
legacy.status-im.pairing.core
@@ -41,6 +43,7 @@
status-im.contexts.onboarding.events
status-im.contexts.shell.activity-center.events
status-im.contexts.shell.activity-center.notification.contact-requests.events
status-im.contexts.shell.jump-to.events
[utils.i18n :as i18n]
[utils.re-frame :as rf]))
@@ -109,14 +112,14 @@
(defn- on-biometric-auth-fail
[{:keys [code]}]
(if (= code "USER_FALLBACK")
(re-frame/dispatch [:profile/logout])
(re-frame/dispatch [:multiaccounts.logout.ui/logout-confirmed])
(utils/show-confirmation
{:title (i18n/label :t/biometric-auth-confirm-title)
:content (i18n/label :t/biometric-auth-confirm-message)
:confirm-button-text (i18n/label :t/biometric-auth-confirm-try-again)
:cancel-button-text (i18n/label :t/biometric-auth-confirm-logout)
:on-accept #(rf/dispatch [:biometric/authenticate {:on-fail on-biometric-auth-fail}])
:on-cancel #(re-frame/dispatch [:profile/logout])})))
:on-cancel #(re-frame/dispatch [:multiaccounts.logout.ui/logout-confirmed])})))
(rf/defn on-return-from-background
[{:keys [db now] :as cofx}]
+2 -1
View File
@@ -91,4 +91,5 @@
cofx
:fleet
fleet
{:on-success #(re-frame/dispatch [:profile/logout])}))))
{:on-success
#(re-frame/dispatch [:logout])}))))
+3 -2
View File
@@ -20,9 +20,10 @@
(chat.events/pop-to-root-and-navigate-to-chat cofx chat-id nil)))
(re-frame/reg-event-fx :chat-removed
(fn [{:keys [db]} [response]]
(fn [{:keys [db]} [response chat-id]]
{:db (dissoc db :current-chat-id)
:fx [[:dispatch [:sanitize-messages-and-process-response response]]
:fx [[:dispatch [:shell/close-switcher-card chat-id]]
[:dispatch [:sanitize-messages-and-process-response response]]
[:dispatch [:pop-to-root :shell-stack]]
[:activity-center.notifications/fetch-unread-count]]}))
+1 -1
View File
@@ -14,7 +14,7 @@
cofx
:log-level
log-level
{:on-success #(re-frame/dispatch [:profile/logout])}))))
{:on-success #(re-frame/dispatch [:logout])}))))
(rf/defn show-change-log-level-confirmation
{:events [:log-level.ui/log-level-selected]}
@@ -0,0 +1,66 @@
(ns legacy.status-im.multiaccounts.logout.core
(:require
[native-module.core :as native-module]
[re-frame.core :as re-frame]
[status-im.common.keychain.events :as keychain]
[status-im.db :as db]
[utils.i18n :as i18n]
[utils.re-frame :as rf]))
(re-frame/reg-fx
::logout
(fn []
(native-module/logout)))
(rf/defn initialize-app-db
[{{:keys [keycard initials-avatar-font-file biometrics]
:network/keys [type status expensive?]
:centralized-metrics/keys [user-confirmed?]}
:db}]
{:db (assoc db/app-db
:centralized-metrics/user-confirmed? user-confirmed?
:network/type type
:network/status status
:network/expensive? expensive?
:initials-avatar-font-file initials-avatar-font-file
:keycard (dissoc keycard :secrets :pin :application-info)
:biometrics biometrics
:syncing nil)})
(rf/defn logout-method
{:events [::logout-method]}
[{:keys [db] :as cofx} {:keys [auth-method logout?]}]
(let [key-uid (get-in db [:profile/profile :key-uid])]
(rf/merge cofx
{:dispatch [:update-theme-and-init-root :progress]
:effects.shell/reset-state nil
:hide-popover nil
::logout nil
:profile.settings/webview-debug-changed false
:keychain/clear-user-password key-uid
:profile/get-profiles-overview #(rf/dispatch
[:profile/get-profiles-overview-success %])}
(keychain/save-auth-method key-uid auth-method)
(initialize-app-db))))
(rf/defn logout
{:events [:logout :multiaccounts.logout.ui/logout-confirmed
:multiaccounts.update.callback/save-settings-success]}
[_]
;; we need to disable notifications before starting the logout process
{:effects/push-notifications-disable nil
:dispatch [:alert-banners/remove-all]
:dispatch-later [{:ms 100
:dispatch [::logout-method
{:auth-method keychain/auth-method-none
:logout? true}]}]})
(rf/defn show-logout-confirmation
{:events [:multiaccounts.logout.ui/logout-pressed]}
[_]
{:ui/show-confirmation
{:title (i18n/label :t/logout-title)
:content (i18n/label :t/logout-are-you-sure)
:confirm-button-text (i18n/label :t/logout)
:on-accept #(re-frame/dispatch [:multiaccounts.logout.ui/logout-confirmed])
:on-cancel nil}})
+3 -3
View File
@@ -62,7 +62,7 @@
(cond
(and public-key own)
(rf/merge cofx
(navigation/pop-to-root :shell-stack)
{:pop-to-root-fx :shell-stack}
(navigation/navigate-to :my-profile nil))
(and public-key (not own))
@@ -78,8 +78,8 @@
(rf/defn handle-eip681
[cofx data]
(rf/merge cofx
{:dispatch-n [[:shell/change-tab :wallet-stack]
[:wallet-legacy/parse-eip681-uri-and-resolve-ens data]]}
{:dispatch [:wallet-legacy/parse-eip681-uri-and-resolve-ens data]}
(navigation/change-tab :wallet-stack)
(navigation/pop-to-root :shell-stack)))
(rf/defn handle-local-pairing
@@ -125,6 +125,6 @@
(i18n/label :t/password-reset-success-message)])
[react/view {:align-items :center}
[quo/button
{:on-press #(re-frame/dispatch [:profile/logout])
{:on-press #(re-frame/dispatch [:logout])
:disabled resetting?}
(i18n/label :t/okay)]]]))
+2 -2
View File
@@ -133,7 +133,7 @@
:params [{:enabled enabled?}]
:on-success (fn []
(log/info "light client set successfully" enabled?)
(re-frame/dispatch [:profile/logout]))
(re-frame/dispatch [:logout]))
:on-error #(log/error "failed to set light client"
{:error %
:enabled? enabled?})}]})
@@ -149,7 +149,7 @@
:params [{:enabled enabled?}]
:on-success (fn []
(log/info "store confirmation set successfully" enabled?)
(re-frame/dispatch [:profile/logout]))
(re-frame/dispatch [:logout]))
:on-error #(log/error "failed to set store confirmation"
{:error %
:enabled? enabled?})}]})
+1
View File
@@ -431,6 +431,7 @@
"../src/js/worklets/core.js" worklet-factory
"../src/js/worklets/shell/bottom_tabs.js" #js {}
"../src/js/worklets/shell/home_stack.js" #js {}
"../src/js/worklets/shell/floating_screen.js" #js {}
"../src/js/worklets/bottom_sheet.js" #js {}
"../src/js/worklets/record_audio.js" #js {}
"../src/js/worklets/scroll_view.js" #js {}
+7 -6
View File
@@ -508,16 +508,17 @@
new-password-hashed
callback))))
(defn convert-to-keycard-profile
[{:keys [key-uid] :as profile} settings password new-password callback]
(defn convert-to-keycard-account
[{:keys [key-uid] :as multiaccount-data} settings current-password# new-password callback]
(log/debug "[native-module] convert-to-keycard-account")
(.convertToKeycardAccount ^js (encryption)
key-uid
(types/clj->json profile)
(types/clj->json multiaccount-data)
(types/clj->json settings)
(:keycard-instance-uid settings)
password
""
current-password#
new-password
#(when callback (callback (types/json->clj %)))))
callback))
(defn backup-disabled-data-dir
[]
@@ -5,6 +5,7 @@
{:margin-top 6
:margin-bottom 6
:margin-left (case type
:jump-to 0
:mention 8
:notification-down 2
:notification-up 2
@@ -13,6 +14,7 @@
:scroll-to-bottom 6
nil)
:margin-right (case type
:jump-to 8
:mention 2
:notification-down 8
:notification-up 8
@@ -26,12 +28,14 @@
{:margin-top 2.5
:margin-bottom 3.5
:margin-left (case type
:jump-to 8
:mention 0
:notification-down 8
:notification-up 8
:search-with-label 0
nil)
:margin-right (case type
:jump-to 0
:mention 8
:notification-down 0
:notification-up 0
@@ -9,7 +9,7 @@
(defn- get-button-color
[{:keys [type pressed? customization-color theme]}]
(if (= type :mention)
(if (#{:jump-to :mention} type)
(if pressed?
(colors/theme-colors
(colors/custom-color customization-color 60)
@@ -25,7 +25,7 @@
(defn- get-icon-and-text-color
[type theme]
(if (= type :mention)
(if (#{:jump-to :mention} type)
colors/white
(colors/theme-colors colors/white colors/neutral-100 theme)))
@@ -33,6 +33,7 @@
[type theme]
[icon/icon
(case type
:jump-to :i/jump-to
:mention :i/mention
:notification-down :i/arrow-down
:notification-up :i/arrow-up
@@ -46,10 +47,10 @@
(defn view
"[dynamic-button opts]
opts
{:type :mention/:notification-down/:notification-up/:search/:search-with-label/:scroll-to-bottom
{:type :jump-to/:mention/:notification-down/:notification-up/:search/:search-with-label/:scroll-to-bottom
:on-press fn
:count mentions or notifications count
:customization-color customize and mention button color}"
:customization-color customize jump-to and mention button color}"
[{:keys [type label on-press customization-color style] :as args}]
(let [theme (quo.theme/use-theme)
[pressed? set-pressed] (rn/use-state false)
@@ -77,13 +78,14 @@
style)}
(when (#{:mention :search :search-with-label :scroll-to-bottom} type)
[icon-view type theme])
(when (#{:mention :notification-down :notification-up :search-with-label} type)
(when (#{:jump-to :mention :notification-down :notification-up :search-with-label} type)
[text/text
{:weight :medium
:size :paragraph-2
:style (assoc (style/text type) :color (get-icon-and-text-color type theme))}
(case type
:jump-to label
:search-with-label label
(:mention :notification-down :notification-up) (str (:count args)))])
(when (#{:notification-down :notification-up} type)
(when (#{:jump-to :notification-down :notification-up} type)
[icon-view type theme])]]))
@@ -3,12 +3,12 @@
(def inner-container
{:flex-direction :row
:justify-content :space-between
:justify-content :center
:flex 1})
(def button-container
{:padding-vertical 8
:flex 1
:width 77.75
:justify-content :center
:align-items :center})
@@ -36,11 +36,10 @@
"Same as rn/image but cache the image source in a js/Set, so the image won't
flicker when re-render on android"
[props]
(let [[loaded-source set-loaded-source] (rn/use-state nil)]
(let [[loaded-source set-loaded-source] (rn/use-state nil)
on-source-loaded (rn/use-callback #(set-loaded-source %))]
(if platform/ios?
[rn/image props]
[:<>
[rn/image
(cond-> props
loaded-source (assoc :source loaded-source))]
[caching-image props set-loaded-source]])))
[rn/image (assoc props :source loaded-source)]
[caching-image props on-source-loaded]])))
+1 -1
View File
@@ -16,7 +16,7 @@
"
[{:keys [holder-name locked?]}]
(let [theme (quo.theme/use-theme)
label (if holder-name
label (if (boolean holder-name)
(i18n/label :t/user-keycard {:name holder-name})
(i18n/label :t/empty-keycard))]
[rn/view {:style (style/card-container locked? theme)}
@@ -23,7 +23,7 @@
[:map
[:type {:optional true}
[:enum :default :tag :action :balance-neutral :balance-negative :balance-positive]]
[:state {:optional true} [:enum :default :selected :active :disabled]]
[:state {:optional true} [:enum :default :selected :active]]
[:blur? {:optional true} [:maybe :boolean]]
[:customization-color {:optional true} [:maybe :schema.common/customization-color]]
[:on-press {:optional true} [:maybe fn?]]
@@ -12,13 +12,12 @@
:else :transparent))
(defn container
[{:keys [state] :as props}]
[props]
{:height 56
:border-radius 12
:background-color (background-color props)
:flex-direction :row
:align-items :center
:opacity (if (= state :disabled) 0.3 1)
:padding-horizontal 12
:padding-vertical 6
:justify-content :space-between})
@@ -112,7 +112,6 @@
:pressed? pressed?})
:on-press-in on-press-in
:on-press on-press
:disabled (= state :disabled)
:on-press-out on-press-out
:accessibility-label :container}
[account-view props]
+2 -4
View File
@@ -3,10 +3,8 @@
(defn container
[container-style]
(merge container-style
{:padding-vertical 7
:padding-horizontal 20
:flex-direction :row
:align-items :flex-start}))
{:flex-direction :row
:align-items :flex-start}))
(def index
{:margin-left 5})
+1 -1
View File
@@ -45,7 +45,7 @@
:or {type :bullet}}]
(let [theme (quo.theme/use-theme)]
[rn/view {:style (style/container container-style)}
[rn/view
[rn/view {:style style/index}
(case type
:step
[step/view
@@ -28,6 +28,8 @@
[dynamic-button-view :search dynamic-buttons
{:position :absolute
:right 8}]]
;; Mid Section (jump-to)
[dynamic-button-view :jump-to dynamic-buttons nil]
;; Right Section
[section
[rn/view
@@ -34,11 +34,12 @@
[])))
(defn- get-button-common-props
[{:keys [theme blur?]}]
[{:keys [jump-to? theme blur?]}]
{:icon-only? true
:size 32
:container-style {:margin-left 12}
:type (cond
jump-to? :black
(and (not blur?) (= :dark theme)) :dark-grey
:else :grey)
:background (when blur? :blur)})
@@ -87,20 +88,19 @@
avatar-props)]]])
(defn- right-section
[{:keys [blur?
[{:keys [jump-to?
blur?
notification
notification-count
activity-center-on-press
scan-on-press
qr-code-on-press
right-section-content]
qr-code-on-press]
:as props}]
(let [theme (quo.theme/use-theme)
button-common-props (get-button-common-props {:theme theme
:blur? blur?})]
button-common-props (get-button-common-props {:theme theme
:jump-to? jump-to?
:blur? blur?})]
[rn/view {:style style/right-section}
(when right-section-content
right-section-content)
[button/button
(assoc button-common-props :accessibility-label :open-scanner-button :on-press scan-on-press)
:i/scan]
@@ -127,6 +127,7 @@
":container-style style map merged with outer view for margins/paddings
:customization-color custom colors
:blur? true/false
:jump-to? true/false
:theme :light/:dark
:notification :mention/:seen/:notification (TODO :mention-seen temporarily used while resolving https://github.com/status-im/status-mobile/issues/17102 )
:avatar-props qu2/user-avatar props
@@ -136,7 +137,6 @@
:qr-code-on-press callback
:notification-count number
:max-unread-notifications used to specify max number for counter
:right-section-content
"
[{:keys [avatar-on-press avatar-props customization-color container-style] :as props}]
[rn/view {:style (merge style/top-nav-container container-style)}
@@ -55,36 +55,26 @@
theme))}])]))
(defn- left-title
[{:keys [title blur? title-icon]}]
[{:keys [title blur?]}]
(let [theme (quo.theme/use-theme)]
[rn/view {:style style/title-container}
[text/text
{:weight :regular
:size :paragraph-2
:style (style/title blur? theme)}
title]
(when title-icon
[icons/icon title-icon
{:accessibility-label :title-icon
:size 12
:color (if blur?
colors/neutral-40
(colors/theme-colors colors/neutral-50
colors/neutral-40
theme))}])]))
title]]))
(defn- left-side
"The description can either be given as a string `subtitle-type` or a component `custom-subtitle`"
[{:keys [title status size blur? custom-subtitle icon subtitle subtitle-type subtitle-color icon-color
customization-color network-image emoji title-icon]
customization-color network-image emoji]
:as props}]
(let [theme (quo.theme/use-theme)]
[rn/view {:style style/left-side}
[rn/view
[left-title
{:title title
:title-icon title-icon
:blur? blur?}]]
[left-title
{:title title
:blur? blur?
:theme theme}]
(if (= status :loading)
[left-loading
{:size size
@@ -142,7 +132,6 @@
[:subtitle {:optional true} [:maybe [:or :string :double]]]
[:custom-subtitle {:optional true} [:maybe fn?]]
[:icon {:optional true} [:maybe :keyword]]
[:title-icon {:optional true} [:maybe :keyword]]
[:emoji {:optional true} [:maybe :string]]
[:customization-color {:optional true} [:maybe :schema.common/customization-color]]
[:network-image {:optional true} [:maybe :schema.common/image-source]]
@@ -1,6 +1,5 @@
(ns quo.components.settings.settings-item.view
(:require
[clojure.string :as string]
[quo.components.avatars.icon-avatar :as icon-avatar]
[quo.components.avatars.user-avatar.view :as user-avatar]
[quo.components.buttons.button.view :as button]
@@ -52,11 +51,6 @@
:status [status-description props]
nil))
(defn emoji-component
[image-props]
[rn/text
(when image-props (string/trim image-props))])
(defn image-component
[{:keys [image image-props description tag blur?]}]
(let [theme (quo.theme/use-theme)]
@@ -67,7 +61,6 @@
:avatar [user-avatar/user-avatar image-props]
:icon-avatar [icon-avatar/icon-avatar image-props]
:token [token/view image-props]
:emoji [emoji-component image-props]
nil)]))
(defn tag-component
@@ -0,0 +1,19 @@
(ns quo.components.switchers.base-card.component-spec
(:require
[quo.components.switchers.base-card.view :as base-card]
[quo.foundations.colors :as colors]
[test-helpers.component :as h]))
(h/describe "Switcher: Base card"
(h/test "Default render"
(h/render [base-card/base-card {}])
(h/is-truthy (h/query-by-label-text :base-card)))
(h/test "Banner render"
(h/render [base-card/base-card {:banner {:source "banner"}}])
(h/is-truthy (h/query-by-label-text :base-card))
(h/is-truthy (h/query-by-label-text :banner)))
(h/test "Customization color"
(h/render [base-card/base-card {:customization-color :blue}])
(h/has-style
(h/query-by-label-text :base-card)
{:backgroundColor (colors/custom-color :blue 50 40)})))
@@ -0,0 +1,24 @@
(ns quo.components.switchers.base-card.style
(:require
[quo.foundations.colors :as colors]))
(defn base-container
[customization-color]
{:width 160
:height 160
:border-radius 16
:background-color (colors/custom-color customization-color 50 40)})
(def thumb-card
{:width 160
:height 120
:border-radius 16
:bottom 0
:position :absolute
:background-color colors/neutral-95
:padding 12})
(def close-button
{:position :absolute
:right 8
:top 8})
@@ -0,0 +1,32 @@
(ns quo.components.switchers.base-card.view
(:require
[quo.components.buttons.button.view :as button]
[quo.components.switchers.base-card.style :as style]
[react-native.core :as rn]))
(defn base-card
[]
(let [card-ref (atom nil)
set-ref #(reset! card-ref %)]
(fn [{:keys [banner on-press on-close customization-color]} & children]
[rn/touchable-opacity
{:on-press on-press
:ref set-ref
:active-opacity 1}
[rn/view
{:accessibility-label :base-card
:style (style/base-container customization-color)}
(when banner
[rn/image
{:accessibility-label :banner
:source (:source banner)
:style {:width 160}}])
[button/button
{:size 24
:type :grey
:icon-only? true
:on-press on-close
:background :photo
:container-style style/close-button}
:i/close]
(into [rn/view {:style style/thumb-card}] children)]])))
@@ -0,0 +1,28 @@
(ns quo.components.switchers.card-content.style
(:require
[quo.foundations.colors :as colors]))
(defn content-container
[status]
{:flex-direction :row
:justify-content :space-between
:align-items (if (= status :mention) :center :flex-end)})
(def notification-container
{:width 20
:height 20
:justify-content :center
:align-items :center
:margin-left 8})
(def message-text
{:color colors/white})
(def sticker
{:width 24
:height 24})
(def gif
{:width 24
:height 24
:border-radius 8})
@@ -0,0 +1,99 @@
(ns quo.components.switchers.card-content.view
(:require
[quo.components.code.snippet-preview.view :as snippet-preview]
[quo.components.common.notification-dot.view :as notification-dot]
[quo.components.counter.counter.view :as counter]
[quo.components.list-items.preview-list.view :as preview-list]
[quo.components.markdown.text :as text]
[quo.components.switchers.card-content.style :as style]
[quo.components.tags.context-tag.view :as tag]
[react-native.core :as rn]
[react-native.fast-image :as fast-image]
[utils.i18n :as i18n]))
(defn content-view
[{:keys [type content customization-color]
{:keys [text duration photos community-avatar
community-name source]} :content}]
[rn/view {:style {:max-width 108}}
(case type
:message
[text/text
{:size :paragraph-2
:weight :regular
:number-of-lines 1
:ellipsize-mode :tail
:style style/message-text}
text]
:photo
[preview-list/view
{:type :collectibles
:more-than-99-label (i18n/label :t/counter-99-plus)
:size :size/s-24}
photos]
:sticker
[fast-image/fast-image
{:accessibility-label :sticker
:source source
:style style/sticker}]
:gif
[fast-image/fast-image
{:accessibility-label :gif
:source source
:style style/gif}]
:audio
[tag/view
{:type :audio
:duration duration
:customization-color customization-color}]
:community
[tag/view
{:type :community
:community-name community-name
:community-logo community-avatar
:size 24}]
:link
[tag/view
{:type :icon
:icon (:icon content)
:context (:text content)
:size 24}]
:code
[snippet-preview/view
{:language (:language content)}
content]
nil)])
(defn notification-indicator
[{:keys [status mention-count customization-color]}]
(when (not= status :read)
[rn/view {:style style/notification-container}
(case status
:unread
[notification-dot/view
{:customization-color customization-color}]
:mention
[counter/view
{:outline false
:customization-color customization-color}
mention-count]
nil)]))
(defn view
[type status customization-color content]
[rn/view {:style (style/content-container status)}
[content-view {:type type :content content :customization-color customization-color}]
[notification-indicator
{:status status
:customization-color customization-color
:mention-count (:mention-count content)}]])
@@ -0,0 +1,6 @@
(ns quo.components.switchers.card-main-info.style
(:require
[quo.foundations.colors :as colors]))
(def subtitle
{:color colors/neutral-40})
@@ -0,0 +1,22 @@
(ns quo.components.switchers.card-main-info.view
(:require
[quo.components.markdown.text :as text]
[quo.components.switchers.card-main-info.style :as style]
[react-native.core :as rn]))
(defn view
[{:keys [title subtitle]}]
[rn/view
[text/text
{:accessibility-label :title
:size :paragraph-1
:weight :semi-bold
:number-of-lines 1
:ellipsize-mode :tail}
title]
[text/text
{:accessibility-label :subtitle
:size :paragraph-2
:weight :medium
:style style/subtitle}
subtitle]])
@@ -0,0 +1,117 @@
(ns quo.components.switchers.group-messaging-card.component-spec
(:require
[quo.components.switchers.group-messaging-card.view :as group-messaging-card]
[quo.components.switchers.utils :as utils]
[test-helpers.component :as h]))
(def photos-list
[{:source (js/require "../resources/images/mock2/photo1.png")}
{:source (js/require "../resources/images/mock2/photo2.png")}
{:source (js/require "../resources/images/mock2/photo3.png")}
{:source (js/require "../resources/images/mock2/photo1.png")}
{:source (js/require "../resources/images/mock2/photo2.png")}
{:source (js/require "../resources/images/mock2/photo3.png")}])
(def sticker {:source (js/require "../resources/images/mock2/sticker.png")})
(def gif {:source (js/require "../resources/images/mock2/gif.png")})
(def coinbase-community (js/require "../resources/images/mock2/coinbase.png"))
(def link-icon (js/require "../resources/images/mock2/status-logo.png"))
(h/describe "Switcher: Group Messaging Card"
(h/test "Default render"
(h/render [group-messaging-card/view {}])
(h/is-truthy (h/query-by-label-text :base-card)))
(h/test "Avatar render"
(h/render [group-messaging-card/view {:avatar true}])
(h/is-truthy (h/query-by-label-text :group-avatar)))
(h/test "Status: Read, Type: Message, Avatar: true"
(h/render [group-messaging-card/view
{:avatar true
:status :read
:type :message
:title "Title"
:content {:text "Last message"}}])
(h/is-truthy (h/get-by-text "Title"))
(h/is-truthy (h/get-by-text (utils/subtitle :message nil)))
(h/is-truthy (h/get-by-text "Last message")))
(h/test "Status: Unread, Type: Message, Avatar: true"
(h/render [group-messaging-card/view
{:avatar true
:status :unread
:type :message
:title "Title"}])
(h/is-truthy (h/query-by-label-text :notification-dot)))
(h/test "Status: Mention, Type: Message, Avatar: true"
(h/render [group-messaging-card/view
{:avatar true
:status :mention
:type :message
:title "Title"
:content {:mention-count 5}}])
(h/is-truthy (h/get-by-test-id :counter-component)))
(h/test "Status: Read, Type: Photo, Avatar: true"
(h/render [group-messaging-card/view
{:avatar true
:status :read
:type :photo
:title "Title"
:content {:photos photos-list}}])
(h/is-truthy (h/get-by-text (utils/subtitle :photo {:photos photos-list}))))
(h/test "Status: Read, Type: Stciker, Avatar: true"
(h/render [group-messaging-card/view
{:avatar true
:status :read
:type :sticker
:title "Title"
:content sticker}])
(h/is-truthy (h/get-by-text (utils/subtitle :sticker nil)))
(h/is-truthy (h/get-by-label-text :sticker)))
(h/test "Status: Read, Type: Gif, Avatar: true"
(h/render [group-messaging-card/view
{:avatar true
:status :read
:type :gif
:title "Title"
:content gif}])
(h/is-truthy (h/get-by-text (utils/subtitle :gif nil)))
(h/is-truthy (h/get-by-label-text :gif)))
(h/test "Status: Read, Type: Audio, Avatar: true"
(h/render-with-theme-provider [group-messaging-card/view
{:avatar true
:status :read
:type :audio
:title "Title"
:content {:duration "00:32"}}])
(h/is-truthy (h/get-by-text (utils/subtitle :audio nil)))
(h/is-truthy (h/get-by-text "00:32")))
(h/test "Status: Read, Type: Community, Avatar: true"
(h/render-with-theme-provider [group-messaging-card/view
{:avatar true
:status :read
:type :community
:title "Title"
:content {:community-avatar coinbase-community
:community-name "Coinbase"}}])
(h/is-truthy (h/get-by-text (utils/subtitle :community nil)))
(h/is-truthy (h/get-by-label-text :group-avatar))
(h/is-truthy (h/get-by-text "Coinbase")))
(h/test "Status: Read, Type: Link, Avatar: true"
(h/render-with-theme-provider [group-messaging-card/view
{:avatar true
:status :read
:type :link
:title "Title"
:content {:icon :placeholder
:text "Rolling St..."}}])
(h/is-truthy (h/get-by-text (utils/subtitle :link nil)))
(h/is-truthy (h/get-by-label-text :group-avatar))
(h/is-truthy (h/get-by-text "Rolling St..."))))
@@ -0,0 +1,17 @@
(ns quo.components.switchers.group-messaging-card.style
(:require
[quo.foundations.colors :as colors]))
(def avatar-container
{:left 10
:top -30
:border-radius 48
:border-width 2
:border-color colors/neutral-95
:position :absolute})
(def content-container
{:flex 1
:flex-direction :column
:justify-content :space-between
:margin-top 16})
@@ -0,0 +1,32 @@
(ns quo.components.switchers.group-messaging-card.view
(:require
[quo.components.avatars.group-avatar.view :as group-avatar]
[quo.components.switchers.base-card.view :as base-card]
[quo.components.switchers.card-content.view :as card-content]
[quo.components.switchers.card-main-info.view :as card-main-info]
[quo.components.switchers.group-messaging-card.style :as style]
[quo.components.switchers.utils :as utils]
[react-native.core :as rn]))
(defn view
"Opts:
:type - keyword -> :message/:photo/:sticker/:gif/:audio/:community/:link/:code
:status - keyword -> :read/:unread/:mention
:profile-color -> keyword or hexstring -> :blue/:army/... or #ABCEDF
:customization-color -> keyword or hexstring -> :blue/:army/... or #ABCEDF"
[{:keys [avatar type status title profile-color customization-color on-close content]
:or {profile-color :blue avatar nil}}]
[base-card/base-card
{:customization-color customization-color
:on-close on-close}
[rn/view {:style style/avatar-container}
[group-avatar/view
{:customization-color customization-color
:picture avatar
:icon-name :i/members
:size :size-48}]]
[rn/view {:style style/content-container}
[card-main-info/view
{:title title
:subtitle (utils/subtitle type content)}]
[card-content/view type status profile-color content]]])
+36
View File
@@ -0,0 +1,36 @@
(ns quo.components.switchers.utils
(:require
[utils.i18n :as i18n]))
(defn subtitle
[type {:keys [photos]}]
(case type
:message
(i18n/label :t/message)
:photo
(i18n/label
(if (= (count photos) 1)
:t/one-photo
:t/n-photos)
{:count (count photos)})
:sticker
(i18n/label :t/sticker)
:gif
(i18n/label :t/gif)
:audio
(i18n/label :t/audio-message)
:community
(i18n/label :t/link-to-community)
:link
(i18n/label :t/external-link)
:code
(i18n/label :t/code-snippet)
""))
@@ -1,14 +0,0 @@
(ns quo.components.tags.network-status-tag.component-spec
(:require
[quo.components.tags.network-status-tag.view :as network-status-tag]
[test-helpers.component :as h]))
(h/describe "Network status component test"
(h/test "5 min ago render"
(h/render [network-status-tag/view
{:label "Updated 5 min ago"}])
(h/is-truthy (h/get-by-text "Updated 5 min ago")))
(h/test "15 min ago render"
(h/render [network-status-tag/view
{:label "Updated 15 min ago"}])
(h/is-truthy (h/get-by-text "Updated 15 min ago"))))
@@ -1,28 +0,0 @@
(ns quo.components.tags.network-status-tag.style
(:require
[quo.foundations.colors :as colors]))
(def main
{:justify-content :center
:align-items :center
:height 24})
(defn inner
[theme]
{:border-width 1
:border-radius 12
:flex 1
:flex-direction :row
:border-color (colors/theme-colors colors/neutral-20 colors/neutral-80 theme)
:align-items :center
:padding-horizontal 8})
(def label
{:color colors/warning-50
:margin-left 6})
(def dot
{:width 8
:height 8
:border-radius 8
:background-color colors/warning-50})
@@ -1,19 +0,0 @@
(ns quo.components.tags.network-status-tag.view
(:require
[quo.components.markdown.text :as text]
[quo.components.tags.network-status-tag.style :as style]
[quo.theme :as quo.theme]
[react-native.core :as rn]))
(defn view
[{:keys [label]}]
(let [theme (quo.theme/use-theme)]
[rn/view {:style style/main}
[rn/view {:style (style/inner theme)}
[rn/view {:style style/dot}]
[text/text
{:style style/label
:weight :medium
:size :label
:align :center}
label]]]))
@@ -8,7 +8,8 @@
(def header
{:flex-direction :row
:justify-content :space-between})
:justify-content :space-between
:height 32})
(def header-title
{:flex 1
@@ -59,6 +59,7 @@
[rn/view {:style (merge style/container container-style)}
[text/text
{:size :heading-1
:number-of-lines 1
:weight :semi-bold
:style style/text
:accessibility-label accessibility-label}
+4 -2
View File
@@ -149,12 +149,12 @@
quo.components.share.qr-code.view
quo.components.share.share-qr-code.view
quo.components.slideshow.slider-bar.view
quo.components.switchers.group-messaging-card.view
quo.components.tabs.account-selector
quo.components.tabs.segmented-tab
quo.components.tabs.tabs.view
quo.components.tags.collectible-tag.view
quo.components.tags.context-tag.view
quo.components.tags.network-status-tag.view
quo.components.tags.network-tags.view
quo.components.tags.number-tag.view
quo.components.tags.permission-tag
@@ -425,6 +425,9 @@
;;;; Slideshow
(def slider-bar quo.components.slideshow.slider-bar.view/view)
;;;; SWITCHER
(def group-messaging-card quo.components.switchers.group-messaging-card.view/view)
;;;; Tabs
(def tabs quo.components.tabs.tabs.view/view)
(def segmented-control quo.components.tabs.segmented-tab/segmented-control)
@@ -435,7 +438,6 @@
(def context-tag quo.components.tags.context-tag.view/view)
(def network-tags quo.components.tags.network-tags.view/view)
(def number-tag quo.components.tags.number-tag.view/view)
(def network-status-tag quo.components.tags.network-status-tag.view/view)
(def permission-tag quo.components.tags.permission-tag/tag)
(def status-tag quo.components.tags.status-tags/status-tag)
(def summary-tag quo.components.tags.summary-tag.view/view)

Some files were not shown because too many files have changed in this diff Show More