Skip to content

Commit

Permalink
Merge branch 'feature/stability_improvements' into develop
Browse files Browse the repository at this point in the history
  • Loading branch information
simonmcl committed Jun 11, 2024
2 parents d7c8f83 + 87b2be4 commit 25b8105
Show file tree
Hide file tree
Showing 20 changed files with 401 additions and 185 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@
"location" : "https://github.com/kukai-wallet/kukai-core-swift",
"state" : {
"branch" : "develop",
"revision" : "27ee93dec720cdf1bff0eeafed17566c1442d2ff"
"revision" : "5b8e07f12b0adb9a5cb66b31535031f091f608d6"
}
},
{
Expand Down
3 changes: 2 additions & 1 deletion Kukai Mobile/Modules/Account/AccountViewModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -346,7 +346,8 @@ class AccountViewModel: ViewModel, UITableViewDiffableDataSourceHandler {
let obj = dataSource?.itemIdentifier(for: atIndexPath)

if obj is XTZAmount {
return Token.xtz(withAmount: DependencyManager.shared.balanceService.account.xtzBalance)
let account = DependencyManager.shared.balanceService.account
return Token.xtz(withAmount: account.xtzBalance, stakedAmount: account.xtzStakedBalance, unstakedAmount: account.xtzUnstakedBalance)

} else if obj is Token {
return obj as? Token
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ class CollectiblesCollectionsViewController: UIViewController, UICollectionViewD
private var movingToDetails = false
private var textFieldDone = false
private var lastSearchedTerm: String? = nil
private var ignoreNextTextFieldDidEnd = true
private var ignoreNextTextFieldDidEnd = false

public weak var delegate: UIViewController? = nil

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ class WelcomeViewController: UIViewController {
if (UIApplication.shared.delegate as? AppDelegate)?.shouldLaunchGhostnet() == true {
DependencyManager.shared.setDefaultTestnetURLs(supressUpdateNotification: true)

} else if DependencyManager.shared.currentNetworkType != .mainnet {
} else if DependencyManager.shared.currentNetworkType != .mainnet {
DependencyManager.shared.setDefaultMainnetURLs(supressUpdateNotification: true)
}

Expand Down
8 changes: 4 additions & 4 deletions Kukai Mobile/Modules/Send/SendTokenAmountViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -56,15 +56,15 @@ class SendTokenAmountViewController: UIViewController {


// Token data
balanceLabel.text = token.balance.normalisedRepresentation
balanceLabel.text = token.availableBalance.normalisedRepresentation
symbolLabel.text = token.symbol
fiatValueLabel?.text = DependencyManager.shared.balanceService.fiatAmountDisplayString(forToken: token, ofAmount: .zero())
tokenIcon.addTokenIcon(token: token)


// Textfield
textfield.validatorTextFieldDelegate = self
textfield.validator = TokenAmountValidator(balanceLimit: token.balance, decimalPlaces: token.decimalPlaces)
textfield.validator = TokenAmountValidator(balanceLimit: token.availableBalance, decimalPlaces: token.decimalPlaces)
textfield.addDoneToolbar()
textfield.numericAndSeperatorOnly = true

Expand All @@ -85,7 +85,7 @@ class SendTokenAmountViewController: UIViewController {
}

@IBAction func maxButtonTapped(_ sender: UIButton) {
textfield.text = selectedToken?.balance.normalisedRepresentation ?? ""
textfield.text = selectedToken?.availableBalance.normalisedRepresentation ?? ""
let _ = textfield.revalidateTextfield()
}

Expand Down Expand Up @@ -168,7 +168,7 @@ extension SendTokenAmountViewController: ValidatorTextFieldDelegate {
}

func validateMaxXTZ(input: String) {
if selectedToken?.isXTZ() == true, let balance = selectedToken?.balance, let inputAmount = XTZAmount(fromNormalisedAmount: input, decimalPlaces: 6), balance == inputAmount {
if selectedToken?.isXTZ() == true, let balance = selectedToken?.availableBalance, let inputAmount = XTZAmount(fromNormalisedAmount: input, decimalPlaces: 6), balance == inputAmount {
maxWarningLabel.isHidden = false
} else {
maxWarningLabel.isHidden = true
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -262,8 +262,8 @@ class SendTokenConfirmViewController: SendAbstractConfirmViewController, SlideBu

// Sum of send amount + fee is greater than balance, need to adjust send amount
// For safety, don't allow this logic coming from WC2, as its likely the user is communicating with a smart contract that likely won't accept recieving less than expected XTZ
if !isWalletConnectOp, let token = currentSendData.chosenToken, token.isXTZ(), let amount = currentSendData.chosenAmount, (amount + fee) >= token.balance, let oneMutez = XTZAmount(fromRpcAmount: "1") {
let updatedValue = ((token.balance - oneMutez) - fee)
if !isWalletConnectOp, let token = currentSendData.chosenToken, token.isXTZ(), let amount = currentSendData.chosenAmount, (amount + fee) >= token.availableBalance, let oneMutez = XTZAmount(fromRpcAmount: "1") {
let updatedValue = ((token.availableBalance - oneMutez) - fee)

if updatedValue < .zero() {
updateAmountDisplay(withValue: .zero())
Expand All @@ -272,10 +272,10 @@ class SendTokenConfirmViewController: SendAbstractConfirmViewController, SlideBu

if isFirstCall {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { [weak self] in
self?.windowError(withTitle: "error-funds-title".localized(), description: String.localized("error-funds-body", withArguments: token.balance.normalisedRepresentation, fee.normalisedRepresentation))
self?.windowError(withTitle: "error-funds-title".localized(), description: String.localized("error-funds-body", withArguments: token.availableBalance.normalisedRepresentation, fee.normalisedRepresentation))
}
} else {
self.windowError(withTitle: "error-funds-title".localized(), description: String.localized("error-funds-body", withArguments: token.balance.normalisedRepresentation, fee.normalisedRepresentation))
self.windowError(withTitle: "error-funds-title".localized(), description: String.localized("error-funds-body", withArguments: token.availableBalance.normalisedRepresentation, fee.normalisedRepresentation))
}

} else {
Expand Down
4 changes: 1 addition & 3 deletions Kukai Mobile/Modules/Stake/StakeViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -87,19 +87,17 @@ class StakeViewController: UIViewController {
}

self.showLoadingView()

let operations = OperationFactory.delegateOperation(to: toAddress, from: selectedWallet.address)
DependencyManager.shared.tezosNodeClient.estimate(operations: operations, walletAddress: selectedWallet.address, base58EncodedPublicKey: selectedWallet.publicKeyBase58encoded()) { [weak self] estimationResult in
self?.hideLoadingView()

switch estimationResult {
case .success(let estimationResult):
TransactionService.shared.currentOperationsAndFeesData = TransactionService.OperationsAndFeesData(estimatedOperations: estimationResult.operations)
TransactionService.shared.currentForgedString = estimationResult.forgedString
self?.loadingViewHideActivity()
self?.performSegue(withIdentifier: "confirm", sender: nil)

case .failure(let estimationError):
self?.hideLoadingView()
self?.windowError(withTitle: "error".localized(), description: estimationError.description)
}
}
Expand Down
10 changes: 8 additions & 2 deletions Kukai Mobile/Services/BalanceService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,10 @@ public class BalanceService {
DependencyManager.shared.activityService.checkAndUpdatePendingTransactions(forAddress: address ?? "", comparedToGroups: DependencyManager.shared.activityService.transactionGroups)

self.account = account

} else if let add = address {
// If local cache fails to parse, models must have change. Delete everything, will trigger a network refresh
deleteAccountCachcedData(forAddress: add)
}

cacheLoadingInProgress = false
Expand Down Expand Up @@ -271,7 +275,7 @@ public class BalanceService {
// MARK: - Refresh

private func fetchAllBalancesTokensAndPrices(forAddress address: String, refreshType: BalanceService.RefreshType, completion: @escaping ((KukaiError?) -> Void)) {
self.currentlyRefreshingAccount = Account(walletAddress: address, xtzBalance: .zero(), tokens: [], nfts: [], recentNFTs: [], liquidityTokens: [], delegate: nil, delegationLevel: nil)
self.currentlyRefreshingAccount = Account(walletAddress: address, xtzBalance: .zero(), xtzStakedBalance: .zero(), xtzUnstakedBalance: .zero(), tokens: [], nfts: [], recentNFTs: [], liquidityTokens: [], delegate: nil, delegationLevel: nil)

var error: KukaiError? = nil
balanceRequestDispathGroup.enter()
Expand All @@ -285,7 +289,7 @@ public class BalanceService {
if refreshType == .useCache || (refreshType == .useCacheIfNotStale && !isCacheStale(forAddress: address)) {
let cachedAccount = DiskService.read(type: Account.self, fromFileName: BalanceService.accountCacheFilename(withAddress: address))

self.currentlyRefreshingAccount = cachedAccount ?? Account(walletAddress: address, xtzBalance: .zero(), tokens: [], nfts: [], recentNFTs: [], liquidityTokens: [], delegate: nil, delegationLevel: nil)
self.currentlyRefreshingAccount = cachedAccount ?? Account(walletAddress: address, xtzBalance: .zero(), xtzStakedBalance: .zero(), xtzUnstakedBalance: .zero(), tokens: [], nfts: [], recentNFTs: [], liquidityTokens: [], delegate: nil, delegationLevel: nil)
self.balanceRequestDispathGroup.leave()

loadCachedExchangeDataIfNotLoaded()
Expand Down Expand Up @@ -536,6 +540,8 @@ public class BalanceService {

let newAccount = Account(walletAddress: self?.currentlyRefreshingAccount.walletAddress ?? "",
xtzBalance: self?.currentlyRefreshingAccount.xtzBalance ?? .zero(),
xtzStakedBalance: self?.currentlyRefreshingAccount.xtzStakedBalance ?? .zero(),
xtzUnstakedBalance: self?.currentlyRefreshingAccount.xtzUnstakedBalance ?? .zero(),
tokens: newTokens,
nfts: newNFTs,
recentNFTs: self?.currentlyRefreshingAccount.recentNFTs ?? [],
Expand Down
1 change: 0 additions & 1 deletion Kukai Mobile/Services/WalletConnectService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,6 @@ public class WalletConnectService {
Pair.configure(metadata: WalletConnectService.metadata)
Sign.configure(crypto: WC2CryptoProvider())


// Monitor connection
Networking.instance.socketConnectionStatusPublisher.sink { status in
Logger.app.info("WC2 - Connection status: changed to \(status == .connected ? "connected" : "disconnected")")
Expand Down
6 changes: 3 additions & 3 deletions Kukai MobileUITests/SharedHelpers.swift
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,9 @@ class SharedHelpers: XCTestCase {
// MARK: - Helpers

func application(resetForEveryInvocation: Bool = false) -> XCUIApplication {
sharedApplication.launchEnvironment = ["XCUITEST-KEYBOARD": "true"]
sharedApplication.launchEnvironment = ["XCUITEST-GHOSTNET": "true"]
sharedApplication.launchEnvironment = ["XCUITEST-STUB-XTZ-PRICE": "true"]
sharedApplication.launchEnvironment["XCUITEST-KEYBOARD"] = "true"
sharedApplication.launchEnvironment["XCUITEST-GHOSTNET"] = "true"
sharedApplication.launchEnvironment["XCUITEST-STUB-XTZ-PRICE"] = "true"


// When starting a new set of tests, clear all the data on the device so no lingering data from a previous failed test is present
Expand Down
94 changes: 93 additions & 1 deletion Kukai MobileUITests/Tests/Test_02_Onboarding.swift
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,7 @@ final class Test_02_Onboarding: XCTestCase {
// Navigate to wallet management
Test_03_Home.handleOpenWalletManagement(app: app)

Test_05_WalletManagement.addAccount(app: app, toWallet: testConfig.walletAddress_HD.truncateTezosAddress(), waitForNewAddress: testConfig.walletAddress_HD_account_1.truncateTezosAddress())
Test_05_WalletManagement.check(app: app, hasSections: 1)
Test_05_WalletManagement.check(app: app, hasWalletsOrAccounts: 2)

Expand Down Expand Up @@ -443,6 +444,75 @@ final class Test_02_Onboarding: XCTestCase {
Test_05_WalletManagement.deleteAllWallets(app: app)
}

func testImportPrivateKey_unencrypted() {
let app = XCUIApplication()
app.staticTexts["Already Have a Wallet"].tap()

Test_02_Onboarding.handleImportPrivateKey(app: app, key: "edsk3KvXD8SVD9GCyU4jbzaFba2HZRad5pQ7ajL79n7rUoc3nfHv5t", encryptedWith: nil)


// Confirm terms and conditions and create a passcode
SharedHelpers.shared.waitForButton("checkmark", exists: true, inElement: app, delay: 5)

app.buttons["checkmark"].tap()
app.staticTexts["Get Started"].tap()

// Create passcode
Test_02_Onboarding.handlePasscode(app: app)
Test_02_Onboarding.handlePasscode(app: app)
Test_04_Account.waitForInitalLoad(app: app)


// App state verification
Test_04_Account.waitForInitalLoad(app: app)


// Navigate to wallet management
Test_03_Home.handleOpenWalletManagement(app: app)

Test_05_WalletManagement.check(app: app, hasSections: 1)
Test_05_WalletManagement.check(app: app, hasWalletsOrAccounts: 1)

let details0 = Test_05_WalletManagement.getWalletDetails(app: app, index: 0)
XCTAssert(details0.title == "tz1Qvps...joCH", details0.title)

Test_05_WalletManagement.deleteAllWallets(app: app)
}

func testImportPrivateKey_encrypted() {
let app = XCUIApplication()
app.staticTexts["Already Have a Wallet"].tap()

Test_02_Onboarding.handleImportPrivateKey(app: app, key: "edesk1L8uVSYd3aug7jbeynzErQTnBxq6G6hJwmeue3yUBt11wp3ULXvcLwYRzDp4LWWvRFNJXRi3LaN7WGiEGhh", encryptedWith: "pa55word")


// Confirm terms and conditions and create a passcode
SharedHelpers.shared.waitForButton("checkmark", exists: true, inElement: app, delay: 5)

app.buttons["checkmark"].tap()
app.staticTexts["Get Started"].tap()

// Create passcode
Test_02_Onboarding.handlePasscode(app: app)
Test_02_Onboarding.handlePasscode(app: app)
Test_04_Account.waitForInitalLoad(app: app)


// App state verification
Test_04_Account.waitForInitalLoad(app: app)


// Navigate to wallet management
Test_03_Home.handleOpenWalletManagement(app: app)

Test_05_WalletManagement.check(app: app, hasSections: 1)
Test_05_WalletManagement.check(app: app, hasWalletsOrAccounts: 1)

let details0 = Test_05_WalletManagement.getWalletDetails(app: app, index: 0)
XCTAssert(details0.title == "tz1Xzte...GuMF", details0.title)

Test_05_WalletManagement.deleteAllWallets(app: app)
}


// MARK: - Helpers
Expand All @@ -469,6 +539,22 @@ final class Test_02_Onboarding: XCTestCase {
app.buttons["send-button"].tap()
}

public static func handleImportPrivateKey(app: XCUIApplication, key: String, encryptedWith: String?) {
app.tables.staticTexts["Import a Private Key"].tap()

app.scrollViews.children(matching: .textView).element.tap()
app.typeText(key)

if let pass = encryptedWith {
app.textFields.firstMatch.tap()
app.typeText(pass)
}

SharedHelpers.shared.typeDone(app: app)

app.buttons["Import"].tap()
}

public static func handleBasicImport(app: XCUIApplication, useAutoComplete: Bool) {
let testConfig = EnvironmentVariables.shared.config()
let seedPhrase = testConfig.seed
Expand Down Expand Up @@ -593,8 +679,14 @@ final class Test_02_Onboarding: XCTestCase {
sleep(2)
}


SharedHelpers.shared.waitForButton("Don’t Merge", exists: true, inElement: settingsApp, delay: 10)

let notNowButton = settingsApp.buttons["Not Now"]
if notNowButton.exists {
notNowButton.tap()
sleep(2)
}

settingsApp.buttons["Don’t Merge"].tap()

SharedHelpers.shared.waitForStaticText("Sign Out", exists: true, inElement: settingsApp, delay: 30)
Expand Down
10 changes: 4 additions & 6 deletions Kukai MobileUITests/Tests/Test_03_Home.swift
Original file line number Diff line number Diff line change
Expand Up @@ -28,20 +28,18 @@ final class Test_03_Home: XCTestCase {

func test_01_importWalletsNeeded() throws {
let app = XCUIApplication()

let testConfig = EnvironmentVariables.shared.config()

// Import the HD wallet and wait for the initial load
// This will be used for ghostnet to perform transactions
Test_02_Onboarding.handleBasicImport(app: app, useAutoComplete: false)

Test_03_Home.handleOpenWalletManagement(app: app)
sleep(2)
Test_05_WalletManagement.addAccount(app: app, toWallet: testConfig.walletAddress_HD.truncateTezosAddress(), waitForNewAddress: testConfig.walletAddress_HD_account_1.truncateTezosAddress())

Test_05_WalletManagement.addMore(app: app)

SharedHelpers.shared.tapSecondaryButton(app: app)
sleep(2)

app.staticTexts["Add Existing Wallet"].tap()
sleep(1)

// Import a known mainnet wallet as a watch wallet, allowing to perform mainnet checks like baker rewards
Test_02_Onboarding.handleImportWatchWallet_address(app: app, address: Test_05_WalletManagement.mainnetWatchWalletAddress)
Expand Down
9 changes: 6 additions & 3 deletions Kukai MobileUITests/Tests/Test_04_Account.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,6 @@ final class Test_04_Account: XCTestCase {

override func setUpWithError() throws {
continueAfterFailure = true

SharedHelpers.shared.application().launch()
}

override func tearDownWithError() throws {
Expand Down Expand Up @@ -388,7 +386,12 @@ final class Test_04_Account: XCTestCase {
bakerButton.tap()
sleep(2)

app.tables.staticTexts["Baking Benjamins"].tap()
let name = "Baking Benjamins"
if app.tables.staticTexts[name].exists {
app.tables.staticTexts["Baking Benjamins"].tap()
} else {
app.tables.staticTexts["tz1YgDU...4jnD"].tap()
}
sleep(2)

SharedHelpers.shared.tapPrimaryButton(app: app)
Expand Down
20 changes: 15 additions & 5 deletions Kukai MobileUITests/Tests/Test_05_WalletManagement.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ final class Test_05_WalletManagement: XCTestCase {
override func setUpWithError() throws {
continueAfterFailure = false

SharedHelpers.shared.application().launch()
XCUIApplication().launch()
}

override func tearDownWithError() throws {
Expand Down Expand Up @@ -123,10 +123,10 @@ final class Test_05_WalletManagement: XCTestCase {
Test_05_WalletManagement.addMore(app: app)
sleep(2)

SharedHelpers.shared.tapPrimaryButton(app: app)
sleep(2)
app.staticTexts["Create a New Wallet"].tap()
sleep(1)

SharedHelpers.shared.tapTertiaryButton(app: app)
app.staticTexts["HD Wallet"].tap()
sleep(2)

let count = app.tables.cells.containing(.staticText, identifier: "accounts-section-header").count
Expand All @@ -150,7 +150,6 @@ final class Test_05_WalletManagement: XCTestCase {




// MARK: - Helpers

public static func check(app: XCUIApplication, hasSections: Int) {
Expand All @@ -165,6 +164,17 @@ final class Test_05_WalletManagement: XCTestCase {
XCTAssert(count == hasWalletsOrAccounts, "\(count) != \(hasWalletsOrAccounts)")
}

public static func addAccount(app: XCUIApplication, toWallet: String, waitForNewAddress: String) {
app.navigationBars.buttons["accounts-nav-add"].tap()
sleep(1)

app.staticTexts["Add account to existing wallet"].tap()
sleep(1)

app.staticTexts[toWallet].tap()
SharedHelpers.shared.waitForStaticText(waitForNewAddress, exists: true, inElement: app, delay: 3)
}

public static func check(app: XCUIApplication, isInEditMode: Bool) {
SharedHelpers.shared.waitForImage("accounts-item-chevron", exists: isInEditMode, inElement: app.tables, delay: 1)

Expand Down
Loading

0 comments on commit 25b8105

Please sign in to comment.