SPB Git

Repository Public

SwapUITests.swift 15.4 KB 290 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Wallet9// File             : UITests/SwapUITests.swift10// Description      : Interface tests of Échanger and Transférer entre réseaux11//                    against the THROWAWAY local stack (random keys, Base = a12//                    local fork holding fake ETH, software passkey). Quotes13//                    come from the real public aggregator APIs, read-only; when14//                    they are unreachable the tests assert the honest empty /15//                    error state instead. Nothing here touches production.16// Module           : UITests17// Repository       : https://git.spboucher.ai/sp-wallet-ios18// Created          : 2026-11-1819// Last Modified    : 2026-11-1820//21// =============================================================================22// AUTHOR & PROFESSIONAL AFFILIATION23// =============================================================================24//25// Author           : Simon-Pierre Boucher26// Position         : Professor of Finance27// Institution      : Université du Québec en Outaouais (UQO)28// Department       : Département des sciences administratives29// Organization     : SP Boucher30//31// Website          : https://spboucher.ai32// Git              : https://git.spboucher.ai33//34// =============================================================================35// OFFICIAL CONTACT DIRECTORY36// =============================================================================37//38// General          : info@spboucher.ai39// Professional     : contact@spboucher.ai40// Direct           : simon@spboucher.ai41// Research         : research@spboucher.ai42// Development      : dev@spboucher.ai43// Support          : support@spboucher.ai44// Security/Admin   : admin@spboucher.ai45// Notifications    : notifications@spboucher.ai46//47// Preferred Contact: support@spboucher.ai48//49// =============================================================================50// COPYRIGHT & INTELLECTUAL PROPERTY51// =============================================================================52//53// Copyright (c) 202654// Simon-Pierre Boucher55//56// All rights reserved where applicable.57//58// This file is governed by the applicable project license,59// copyright notices, institutional agreements and relevant law.60//61// Unless expressly authorized by the applicable license or62// rights holder, copying, redistribution, sublicensing,63// publication and commercial exploitation are not permitted.64//65// Existing third-party rights and notices remain unaffected.66//67// =============================================================================68// CONFIDENTIALITY & SECURITY69// =============================================================================70//71// Classification   : Public72// Distribution     : Public repository; use is governed by the project license73// Security Contact : admin@spboucher.ai74//75// Access to this source does not independently grant permission76// to redistribute or disclose confidential materials.77//78// Do not embed credentials, private keys, access tokens,79// certificates or confidential personal information.80//81// =============================================================================82// LICENSE & MAINTENANCE83// =============================================================================84//85// License          : None specified (no license file in this repository)86// Maintainer       : Simon-Pierre Boucher87// Technical Contact: dev@spboucher.ai88//89// =============================================================================90// END OF SP BOUCHER SOURCE HEADER91// =============================================================================9293import XCTest9495final class SwapUITests: XCTestCase {96    override func setUpWithError() throws {97        continueAfterFailure = false98        try XCTSkipUnless(Stack.isUp, "the throwaway stack is not running (dev-stack.sh up-fork)")99    }100101    private func any(_ app: XCUIApplication, _ id: String) -> XCUIElement { app.descendants(matching: .any)[id].firstMatch }102    private func openSection(_ app: XCUIApplication, _ section: String) {103        if isPad { go(app, section) } else { app.buttons["quick.\(section)"].tap() }104    }105    /** Open a menu and pick the entry whose label starts with `prefix`. */106    private func pick(_ app: XCUIApplication, menu: String, startsWith prefix: String, file: StaticString = #filePath, line: UInt = #line) {107        let m = any(app, menu)108        XCTAssertTrue(m.waitForExistence(timeout: 20), "menu \(menu)", file: file, line: line)109        m.tap()110        let item = app.buttons.matching(NSPredicate(format: "label BEGINSWITH %@", prefix)).firstMatch111        XCTAssertTrue(item.waitForExistence(timeout: 5), "entry \(prefix) of \(menu)", file: file, line: line)112        item.tap()113    }114    private func scrollTo(_ app: XCUIApplication, _ el: XCUIElement, max: Int = 8) {115        var n = 0116        while !(el.exists && el.isHittable), n < max { app.swipeUp(velocity: .slow); n += 1 }117    }118    /** Base, ETH → USDC, the given amount; no tolerance chosen yet. */119    private func fillSwap(_ app: XCUIApplication, amount: String) {120        pick(app, menu: "swap.network", startsWith: "Base")121        pick(app, menu: "swap.from", startsWith: "ETH")122        pick(app, menu: "swap.to", startsWith: "USDC")123        let field = app.textFields["swap.amount"]124        XCTAssertTrue(field.waitForExistence(timeout: 5)); field.tap(); field.typeText(amount)125    }126    /** Wait for the end of a quote search; true when at least one route can be picked. */127    private func waitForQuotes(_ app: XCUIApplication) -> Bool {128        let deadline = Date().addingTimeInterval(60)129        while Date() < deadline {130            if any(app, "swap.route.select.0").exists { return true }131            if any(app, "swap.quotes.error").exists || any(app, "swap.quotes.empty").exists || any(app, "swap.quotes.compareOnly").exists { return false }132            RunLoop.current.run(until: Date().addingTimeInterval(1))133        }134        return false135    }136137    func test1QuotesNeedAnExplicitToleranceAndNeverSelectARoute() {138        let app = signIn(Stack.app())139        openSection(app, "swap")140        XCTAssertTrue(any(app, "swap.network").waitForExistence(timeout: 20), "the swap form appears once the server's catalog is read")141        shot("swap-01-empty")142        fillSwap(app, amount: "0.001")143        let current = app.staticTexts["swap.slippage.current"]144        scrollTo(app, current)145        XCTAssertTrue(current.label.contains("choisir"), "no tolerance is preselected: \(current.label)")146        XCTAssertTrue(any(app, "swap.quotes.waiting").exists, "no quote is asked before the tolerance is chosen")147        shot("swap-02-no-tolerance")148        let half = app.buttons["swap.slippage.50"]149        scrollTo(app, half); half.tap()150        XCTAssertTrue(current.label.contains("0,5") || current.label.contains("0.5"), "the chosen tolerance stays visible: \(current.label)")151        let executable = waitForQuotes(app)152        app.swipeUp(velocity: .slow)153        shot("swap-03-quotes")154        let prepare = app.buttons["swap.prepare"]155        scrollTo(app, prepare)156        XCTAssertTrue(prepare.exists)157        XCTAssertFalse(prepare.isEnabled, "routes arriving select nothing: the owner has not picked one")158        shot("swap-04-nothing-picked")159        if !executable {160            XCTAssertTrue(any(app, "swap.quotes.error").exists || any(app, "swap.quotes.empty").exists || any(app, "swap.quotes.compareOnly").exists, "without an executable route the screen says why")161        }162        scrollTo(app, any(app, "swap.providers"))163        XCTAssertTrue(app.staticTexts["Exécute"].firstMatch.exists || app.staticTexts["Cotation seulement"].firstMatch.exists, "each provider says whether it executes or only quotes")164        shot("swap-05-providers")165    }166167    func test2SwapOnTheForkFromThePickedRouteToTheChainsAnswer() throws {168        try XCTSkipUnless(Stack.hasFork, "needs the local fork (dev-stack.sh up-fork)")169        let app = signIn(Stack.app())170        openSection(app, "swap")171        fillSwap(app, amount: "0.01")172        let half = app.buttons["swap.slippage.50"]173        scrollTo(app, half); half.tap()174        try XCTSkipUnless(waitForQuotes(app), "no executable quote from the public aggregator right now (state asserted in test1)")175        let select = any(app, "swap.route.select.0")176        scrollTo(app, select); select.tap()177        let prepare = app.buttons["swap.prepare"]178        scrollTo(app, prepare)179        let shownMin = any(app, "swap.selected.min")180        XCTAssertTrue(shownMin.exists, "the minimum of the picked route is restated next to the action")181        shot("swap-06-picked")182        XCTAssertTrue(prepare.isEnabled); prepare.tap()183184        // the server prepared a firm route and returned its intent; the Core verified it against the request and the challenge185        let amount = app.staticTexts["review.amount"]186        let refused = any(app, "op.error"), moved = any(app, "swap.quoteMoved"), lower = any(app, "swap.refused")187        func wait(_ seconds: TimeInterval) { let d = Date().addingTimeInterval(seconds); while Date() < d, !amount.exists, !refused.exists, !moved.exists, !lower.exists { RunLoop.current.run(until: Date().addingTimeInterval(0.5)) } }188        wait(60)189        if lower.exists {190            // the firm minimum came out below the minimum displayed: the app refused it, withdrew the proposal, shows both figures.191            // Taking the firm minimum is an explicit second choice, and the review must then say that it is lower.192            shot("swap-07-firm-minimum-lower")193            XCTAssertTrue(app.buttons["swap.requote"].exists, "a new quote is offered")194            let firm = app.buttons["swap.prepareFirm"]195            scrollTo(app, firm)196            try XCTSkipUnless(firm.isEnabled, "the quote expired meanwhile: only a new quote is offered (nothing was approved)")197            firm.tap()198            let d = Date().addingTimeInterval(60); while Date() < d, !amount.exists, !refused.exists, !moved.exists { RunLoop.current.run(until: Date().addingTimeInterval(0.5)) }199        }200        if !amount.exists, moved.exists || refused.exists {201            shot("swap-07-not-prepared")202            throw XCTSkip("the server refused the firm route (price moved or a limit): the refusal is shown as served; nothing was approved")203        }204        XCTAssertTrue(amount.exists, "the verified review appears")205        XCTAssertTrue(amount.label.contains("0,01") || amount.label.contains("0.01"), amount.label)206        XCTAssertTrue(amount.label.contains("ETH"))207        XCTAssertTrue(app.staticTexts["Minimum reçu garanti"].firstMatch.exists, "the guaranteed minimum is read from the intent")208        shot("swap-07-review")209        app.swipeUp(); shot("swap-08-review-2")210        let approve = app.buttons["op.approve"]211        scrollTo(app, approve)212        XCTAssertTrue(approve.exists); approve.tap()213214        let outcome = any(app, "optracker.outcome")215        XCTAssertTrue(outcome.waitForExistence(timeout: 60), "after the passkey the app follows the swap")216        shot("swap-09-tracking")217        // until the chain says so, nothing is shown as received218        let received = any(app, "optracker.received"), mined = any(app, "optracker.receivedNotFinal"), notYet = any(app, "optracker.notReceived")219        // the fork only mines when a transaction arrives: finality is reached when something else mines blocks (the run script does)220        let end = Date().addingTimeInterval(150)221        while Date() < end, !received.exists, !outcome.label.contains("Échoué") {222            if mined.exists { XCTAssertFalse(outcome.label.contains("confirmé"), "a mined, non-final swap is not announced as confirmed") }223            RunLoop.current.run(until: Date().addingTimeInterval(2))224        }225        shot("swap-10-outcome")226        XCTAssertFalse(outcome.label.contains("Échoué"), "state shown: \(outcome.label)")227        if received.exists {228            XCTAssertTrue(outcome.label.contains("confirmé"), "the final amount is shown only with the confirmed state: \(outcome.label)")229            XCTAssertTrue(received.label.contains("USDC"))230        } else {231            XCTAssertTrue(mined.exists || notYet.exists, "not final: the screen says so instead of showing a final amount")232            XCTAssertTrue(outcome.label.contains("En cours"), outcome.label)233        }234        app.buttons["op.done"].firstMatch.tap()235    }236237    func test3BridgeFormShowsServedSpeedsAndRefusesWhatCannotBeReceived() {238        let app = signIn(Stack.app())239        openSection(app, "bridge")240        XCTAssertTrue(any(app, "cctp.from").waitForExistence(timeout: 20), "the CCTP form lists the networks the server serves")241        pick(app, menu: "cctp.from", startsWith: "Base")242        pick(app, menu: "cctp.to", startsWith: "Arbitrum")243        let field = app.textFields["cctp.amount"]244        XCTAssertTrue(field.waitForExistence(timeout: 5)); field.tap(); field.typeText("5")245        shot("bridge-01-form")246        app.swipeUp(velocity: .slow)247        let standard = any(app, "cctp.speed.standard"), error = any(app, "cctp.quote.error")248        let deadline = Date().addingTimeInterval(40)249        while Date() < deadline, !standard.exists, !error.exists { RunLoop.current.run(until: Date().addingTimeInterval(0.5)) }250        XCTAssertTrue(standard.exists || error.exists, "the served speeds, or the server's refusal")251        shot("bridge-02-quote")252        let prepare = app.buttons["cctp.prepare"]253        scrollTo(app, prepare)254        XCTAssertTrue(prepare.exists)255        XCTAssertFalse(prepare.isEnabled, "no speed is chosen for the owner, and this wallet cannot pay the destination's gas")256        shot("bridge-03-blocked")257    }258259    /** Every sheet of the section resolves its environment (a missing object is a crash): opened on an unknown id, each shows the server's answer. */260    func test5EverySheetOfTheBridgeSectionOpens() {261        for (kind, close) in [("tracking", "op.close"), ("plan", "plan.close")] {262            let app = Stack.app()263            app.launchEnvironment["SPWALLET_UITEST_BRIDGE_SHEET"] = kind264            signIn(app)265            openSection(app, "bridge")266            let button = app.buttons[close]267            XCTAssertTrue(button.waitForExistence(timeout: 20), "the \(kind) sheet is presented")268            RunLoop.current.run(until: Date().addingTimeInterval(4)) // let it ask the server269            XCTAssertEqual(app.state, .runningForeground, "the sheet's content found its environment")270            shot("sheet-\(kind)")271            button.tap()272            XCTAssertTrue(any(app, "bridge.tool").waitForExistence(timeout: 10))273            app.terminate()274        }275    }276277    func test4CrossNetworkToolShowsServedCapabilities() {278        let app = signIn(Stack.app())279        openSection(app, "bridge")280        let tool = app.buttons["Échange entre réseaux"].firstMatch281        XCTAssertTrue(tool.waitForExistence(timeout: 20)); tool.tap()282        XCTAssertTrue(any(app, "cross.from").waitForExistence(timeout: 20))283        shot("cross-01-form")284        let caps = any(app, "cross.capabilities")285        scrollTo(app, caps)286        XCTAssertTrue(caps.waitForExistence(timeout: 20), "what the server serves (THORChain assets, plan limits) is displayed")287        shot("cross-02-capabilities")288    }289}290
Files main
Menu

Theme