Skip to content
This repository was archived by the owner on Sep 3, 2026. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ class TonConnectViewModel(
private val getWalletByAddress: (String) -> ITONWallet?,
private val onRequestApproved: () -> Unit = {},
private val onRequestRejected: () -> Unit = {},
private val onRequestFailed: (String) -> Unit = {},
private val onSessionsChanged: () -> Unit = {},
private val onEmbeddedRequest: (TONWalletKitEvent) -> Unit = {},
) : ViewModel() {
Expand Down Expand Up @@ -207,6 +208,7 @@ class TonConnectViewModel(
isProcessing = false,
error = error.message ?: "Failed to approve transaction",
)
onRequestFailed(error.message ?: "Failed to approve transaction")
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,6 @@ import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.json.JSONObject
import java.math.BigInteger
import javax.inject.Inject
import kotlin.collections.ArrayDeque
import kotlin.collections.firstOrNull
Expand Down Expand Up @@ -151,6 +150,7 @@ class WalletKitViewModel @Inject constructor(
getWalletByAddress = { address -> lifecycleManager.tonWallets[address] },
onRequestApproved = { onTonConnectRequestApproved() },
onRequestRejected = { onTonConnectRequestRejected() },
onRequestFailed = { message -> onTonConnectRequestFailed(message) },
onSessionsChanged = { viewModelScope.launch { sessionsViewModel.refresh() } },
onEmbeddedRequest = { followUp -> handleSdkEvent(followUp) },
)
Expand Down Expand Up @@ -479,6 +479,12 @@ class WalletKitViewModel @Inject constructor(
pendingTonConnectAction = null
}

private fun onTonConnectRequestFailed(message: String) {
pendingTonConnectAction = null
dismissSheet()
eventLogger.showTemporaryStatus(uiString(R.string.wallet_status_transaction_failed, message))
}

private fun onTonConnectRequestRejected() {
when (val action = pendingTonConnectAction) {
is TonConnectAction.Connect -> {
Expand Down Expand Up @@ -1391,79 +1397,38 @@ class WalletKitViewModel @Inject constructor(

private fun onTransactionRequest(request: TONWalletTransactionRequest) {
Log.d(LOG_TAG, "=== onTransactionRequest called ===")
// Extract wallet address from active wallet
val walletAddress = state.value.activeWalletAddress ?: ""
val dAppInfo = request.event.dAppInfo
val fallbackDAppName = uiString(R.string.wallet_event_generic_dapp)
val txRequest = request.event.request

Log.d(LOG_TAG, "Transaction request - walletAddress: $walletAddress, dAppName: ${dAppInfo?.name}")

// Check balance before showing transaction UI (like web demo-wallet does)
viewModelScope.launch {
val wallet = lifecycleManager.tonWallets[walletAddress]
if (wallet != null) {
try {
val balance = wallet.balance()
val totalAmount = txRequest.messages.sumOf { msg ->
msg.amount.toBigIntegerOrNull() ?: BigInteger.ZERO
}
Log.d(LOG_TAG, "Balance check: balance=${balance.value}, totalAmount=$totalAmount")

if (balance.value.toBigInteger() < totalAmount) {
Log.d(LOG_TAG, "Insufficient balance - auto-rejecting transaction")
// Use NonCancellable to ensure rejection completes even if Activity goes to background
withContext(NonCancellable) {
// Use BAD_REQUEST_ERROR (1) for insufficient balance, matching web demo-wallet
request.reject("Insufficient balance", BAD_REQUEST_ERROR_CODE)
}
return@launch
}
} catch (e: Exception) {
Log.e(LOG_TAG, "Failed to check balance, proceeding with transaction UI", e)
// Continue to show the UI even if balance check fails
}
}

// Map actual transaction messages from request
val messages = txRequest.messages.map { msg ->
// Try to decode comment from payload if it's a simple text comment
val comment = try {
msg.payload?.let { _ ->
// Simple text comments are base64 encoded with opcode 0
// For now, we'll just show null - full decoding can be added later
null
}
} catch (_: Exception) {
null
}

TransactionMessageUi(
to = msg.address,
amount = msg.amount,
comment = comment,
payload = msg.payload?.value,
stateInit = msg.stateInit?.value,
)
}

val uiRequest = TransactionRequestUi(
id = request.hashCode().toString(),
walletAddress = walletAddress,
dAppName = dAppInfo?.name ?: fallbackDAppName,
validUntil = txRequest.validUntil?.toLong(),
messages = messages,
preview = null,
raw = JSONObject(),
transactionRequest = request,
val messages = txRequest.messages.map { msg ->
TransactionMessageUi(
to = msg.address,
amount = msg.amount,
comment = null,
payload = msg.payload?.value,
stateInit = msg.stateInit?.value,
)

Log.d(LOG_TAG, "Setting sheet to Transaction state with ${messages.size} messages")
uiCoordinator.setSheet(SheetState.Transaction(uiRequest))
Log.d(LOG_TAG, "Sheet state updated: ${state.value.sheetState}")
val eventDAppName = dAppInfo?.name ?: fallbackDAppName
eventLogger.log(R.string.wallet_event_transaction_request, eventDAppName)
}

val uiRequest = TransactionRequestUi(
id = request.hashCode().toString(),
walletAddress = walletAddress,
dAppName = dAppInfo?.name ?: fallbackDAppName,
validUntil = txRequest.validUntil?.toLong(),
messages = messages,
preview = null,
raw = JSONObject(),
transactionRequest = request,
)

Log.d(LOG_TAG, "Setting sheet to Transaction state with ${messages.size} messages")
uiCoordinator.setSheet(SheetState.Transaction(uiRequest))
val eventDAppName = dAppInfo?.name ?: fallbackDAppName
eventLogger.log(R.string.wallet_event_transaction_request, eventDAppName)
}

private fun onSignMessageRequest(request: TONWalletSignMessageRequest) {
Expand Down
1 change: 1 addition & 0 deletions AndroidDemo/app/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,7 @@
<string name="wallet_error_reject_transaction">Failed to reject transaction</string>
<string name="wallet_event_sign_data_approved">✅ Sign data approved</string>
<string name="wallet_status_signed_success">✅ Signed successfully</string>
<string name="wallet_status_transaction_failed">⚠️ Transaction failed: %1$s</string>
<string name="wallet_status_walletkit_ready">WalletKit ready</string>
<string name="wallet_event_sign_data_failed">❌ Sign data approval failed: %1$s</string>
<string name="wallet_error_approve_sign_request">Failed to approve sign request</string>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -145,11 +145,15 @@ data class TONWalletKitConfiguration(
*
* @property url API endpoint URL (optional, uses default if not provided)
* @property key API key for authentication
* @property timeout Per-request timeout in milliseconds for the built-in API client (optional;
* the SDK default applies when not set). Only honoured for the `TONCENTER` / `TONAPI` client
* types; the `DEFAULT` type uses the SDK's built-in default.
*/
@Serializable
data class APIClientConfiguration(
val url: String? = null,
val key: String,
val timeout: Long? = null,
)
Comment thread
nikdim03 marked this conversation as resolved.
Resolved

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39676,11 +39676,14 @@ async function initTonWalletKit(config, deps) {
if (type === "tonapi") apiClient = new ApiClientTonApi({
endpoint: netConfig.apiClientConfiguration?.url,
apiKey: netConfig.apiClientConfiguration?.key,
timeout: netConfig.apiClientConfiguration?.timeout,
network: netConfig.network
});
else if (type === "toncenter") apiClient = new ApiClientToncenter({
endpoint: netConfig.apiClientConfiguration?.url,
apiKey: netConfig.apiClientConfiguration?.key
apiKey: netConfig.apiClientConfiguration?.key,
timeout: netConfig.apiClientConfiguration?.timeout,
network: netConfig.network
});
else apiClient = netConfig.apiClientConfiguration;
networksConfig[netConfig.network.chainId] = { apiClient };
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,7 @@ internal class InitializationManager(
putJsonObject("apiClientConfiguration") {
apiConfig.url?.takeIf { it.isNotBlank() }?.let { put("url", it) }
apiConfig.key?.takeIf { it.isNotBlank() }?.let { put("key", it) }
apiConfig.timeout?.let { put("timeout", it) }
}
}
}
Expand Down
Loading