Repository Public
1// SP Wallet Core2// File: Tests/SPWalletLiveTests/LiveTransferTests.swift3// Description: The complete send path against a throwaway stack whose Base network is a LOCAL anvil fork holding 1 fake ETH4// (Scripts/dev-stack.sh up-fork): draft → frozen intent → local verification of the challenge → passkey assertion →5// isolated signer → broadcast to the fork → confirmations. Plus the refusals: cancelled passkey, replayed assertion,6// rejected proposal, amount above the signer's limit. No real network ever receives anything.7// Skipped unless SPW_LIVE_ORIGIN is set and the stack was started with up-fork.8//9// Author: Simon-Pierre Boucher10// Contact: contact@spboucher.ai11import Foundation12import Testing13import SPWalletCore14import SPWalletTestSupport1516enum Fork {17 static var address: String? { try? String(contentsOfFile: Live.dir + "/fork-address", encoding: .utf8).trimmingCharacters(in: .whitespacesAndNewlines) }18 static var enabled: Bool { Live.enabled && address != nil }19 static var rpc: URL { URL(string: "http://127.0.0.1:\((URL(string: Live.origin!)!.port ?? 8750) + 2)")! }2021 @discardableResult static func call(_ method: String, _ params: String = "[]") async throws -> JSONValue {22 var r = URLRequest(url: rpc); r.httpMethod = "POST"23 r.setValue("application/json", forHTTPHeaderField: "Content-Type")24 r.httpBody = Data(#"{"jsonrpc":"2.0","id":1,"method":"\#(method)","params":\#(params)}"#.utf8)25 let (d, _) = try await URLSession.shared.data(for: r)26 return try JSONDecoder().decode(JSONValue.self, from: d)["result"] ?? .null27 }28 static func balance(_ address: String) async throws -> String { try await call("eth_getBalance", #"["\#(address)","latest"]"#).stringValue ?? "" }29 /** A fresh address that no one controls and that has never been used (20 random bytes, lower case: accepted without checksum). */30 static func freshAddress() -> String { "0x" + (0..<20).map { _ in String(format: "%02x", UInt8.random(in: 0...255)) }.joined() }31}3233@Suite(.enabled(if: Fork.enabled), .serialized) struct LiveTransferTests {34 @Test func aTransferGoesFromDraftToTheChainThroughTheSignerWithAPasskeyOverItsIntent() async throws {35 let (client, passkey) = try await Live.make()36 let t = TransfersAPI(client), to = Fork.freshAddress()37 let draft = try await t.draft(TransferRequest(network: "base", asset: "native", to: to, amount: "0.001", note: "live test"), idempotencyKey: APIClient.newIdempotencyKey())38 #expect(draft.state == .draft && draft.amount == "1000000000000000")39 #expect(draft.warnings?.contains("new_destination") == true)4041 let approval = try await t.requestApproval(for: draft)42 // what will be signed is what was asked43 #expect(approval.intent.kind == .transfer && approval.intent.network == "base" && approval.intent.amount == "1000000000000000")44 #expect(approval.intent.to.lowercased() == to && approval.intent.from == Fork.address)45 #expect(approval.intent.evm != nil && approval.intent.expiry > Date())46 #expect(approval.proposal.state == .pendingApproval)47 #expect(approval.proposal.intentHash == approval.approval.digest.hex)4849 let before = passkey.signedChallenges.count50 let sent = try await t.approve(approval, with: passkey)51 // the passkey signed exactly one challenge, and it is the hash of the intent that was reviewed52 #expect(passkey.signedChallenges.count == before + 1)53 #expect(passkey.signedChallenges.last == approval.approval.digest)54 #expect([.broadcast, .confirming, .finalized].contains(sent.state), "state after approval: \(sent.state)")55 #expect(sent.txid?.hasPrefix("0x") == true)5657 // the chain (the local fork) really moved the funds58 #expect(try await Fork.balance(to) == "0x38d7ea4c68000")59 // a broadcast transaction is not a confirmed one: the state only becomes final after the network confirms60 var last = try await t.status(draft.id)61 for _ in 0..<40 where !last.state.isTerminal {62 try await Fork.call("anvil_mine", #"["0x40"]"#)63 try await Task.sleep(for: .seconds(3))64 last = try await t.status(draft.id)65 }66 #expect(last.state == .finalized, "final state: \(last.state) \(last.error ?? "")")67 #expect((last.confirmations ?? 0) > 0)6869 let activity = try await WalletAPI(client).activity()70 #expect(activity.contains { $0.id == draft.id && $0.kind == "send" && $0.isSettled })7172 // replaying the same approval is refused: the proposal is single-use73 do { _ = try await t.approve(approval, with: passkey); Issue.record("a second approval of the same proposal must be refused") }74 catch let e as APIError { #expect(e.code == "bad_state") }75 }7677 @Test func aDismissedPasskeySignsNothingAndLeavesTheProposalPendingThenRejectable() async throws {78 let (client, passkey) = try await Live.make()79 let t = TransfersAPI(client), to = Fork.freshAddress()80 let draft = try await t.draft(TransferRequest(network: "base", asset: "native", to: to, amount: "0.0005"), idempotencyKey: APIClient.newIdempotencyKey())81 let approval = try await t.requestApproval(for: draft)82 let before = passkey.signedChallenges.count83 passkey.failNext = .cancelled84 await #expect(throws: PasskeyError.cancelled) { _ = try await t.approve(approval, with: passkey) }85 #expect(passkey.signedChallenges.count == before)86 #expect(try await t.proposal(draft.id).state == .pendingApproval)87 #expect(try await Fork.balance(to) == "0x0")88 #expect(try await t.reject(draft.id).state == .rejected)89 // once rejected it can no longer be approved, even with a valid assertion over its intent90 do { _ = try await t.approve(approval, with: passkey); Issue.record("a rejected proposal must not be approvable") }91 catch let e as APIError { #expect(e.code == "bad_state") }92 #expect(try await Fork.balance(to) == "0x0")93 }9495 @Test func anAssertionOverAnotherIntentIsRefusedByTheSigner() async throws {96 let (client, passkey) = try await Live.make()97 let t = TransfersAPI(client), toA = Fork.freshAddress(), toB = Fork.freshAddress()98 let a = try await t.requestApproval(for: try await t.draft(TransferRequest(network: "base", asset: "native", to: toA, amount: "0.0001"), idempotencyKey: APIClient.newIdempotencyKey()))99 // a passkey signature over the intent of A …100 let assertionForA = try await passkey.assert(a.approval.options, rpId: "localhost")101 _ = try await t.reject(a.proposal.id)102 // … presented for B (another destination) must not sign B103 let b = try await t.requestApproval(for: try await t.draft(TransferRequest(network: "base", asset: "native", to: toB, amount: "0.0001"), idempotencyKey: APIClient.newIdempotencyKey()))104 do { _ = try await t.submit(assertion: assertionForA, proposalId: b.proposal.id); Issue.record("the signer must refuse an assertion bound to another intent") }105 catch let e as APIError { #expect(e.status >= 400, "refused with \(e.code): \(e.message)") }106 #expect(try await Fork.balance(toB) == "0x0")107 #expect(try await t.proposal(b.proposal.id).state == .failed)108 }109110 @Test func anAmountAboveTheSignersLimitIsRefusedAtTheDraft() async throws {111 let (client, _) = try await Live.make()112 do {113 _ = try await TransfersAPI(client).draft(TransferRequest(network: "base", asset: "native", to: Fork.freshAddress(), amount: "0.5"), idempotencyKey: APIClient.newIdempotencyKey())114 Issue.record("0.5 ETH is above the per-transfer limit of the signer's policy")115 } catch let e as APIError { #expect(e.code == "policy" && e.status == 422) }116 }117}118