diff --git a/packages/swift-sdk/Package.swift b/packages/swift-sdk/Package.swift index 5d7f4b2d8b1..8d4f1a60b8e 100644 --- a/packages/swift-sdk/Package.swift +++ b/packages/swift-sdk/Package.swift @@ -24,8 +24,16 @@ let package = Package( name: "SwiftDashSDK", dependencies: ["DashSDKFFI"], path: "Sources/SwiftDashSDK", - exclude: ["KeyWallet/README.md"] + exclude: ["KeyWallet/README.md"], + linkerSettings: [.linkedFramework("SystemConfiguration")] ), + + // Tests + .testTarget( + name: "SwiftDashSDKTests", + dependencies: ["SwiftDashSDK"], + path: "Tests/SwiftDashSDKTests" + ) ], swiftLanguageModes: [.v6] ) diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWallet.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWallet.swift index 908d4e8dab0..b55de97ffb2 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWallet.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWallet.swift @@ -15,7 +15,7 @@ public class PlatformWallet { } /// Create a new Platform Wallet from a 64-byte seed - public static func fromSeed(_ seed: Data) throws -> PlatformWallet { + public static func fromSeed(_ seed: Data, network: Network = .testnet) throws -> PlatformWallet { guard seed.count == 64 else { throw PlatformWalletError.invalidParameter } @@ -25,6 +25,7 @@ public class PlatformWallet { let result = seed.withUnsafeBytes { seedPtr in platform_wallet_info_create_from_seed( + network, seedPtr.baseAddress?.assumingMemoryBound(to: UInt8.self), seed.count, &handle, @@ -40,7 +41,11 @@ public class PlatformWallet { } /// Create a new Platform Wallet from a BIP39 mnemonic phrase - public static func fromMnemonic(_ mnemonic: String, passphrase: String? = nil) throws -> PlatformWallet { + public static func fromMnemonic( + _ mnemonic: String, + passphrase: String? = nil, + network: Network = .testnet + ) throws -> PlatformWallet { var handle: Handle = NULL_HANDLE var error = PlatformWalletFFIError() @@ -48,6 +53,7 @@ public class PlatformWallet { let passphraseCStr = passphrase != nil ? (passphrase! as NSString).utf8String : nil let result = platform_wallet_info_create_from_mnemonic( + network, mnemonicCStr, passphraseCStr, &handle, @@ -73,7 +79,6 @@ public class PlatformWallet { let result = platform_wallet_info_get_identity_manager( handle, - network.ffiValue, &managerHandle, &error ) @@ -93,7 +98,6 @@ public class PlatformWallet { let result = platform_wallet_info_set_identity_manager( handle, - network.ffiValue, manager.handle, &error ) diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletFFI.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletFFI.swift index e0b0215c14a..6aa222a3593 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletFFI.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletFFI.swift @@ -7,6 +7,7 @@ import Foundation @_silgen_name("platform_wallet_info_create_from_seed") func platform_wallet_info_create_from_seed( + _ network: Network, _ seed: UnsafePointer?, _ seed_len: Int, _ out_handle: UnsafeMutablePointer, @@ -15,6 +16,7 @@ func platform_wallet_info_create_from_seed( @_silgen_name("platform_wallet_info_create_from_mnemonic") func platform_wallet_info_create_from_mnemonic( + _ network: Network, _ mnemonic: UnsafePointer?, _ passphrase: UnsafePointer?, _ out_handle: UnsafeMutablePointer, @@ -24,7 +26,6 @@ func platform_wallet_info_create_from_mnemonic( @_silgen_name("platform_wallet_info_get_identity_manager") func platform_wallet_info_get_identity_manager( _ wallet_handle: Handle, - _ network: NetworkType, _ out_manager_handle: UnsafeMutablePointer, _ out_error: UnsafeMutablePointer ) -> PlatformWalletFFIResult @@ -32,7 +33,6 @@ func platform_wallet_info_get_identity_manager( @_silgen_name("platform_wallet_info_set_identity_manager") func platform_wallet_info_set_identity_manager( _ wallet_handle: Handle, - _ network: NetworkType, _ manager_handle: Handle, _ out_error: UnsafeMutablePointer ) -> PlatformWalletFFIResult diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletTypes.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletTypes.swift index 44062256899..284192d39c3 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletTypes.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletTypes.swift @@ -24,7 +24,8 @@ typealias NetworkType = UInt32 typealias PlatformWalletFFIResult = Int32 struct PlatformWalletFFIError { - var message: UnsafePointer? + var code: PlatformWalletFFIResult = 0 + var message: UnsafePointer? = nil } struct FFIBlockTime { @@ -33,19 +34,21 @@ struct FFIBlockTime { var timestamp: UInt64 } -// Error result codes (must match Rust enum values) +// Error result codes (must match Rust enum PlatformWalletFFIResult in rs-platform-wallet-ffi/src/error.rs) let Success: PlatformWalletFFIResult = 0 -let ErrorNullPointer: PlatformWalletFFIResult = 1 -let ErrorInvalidHandle: PlatformWalletFFIResult = 2 -let ErrorInvalidParameter: PlatformWalletFFIResult = 3 -let ErrorInvalidIdentifier: PlatformWalletFFIResult = 4 -let ErrorInvalidNetwork: PlatformWalletFFIResult = 5 +let ErrorInvalidHandle: PlatformWalletFFIResult = 1 +let ErrorInvalidParameter: PlatformWalletFFIResult = 2 +let ErrorNullPointer: PlatformWalletFFIResult = 3 +let ErrorSerialization: PlatformWalletFFIResult = 4 +let ErrorDeserialization: PlatformWalletFFIResult = 5 let ErrorWalletOperation: PlatformWalletFFIResult = 6 let ErrorIdentityNotFound: PlatformWalletFFIResult = 7 let ErrorContactNotFound: PlatformWalletFFIResult = 8 -let ErrorUtf8Conversion: PlatformWalletFFIResult = 9 -let ErrorSerialization: PlatformWalletFFIResult = 10 -let ErrorDeserialization: PlatformWalletFFIResult = 11 +let ErrorInvalidNetwork: PlatformWalletFFIResult = 9 +let ErrorInvalidIdentifier: PlatformWalletFFIResult = 10 +let ErrorMemoryAllocation: PlatformWalletFFIResult = 11 +let ErrorUtf8Conversion: PlatformWalletFFIResult = 12 +let ErrorUnknown: PlatformWalletFFIResult = 99 /// Platform Wallet error types public enum PlatformWalletError: Error { diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/SwiftDashSDK.swift b/packages/swift-sdk/Sources/SwiftDashSDK/SwiftDashSDK.swift index 4933dfb2961..28ad377672b 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/SwiftDashSDK.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/SwiftDashSDK.swift @@ -5,3 +5,14 @@ public typealias Network = DashSDKNetwork public typealias ErrorCode = DashSDKErrorCode public typealias SDKConfig = DashSDKConfig + +// Named constants for `Network` (imported from C as a raw-value struct +// without Swift case names). Raw values match the `DashSDKNetwork` C enum +// in rs-sdk-ffi.h. +public extension DashSDKNetwork { + static let mainnet = DashSDKNetwork(rawValue: 0) + static let testnet = DashSDKNetwork(rawValue: 1) + static let regtest = DashSDKNetwork(rawValue: 2) + static let devnet = DashSDKNetwork(rawValue: 3) + static let local = DashSDKNetwork(rawValue: 4) +} diff --git a/packages/swift-sdk/SwiftTests/Package.swift b/packages/swift-sdk/SwiftTests/Package.swift deleted file mode 100644 index 2500f1b1d86..00000000000 --- a/packages/swift-sdk/SwiftTests/Package.swift +++ /dev/null @@ -1,31 +0,0 @@ -// swift-tools-version: 6.0 -import PackageDescription - -let package = Package( - name: "SwiftDashSDKTests", - platforms: [ - .macOS(.v10_15), - .iOS(.v13) - ], - products: [ - .library( - name: "SwiftDashSDKTests", - targets: ["SwiftDashSDKTests"]), - ], - dependencies: [], - targets: [ - .target( - name: "SwiftDashSDKMock", - dependencies: [], - path: "Sources/SwiftDashSDKMock", - publicHeadersPath: "." - ), - .testTarget( - name: "SwiftDashSDKTests", - dependencies: ["SwiftDashSDKMock"], - path: "Tests/SwiftDashSDKTests", - exclude: ["*.o", "*.d", "*.swiftdeps"] - ), - ], - swiftLanguageVersions: [.v6] -) diff --git a/packages/swift-sdk/SwiftTests/Sources/SwiftDashSDKMock/SwiftDashSDK.h b/packages/swift-sdk/SwiftTests/Sources/SwiftDashSDKMock/SwiftDashSDK.h deleted file mode 100644 index 0238e502a2f..00000000000 --- a/packages/swift-sdk/SwiftTests/Sources/SwiftDashSDKMock/SwiftDashSDK.h +++ /dev/null @@ -1,329 +0,0 @@ -/* Generated with cbindgen:0.27.0 */ - -/* Warning, this file is autogenerated by cbindgen. Don't modify this manually. */ - -#include -#include -#include -#include -#include - -// Error codes for Swift Dash Platform operations -typedef enum SwiftDashSwiftDashErrorCode { - // Operation completed successfully - Success = 0, - // Invalid parameter passed to function - InvalidParameter = 1, - // SDK not initialized or in invalid state - InvalidState = 2, - // Network error occurred - NetworkError = 3, - // Serialization/deserialization error - SerializationError = 4, - // Platform protocol error - ProtocolError = 5, - // Cryptographic operation failed - CryptoError = 6, - // Resource not found - NotFound = 7, - // Operation timed out - Timeout = 8, - // Feature not implemented - NotImplemented = 9, - // Internal error - InternalError = 99, -} SwiftDashSwiftDashErrorCode; - -// Network types for Dash Platform -typedef enum SwiftDashSwiftDashNetwork { - Mainnet = 0, - Testnet = 1, - Devnet = 2, - Local = 3, -} SwiftDashSwiftDashNetwork; - -// Opaque handle to an SDK instance -typedef struct SwiftDashSDKHandle SwiftDashSDKHandle; - -// Error structure for Swift interop -typedef struct SwiftDashSwiftDashError { - // Error code - enum SwiftDashSwiftDashErrorCode code; - // Human-readable error message (null-terminated C string) - // Caller must free this with swift_dash_error_free - char *message; -} SwiftDashSwiftDashError; - -// Swift result that wraps either success or error -typedef struct SwiftDashSwiftDashResult { - bool success; - void *data; - struct SwiftDashSwiftDashError *error; -} SwiftDashSwiftDashResult; - -// Information about a data contract -typedef struct SwiftDashSwiftDashDataContractInfo { - char *id; - char *owner_id; - uint32_t version; - char *schema_json; -} SwiftDashSwiftDashDataContractInfo; - -// Information about a document -typedef struct SwiftDashSwiftDashDocumentInfo { - char *id; - char *owner_id; - char *data_contract_id; - char *document_type; - uint64_t revision; - int64_t created_at; - int64_t updated_at; -} SwiftDashSwiftDashDocumentInfo; - -// Information about an identity -typedef struct SwiftDashSwiftDashIdentityInfo { - char *id; - uint64_t balance; - uint64_t revision; - uint32_t public_keys_count; -} SwiftDashSwiftDashIdentityInfo; - -// Result of a credit transfer operation -typedef struct SwiftDashSwiftDashTransferCreditsResult { - uint64_t amount; - char *recipient_id; - uint8_t *transaction_data; - size_t transaction_data_len; -} SwiftDashSwiftDashTransferCreditsResult; - -// Binary data container for results -typedef struct SwiftDashSwiftDashBinaryData { - uint8_t *data; - size_t len; -} SwiftDashSwiftDashBinaryData; - -// Configuration for the Swift Dash Platform SDK -typedef struct SwiftDashSwiftDashSDKConfig { - enum SwiftDashSwiftDashNetwork network; - const char *dapi_addresses; -} SwiftDashSwiftDashSDKConfig; - -// Settings for put operations -typedef struct SwiftDashSwiftDashPutSettings { - uint64_t connect_timeout_ms; - uint64_t timeout_ms; - uint32_t retries; - bool ban_failed_address; - uint64_t identity_nonce_stale_time_s; - uint16_t user_fee_increase; - bool allow_signing_with_any_security_level; - bool allow_signing_with_any_purpose; - uint64_t wait_timeout_ms; -} SwiftDashSwiftDashPutSettings; - -// Swift-compatible signer interface -// -// This represents a callback-based signer for iOS/Swift applications. -// The actual signer implementation will be provided by the iOS app. -// Type alias for signing callback -typedef unsigned char *(*SwiftDashSwiftSignCallback)(const unsigned char *identity_public_key_bytes, - size_t identity_public_key_len, - const unsigned char *data, - size_t data_len, - size_t *result_len); - -// Type alias for can_sign callback -typedef bool (*SwiftDashSwiftCanSignCallback)(const unsigned char *identity_public_key_bytes, - size_t identity_public_key_len); - -// Swift signer configuration -typedef struct SwiftDashSwiftDashSigner { - SwiftDashSwiftSignCallback sign_callback; - SwiftDashSwiftCanSignCallback can_sign_callback; -} SwiftDashSwiftDashSigner; - -// Token information -typedef struct SwiftDashSwiftDashTokenInfo { - char *contract_id; - char *name; - char *symbol; - uint64_t total_supply; - uint8_t decimals; -} SwiftDashSwiftDashTokenInfo; - -// Initialize the Swift SDK library. -// This should be called once at app startup before using any other functions. -void swift_dash_sdk_init(void); - -// Get the version of the Swift Dash SDK library -const char *swift_dash_sdk_version(void); - -// Fetch a data contract by ID -char *swift_dash_data_contract_fetch(const struct SwiftDashSDKHandle *sdk_handle, - const char *contract_id); - -// Get data contract history -char *swift_dash_data_contract_get_history(const struct SwiftDashSDKHandle *sdk_handle, - const char *contract_id, - uint32_t limit, - uint32_t offset); - -// Create a new data contract (simplified - returns not implemented) -struct SwiftDashSwiftDashResult swift_dash_data_contract_create(const struct SwiftDashSDKHandle *sdk_handle, - const char *schema_json, - const char *owner_id); - -// Update an existing data contract (simplified - returns not implemented) -struct SwiftDashSwiftDashResult swift_dash_data_contract_update(const struct SwiftDashSDKHandle *sdk_handle, - const char *contract_id, - const char *schema_json, - uint32_t version); - -// Free data contract info structure -void swift_dash_data_contract_info_free(struct SwiftDashSwiftDashDataContractInfo *info); - -// Fetch a document by ID (simplified - returns not implemented) -char *swift_dash_document_fetch(const struct SwiftDashSDKHandle *sdk_handle, - const char *data_contract_id, - const char *document_type, - const char *document_id); - -// Search for documents (simplified - returns not implemented) -char *swift_dash_document_search(const struct SwiftDashSDKHandle *sdk_handle, - const char *data_contract_id, - const char *document_type, - const char *query_json, - uint32_t limit); - -// Create a new document (simplified - returns not implemented) -struct SwiftDashSwiftDashResult swift_dash_document_create(const struct SwiftDashSDKHandle *sdk_handle, - const char *data_contract_id, - const char *document_type, - const char *properties_json, - const char *identity_id); - -// Update an existing document (simplified - returns not implemented) -struct SwiftDashSwiftDashResult swift_dash_document_update(const struct SwiftDashSDKHandle *sdk_handle, - const char *document_id, - const char *properties_json, - uint64_t revision); - -// Delete a document (simplified - returns not implemented) -struct SwiftDashSwiftDashResult swift_dash_document_delete(const struct SwiftDashSDKHandle *sdk_handle, - const char *document_id); - -// Free document info structure -void swift_dash_document_info_free(struct SwiftDashSwiftDashDocumentInfo *info); - -// Free an error message -void swift_dash_error_free(struct SwiftDashSwiftDashError *error); - -// Free a C string allocated by Swift SDK -void swift_dash_string_free(char *s); - -// Free bytes allocated by callback functions -void swift_dash_bytes_free(uint8_t *bytes, size_t len); - -// Fetch an identity by ID -char *swift_dash_identity_fetch(const struct SwiftDashSDKHandle *sdk_handle, - const char *identity_id); - -// Get identity balance -uint64_t swift_dash_identity_get_balance(const struct SwiftDashSDKHandle *sdk_handle, - const char *identity_id); - -// Resolve identity name -char *swift_dash_identity_resolve_name(const struct SwiftDashSDKHandle *sdk_handle, - const char *name); - -// Transfer credits (simplified implementation) -struct SwiftDashSwiftDashResult swift_dash_identity_transfer_credits(const struct SwiftDashSDKHandle *sdk_handle, - const char *from_identity_id, - const char *to_identity_id, - uint64_t amount, - const uint8_t *private_key, - size_t private_key_len); - -// Create a new identity (mock for now) -struct SwiftDashSwiftDashResult swift_dash_identity_create(const struct SwiftDashSDKHandle *sdk_handle, - const uint8_t *public_key, - size_t public_key_len); - -// Free identity info structure -void swift_dash_identity_info_free(struct SwiftDashSwiftDashIdentityInfo *info); - -// Free transfer result structure -void swift_dash_transfer_credits_result_free(struct SwiftDashSwiftDashTransferCreditsResult *result); - -// Free binary data structure -void swift_dash_binary_data_free(struct SwiftDashSwiftDashBinaryData *data); - -// Create a new SDK instance -struct SwiftDashSDKHandle *swift_dash_sdk_create(struct SwiftDashSwiftDashSDKConfig config); - -// Destroy an SDK instance -void swift_dash_sdk_destroy(struct SwiftDashSDKHandle *handle); - -// Get the network the SDK is configured for -enum SwiftDashSwiftDashNetwork swift_dash_sdk_get_network(const struct SwiftDashSDKHandle *handle); - -// Get SDK version -const char *swift_dash_sdk_get_version(void); - -// Create default settings for put operations -struct SwiftDashSwiftDashPutSettings swift_dash_put_settings_default(void); - -// Create default config for mainnet -struct SwiftDashSwiftDashSDKConfig swift_dash_sdk_config_mainnet(void); - -// Create default config for testnet -struct SwiftDashSwiftDashSDKConfig swift_dash_sdk_config_testnet(void); - -// Create default config for local development -struct SwiftDashSwiftDashSDKConfig swift_dash_sdk_config_local(void); - -// Create a new signer with callbacks -struct SwiftDashSwiftDashSigner *swift_dash_signer_create(SwiftDashSwiftSignCallback sign_callback, - SwiftDashSwiftCanSignCallback can_sign_callback); - -// Free a signer -void swift_dash_signer_free(struct SwiftDashSwiftDashSigner *signer); - -// Test if a signer can sign with a given key -bool swift_dash_signer_can_sign(const struct SwiftDashSwiftDashSigner *signer, - const unsigned char *identity_public_key_bytes, - size_t identity_public_key_len); - -// Sign data with a signer -unsigned char *swift_dash_signer_sign(const struct SwiftDashSwiftDashSigner *signer, - const unsigned char *identity_public_key_bytes, - size_t identity_public_key_len, - const unsigned char *data, - size_t data_len, - size_t *result_len); - -// Get token total supply -char *swift_dash_token_get_total_supply(const struct SwiftDashSDKHandle *sdk_handle, - const char *token_contract_id); - -// Transfer tokens (simplified - returns not implemented) -struct SwiftDashSwiftDashResult swift_dash_token_transfer(const struct SwiftDashSDKHandle *sdk_handle, - const char *token_contract_id, - const char *from_identity_id, - const char *to_identity_id, - uint64_t amount); - -// Mint tokens (simplified - returns not implemented) -struct SwiftDashSwiftDashResult swift_dash_token_mint(const struct SwiftDashSDKHandle *sdk_handle, - const char *token_contract_id, - const char *to_identity_id, - uint64_t amount); - -// Burn tokens (simplified - returns not implemented) -struct SwiftDashSwiftDashResult swift_dash_token_burn(const struct SwiftDashSDKHandle *sdk_handle, - const char *token_contract_id, - const char *from_identity_id, - uint64_t amount); - -// Free token info structure -void swift_dash_token_info_free(struct SwiftDashSwiftDashTokenInfo *info); diff --git a/packages/swift-sdk/SwiftTests/Sources/SwiftDashSDKMock/SwiftDashSDKMock.c b/packages/swift-sdk/SwiftTests/Sources/SwiftDashSDKMock/SwiftDashSDKMock.c deleted file mode 100644 index 6b92b3ca16c..00000000000 --- a/packages/swift-sdk/SwiftTests/Sources/SwiftDashSDKMock/SwiftDashSDKMock.c +++ /dev/null @@ -1,441 +0,0 @@ -// Test-only C mock implementation of SwiftDashSDK FFI, linked by SwiftTests/Package.swift target `SwiftDashSDKMock`. -// Used by SwiftTests unit tests to exercise Swift wrapper behavior without depending on a real Rust backend. - -#include "SwiftDashSDK.h" -#include -#include -#include -#include - -// Global state for testing -static int g_initialized = 0; -static int g_sdk_count = 0; - -// Test configuration data -static const char* g_existing_identity_id = "4EfA9Jrvv3nnCFdSf7fad59851iiTRZ6Wcu6YVJ4iSeF"; -static const char* g_existing_data_contract_id = "GWRSAVFMjXx8HpQFaNJMqBV7MBgMK4br5UESsB4S31Ec"; - -// Error helper -static struct SwiftDashSwiftDashError* create_error(enum SwiftDashSwiftDashErrorCode code, const char* message) { - struct SwiftDashSwiftDashError* error = malloc(sizeof(struct SwiftDashSwiftDashError)); - error->code = code; - error->message = strdup(message); - return error; -} - -// Result helpers -static struct SwiftDashSwiftDashResult success_result(void* data) { - struct SwiftDashSwiftDashResult result = { - .success = true, - .data = data, - .error = NULL - }; - return result; -} - -static struct SwiftDashSwiftDashResult error_result(enum SwiftDashSwiftDashErrorCode code, const char* message) { - struct SwiftDashSwiftDashResult result = { - .success = false, - .data = NULL, - .error = create_error(code, message) - }; - return result; -} - -// Mock implementations - -void swift_dash_sdk_init(void) { - g_initialized = 1; -} - -const char *swift_dash_sdk_version(void) { - return "2.0.0-mock"; -} - -struct SwiftDashSDKHandle *swift_dash_sdk_create(struct SwiftDashSwiftDashSDKConfig config) { - if (!g_initialized) return NULL; - - g_sdk_count++; - // Return a non-null dummy pointer - return (struct SwiftDashSDKHandle *)((uintptr_t)0x1000 + g_sdk_count); -} - -void swift_dash_sdk_destroy(struct SwiftDashSDKHandle *handle) { - if (handle != NULL) { - g_sdk_count--; - } -} - -enum SwiftDashSwiftDashNetwork swift_dash_sdk_get_network(const struct SwiftDashSDKHandle *handle) { - if (handle == NULL) { - return Testnet; // Default - } - // Mock: return testnet for simplicity - return Testnet; -} - -const char *swift_dash_sdk_get_version(void) { - return strdup("2.0.0-mock"); -} - -struct SwiftDashSwiftDashSDKConfig swift_dash_sdk_config_mainnet(void) { - struct SwiftDashSwiftDashSDKConfig config = { - .network = Mainnet, - .dapi_addresses = "mainnet-seeds.dash.org:443" - }; - return config; -} - -struct SwiftDashSwiftDashSDKConfig swift_dash_sdk_config_testnet(void) { - struct SwiftDashSwiftDashSDKConfig config = { - .network = Testnet, - .dapi_addresses = "testnet-seeds.dash.org:443" - }; - return config; -} - -struct SwiftDashSwiftDashSDKConfig swift_dash_sdk_config_local(void) { - struct SwiftDashSwiftDashSDKConfig config = { - .network = Local, - .dapi_addresses = "127.0.0.1:3000" - }; - return config; -} - -struct SwiftDashSwiftDashPutSettings swift_dash_put_settings_default(void) { - struct SwiftDashSwiftDashPutSettings settings = { - .connect_timeout_ms = 0, - .timeout_ms = 0, - .retries = 0, - .ban_failed_address = false, - .identity_nonce_stale_time_s = 0, - .user_fee_increase = 0, - .allow_signing_with_any_security_level = false, - .allow_signing_with_any_purpose = false, - .wait_timeout_ms = 0 - }; - return settings; -} - -// Identity functions -char *swift_dash_identity_fetch(const struct SwiftDashSDKHandle *sdk_handle, const char *identity_id) { - if (sdk_handle == NULL || identity_id == NULL) return NULL; - - // Return null for non-existent identities - if (strcmp(identity_id, "1111111111111111111111111111111111111111111") == 0) { - return NULL; - } - - // Return mock identity JSON for known identity - if (strcmp(identity_id, g_existing_identity_id) == 0) { - const char* json = "{\"id\":\"4EfA9Jrvv3nnCFdSf7fad59851iiTRZ6Wcu6YVJ4iSeF\",\"publicKeys\":[{\"id\":0,\"type\":0,\"purpose\":0,\"securityLevel\":2,\"data\":\"test_key\"}]}"; - return strdup(json); - } - - return NULL; -} - -uint64_t swift_dash_identity_get_balance(const struct SwiftDashSDKHandle *sdk_handle, const char *identity_id) { - if (sdk_handle == NULL || identity_id == NULL) return 0; - - if (strcmp(identity_id, g_existing_identity_id) == 0) { - return 1000000; // Mock balance - } - - return 0; -} - -char *swift_dash_identity_resolve_name(const struct SwiftDashSDKHandle *sdk_handle, const char *name) { - if (sdk_handle == NULL || name == NULL) return NULL; - - if (strcmp(name, "dash") == 0) { - const char* json = "{\"identity\":\"4EfA9Jrvv3nnCFdSf7fad59851iiTRZ6Wcu6YVJ4iSeF\",\"alias\":\"dash\"}"; - return strdup(json); - } - - return NULL; -} - -struct SwiftDashSwiftDashResult swift_dash_identity_transfer_credits(const struct SwiftDashSDKHandle *sdk_handle, - const char *from_identity_id, - const char *to_identity_id, - uint64_t amount, - const uint8_t *private_key, - size_t private_key_len) { - if (sdk_handle == NULL || from_identity_id == NULL || to_identity_id == NULL || private_key == NULL) { - return error_result(InvalidParameter, "Missing required parameters"); - } - - return error_result(NotImplemented, "Credit transfer not yet implemented"); -} - -struct SwiftDashSwiftDashResult swift_dash_identity_create(const struct SwiftDashSDKHandle *sdk_handle, - const uint8_t *public_key, - size_t public_key_len) { - if (sdk_handle == NULL || public_key == NULL) { - return error_result(InvalidParameter, "Missing required parameters"); - } - - return error_result(NotImplemented, "Identity creation not yet implemented"); -} - -// Data contract functions -char *swift_dash_data_contract_fetch(const struct SwiftDashSDKHandle *sdk_handle, const char *contract_id) { - if (sdk_handle == NULL || contract_id == NULL) return NULL; - - // Return null for non-existent contracts - if (strcmp(contract_id, "1111111111111111111111111111111111111111111") == 0) { - return NULL; - } - - // Return mock contract JSON for known contract - if (strcmp(contract_id, g_existing_data_contract_id) == 0) { - const char* json = "{\"id\":\"GWRSAVFMjXx8HpQFaNJMqBV7MBgMK4br5UESsB4S31Ec\",\"version\":1,\"documents\":{\"domain\":{\"type\":\"object\"}}}"; - return strdup(json); - } - - return NULL; -} - -char *swift_dash_data_contract_get_history(const struct SwiftDashSDKHandle *sdk_handle, - const char *contract_id, - uint32_t limit, - uint32_t offset) { - if (sdk_handle == NULL || contract_id == NULL) return NULL; - - if (strcmp(contract_id, g_existing_data_contract_id) == 0) { - const char* json = "{\"contract_id\":\"GWRSAVFMjXx8HpQFaNJMqBV7MBgMK4br5UESsB4S31Ec\",\"history\":[]}"; - return strdup(json); - } - - return NULL; -} - -struct SwiftDashSwiftDashResult swift_dash_data_contract_create(const struct SwiftDashSDKHandle *sdk_handle, - const char *schema_json, - const char *owner_id) { - if (sdk_handle == NULL || schema_json == NULL || owner_id == NULL) { - return error_result(InvalidParameter, "Missing required parameters"); - } - - return error_result(NotImplemented, "Data contract creation not yet implemented"); -} - -struct SwiftDashSwiftDashResult swift_dash_data_contract_update(const struct SwiftDashSDKHandle *sdk_handle, - const char *contract_id, - const char *schema_json, - uint32_t version) { - if (sdk_handle == NULL || contract_id == NULL || schema_json == NULL) { - return error_result(InvalidParameter, "Missing required parameters"); - } - - return error_result(NotImplemented, "Data contract update not yet implemented"); -} - -// Document functions -char *swift_dash_document_fetch(const struct SwiftDashSDKHandle *sdk_handle, - const char *data_contract_id, - const char *document_type, - const char *document_id) { - if (sdk_handle == NULL || data_contract_id == NULL || document_type == NULL || document_id == NULL) { - return NULL; - } - - return NULL; // Document fetching not implemented in mock -} - -char *swift_dash_document_search(const struct SwiftDashSDKHandle *sdk_handle, - const char *data_contract_id, - const char *document_type, - const char *query_json, - uint32_t limit) { - if (sdk_handle == NULL || data_contract_id == NULL || document_type == NULL) { - return NULL; - } - - return NULL; // Document search not implemented in mock -} - -struct SwiftDashSwiftDashResult swift_dash_document_create(const struct SwiftDashSDKHandle *sdk_handle, - const char *data_contract_id, - const char *document_type, - const char *properties_json, - const char *identity_id) { - if (sdk_handle == NULL || data_contract_id == NULL || document_type == NULL) { - return error_result(InvalidParameter, "Missing required parameters"); - } - - return error_result(NotImplemented, "Document creation not yet implemented"); -} - -struct SwiftDashSwiftDashResult swift_dash_document_update(const struct SwiftDashSDKHandle *sdk_handle, - const char *document_id, - const char *properties_json, - uint64_t revision) { - if (sdk_handle == NULL || document_id == NULL) { - return error_result(InvalidParameter, "Missing required parameters"); - } - - return error_result(NotImplemented, "Document update not yet implemented"); -} - -struct SwiftDashSwiftDashResult swift_dash_document_delete(const struct SwiftDashSDKHandle *sdk_handle, - const char *document_id) { - if (sdk_handle == NULL || document_id == NULL) { - return error_result(InvalidParameter, "Missing required parameters"); - } - - return error_result(NotImplemented, "Document deletion not yet implemented"); -} - -// Signer functions -struct SwiftDashSwiftDashSigner *swift_dash_signer_create(SwiftDashSwiftSignCallback sign_callback, - SwiftDashSwiftCanSignCallback can_sign_callback) { - if (sign_callback == NULL || can_sign_callback == NULL) return NULL; - - struct SwiftDashSwiftDashSigner *signer = malloc(sizeof(struct SwiftDashSwiftDashSigner)); - signer->sign_callback = sign_callback; - signer->can_sign_callback = can_sign_callback; - return signer; -} - -void swift_dash_signer_free(struct SwiftDashSwiftDashSigner *signer) { - if (signer != NULL) { - free(signer); - } -} - -bool swift_dash_signer_can_sign(const struct SwiftDashSwiftDashSigner *signer, - const unsigned char *identity_public_key_bytes, - size_t identity_public_key_len) { - if (signer == NULL || identity_public_key_bytes == NULL) return false; - - return signer->can_sign_callback(identity_public_key_bytes, identity_public_key_len); -} - -unsigned char *swift_dash_signer_sign(const struct SwiftDashSwiftDashSigner *signer, - const unsigned char *identity_public_key_bytes, - size_t identity_public_key_len, - const unsigned char *data, - size_t data_len, - size_t *result_len) { - if (signer == NULL || identity_public_key_bytes == NULL || data == NULL || result_len == NULL) { - return NULL; - } - - return signer->sign_callback(identity_public_key_bytes, identity_public_key_len, data, data_len, result_len); -} - -// Token functions -char *swift_dash_token_get_total_supply(const struct SwiftDashSDKHandle *sdk_handle, const char *token_contract_id) { - if (sdk_handle == NULL || token_contract_id == NULL) return NULL; - - // Mock token supply - return strdup("1000000000"); -} - -struct SwiftDashSwiftDashResult swift_dash_token_transfer(const struct SwiftDashSDKHandle *sdk_handle, - const char *token_contract_id, - const char *from_identity_id, - const char *to_identity_id, - uint64_t amount) { - if (sdk_handle == NULL || token_contract_id == NULL || from_identity_id == NULL || to_identity_id == NULL) { - return error_result(InvalidParameter, "Missing required parameters"); - } - - return error_result(NotImplemented, "Token transfer not yet implemented"); -} - -struct SwiftDashSwiftDashResult swift_dash_token_mint(const struct SwiftDashSDKHandle *sdk_handle, - const char *token_contract_id, - const char *to_identity_id, - uint64_t amount) { - if (sdk_handle == NULL || token_contract_id == NULL || to_identity_id == NULL) { - return error_result(InvalidParameter, "Missing required parameters"); - } - - return error_result(NotImplemented, "Token minting not yet implemented"); -} - -struct SwiftDashSwiftDashResult swift_dash_token_burn(const struct SwiftDashSDKHandle *sdk_handle, - const char *token_contract_id, - const char *from_identity_id, - uint64_t amount) { - if (sdk_handle == NULL || token_contract_id == NULL || from_identity_id == NULL) { - return error_result(InvalidParameter, "Missing required parameters"); - } - - return error_result(NotImplemented, "Token burning not yet implemented"); -} - -// Memory management -void swift_dash_error_free(struct SwiftDashSwiftDashError *error) { - if (error != NULL) { - if (error->message != NULL) { - free(error->message); - } - free(error); - } -} - -void swift_dash_string_free(char *s) { - if (s != NULL) { - free(s); - } -} - -void swift_dash_bytes_free(uint8_t *bytes, size_t len) { - if (bytes != NULL) { - free(bytes); - } -} - -void swift_dash_identity_info_free(struct SwiftDashSwiftDashIdentityInfo *info) { - if (info != NULL) { - if (info->id != NULL) free(info->id); - free(info); - } -} - -void swift_dash_document_info_free(struct SwiftDashSwiftDashDocumentInfo *info) { - if (info != NULL) { - if (info->id != NULL) free(info->id); - if (info->owner_id != NULL) free(info->owner_id); - if (info->data_contract_id != NULL) free(info->data_contract_id); - if (info->document_type != NULL) free(info->document_type); - free(info); - } -} - -void swift_dash_data_contract_info_free(struct SwiftDashSwiftDashDataContractInfo *info) { - if (info != NULL) { - if (info->id != NULL) free(info->id); - if (info->owner_id != NULL) free(info->owner_id); - if (info->schema_json != NULL) free(info->schema_json); - free(info); - } -} - -void swift_dash_binary_data_free(struct SwiftDashSwiftDashBinaryData *data) { - if (data != NULL) { - if (data->data != NULL) free(data->data); - free(data); - } -} - -void swift_dash_transfer_credits_result_free(struct SwiftDashSwiftDashTransferCreditsResult *result) { - if (result != NULL) { - if (result->recipient_id != NULL) free(result->recipient_id); - if (result->transaction_data != NULL) free(result->transaction_data); - free(result); - } -} - -void swift_dash_token_info_free(struct SwiftDashSwiftDashTokenInfo *info) { - if (info != NULL) { - if (info->contract_id != NULL) free(info->contract_id); - if (info->name != NULL) free(info->name); - if (info->symbol != NULL) free(info->symbol); - free(info); - } -} diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDK.h b/packages/swift-sdk/SwiftTests/SwiftDashSDK.h deleted file mode 100644 index 53e14b4537a..00000000000 --- a/packages/swift-sdk/SwiftTests/SwiftDashSDK.h +++ /dev/null @@ -1,191 +0,0 @@ -// Mock header file for Swift Dash SDK -// This represents what would be generated by cbindgen - -#ifndef SWIFT_DASH_SDK_H -#define SWIFT_DASH_SDK_H - -#include -#include -#include - -// Error codes -typedef enum { - SwiftDashErrorCode_Success = 0, - SwiftDashErrorCode_InvalidParameter = 1, - SwiftDashErrorCode_InvalidState = 2, - SwiftDashErrorCode_NetworkError = 3, - SwiftDashErrorCode_SerializationError = 4, - SwiftDashErrorCode_ProtocolError = 5, - SwiftDashErrorCode_CryptoError = 6, - SwiftDashErrorCode_NotFound = 7, - SwiftDashErrorCode_Timeout = 8, - SwiftDashErrorCode_NotImplemented = 9, - SwiftDashErrorCode_InternalError = 99, -} SwiftDashErrorCode; - -// Network types -typedef enum { - SwiftDashNetwork_Mainnet = 0, - SwiftDashNetwork_Testnet = 1, - SwiftDashNetwork_Devnet = 2, - SwiftDashNetwork_Local = 3, -} SwiftDashNetwork; - -// Opaque handle types -typedef struct SDKHandle SDKHandle; -typedef struct IdentityHandle IdentityHandle; -typedef struct DataContractHandle DataContractHandle; -typedef struct DocumentHandle DocumentHandle; -typedef struct SignerHandle SignerHandle; - -// Error structure -typedef struct { - SwiftDashErrorCode code; - char *message; -} SwiftDashError; - -// SDK Configuration -typedef struct { - SwiftDashNetwork network; - bool skip_asset_lock_proof_verification; - uint32_t request_retry_count; - uint64_t request_timeout_ms; -} SwiftDashSDKConfig; - -// Put settings -typedef struct { - uint64_t connect_timeout_ms; - uint64_t timeout_ms; - uint32_t retries; - bool ban_failed_address; - uint64_t identity_nonce_stale_time_s; - uint16_t user_fee_increase; - bool allow_signing_with_any_security_level; - bool allow_signing_with_any_purpose; - uint64_t wait_timeout_ms; -} SwiftDashPutSettings; - -// Identity info -typedef struct { - char *id; - uint64_t balance; - uint64_t revision; - uint32_t public_keys_count; -} SwiftDashIdentityInfo; - -// Document info -typedef struct { - char *id; - char *owner_id; - char *data_contract_id; - char *document_type; - uint64_t revision; - int64_t created_at; - int64_t updated_at; -} SwiftDashDocumentInfo; - -// Binary data -typedef struct { - uint8_t *data; - size_t len; -} SwiftDashBinaryData; - -// Transfer credits result -typedef struct { - uint64_t amount; - char *recipient_id; - uint8_t *transaction_data; - size_t transaction_data_len; -} SwiftDashTransferCreditsResult; - -// SDK functions -void swift_dash_sdk_init(void); -SDKHandle *swift_dash_sdk_create(SwiftDashSDKConfig config); -void swift_dash_sdk_destroy(SDKHandle *handle); -SwiftDashNetwork swift_dash_sdk_get_network(SDKHandle *handle); -char *swift_dash_sdk_get_version(void); - -// Configuration helpers -SwiftDashSDKConfig swift_dash_sdk_config_mainnet(void); -SwiftDashSDKConfig swift_dash_sdk_config_testnet(void); -SwiftDashSDKConfig swift_dash_sdk_config_local(void); -SwiftDashPutSettings swift_dash_put_settings_default(void); - -// Identity functions -IdentityHandle *swift_dash_identity_fetch(SDKHandle *sdk_handle, const char *identity_id); -SwiftDashIdentityInfo *swift_dash_identity_get_info(IdentityHandle *identity_handle); -SwiftDashBinaryData *swift_dash_identity_put_to_platform_with_instant_lock( - SDKHandle *sdk_handle, - IdentityHandle *identity_handle, - uint32_t public_key_id, - SignerHandle *signer_handle, - const SwiftDashPutSettings *settings -); -IdentityHandle *swift_dash_identity_put_to_platform_with_instant_lock_and_wait( - SDKHandle *sdk_handle, - IdentityHandle *identity_handle, - uint32_t public_key_id, - SignerHandle *signer_handle, - const SwiftDashPutSettings *settings -); -SwiftDashTransferCreditsResult *swift_dash_identity_transfer_credits( - SDKHandle *sdk_handle, - IdentityHandle *identity_handle, - const char *recipient_id, - uint64_t amount, - uint32_t public_key_id, - SignerHandle *signer_handle, - const SwiftDashPutSettings *settings -); - -// Data contract functions -DataContractHandle *swift_dash_data_contract_fetch(SDKHandle *sdk_handle, const char *contract_id); -DataContractHandle *swift_dash_data_contract_create( - SDKHandle *sdk_handle, - const char *owner_identity_id, - const char *schema_json -); -char *swift_dash_data_contract_get_info(DataContractHandle *contract_handle); -SwiftDashBinaryData *swift_dash_data_contract_put_to_platform( - SDKHandle *sdk_handle, - DataContractHandle *contract_handle, - uint32_t public_key_id, - SignerHandle *signer_handle, - const SwiftDashPutSettings *settings -); - -// Document functions -DocumentHandle *swift_dash_document_create( - SDKHandle *sdk_handle, - DataContractHandle *contract_handle, - const char *owner_identity_id, - const char *document_type, - const char *data_json -); -DocumentHandle *swift_dash_document_fetch( - SDKHandle *sdk_handle, - DataContractHandle *contract_handle, - const char *document_type, - const char *document_id -); -SwiftDashDocumentInfo *swift_dash_document_get_info(DocumentHandle *document_handle); -SwiftDashBinaryData *swift_dash_document_put_to_platform( - SDKHandle *sdk_handle, - DocumentHandle *document_handle, - uint32_t public_key_id, - SignerHandle *signer_handle, - const SwiftDashPutSettings *settings -); - -// Signer functions -SignerHandle *swift_dash_signer_create_test(void); -void swift_dash_signer_destroy(SignerHandle *handle); - -// Memory management -void swift_dash_error_free(SwiftDashError *error); -void swift_dash_identity_info_free(SwiftDashIdentityInfo *info); -void swift_dash_document_info_free(SwiftDashDocumentInfo *info); -void swift_dash_binary_data_free(SwiftDashBinaryData *data); -void swift_dash_transfer_credits_result_free(SwiftDashTransferCreditsResult *result); - -#endif // SWIFT_DASH_SDK_H diff --git a/packages/swift-sdk/SwiftTests/TEST_FIX_SUMMARY.md b/packages/swift-sdk/SwiftTests/TEST_FIX_SUMMARY.md deleted file mode 100644 index 478adbb9061..00000000000 --- a/packages/swift-sdk/SwiftTests/TEST_FIX_SUMMARY.md +++ /dev/null @@ -1,35 +0,0 @@ -# Swift Test Fixes Summary - -## Issues Fixed - -1. **Type naming mismatches**: Fixed double prefixes (SwiftDashSwiftDash) in the mock implementation -2. **Header file synchronization**: Updated both header files to match -3. **Enum constants**: Added Swift constants file for network types and error codes -4. **Function signatures**: Updated mock implementation to match the unified SDK API -5. **Memory management functions**: Added missing free functions -6. **SDK handle types**: Changed from `UnsafeMutablePointer` to `OpaquePointer` - -## Remaining Issues - -1. **Document tests**: Need to update to use contract handles instead of string IDs -2. **Identity tests**: Need to update transfer_credits to use new API with identity/signer handles -3. **Result vs Handle returns**: Many tests expect result structs but API returns handles -4. **Missing functions**: Some test functions (e.g., swift_dash_document_search) are not in the API - -## Compilation Status - -The mock C implementation now compiles successfully. The Swift tests have various compilation errors due to: -- API differences between the test expectations and the unified SDK -- Functions that return handles instead of result structs -- Tests trying to use old API signatures - -## Recommendation - -The tests need significant refactoring to match the new unified SDK API. The main patterns to update: - -1. Functions that previously returned results now return handles -2. Transfer operations now require identity handles and signer handles -3. Document operations require contract handles instead of contract ID strings -4. Some operations from the old API are no longer available - -The mock implementation is correctly structured but the tests themselves need to be updated to match the new API. diff --git a/packages/swift-sdk/SwiftTests/Tests/SwiftDashSDKTests/ContactRequestTests.swift b/packages/swift-sdk/SwiftTests/Tests/SwiftDashSDKTests/ContactRequestTests.swift deleted file mode 100644 index 89812c25725..00000000000 --- a/packages/swift-sdk/SwiftTests/Tests/SwiftDashSDKTests/ContactRequestTests.swift +++ /dev/null @@ -1,211 +0,0 @@ -import XCTest -@testable import SwiftDashSDK - -class ContactRequestTests: XCTestCase { - - var senderId: Identifier! - var recipientId: Identifier! - var encryptedPublicKey: Data! - - override func setUp() { - super.setUp() - - do { - senderId = try Identifier.random() - recipientId = try Identifier.random() - // Create mock encrypted public key (in real usage, this would be ECDH encrypted) - encryptedPublicKey = Data(count: 65) // Example size for encrypted secp256k1 public key - } catch { - XCTFail("Failed to set up test: \(error)") - } - } - - // MARK: - Creation Tests - - func testCreateContactRequest() throws { - let contactRequest = try ContactRequest.create( - senderId: senderId, - recipientId: recipientId, - senderKeyIndex: 0, - recipientKeyIndex: 0, - accountReference: 0, - encryptedPublicKey: encryptedPublicKey, - createdAt: UInt64(Date().timeIntervalSince1970 * 1000) - ) - - XCTAssertNotNil(contactRequest, "Should create contact request") - } - - func testCreateContactRequestWithCustomValues() throws { - let timestamp = UInt64(1234567890000) - let contactRequest = try ContactRequest.create( - senderId: senderId, - recipientId: recipientId, - senderKeyIndex: 5, - recipientKeyIndex: 3, - accountReference: 1, - encryptedPublicKey: encryptedPublicKey, - createdAt: timestamp - ) - - XCTAssertNotNil(contactRequest, "Should create contact request with custom values") - } - - // MARK: - Getter Tests - - func testGetSenderId() throws { - let contactRequest = try ContactRequest.create( - senderId: senderId, - recipientId: recipientId, - senderKeyIndex: 0, - recipientKeyIndex: 0, - accountReference: 0, - encryptedPublicKey: encryptedPublicKey, - createdAt: UInt64(Date().timeIntervalSince1970 * 1000) - ) - - let retrievedSenderId = try contactRequest.getSenderId() - XCTAssertEqual(retrievedSenderId.bytes, senderId.bytes, "Should retrieve correct sender ID") - } - - func testGetRecipientId() throws { - let contactRequest = try ContactRequest.create( - senderId: senderId, - recipientId: recipientId, - senderKeyIndex: 0, - recipientKeyIndex: 0, - accountReference: 0, - encryptedPublicKey: encryptedPublicKey, - createdAt: UInt64(Date().timeIntervalSince1970 * 1000) - ) - - let retrievedRecipientId = try contactRequest.getRecipientId() - XCTAssertEqual(retrievedRecipientId.bytes, recipientId.bytes, "Should retrieve correct recipient ID") - } - - func testGetSenderKeyIndex() throws { - let expectedIndex: UInt32 = 7 - let contactRequest = try ContactRequest.create( - senderId: senderId, - recipientId: recipientId, - senderKeyIndex: expectedIndex, - recipientKeyIndex: 0, - accountReference: 0, - encryptedPublicKey: encryptedPublicKey, - createdAt: UInt64(Date().timeIntervalSince1970 * 1000) - ) - - let retrievedIndex = try contactRequest.getSenderKeyIndex() - XCTAssertEqual(retrievedIndex, expectedIndex, "Should retrieve correct sender key index") - } - - func testGetRecipientKeyIndex() throws { - let expectedIndex: UInt32 = 9 - let contactRequest = try ContactRequest.create( - senderId: senderId, - recipientId: recipientId, - senderKeyIndex: 0, - recipientKeyIndex: expectedIndex, - accountReference: 0, - encryptedPublicKey: encryptedPublicKey, - createdAt: UInt64(Date().timeIntervalSince1970 * 1000) - ) - - let retrievedIndex = try contactRequest.getRecipientKeyIndex() - XCTAssertEqual(retrievedIndex, expectedIndex, "Should retrieve correct recipient key index") - } - - func testGetAccountReference() throws { - let expectedReference: UInt32 = 2 - let contactRequest = try ContactRequest.create( - senderId: senderId, - recipientId: recipientId, - senderKeyIndex: 0, - recipientKeyIndex: 0, - accountReference: expectedReference, - encryptedPublicKey: encryptedPublicKey, - createdAt: UInt64(Date().timeIntervalSince1970 * 1000) - ) - - let retrievedReference = try contactRequest.getAccountReference() - XCTAssertEqual(retrievedReference, expectedReference, "Should retrieve correct account reference") - } - - func testGetEncryptedPublicKey() throws { - let contactRequest = try ContactRequest.create( - senderId: senderId, - recipientId: recipientId, - senderKeyIndex: 0, - recipientKeyIndex: 0, - accountReference: 0, - encryptedPublicKey: encryptedPublicKey, - createdAt: UInt64(Date().timeIntervalSince1970 * 1000) - ) - - let retrievedKey = try contactRequest.getEncryptedPublicKey() - XCTAssertEqual(retrievedKey, encryptedPublicKey, "Should retrieve correct encrypted public key") - } - - func testGetCreatedAt() throws { - let expectedTimestamp = UInt64(1234567890000) - let contactRequest = try ContactRequest.create( - senderId: senderId, - recipientId: recipientId, - senderKeyIndex: 0, - recipientKeyIndex: 0, - accountReference: 0, - encryptedPublicKey: encryptedPublicKey, - createdAt: expectedTimestamp - ) - - let retrievedTimestamp = try contactRequest.getCreatedAt() - XCTAssertEqual(retrievedTimestamp, expectedTimestamp, "Should retrieve correct creation timestamp") - } - - // MARK: - Memory Management Tests - - func testContactRequestDeinit() throws { - var contactRequest: ContactRequest? = try ContactRequest.create( - senderId: senderId, - recipientId: recipientId, - senderKeyIndex: 0, - recipientKeyIndex: 0, - accountReference: 0, - encryptedPublicKey: encryptedPublicKey, - createdAt: UInt64(Date().timeIntervalSince1970 * 1000) - ) - let handle = contactRequest?.handle - - XCTAssertNotNil(handle) - - // Release contact request - should call deinit - contactRequest = nil - - // If this doesn't crash, memory management is working - XCTAssertNil(contactRequest) - } - - // MARK: - Edge Cases - - func testCreateWithEmptyEncryptedKey() { - let emptyKey = Data() - - // This might be valid or invalid depending on FFI implementation - // Test that it doesn't crash - do { - let contactRequest = try ContactRequest.create( - senderId: senderId, - recipientId: recipientId, - senderKeyIndex: 0, - recipientKeyIndex: 0, - accountReference: 0, - encryptedPublicKey: emptyKey, - createdAt: UInt64(Date().timeIntervalSince1970 * 1000) - ) - XCTAssertNotNil(contactRequest) - } catch { - // Expected to fail - empty key should not be allowed - XCTAssertTrue(error is PlatformWalletError) - } - } -} diff --git a/packages/swift-sdk/SwiftTests/Tests/SwiftDashSDKTests/DataContractTests.swift b/packages/swift-sdk/SwiftTests/Tests/SwiftDashSDKTests/DataContractTests.swift deleted file mode 100644 index a363e1ca979..00000000000 --- a/packages/swift-sdk/SwiftTests/Tests/SwiftDashSDKTests/DataContractTests.swift +++ /dev/null @@ -1,295 +0,0 @@ -import XCTest -import SwiftDashSDKMock - -class DataContractTests: XCTestCase { - - var sdk: UnsafeMutablePointer? - - // Test configuration data - matching rs-sdk-ffi test vectors - let existingDataContractId = "GWRSAVFMjXx8HpQFaNJMqBV7MBgMK4br5UESsB4S31Ec" - let nonExistentContractId = "1111111111111111111111111111111111111111111" - let existingIdentityId = "4EfA9Jrvv3nnCFdSf7fad59851iiTRZ6Wcu6YVJ4iSeF" - - override func setUp() { - super.setUp() - swift_dash_sdk_init() - - let config = swift_dash_sdk_config_testnet() - sdk = swift_dash_sdk_create(config) - XCTAssertNotNil(sdk, "SDK should be created successfully") - } - - override func tearDown() { - if let sdk = sdk { - swift_dash_sdk_destroy(sdk) - } - super.tearDown() - } - - // MARK: - Data Contract Fetch Tests - - func testDataContractFetchNotFound() { - guard let sdk = sdk else { - XCTFail("SDK not initialized") - return - } - - let result = swift_dash_data_contract_fetch(sdk, nonExistentContractId) - XCTAssertNil(result, "Non-existent data contract should return nil") - } - - func testDataContractFetch() { - guard let sdk = sdk else { - XCTFail("SDK not initialized") - return - } - - let result = swift_dash_data_contract_fetch(sdk, existingDataContractId) - XCTAssertNotNil(result, "Existing data contract should return data") - - if let jsonString = result { - let jsonStr = String(cString: jsonString) - XCTAssertFalse(jsonStr.isEmpty, "JSON string should not be empty") - - // Verify we can parse the JSON - guard let jsonData = jsonStr.data(using: .utf8), - let json = try? JSONSerialization.jsonObject(with: jsonData) as? [String: Any] else { - XCTFail("Should be valid JSON") - return - } - - // Verify we got a data contract back - XCTAssertNotNil(json["id"], "Data contract should have an id field") - XCTAssertNotNil(json["version"], "Data contract should have a version field") - - // Verify the contract ID matches - if let id = json["id"] as? String { - XCTAssertEqual(id, existingDataContractId, "Contract ID should match requested ID") - } - - // Clean up - swift_dash_string_free(jsonString) - } - } - - func testDataContractFetchWithNullSDK() { - let result = swift_dash_data_contract_fetch(nil, existingDataContractId) - XCTAssertNil(result, "Should return nil for null SDK handle") - } - - func testDataContractFetchWithNullContractId() { - guard let sdk = sdk else { - XCTFail("SDK not initialized") - return - } - - let result = swift_dash_data_contract_fetch(sdk, nil) - XCTAssertNil(result, "Should return nil for null contract ID") - } - - // MARK: - Data Contract History Tests - - func testDataContractHistory() { - guard let sdk = sdk else { - XCTFail("SDK not initialized") - return - } - - let result = swift_dash_data_contract_get_history(sdk, existingDataContractId, 10, 0) - - if let jsonString = result { - let jsonStr = String(cString: jsonString) - XCTAssertFalse(jsonStr.isEmpty, "JSON string should not be empty") - - // Verify we can parse the JSON - guard let jsonData = jsonStr.data(using: .utf8), - let json = try? JSONSerialization.jsonObject(with: jsonData) as? [String: Any] else { - XCTFail("Should be valid JSON") - return - } - - // Should have contract_id and history fields - XCTAssertNotNil(json["contract_id"], "Should have contract_id field") - XCTAssertNotNil(json["history"], "Should have history field") - - if let contractId = json["contract_id"] as? String { - XCTAssertEqual(contractId, existingDataContractId, "Contract ID should match") - } - - // Clean up - swift_dash_string_free(jsonString) - } - } - - func testDataContractHistoryNotFound() { - guard let sdk = sdk else { - XCTFail("SDK not initialized") - return - } - - let result = swift_dash_data_contract_get_history(sdk, nonExistentContractId, 10, 0) - XCTAssertNil(result, "Non-existent contract should have no history") - } - - func testDataContractHistoryWithNullSDK() { - let result = swift_dash_data_contract_get_history(nil, existingDataContractId, 10, 0) - XCTAssertNil(result, "Should return nil for null SDK handle") - } - - func testDataContractHistoryWithNullContractId() { - guard let sdk = sdk else { - XCTFail("SDK not initialized") - return - } - - let result = swift_dash_data_contract_get_history(sdk, nil, 10, 0) - XCTAssertNil(result, "Should return nil for null contract ID") - } - - // MARK: - Data Contract Creation Tests - - func testDataContractCreate() { - guard let sdk = sdk else { - XCTFail("SDK not initialized") - return - } - - let schemaJson = """ - { - "documents": { - "message": { - "type": "object", - "properties": { - "content": { - "type": "string", - "maxLength": 256 - } - }, - "required": ["content"] - } - } - } - """ - - let result = swift_dash_data_contract_create(sdk, schemaJson, existingIdentityId) - - // Since this is not implemented in mock, should return not implemented error - XCTAssertFalse(result.success, "Data contract creation should fail (not implemented)") - XCTAssertNotNil(result.error, "Should have error for not implemented") - - if let error = result.error { - XCTAssertEqual(error.pointee.code, NotImplemented, "Should be NotImplemented error") - - if let message = error.pointee.message { - let messageStr = String(cString: message) - XCTAssertTrue(messageStr.contains("not yet implemented"), "Error message should mention not implemented") - } - - // Clean up error - swift_dash_error_free(error) - } - } - - func testDataContractCreateWithNullParams() { - guard let sdk = sdk else { - XCTFail("SDK not initialized") - return - } - - let schemaJson = "{\"documents\":{\"test\":{\"type\":\"object\"}}}" - - // Test with null SDK - var result = swift_dash_data_contract_create(nil, schemaJson, existingIdentityId) - XCTAssertFalse(result.success, "Should fail with null SDK") - if let error = result.error { - XCTAssertEqual(error.pointee.code, InvalidParameter, "Should be InvalidParameter error") - swift_dash_error_free(error) - } - - // Test with null schema JSON - result = swift_dash_data_contract_create(sdk, nil, existingIdentityId) - XCTAssertFalse(result.success, "Should fail with null schema JSON") - if let error = result.error { - XCTAssertEqual(error.pointee.code, InvalidParameter, "Should be InvalidParameter error") - swift_dash_error_free(error) - } - - // Test with null owner ID - result = swift_dash_data_contract_create(sdk, schemaJson, nil) - XCTAssertFalse(result.success, "Should fail with null owner ID") - if let error = result.error { - XCTAssertEqual(error.pointee.code, InvalidParameter, "Should be InvalidParameter error") - swift_dash_error_free(error) - } - } - - // MARK: - Data Contract Update Tests - - func testDataContractUpdate() { - guard let sdk = sdk else { - XCTFail("SDK not initialized") - return - } - - let schemaJson = """ - { - "documents": { - "message": { - "type": "object", - "properties": { - "content": { - "type": "string", - "maxLength": 512 - } - }, - "required": ["content"] - } - } - } - """ - - let result = swift_dash_data_contract_update(sdk, existingDataContractId, schemaJson, 2) - - // Since this is not implemented in mock, should return not implemented error - XCTAssertFalse(result.success, "Data contract update should fail (not implemented)") - XCTAssertNotNil(result.error, "Should have error for not implemented") - - if let error = result.error { - XCTAssertEqual(error.pointee.code, NotImplemented, "Should be NotImplemented error") - swift_dash_error_free(error) - } - } - - func testDataContractUpdateWithNullParams() { - guard let sdk = sdk else { - XCTFail("SDK not initialized") - return - } - - let schemaJson = "{\"documents\":{\"test\":{\"type\":\"object\"}}}" - - // Test with null SDK - var result = swift_dash_data_contract_update(nil, existingDataContractId, schemaJson, 2) - XCTAssertFalse(result.success, "Should fail with null SDK") - if let error = result.error { - XCTAssertEqual(error.pointee.code, InvalidParameter, "Should be InvalidParameter error") - swift_dash_error_free(error) - } - - // Test with null contract ID - result = swift_dash_data_contract_update(sdk, nil, schemaJson, 2) - XCTAssertFalse(result.success, "Should fail with null contract ID") - if let error = result.error { - XCTAssertEqual(error.pointee.code, InvalidParameter, "Should be InvalidParameter error") - swift_dash_error_free(error) - } - - // Test with null schema JSON - result = swift_dash_data_contract_update(sdk, existingDataContractId, nil, 2) - XCTAssertFalse(result.success, "Should fail with null schema JSON") - if let error = result.error { - XCTAssertEqual(error.pointee.code, InvalidParameter, "Should be InvalidParameter error") - swift_dash_error_free(error) - } - } -} diff --git a/packages/swift-sdk/SwiftTests/Tests/SwiftDashSDKTests/DocumentTests.swift b/packages/swift-sdk/SwiftTests/Tests/SwiftDashSDKTests/DocumentTests.swift deleted file mode 100644 index 45747ee044a..00000000000 --- a/packages/swift-sdk/SwiftTests/Tests/SwiftDashSDKTests/DocumentTests.swift +++ /dev/null @@ -1,406 +0,0 @@ -import XCTest -import SwiftDashSDKMock - -class DocumentTests: XCTestCase { - - var sdk: UnsafeMutablePointer? - - // Test configuration data - matching rs-sdk-ffi test vectors - let existingDataContractId = "GWRSAVFMjXx8HpQFaNJMqBV7MBgMK4br5UESsB4S31Ec" - let existingIdentityId = "4EfA9Jrvv3nnCFdSf7fad59851iiTRZ6Wcu6YVJ4iSeF" - let documentType = "domain" - let nonExistentDocumentId = "1111111111111111111111111111111111111111111" - - override func setUp() { - super.setUp() - swift_dash_sdk_init() - - let config = swift_dash_sdk_config_testnet() - sdk = swift_dash_sdk_create(config) - XCTAssertNotNil(sdk, "SDK should be created successfully") - } - - override func tearDown() { - if let sdk = sdk { - swift_dash_sdk_destroy(sdk) - } - super.tearDown() - } - - // MARK: - Document Fetch Tests - - func testDocumentFetchNotImplemented() { - guard let sdk = sdk else { - XCTFail("SDK not initialized") - return - } - - let result = swift_dash_document_fetch(sdk, existingDataContractId, documentType, nonExistentDocumentId) - XCTAssertNil(result, "Document fetching not implemented in mock") - } - - func testDocumentFetchWithNullSDK() { - let result = swift_dash_document_fetch(nil, existingDataContractId, documentType, nonExistentDocumentId) - XCTAssertNil(result, "Should return nil for null SDK handle") - } - - func testDocumentFetchWithNullParams() { - guard let sdk = sdk else { - XCTFail("SDK not initialized") - return - } - - // Test with null data contract ID - var result = swift_dash_document_fetch(sdk, nil, documentType, nonExistentDocumentId) - XCTAssertNil(result, "Should return nil for null data contract ID") - - // Test with null document type - result = swift_dash_document_fetch(sdk, existingDataContractId, nil, nonExistentDocumentId) - XCTAssertNil(result, "Should return nil for null document type") - - // Test with null document ID - result = swift_dash_document_fetch(sdk, existingDataContractId, documentType, nil) - XCTAssertNil(result, "Should return nil for null document ID") - } - - // MARK: - Document Search Tests - - func testDocumentSearchNotImplemented() { - guard let sdk = sdk else { - XCTFail("SDK not initialized") - return - } - - let queryJson = """ - { - "where": [ - ["normalizedLabel", "==", "dash"] - ] - } - """ - - let result = swift_dash_document_search(sdk, existingDataContractId, documentType, queryJson, 10) - XCTAssertNil(result, "Document search not implemented in mock") - } - - func testDocumentSearchWithNullSDK() { - let queryJson = "{\"where\":[]}" - let result = swift_dash_document_search(nil, existingDataContractId, documentType, queryJson, 10) - XCTAssertNil(result, "Should return nil for null SDK handle") - } - - func testDocumentSearchWithNullParams() { - guard let sdk = sdk else { - XCTFail("SDK not initialized") - return - } - - let queryJson = "{\"where\":[]}" - - // Test with null data contract ID - var result = swift_dash_document_search(sdk, nil, documentType, queryJson, 10) - XCTAssertNil(result, "Should return nil for null data contract ID") - - // Test with null document type - result = swift_dash_document_search(sdk, existingDataContractId, nil, queryJson, 10) - XCTAssertNil(result, "Should return nil for null document type") - - // Test with null query (query can be null for some search operations) - result = swift_dash_document_search(sdk, existingDataContractId, documentType, nil, 10) - XCTAssertNil(result, "Should return nil for null query in mock") - } - - // MARK: - Document Creation Tests - - func testDocumentCreate() { - guard let sdk = sdk else { - XCTFail("SDK not initialized") - return - } - - let propertiesJson = """ - { - "label": "test", - "normalizedLabel": "test", - "normalizedParentDomainName": "dash", - "records": { - "dashUniqueIdentityId": "4EfA9Jrvv3nnCFdSf7fad59851iiTRZ6Wcu6YVJ4iSeF" - } - } - """ - - let result = swift_dash_document_create(sdk, existingDataContractId, documentType, propertiesJson, existingIdentityId) - - // Since this is not implemented in mock, should return not implemented error - XCTAssertFalse(result.success, "Document creation should fail (not implemented)") - XCTAssertNotNil(result.error, "Should have error for not implemented") - - if let error = result.error { - XCTAssertEqual(error.pointee.code, NotImplemented, "Should be NotImplemented error") - - if let message = error.pointee.message { - let messageStr = String(cString: message) - XCTAssertTrue(messageStr.contains("not yet implemented"), "Error message should mention not implemented") - } - - // Clean up error - swift_dash_error_free(error) - } - } - - func testDocumentCreateWithNullParams() { - guard let sdk = sdk else { - XCTFail("SDK not initialized") - return - } - - let propertiesJson = "{\"content\":\"test\"}" - - // Test with null SDK - var result = swift_dash_document_create(nil, existingDataContractId, documentType, propertiesJson, existingIdentityId) - XCTAssertFalse(result.success, "Should fail with null SDK") - if let error = result.error { - XCTAssertEqual(error.pointee.code, InvalidParameter, "Should be InvalidParameter error") - swift_dash_error_free(error) - } - - // Test with null data contract ID - result = swift_dash_document_create(sdk, nil, documentType, propertiesJson, existingIdentityId) - XCTAssertFalse(result.success, "Should fail with null data contract ID") - if let error = result.error { - XCTAssertEqual(error.pointee.code, InvalidParameter, "Should be InvalidParameter error") - swift_dash_error_free(error) - } - - // Test with null document type - result = swift_dash_document_create(sdk, existingDataContractId, nil, propertiesJson, existingIdentityId) - XCTAssertFalse(result.success, "Should fail with null document type") - if let error = result.error { - XCTAssertEqual(error.pointee.code, InvalidParameter, "Should be InvalidParameter error") - swift_dash_error_free(error) - } - } - - // MARK: - Document Update Tests - - func testDocumentUpdate() { - guard let sdk = sdk else { - XCTFail("SDK not initialized") - return - } - - let propertiesJson = """ - { - "label": "updated-test", - "normalizedLabel": "updated-test", - "normalizedParentDomainName": "dash", - "records": { - "dashUniqueIdentityId": "4EfA9Jrvv3nnCFdSf7fad59851iiTRZ6Wcu6YVJ4iSeF" - } - } - """ - - let result = swift_dash_document_update(sdk, nonExistentDocumentId, propertiesJson, 2) - - // Since this is not implemented in mock, should return not implemented error - XCTAssertFalse(result.success, "Document update should fail (not implemented)") - XCTAssertNotNil(result.error, "Should have error for not implemented") - - if let error = result.error { - XCTAssertEqual(error.pointee.code, NotImplemented, "Should be NotImplemented error") - swift_dash_error_free(error) - } - } - - func testDocumentUpdateWithNullParams() { - guard let sdk = sdk else { - XCTFail("SDK not initialized") - return - } - - let propertiesJson = "{\"content\":\"updated\"}" - - // Test with null SDK - var result = swift_dash_document_update(nil, nonExistentDocumentId, propertiesJson, 2) - XCTAssertFalse(result.success, "Should fail with null SDK") - if let error = result.error { - XCTAssertEqual(error.pointee.code, InvalidParameter, "Should be InvalidParameter error") - swift_dash_error_free(error) - } - - // Test with null document ID - result = swift_dash_document_update(sdk, nil, propertiesJson, 2) - XCTAssertFalse(result.success, "Should fail with null document ID") - if let error = result.error { - XCTAssertEqual(error.pointee.code, InvalidParameter, "Should be InvalidParameter error") - swift_dash_error_free(error) - } - } - - // MARK: - Document Deletion Tests - - func testDocumentDelete() { - guard let sdk = sdk else { - XCTFail("SDK not initialized") - return - } - - let result = swift_dash_document_delete(sdk, nonExistentDocumentId) - - // Since this is not implemented in mock, should return not implemented error - XCTAssertFalse(result.success, "Document deletion should fail (not implemented)") - XCTAssertNotNil(result.error, "Should have error for not implemented") - - if let error = result.error { - XCTAssertEqual(error.pointee.code, NotImplemented, "Should be NotImplemented error") - swift_dash_error_free(error) - } - } - - func testDocumentDeleteWithNullParams() { - guard let sdk = sdk else { - XCTFail("SDK not initialized") - return - } - - // Test with null SDK - var result = swift_dash_document_delete(nil, nonExistentDocumentId) - XCTAssertFalse(result.success, "Should fail with null SDK") - if let error = result.error { - XCTAssertEqual(error.pointee.code, InvalidParameter, "Should be InvalidParameter error") - swift_dash_error_free(error) - } - - // Test with null document ID - result = swift_dash_document_delete(sdk, nil) - XCTAssertFalse(result.success, "Should fail with null document ID") - if let error = result.error { - XCTAssertEqual(error.pointee.code, InvalidParameter, "Should be InvalidParameter error") - swift_dash_error_free(error) - } - } - - // MARK: - Complex Query Examples - - func testComplexDocumentQueries() { - guard let sdk = sdk else { - XCTFail("SDK not initialized") - return - } - - // Test various query patterns that would be used in real applications - let queries = [ - // Simple equality query - """ - { - "where": [ - ["normalizedLabel", "==", "dash"] - ] - } - """, - // Range query - """ - { - "where": [ - ["$createdAt", ">=", 1640000000000], - ["$createdAt", "<=", 1650000000000] - ], - "orderBy": [["$createdAt", "desc"]], - "limit": 100 - } - """, - // Complex query with multiple conditions - """ - { - "where": [ - ["normalizedParentDomainName", "==", "dash"], - ["records.dashUniqueIdentityId", "!=", null] - ], - "orderBy": [["normalizedLabel", "asc"]], - "startAt": 0, - "limit": 50 - } - """, - // Prefix search - """ - { - "where": [ - ["normalizedLabel", "startsWith", "test"] - ], - "orderBy": [["normalizedLabel", "asc"]] - } - """ - ] - - for (index, query) in queries.enumerated() { - let result = swift_dash_document_search(sdk, existingDataContractId, documentType, query, 10) - // All should return nil in mock implementation - XCTAssertNil(result, "Query \(index + 1) should return nil in mock") - } - } - - // MARK: - Document Schema Examples - - func testDifferentDocumentTypes() { - guard let sdk = sdk else { - XCTFail("SDK not initialized") - return - } - - // Test different document type structures - let documentExamples = [ - // DPNS domain document - (type: "domain", properties: """ - { - "label": "example", - "normalizedLabel": "example", - "normalizedParentDomainName": "dash", - "preorderSalt": "1234567890abcdef", - "records": { - "dashUniqueIdentityId": "4EfA9Jrvv3nnCFdSf7fad59851iiTRZ6Wcu6YVJ4iSeF" - }, - "subdomainRules": { - "allowSubdomains": true - } - } - """), - // Profile document - (type: "profile", properties: """ - { - "publicMessage": "Hello from Dash Platform!", - "displayName": "Test User", - "avatarUrl": "https://example.com/avatar.png", - "avatarHash": "abcdef1234567890", - "avatarFingerprint": "fingerprint123" - } - """), - // Contact request document - (type: "contactRequest", properties: """ - { - "toUserId": "7777777777777777777777777777777777777777777", - "encryptedPublicKey": "encrypted_key_data", - "senderKeyIndex": 0, - "recipientKeyIndex": 1, - "accountReference": 0 - } - """) - ] - - for example in documentExamples { - let result = swift_dash_document_create( - sdk, - existingDataContractId, - example.type, - example.properties, - existingIdentityId - ) - - // All should fail with not implemented in mock - XCTAssertFalse(result.success, "\(example.type) creation should fail (not implemented)") - if let error = result.error { - XCTAssertEqual(error.pointee.code, NotImplemented, "Should be NotImplemented error") - swift_dash_error_free(error) - } - } - } -} diff --git a/packages/swift-sdk/SwiftTests/Tests/SwiftDashSDKTests/EstablishedContactTests.swift b/packages/swift-sdk/SwiftTests/Tests/SwiftDashSDKTests/EstablishedContactTests.swift deleted file mode 100644 index b3c925cbad3..00000000000 --- a/packages/swift-sdk/SwiftTests/Tests/SwiftDashSDKTests/EstablishedContactTests.swift +++ /dev/null @@ -1,110 +0,0 @@ -import XCTest -@testable import SwiftDashSDK - -class EstablishedContactTests: XCTestCase { - - // Note: EstablishedContact objects are typically obtained from ManagedIdentity - // These tests verify API correctness but most functionality requires integration testing - - // MARK: - API Existence Tests - - func testEstablishedContactAPIExists() { - // Verify that EstablishedContact class exists and has expected methods - // This is a compile-time check more than a runtime test - - XCTAssertTrue(true, "EstablishedContact API exists") - } - - // MARK: - Integration Test Placeholders - - func testGetContactIdentityId() throws { - throw XCTSkip("Requires integration test with real identity data") - } - - func testGetAlias() throws { - throw XCTSkip("Requires integration test with real contact data") - } - - func testSetAlias() throws { - throw XCTSkip("Requires integration test with real contact data") - } - - func testClearAlias() throws { - throw XCTSkip("Requires integration test with real contact data") - } - - func testGetNote() throws { - throw XCTSkip("Requires integration test with real contact data") - } - - func testSetNote() throws { - throw XCTSkip("Requires integration test with real contact data") - } - - func testClearNote() throws { - throw XCTSkip("Requires integration test with real contact data") - } - - func testIsHidden() throws { - throw XCTSkip("Requires integration test with real contact data") - } - - func testHide() throws { - throw XCTSkip("Requires integration test with real contact data") - } - - func testUnhide() throws { - throw XCTSkip("Requires integration test with real contact data") - } - - // MARK: - Memory Management Tests - - func testEstablishedContactDeinit() { - // Cannot easily test without real contact - // Verified through integration tests - XCTAssertTrue(true, "Placeholder for memory management verification") - } -} - -// MARK: - Integration Test Notes - -/* - Full integration tests for EstablishedContact require: - - 1. Two ManagedIdentity instances - 2. Sending contact requests between them - 3. Accepting to establish the contact - 4. Retrieving the EstablishedContact from one identity - 5. Testing all metadata operations (alias, note, hide/unhide) - - These tests should be in IntegrationTests.swift with full Platform SDK setup: - - Create two test identities - - Send bidirectional contact requests - - Verify auto-establishment - - Test alias operations (set, get, clear) - - Test note operations (set, get, clear) - - Test visibility (hide, unhide, isHidden) - - Verify persistence across operations - - Example flow: - ```swift - let identity1 = createTestIdentity() - let identity2 = createTestIdentity() - - try identity1.sendContactRequest(to: identity2.id, ...) - try identity2.acceptContactRequest(from: identity1.id) - - let contact = try identity1.getEstablishedContact(identity2.id) - try contact.setAlias("Alice") - XCTAssertEqual(try contact.getAlias(), "Alice") - - try contact.setNote("Met at conference") - XCTAssertEqual(try contact.getNote(), "Met at conference") - - XCTAssertFalse(try contact.isHidden()) - try contact.hide() - XCTAssertTrue(try contact.isHidden()) - try contact.unhide() - XCTAssertFalse(try contact.isHidden()) - ``` - */ diff --git a/packages/swift-sdk/SwiftTests/Tests/SwiftDashSDKTests/IdentityManagerTests.swift b/packages/swift-sdk/SwiftTests/Tests/SwiftDashSDKTests/IdentityManagerTests.swift deleted file mode 100644 index 8f3ae5c41f6..00000000000 --- a/packages/swift-sdk/SwiftTests/Tests/SwiftDashSDKTests/IdentityManagerTests.swift +++ /dev/null @@ -1,103 +0,0 @@ -import XCTest -@testable import SwiftDashSDK - -class IdentityManagerTests: XCTestCase { - - var identityManager: IdentityManager! - var testIdentityId: Identifier! - - override func setUp() { - super.setUp() - - do { - identityManager = try IdentityManager.create() - testIdentityId = try Identifier.random() - } catch { - XCTFail("Failed to set up test: \(error)") - } - } - - // MARK: - Creation Tests - - func testCreateIdentityManager() throws { - let manager = try IdentityManager.create() - XCTAssertNotNil(manager, "Should create identity manager") - } - - // MARK: - Identity Count Tests - - func testInitialIdentityCount() throws { - let count = try identityManager.getIdentityCount() - XCTAssertEqual(count, 0, "New manager should have 0 identities") - } - - // MARK: - Get All Identity IDs Tests - - func testGetAllIdentityIdsEmpty() throws { - let ids = try identityManager.getAllIdentityIds() - XCTAssertEqual(ids.count, 0, "New manager should have no identities") - } - - // MARK: - Primary Identity Tests - - func testGetPrimaryIdentityIdWhenNone() throws { - let primaryId = try identityManager.getPrimaryIdentityId() - XCTAssertNil(primaryId, "Should return nil when no primary identity") - } - - func testSetPrimaryIdentity() throws { - // This test would require adding an identity first - // For now, we test that the method exists and can be called - // In a real scenario, you'd add an identity then set it as primary - - // This should throw an error since identity doesn't exist - XCTAssertThrowsError(try identityManager.setPrimaryIdentity(testIdentityId)) { error in - XCTAssertTrue(error is PlatformWalletError) - } - } - - // MARK: - Get Identity Tests - - func testGetNonExistentIdentity() throws { - XCTAssertThrowsError(try identityManager.getIdentity(testIdentityId)) { error in - XCTAssertTrue(error is PlatformWalletError) - if case PlatformWalletError.identityNotFound = error { - // Expected error - } else { - XCTFail("Expected identityNotFound error, got \(error)") - } - } - } - - // MARK: - Remove Identity Tests - - func testRemoveNonExistentIdentity() throws { - // Should handle gracefully or throw appropriate error - XCTAssertThrowsError(try identityManager.removeIdentity(testIdentityId)) { error in - XCTAssertTrue(error is PlatformWalletError) - } - } - - // MARK: - Memory Management Tests - - func testIdentityManagerDeinit() throws { - var manager: IdentityManager? = try IdentityManager.create() - let handle = manager?.handle - - XCTAssertNotNil(handle) - - // Release manager - should call deinit - manager = nil - - // If this doesn't crash, memory management is working - XCTAssertNil(manager) - } - - // MARK: - Integration Tests (would require real identity data) - - // Note: Full integration tests with actual identities would require: - // 1. Creating a ManagedIdentity from real identity bytes - // 2. Adding it to the manager - // 3. Testing retrieval, primary identity setting, etc. - // These tests are included in the integration test suite -} diff --git a/packages/swift-sdk/SwiftTests/Tests/SwiftDashSDKTests/IdentityTests.swift b/packages/swift-sdk/SwiftTests/Tests/SwiftDashSDKTests/IdentityTests.swift deleted file mode 100644 index f9437235926..00000000000 --- a/packages/swift-sdk/SwiftTests/Tests/SwiftDashSDKTests/IdentityTests.swift +++ /dev/null @@ -1,313 +0,0 @@ -import XCTest -import SwiftDashSDKMock - -class IdentityTests: XCTestCase { - - var sdk: UnsafeMutablePointer? - - // Test configuration data - matching rs-sdk-ffi test vectors - let existingIdentityId = "4EfA9Jrvv3nnCFdSf7fad59851iiTRZ6Wcu6YVJ4iSeF" - let nonExistentIdentityId = "1111111111111111111111111111111111111111111" - - override func setUp() { - super.setUp() - swift_dash_sdk_init() - - let config = swift_dash_sdk_config_testnet() - sdk = swift_dash_sdk_create(config) - XCTAssertNotNil(sdk, "SDK should be created successfully") - } - - override func tearDown() { - if let sdk = sdk { - swift_dash_sdk_destroy(sdk) - } - super.tearDown() - } - - // MARK: - Identity Fetch Tests - - func testIdentityFetchNotFound() { - guard let sdk = sdk else { - XCTFail("SDK not initialized") - return - } - - let result = swift_dash_identity_fetch(sdk, nonExistentIdentityId) - XCTAssertNil(result, "Non-existent identity should return nil") - } - - func testIdentityFetch() { - guard let sdk = sdk else { - XCTFail("SDK not initialized") - return - } - - let result = swift_dash_identity_fetch(sdk, existingIdentityId) - XCTAssertNotNil(result, "Existing identity should return data") - - if let jsonString = result { - let jsonStr = String(cString: jsonString) - XCTAssertFalse(jsonStr.isEmpty, "JSON string should not be empty") - - // Verify we can parse the JSON - guard let jsonData = jsonStr.data(using: .utf8), - let json = try? JSONSerialization.jsonObject(with: jsonData) as? [String: Any] else { - XCTFail("Should be valid JSON") - return - } - - // Verify we got an identity back - XCTAssertNotNil(json["id"], "Identity should have an id field") - XCTAssertNotNil(json["publicKeys"], "Identity should have publicKeys field") - - // Verify the identity ID matches - if let id = json["id"] as? String { - XCTAssertEqual(id, existingIdentityId, "Identity ID should match requested ID") - } - - // Clean up - swift_dash_string_free(jsonString) - } - } - - func testIdentityFetchWithNullSDK() { - let result = swift_dash_identity_fetch(nil, existingIdentityId) - XCTAssertNil(result, "Should return nil for null SDK handle") - } - - func testIdentityFetchWithNullIdentityId() { - guard let sdk = sdk else { - XCTFail("SDK not initialized") - return - } - - let result = swift_dash_identity_fetch(sdk, nil) - XCTAssertNil(result, "Should return nil for null identity ID") - } - - // MARK: - Identity Balance Tests - - func testIdentityBalance() { - guard let sdk = sdk else { - XCTFail("SDK not initialized") - return - } - - let balance = swift_dash_identity_get_balance(sdk, existingIdentityId) - XCTAssertGreaterThan(balance, 0, "Existing identity should have a balance") - - // Mock returns 1000000 credits - XCTAssertEqual(balance, 1000000, "Mock should return 1000000 credits") - } - - func testIdentityBalanceNotFound() { - guard let sdk = sdk else { - XCTFail("SDK not initialized") - return - } - - let balance = swift_dash_identity_get_balance(sdk, nonExistentIdentityId) - XCTAssertEqual(balance, 0, "Non-existent identity should have zero balance") - } - - func testIdentityBalanceWithNullSDK() { - let balance = swift_dash_identity_get_balance(nil, existingIdentityId) - XCTAssertEqual(balance, 0, "Should return 0 for null SDK handle") - } - - func testIdentityBalanceWithNullIdentityId() { - guard let sdk = sdk else { - XCTFail("SDK not initialized") - return - } - - let balance = swift_dash_identity_get_balance(sdk, nil) - XCTAssertEqual(balance, 0, "Should return 0 for null identity ID") - } - - // MARK: - Identity Name Resolution Tests - - func testIdentityResolveByAlias() { - guard let sdk = sdk else { - XCTFail("SDK not initialized") - return - } - - let result = swift_dash_identity_resolve_name(sdk, "dash") - XCTAssertNotNil(result, "Should resolve existing alias") - - if let jsonString = result { - let jsonStr = String(cString: jsonString) - XCTAssertFalse(jsonStr.isEmpty, "JSON string should not be empty") - - // Verify we can parse the JSON - guard let jsonData = jsonStr.data(using: .utf8), - let json = try? JSONSerialization.jsonObject(with: jsonData) as? [String: Any] else { - XCTFail("Should be valid JSON") - return - } - - // Verify we got identity and alias fields - XCTAssertNotNil(json["identity"], "Should have identity field") - XCTAssertNotNil(json["alias"], "Should have alias field") - - if let alias = json["alias"] as? String { - XCTAssertEqual(alias, "dash", "Alias should match requested name") - } - - // Clean up - swift_dash_string_free(jsonString) - } - } - - func testIdentityResolveNonExistentName() { - guard let sdk = sdk else { - XCTFail("SDK not initialized") - return - } - - let result = swift_dash_identity_resolve_name(sdk, "nonexistent_name_12345") - XCTAssertNil(result, "Non-existent name should return nil") - } - - func testIdentityResolveWithNullSDK() { - let result = swift_dash_identity_resolve_name(nil, "dash") - XCTAssertNil(result, "Should return nil for null SDK handle") - } - - func testIdentityResolveWithNullName() { - guard let sdk = sdk else { - XCTFail("SDK not initialized") - return - } - - let result = swift_dash_identity_resolve_name(sdk, nil) - XCTAssertNil(result, "Should return nil for null name") - } - - // MARK: - Identity Transfer Credits Tests - - func testIdentityTransferCredits() { - guard let sdk = sdk else { - XCTFail("SDK not initialized") - return - } - - let privateKey: [UInt8] = Array(repeating: 0x42, count: 32) // Mock private key - let amount: UInt64 = 1000 - - let result = swift_dash_identity_transfer_credits( - sdk, - existingIdentityId, - "7777777777777777777777777777777777777777777", // recipient - amount, - privateKey, - privateKey.count - ) - - // Since this is not implemented in mock, should return not implemented error - XCTAssertFalse(result.success, "Credit transfer should fail (not implemented)") - XCTAssertNotNil(result.error, "Should have error for not implemented") - - if let error = result.error { - XCTAssertEqual(error.pointee.code, NotImplemented, "Should be NotImplemented error") - - if let message = error.pointee.message { - let messageStr = String(cString: message) - XCTAssertTrue(messageStr.contains("not yet implemented"), "Error message should mention not implemented") - } - - // Clean up error - swift_dash_error_free(error) - } - } - - func testIdentityTransferCreditsWithNullParams() { - guard let sdk = sdk else { - XCTFail("SDK not initialized") - return - } - - let privateKey: [UInt8] = Array(repeating: 0x42, count: 32) - - // Test with null SDK - var result = swift_dash_identity_transfer_credits( - nil, - existingIdentityId, - "7777777777777777777777777777777777777777777", - 1000, - privateKey, - privateKey.count - ) - - XCTAssertFalse(result.success, "Should fail with null SDK") - if let error = result.error { - XCTAssertEqual(error.pointee.code, InvalidParameter, "Should be InvalidParameter error") - swift_dash_error_free(error) - } - - // Test with null from_identity_id - result = swift_dash_identity_transfer_credits( - sdk, - nil, - "7777777777777777777777777777777777777777777", - 1000, - privateKey, - privateKey.count - ) - - XCTAssertFalse(result.success, "Should fail with null from_identity_id") - if let error = result.error { - XCTAssertEqual(error.pointee.code, InvalidParameter, "Should be InvalidParameter error") - swift_dash_error_free(error) - } - } - - // MARK: - Identity Creation Tests - - func testIdentityCreate() { - guard let sdk = sdk else { - XCTFail("SDK not initialized") - return - } - - let publicKey: [UInt8] = Array(repeating: 0x33, count: 33) // Mock public key - - let result = swift_dash_identity_create(sdk, publicKey, publicKey.count) - - // Since this is not implemented in mock, should return not implemented error - XCTAssertFalse(result.success, "Identity creation should fail (not implemented)") - XCTAssertNotNil(result.error, "Should have error for not implemented") - - if let error = result.error { - XCTAssertEqual(error.pointee.code, NotImplemented, "Should be NotImplemented error") - swift_dash_error_free(error) - } - } - - func testIdentityCreateWithNullParams() { - guard let sdk = sdk else { - XCTFail("SDK not initialized") - return - } - - let publicKey: [UInt8] = Array(repeating: 0x33, count: 33) - - // Test with null SDK - var result = swift_dash_identity_create(nil, publicKey, publicKey.count) - XCTAssertFalse(result.success, "Should fail with null SDK") - if let error = result.error { - XCTAssertEqual(error.pointee.code, InvalidParameter, "Should be InvalidParameter error") - swift_dash_error_free(error) - } - - // Test with null public key - result = swift_dash_identity_create(sdk, nil, 0) - XCTAssertFalse(result.success, "Should fail with null public key") - if let error = result.error { - XCTAssertEqual(error.pointee.code, InvalidParameter, "Should be InvalidParameter error") - swift_dash_error_free(error) - } - } -} diff --git a/packages/swift-sdk/SwiftTests/Tests/SwiftDashSDKTests/ManagedIdentityTests.swift b/packages/swift-sdk/SwiftTests/Tests/SwiftDashSDKTests/ManagedIdentityTests.swift deleted file mode 100644 index 6b1ab174f00..00000000000 --- a/packages/swift-sdk/SwiftTests/Tests/SwiftDashSDKTests/ManagedIdentityTests.swift +++ /dev/null @@ -1,114 +0,0 @@ -import XCTest -@testable import SwiftDashSDK - -class ManagedIdentityTests: XCTestCase { - - // Note: Most ManagedIdentity tests require real identity bytes from DPP - // These tests focus on API correctness and error handling - - // MARK: - Creation Tests - - func testCreateFromInvalidIdentityBytes() { - let invalidBytes = Data(count: 10) // Too short - - XCTAssertThrowsError(try ManagedIdentity.fromIdentityBytes(invalidBytes)) { error in - XCTAssertTrue(error is PlatformWalletError) - } - } - - // MARK: - Contact Request ID Retrieval Tests - - // Note: These tests verify the API works, but would need a properly initialized - // identity with contact data to return non-empty results - - func testGetSentContactRequestIdsWithEmptyIdentity() throws { - // This would need a real identity to test properly - // For now, we verify the API exists and doesn't crash with empty data - - // Skip this test until we have proper integration test setup - throw XCTSkip("Requires real identity data for proper testing") - } - - func testGetIncomingContactRequestIdsAPI() throws { - // Skip until integration tests are set up - throw XCTSkip("Requires real identity data for proper testing") - } - - func testGetEstablishedContactIdsAPI() throws { - // Skip until integration tests are set up - throw XCTSkip("Requires real identity data for proper testing") - } - - // MARK: - Contact Request Sending Tests - - func testSendContactRequestAPI() throws { - // Skip until integration tests are set up - throw XCTSkip("Requires real identity data for proper testing") - } - - func testAcceptContactRequestAPI() throws { - // Skip until integration tests are set up - throw XCTSkip("Requires real identity data for proper testing") - } - - func testRejectContactRequestAPI() throws { - // Skip until integration tests are set up - throw XCTSkip("Requires real identity data for proper testing") - } - - // MARK: - Label Tests - - func testLabelAPI() throws { - // Skip until integration tests are set up - throw XCTSkip("Requires real identity data for proper testing") - } - - // MARK: - Balance Tests - - func testBalanceAPI() throws { - // Skip until integration tests are set up - throw XCTSkip("Requires real identity data for proper testing") - } - - // MARK: - Block Time Tests - - func testBlockTimeAPI() throws { - // Skip until integration tests are set up - throw XCTSkip("Requires real identity data for proper testing") - } - - // MARK: - Contact Establishment Check - - func testIsContactEstablishedAPI() throws { - // Skip until integration tests are set up - throw XCTSkip("Requires real identity data for proper testing") - } - - // MARK: - Memory Management Tests - - func testManagedIdentityDeinit() { - // We can't easily test deinit without creating a real identity - // This is verified through integration tests - XCTAssertTrue(true, "Placeholder for memory management verification") - } -} - -// MARK: - Integration Test Notes - -/* - Full integration tests for ManagedIdentity require: - - 1. Creating a real DPP identity with proper structure - 2. Serializing it to bytes - 3. Creating ManagedIdentity from those bytes - 4. Testing all getters/setters with real data - - These tests should be in a separate integration test suite that: - - Uses real identity creation from Platform SDK - - Tests full contact request flow (send, receive, accept) - - Verifies contact establishment - - Tests label and metadata operations - - Validates balance tracking - - See IntegrationTests.swift for comprehensive testing with real data. - */ diff --git a/packages/swift-sdk/SwiftTests/Tests/SwiftDashSDKTests/MemoryManagementTests.swift b/packages/swift-sdk/SwiftTests/Tests/SwiftDashSDKTests/MemoryManagementTests.swift deleted file mode 100644 index 3917d959b0a..00000000000 --- a/packages/swift-sdk/SwiftTests/Tests/SwiftDashSDKTests/MemoryManagementTests.swift +++ /dev/null @@ -1,232 +0,0 @@ -import XCTest -import SwiftDashSDKMock - -class MemoryManagementTests: XCTestCase { - - var sdk: UnsafeMutablePointer? - - override func setUp() { - super.setUp() - swift_dash_sdk_init() - - let config = swift_dash_sdk_config_testnet() - sdk = swift_dash_sdk_create(config) - XCTAssertNotNil(sdk, "SDK should be created successfully") - } - - override func tearDown() { - if let sdk = sdk { - swift_dash_sdk_destroy(sdk) - } - super.tearDown() - } - - // MARK: - String Memory Management Tests - - func testStringFreeWithNullPointer() { - // Should not crash - swift_dash_string_free(nil) - } - - func testStringFreeWithValidPointer() { - guard let sdk = sdk else { - XCTFail("SDK not initialized") - return - } - - // Get a string from the API - let version = swift_dash_sdk_get_version() - XCTAssertNotNil(version) - - if let version = version { - // This should not crash - swift_dash_string_free(version) - } - - } - - // MARK: - Error Memory Management Tests - - func testErrorFreeWithNullPointer() { - // Should not crash - swift_dash_error_free(nil) - } - - func testErrorFreeWithValidPointer() { - guard let sdk = sdk else { - XCTFail("SDK not initialized") - return - } - - // Generate an error - let result = swift_dash_identity_create(sdk, nil, 0) - XCTAssertFalse(result.success) - XCTAssertNotNil(result.error) - - if let error = result.error { - // This should not crash - swift_dash_error_free(error) - } - - } - - // MARK: - Binary Data Memory Management Tests - - func testBinaryDataFreeWithNullPointer() { - // Should not crash - swift_dash_binary_data_free(nil) - } - - // MARK: - Info Structure Memory Management Tests - - func testIdentityInfoFreeWithNullPointer() { - // Should not crash - swift_dash_identity_info_free(nil) - } - - func testDataContractInfoFreeWithNullPointer() { - // Should not crash - swift_dash_data_contract_info_free(nil) - } - - func testDocumentInfoFreeWithNullPointer() { - // Should not crash - swift_dash_document_info_free(nil) - } - - func testTransferCreditsResultFreeWithNullPointer() { - // Should not crash - swift_dash_transfer_credits_result_free(nil) - } - - func testTokenInfoFreeWithNullPointer() { - // Should not crash - swift_dash_token_info_free(nil) - } - - // MARK: - Signer Memory Management Tests - - func testSignerFreeWithNullPointer() { - // Should not crash - swift_dash_signer_free(nil) - } - - func testSignerCreateAndFree() { - // Mock sign callback - let signCallback: SwiftDashSwiftSignCallback = { _, _, _, _, resultLen in - resultLen?.pointee = 64 - let result = malloc(64) - return result?.assumingMemoryBound(to: UInt8.self) - } - - // Mock can_sign callback - let canSignCallback: SwiftDashSwiftCanSignCallback = { _, _ in - return true - } - - let signer = swift_dash_signer_create(signCallback, canSignCallback) - XCTAssertNotNil(signer, "Signer should be created successfully") - - if let signer = signer { - swift_dash_signer_free(signer) - } - - } - - // MARK: - Bytes Memory Management Tests - - func testBytesFreeWithNullPointer() { - // Should not crash - swift_dash_bytes_free(nil, 0) - } - - func testBytesFreeWithValidPointer() { - // Allocate some bytes - let size = 64 - let bytes = malloc(size)?.assumingMemoryBound(to: UInt8.self) - XCTAssertNotNil(bytes) - - if let bytes = bytes { - // Fill with some data - for i in 0..] = [] - - for _ in 0..<5 { - if let newSdk = swift_dash_sdk_create(config) { - sdks.append(newSdk) - } - } - - XCTAssertEqual(sdks.count, 5, "Should create 5 SDK instances") - - // Destroy all instances - for sdk in sdks { - swift_dash_sdk_destroy(sdk) - } - - } - - // MARK: - Memory Leak Prevention Tests - - func testMemoryLeakPrevention() { - guard let sdk = sdk else { - XCTFail("SDK not initialized") - return - } - - // Stress-test allocation paths to catch memory leaks. - // 100 iterations per path is enough to surface leaks without - // making the test suite slow. - let iterations = 100 - - for _ in 0..() - - // Generate 100 random identifiers - for _ in 0..<100 { - let identifier = try Identifier.random() - let hexString = identifier.hexString - - XCTAssertEqual(hexString.count, 64, "Hex string should be 64 characters (32 bytes)") - XCTAssertFalse(identifiers.contains(hexString), "Should generate unique identifiers") - - identifiers.insert(hexString) - } - - XCTAssertEqual(identifiers.count, 100, "All identifiers should be unique") - } - - func testIdentifierHexConversions() throws { - // Test various hex patterns - let testCases: [String] = [ - "0000000000000000000000000000000000000000000000000000000000000000", - "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", - "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", - "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef" - ] - - for hexString in testCases { - let identifier = try Identifier(hexString: hexString) - let roundTrip = identifier.hexString - - XCTAssertEqual(roundTrip, hexString, "Hex string should round-trip correctly") - } - } - - // MARK: - Memory Management Stress Tests - - func testWalletCreationStressTest() throws { - // Create and destroy many wallets to test memory management - for i in 0..<100 { - let mnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about" - let wallet = try PlatformWallet.fromMnemonic(mnemonic, passphrase: "test\(i)") - let manager = try wallet.getIdentityManager(for: .testnet) - let count = try manager.getIdentityCount() - - XCTAssertGreaterThanOrEqual(count, 0) - } - - // If this completes without crashing, memory management is working - XCTAssertTrue(true, "Stress test completed") - } - - func testIdentifierCreationStressTest() throws { - // Create many identifiers to test memory management - var identifiers: [Identifier] = [] - - for _ in 0..<1000 { - let identifier = try Identifier.random() - identifiers.append(identifier) - } - - XCTAssertEqual(identifiers.count, 1000) - - // Verify all are unique - let uniqueHexStrings = Set(identifiers.map { $0.hexString }) - XCTAssertEqual(uniqueHexStrings.count, 1000, "All identifiers should be unique") - } - - func testContactRequestStressTest() throws { - // Create many contact requests to test memory management - let senderId = try Identifier.random() - let recipientId = try Identifier.random() - let encryptedKey = Data(count: 65) - - for i in 0..<100 { - let request = try ContactRequest.create( - senderId: senderId, - recipientId: recipientId, - senderKeyIndex: UInt32(i), - recipientKeyIndex: 0, - accountReference: 0, - encryptedPublicKey: encryptedKey, - createdAt: UInt64(Date().timeIntervalSince1970 * 1000) - ) - - let keyIndex = try request.getSenderKeyIndex() - XCTAssertEqual(keyIndex, UInt32(i)) - } - - XCTAssertTrue(true, "Stress test completed") - } - - // MARK: - Error Handling Integration - - func testWalletCreationErrorHandling() { - // Test invalid mnemonic - XCTAssertThrowsError(try PlatformWallet.fromMnemonic("invalid mnemonic phrase")) { error in - XCTAssertTrue(error is PlatformWalletError) - } - - // Test invalid seed size - let invalidSeed = Data(count: 10) - XCTAssertThrowsError(try PlatformWallet.fromSeed(invalidSeed)) { error in - if case PlatformWalletError.invalidParameter = error { - // Expected - } else { - XCTFail("Expected invalidParameter error, got \(error)") - } - } - } - - func testIdentityManagerErrorHandling() throws { - let manager = try IdentityManager.create() - let nonExistentId = try Identifier.random() - - // Test getting non-existent identity - XCTAssertThrowsError(try manager.getIdentity(nonExistentId)) { error in - if case PlatformWalletError.identityNotFound = error { - // Expected - } else { - XCTFail("Expected identityNotFound error, got \(error)") - } - } - - // Test removing non-existent identity - XCTAssertThrowsError(try manager.removeIdentity(nonExistentId)) { error in - XCTAssertTrue(error is PlatformWalletError) - } - - // Test setting non-existent identity as primary - XCTAssertThrowsError(try manager.setPrimaryIdentity(nonExistentId)) { error in - XCTAssertTrue(error is PlatformWalletError) - } - } - - // MARK: - Thread Safety Tests (if applicable) - - func testConcurrentWalletCreation() throws { - let expectation = self.expectation(description: "Concurrent wallet creation") - expectation.expectedFulfillmentCount = 10 - - let queue = DispatchQueue(label: "test.concurrent", attributes: .concurrent) - - for i in 0..<10 { - queue.async { - do { - let mnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about" - let wallet = try PlatformWallet.fromMnemonic(mnemonic, passphrase: "test\(i)") - let manager = try wallet.getIdentityManager(for: .testnet) - _ = try manager.getIdentityCount() - expectation.fulfill() - } catch { - XCTFail("Concurrent creation failed: \(error)") - } - } - } - - waitForExpectations(timeout: 10.0) - } - - func testConcurrentIdentifierGeneration() throws { - let expectation = self.expectation(description: "Concurrent identifier generation") - expectation.expectedFulfillmentCount = 100 - - let queue = DispatchQueue(label: "test.concurrent", attributes: .concurrent) - let identifiersLock = NSLock() - var identifiers: [String] = [] - - for _ in 0..<100 { - queue.async { - do { - let identifier = try Identifier.random() - identifiersLock.lock() - identifiers.append(identifier.hexString) - identifiersLock.unlock() - expectation.fulfill() - } catch { - XCTFail("Concurrent generation failed: \(error)") - } - } - } - - waitForExpectations(timeout: 10.0) - - // Verify uniqueness - let uniqueIdentifiers = Set(identifiers) - XCTAssertEqual(uniqueIdentifiers.count, 100, "All concurrently generated identifiers should be unique") - } -} - -// MARK: - Integration Test Notes - -/* - These integration tests verify: - - 1. Full roundtrip of wallet creation and identity management - 2. Proper memory management under stress - 3. Error handling across FFI boundary - 4. Thread safety of concurrent operations - 5. Data integrity through FFI conversions - - Additional tests that require Platform SDK connection: - - Creating real identities on testnet - - Sending and accepting actual contact requests - - Testing established contact metadata persistence - - Verifying balance tracking - - Testing key synchronization - - For full end-to-end testing, see SwiftExampleApp which demonstrates: - - Real wallet and identity lifecycle - - Contact request bidirectional flow - - Established contact management - - Integration with Core wallet for funding - */ diff --git a/packages/swift-sdk/SwiftTests/Tests/SwiftDashSDKTests/PlatformWalletTypesTests.swift b/packages/swift-sdk/SwiftTests/Tests/SwiftDashSDKTests/PlatformWalletTypesTests.swift deleted file mode 100644 index cd73b46261f..00000000000 --- a/packages/swift-sdk/SwiftTests/Tests/SwiftDashSDKTests/PlatformWalletTypesTests.swift +++ /dev/null @@ -1,169 +0,0 @@ -import XCTest -@testable import SwiftDashSDK - -class PlatformWalletTypesTests: XCTestCase { - - // MARK: - Network Tests - - func testNetworkFFIValues() { - XCTAssertEqual(Network.mainnet.ffiValue, 0) - XCTAssertEqual(Network.testnet.ffiValue, 1) - XCTAssertEqual(Network.devnet.ffiValue, 2) - XCTAssertEqual(Network.local.ffiValue, 3) - } - - // MARK: - BlockTime Tests - - func testBlockTimeInit() { - let blockTime = BlockTime(height: 100, coreHeight: 200, timestamp: 1234567890) - - XCTAssertEqual(blockTime.height, 100) - XCTAssertEqual(blockTime.coreHeight, 200) - XCTAssertEqual(blockTime.timestamp, 1234567890) - } - - func testBlockTimeFFIConversion() { - let swiftBlockTime = BlockTime(height: 100, coreHeight: 200, timestamp: 1234567890) - let ffiBlockTime = swiftBlockTime.ffiValue - - XCTAssertEqual(ffiBlockTime.height, 100) - XCTAssertEqual(ffiBlockTime.core_height, 200) - XCTAssertEqual(ffiBlockTime.timestamp, 1234567890) - - // Convert back - let convertedBack = BlockTime(ffiBlockTime: ffiBlockTime) - XCTAssertEqual(convertedBack.height, swiftBlockTime.height) - XCTAssertEqual(convertedBack.coreHeight, swiftBlockTime.coreHeight) - XCTAssertEqual(convertedBack.timestamp, swiftBlockTime.timestamp) - } - - // MARK: - Identifier Tests - - func testIdentifierFromBytes() throws { - let bytes: [UInt8] = Array(repeating: 0x42, count: 32) - let identifier = try Identifier(bytes: bytes) - - XCTAssertEqual(identifier.bytes, bytes) - } - - func testIdentifierFromInvalidBytes() { - let invalidBytes: [UInt8] = Array(repeating: 0x42, count: 10) // Wrong size - - XCTAssertThrowsError(try Identifier(bytes: invalidBytes)) { error in - XCTAssertTrue(error is PlatformWalletError) - if case PlatformWalletError.invalidParameter = error { - // Expected error - } else { - XCTFail("Expected invalidParameter error, got \(error)") - } - } - } - - func testIdentifierFromHexString() throws { - let hexString = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" - let identifier = try Identifier(hexString: hexString) - - XCTAssertEqual(identifier.bytes.count, 32) - XCTAssertEqual(identifier.hexString, hexString) - } - - func testIdentifierFromInvalidHexString() { - let invalidHex = "not-hex-string" - - XCTAssertThrowsError(try Identifier(hexString: invalidHex)) { error in - XCTAssertTrue(error is PlatformWalletError) - } - } - - func testIdentifierFromShortHexString() { - let shortHex = "0123456789abcdef" // Only 16 bytes - - XCTAssertThrowsError(try Identifier(hexString: shortHex)) { error in - XCTAssertTrue(error is PlatformWalletError) - } - } - - func testIdentifierHexStringRoundTrip() throws { - let originalHex = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" - let identifier = try Identifier(hexString: originalHex) - let convertedHex = identifier.hexString - - XCTAssertEqual(convertedHex, originalHex) - } - - func testIdentifierRandom() throws { - let id1 = try Identifier.random() - let id2 = try Identifier.random() - - XCTAssertEqual(id1.bytes.count, 32) - XCTAssertEqual(id2.bytes.count, 32) - - // Random IDs should be different - XCTAssertNotEqual(id1.bytes, id2.bytes, "Random identifiers should be unique") - } - - func testIdentifierFFIConversion() throws { - let bytes: [UInt8] = (0..<32).map { UInt8($0) } - let identifier = try Identifier(bytes: bytes) - - let ffiValue = identifier.ffiValue - let convertedBack = Identifier(ffiIdentifier: ffiValue) - - XCTAssertEqual(convertedBack.bytes, identifier.bytes) - } - - // MARK: - Data Hex Extension Tests - - func testDataFromHexString() { - let hexString = "48656c6c6f" // "Hello" in hex - let data = Data(hexString: hexString) - - XCTAssertNotNil(data) - XCTAssertEqual(data?.count, 5) - - if let data = data { - let string = String(data: data, encoding: .utf8) - XCTAssertEqual(string, "Hello") - } - } - - func testDataFromInvalidHexString() { - let invalidHex = "xyz" - let data = Data(hexString: invalidHex) - - XCTAssertNil(data) - } - - func testDataFromOddLengthHexString() { - let oddHex = "123" // Odd number of characters - let data = Data(hexString: oddHex) - - // Should handle gracefully (depends on implementation) - // Current implementation treats this as 1 byte - XCTAssertNotNil(data) - } - - // MARK: - PlatformWalletError Tests - - func testPlatformWalletErrorMapping() { - // Test that error mapping from FFI results works correctly - // This is tested indirectly through other tests, but we can verify the enum exists - - let errors: [PlatformWalletError] = [ - .nullPointer, - .invalidHandle, - .invalidParameter, - .invalidIdentifier, - .invalidNetwork, - .walletOperation("test"), - .identityNotFound, - .contactNotFound, - .utf8Conversion, - .serialization, - .deserialization, - .unknown("test") - ] - - XCTAssertEqual(errors.count, 12, "All error cases should be defined") - } -} diff --git a/packages/swift-sdk/SwiftTests/Tests/SwiftDashSDKTests/SDKTests.swift b/packages/swift-sdk/SwiftTests/Tests/SwiftDashSDKTests/SDKTests.swift deleted file mode 100644 index 0c5d1fbdf3d..00000000000 --- a/packages/swift-sdk/SwiftTests/Tests/SwiftDashSDKTests/SDKTests.swift +++ /dev/null @@ -1,132 +0,0 @@ -import XCTest -import SwiftDashSDKMock - -class SDKTests: XCTestCase { - - override func setUp() { - super.setUp() - // Initialize the SDK before each test - swift_dash_sdk_init() - } - - // MARK: - Initialization Tests - - func testSDKInitialization() { - let version = swift_dash_sdk_get_version() - XCTAssertNotNil(version, "SDK should provide a version after initialization") - if let version = version { - swift_dash_string_free(version) - } - } - - func testSDKVersion() { - let version = swift_dash_sdk_get_version() - XCTAssertNotNil(version) - - if let version = version { - let versionString = String(cString: version) - XCTAssertFalse(versionString.isEmpty) - XCTAssertTrue( - versionString.range( - of: #"^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$"#, - options: .regularExpression - ) != nil, - "Version should match semantic version format" - ) - swift_dash_string_free(version) - } - } - - // MARK: - Configuration Tests - - func testMainnetConfiguration() { - let config = swift_dash_sdk_config_mainnet() - - XCTAssertEqual(config.network, Mainnet) - XCTAssertNotNil(config.dapi_addresses) - - let dapiAddresses = String(cString: config.dapi_addresses) - XCTAssertFalse(dapiAddresses.isEmpty) - } - - func testTestnetConfiguration() { - let config = swift_dash_sdk_config_testnet() - - XCTAssertEqual(config.network, Testnet) - XCTAssertNotNil(config.dapi_addresses) - - let dapiAddresses = String(cString: config.dapi_addresses) - XCTAssertFalse(dapiAddresses.isEmpty) - } - - func testLocalConfiguration() { - let config = swift_dash_sdk_config_local() - - XCTAssertEqual(config.network, Local) - XCTAssertNotNil(config.dapi_addresses) - - let dapiAddresses = String(cString: config.dapi_addresses) - XCTAssertTrue(dapiAddresses.contains("127.0.0.1")) - } - - func testDefaultPutSettings() { - let settings = swift_dash_put_settings_default() - - XCTAssertEqual(settings.connect_timeout_ms, 0) - XCTAssertEqual(settings.timeout_ms, 0) - XCTAssertEqual(settings.retries, 0) - XCTAssertFalse(settings.ban_failed_address) - XCTAssertEqual(settings.identity_nonce_stale_time_s, 0) - XCTAssertEqual(settings.user_fee_increase, 0) - XCTAssertFalse(settings.allow_signing_with_any_security_level) - XCTAssertFalse(settings.allow_signing_with_any_purpose) - XCTAssertEqual(settings.wait_timeout_ms, 0) - } - - // MARK: - SDK Lifecycle Tests - - func testSDKCreateAndDestroy() { - let config = swift_dash_sdk_config_testnet() - let sdk = swift_dash_sdk_create(config) - - XCTAssertNotNil(sdk) - - if let sdk = sdk { - // Test we can get network from SDK - let network = swift_dash_sdk_get_network(sdk) - XCTAssertEqual(network, Testnet) - - // Clean up - swift_dash_sdk_destroy(sdk) - } - } - - func testSDKDestroyNullHandle() { - // Should not crash - swift_dash_sdk_destroy(nil) - } - - func testGetNetworkWithNullHandle() { - let network = swift_dash_sdk_get_network(nil) - XCTAssertEqual(network, Testnet, "Should return default network for null handle") - } - - // MARK: - Custom Put Settings Tests - - func testCustomPutSettings() { - var settings = swift_dash_put_settings_default() - - // Customize settings - settings.timeout_ms = 60000 // 60 seconds - settings.wait_timeout_ms = 120000 // 2 minutes - settings.retries = 5 - settings.ban_failed_address = true - settings.user_fee_increase = 10 // 10% increase - - XCTAssertEqual(settings.timeout_ms, 60000) - XCTAssertEqual(settings.wait_timeout_ms, 120000) - XCTAssertEqual(settings.retries, 5) - XCTAssertTrue(settings.ban_failed_address) - XCTAssertEqual(settings.user_fee_increase, 10) - } -} diff --git a/packages/swift-sdk/SwiftTests/Tests/SwiftDashSDKTests/SwiftConstants.swift b/packages/swift-sdk/SwiftTests/Tests/SwiftDashSDKTests/SwiftConstants.swift deleted file mode 100644 index 20a9ed73348..00000000000 --- a/packages/swift-sdk/SwiftTests/Tests/SwiftDashSDKTests/SwiftConstants.swift +++ /dev/null @@ -1,13 +0,0 @@ -// Swift constants for SwiftDashSDK -import SwiftDashSDKMock -import Foundation - -// Network type constants -public let Mainnet = SwiftDashNetwork_Mainnet -public let Testnet = SwiftDashNetwork_Testnet -public let Devnet = SwiftDashNetwork_Devnet -public let Local = SwiftDashNetwork_Local - -// Error code constants -public let InvalidParameter = SwiftDashErrorCode_InvalidParameter -public let NotImplemented = SwiftDashErrorCode_NotImplemented diff --git a/packages/swift-sdk/SwiftTests/Tests/SwiftDashSDKTests/TokenTests.swift b/packages/swift-sdk/SwiftTests/Tests/SwiftDashSDKTests/TokenTests.swift deleted file mode 100644 index 9ebb245dc46..00000000000 --- a/packages/swift-sdk/SwiftTests/Tests/SwiftDashSDKTests/TokenTests.swift +++ /dev/null @@ -1,246 +0,0 @@ -import XCTest -import SwiftDashSDKMock - -class TokenTests: XCTestCase { - - var sdk: UnsafeMutablePointer? - - // Test configuration data - let tokenContractId = "GWRSAVFMjXx8HpQFaNJMqBV7MBgMK4br5UESsB4S31Ec" - let existingIdentityId = "4EfA9Jrvv3nnCFdSf7fad59851iiTRZ6Wcu6YVJ4iSeF" - let recipientIdentityId = "7777777777777777777777777777777777777777777" - - override func setUp() { - super.setUp() - swift_dash_sdk_init() - - let config = swift_dash_sdk_config_testnet() - sdk = swift_dash_sdk_create(config) - XCTAssertNotNil(sdk, "SDK should be created successfully") - } - - override func tearDown() { - if let sdk = sdk { - swift_dash_sdk_destroy(sdk) - } - super.tearDown() - } - - // MARK: - Token Total Supply Tests - - func testTokenGetTotalSupply() { - guard let sdk = sdk else { - XCTFail("SDK not initialized") - return - } - - let result = swift_dash_token_get_total_supply(sdk, tokenContractId) - XCTAssertNotNil(result, "Should return total supply") - - if let supplyString = result { - let supplyStr = String(cString: supplyString) - XCTAssertFalse(supplyStr.isEmpty, "Supply string should not be empty") - - // Mock returns "1000000000" - XCTAssertEqual(supplyStr, "1000000000", "Mock should return 1000000000") - - // Clean up - swift_dash_string_free(supplyString) - } - } - - func testTokenGetTotalSupplyWithNullSDK() { - let result = swift_dash_token_get_total_supply(nil, tokenContractId) - XCTAssertNil(result, "Should return nil for null SDK handle") - } - - func testTokenGetTotalSupplyWithNullContractId() { - guard let sdk = sdk else { - XCTFail("SDK not initialized") - return - } - - let result = swift_dash_token_get_total_supply(sdk, nil) - XCTAssertNil(result, "Should return nil for null contract ID") - } - - // MARK: - Token Transfer Tests - - func testTokenTransfer() { - guard let sdk = sdk else { - XCTFail("SDK not initialized") - return - } - - let amount: UInt64 = 1000 - - let result = swift_dash_token_transfer( - sdk, - tokenContractId, - existingIdentityId, - recipientIdentityId, - amount - ) - - // Since this is not implemented in mock, should return not implemented error - XCTAssertFalse(result.success, "Token transfer should fail (not implemented)") - XCTAssertNotNil(result.error, "Should have error for not implemented") - - if let error = result.error { - XCTAssertEqual(error.pointee.code, NotImplemented, "Should be NotImplemented error") - - if let message = error.pointee.message { - let messageStr = String(cString: message) - XCTAssertTrue(messageStr.contains("not yet implemented"), "Error message should mention not implemented") - } - - // Clean up error - swift_dash_error_free(error) - } - } - - func testTokenTransferWithNullParams() { - guard let sdk = sdk else { - XCTFail("SDK not initialized") - return - } - - // Test with null SDK - var result = swift_dash_token_transfer(nil, tokenContractId, existingIdentityId, recipientIdentityId, 1000) - XCTAssertFalse(result.success, "Should fail with null SDK") - if let error = result.error { - XCTAssertEqual(error.pointee.code, InvalidParameter, "Should be InvalidParameter error") - swift_dash_error_free(error) - } - - // Test with null token contract ID - result = swift_dash_token_transfer(sdk, nil, existingIdentityId, recipientIdentityId, 1000) - XCTAssertFalse(result.success, "Should fail with null token contract ID") - if let error = result.error { - XCTAssertEqual(error.pointee.code, InvalidParameter, "Should be InvalidParameter error") - swift_dash_error_free(error) - } - - // Test with null from identity ID - result = swift_dash_token_transfer(sdk, tokenContractId, nil, recipientIdentityId, 1000) - XCTAssertFalse(result.success, "Should fail with null from identity ID") - if let error = result.error { - XCTAssertEqual(error.pointee.code, InvalidParameter, "Should be InvalidParameter error") - swift_dash_error_free(error) - } - - // Test with null to identity ID - result = swift_dash_token_transfer(sdk, tokenContractId, existingIdentityId, nil, 1000) - XCTAssertFalse(result.success, "Should fail with null to identity ID") - if let error = result.error { - XCTAssertEqual(error.pointee.code, InvalidParameter, "Should be InvalidParameter error") - swift_dash_error_free(error) - } - } - - // MARK: - Token Mint Tests - - func testTokenMint() { - guard let sdk = sdk else { - XCTFail("SDK not initialized") - return - } - - let amount: UInt64 = 5000 - - let result = swift_dash_token_mint(sdk, tokenContractId, existingIdentityId, amount) - - // Since this is not implemented in mock, should return not implemented error - XCTAssertFalse(result.success, "Token minting should fail (not implemented)") - XCTAssertNotNil(result.error, "Should have error for not implemented") - - if let error = result.error { - XCTAssertEqual(error.pointee.code, NotImplemented, "Should be NotImplemented error") - swift_dash_error_free(error) - } - } - - func testTokenMintWithNullParams() { - guard let sdk = sdk else { - XCTFail("SDK not initialized") - return - } - - // Test with null SDK - var result = swift_dash_token_mint(nil, tokenContractId, existingIdentityId, 1000) - XCTAssertFalse(result.success, "Should fail with null SDK") - if let error = result.error { - XCTAssertEqual(error.pointee.code, InvalidParameter, "Should be InvalidParameter error") - swift_dash_error_free(error) - } - - // Test with null token contract ID - result = swift_dash_token_mint(sdk, nil, existingIdentityId, 1000) - XCTAssertFalse(result.success, "Should fail with null token contract ID") - if let error = result.error { - XCTAssertEqual(error.pointee.code, InvalidParameter, "Should be InvalidParameter error") - swift_dash_error_free(error) - } - - // Test with null to identity ID - result = swift_dash_token_mint(sdk, tokenContractId, nil, 1000) - XCTAssertFalse(result.success, "Should fail with null to identity ID") - if let error = result.error { - XCTAssertEqual(error.pointee.code, InvalidParameter, "Should be InvalidParameter error") - swift_dash_error_free(error) - } - } - - // MARK: - Token Burn Tests - - func testTokenBurn() { - guard let sdk = sdk else { - XCTFail("SDK not initialized") - return - } - - let amount: UInt64 = 2000 - - let result = swift_dash_token_burn(sdk, tokenContractId, existingIdentityId, amount) - - // Since this is not implemented in mock, should return not implemented error - XCTAssertFalse(result.success, "Token burning should fail (not implemented)") - XCTAssertNotNil(result.error, "Should have error for not implemented") - - if let error = result.error { - XCTAssertEqual(error.pointee.code, NotImplemented, "Should be NotImplemented error") - swift_dash_error_free(error) - } - } - - func testTokenBurnWithNullParams() { - guard let sdk = sdk else { - XCTFail("SDK not initialized") - return - } - - // Test with null SDK - var result = swift_dash_token_burn(nil, tokenContractId, existingIdentityId, 1000) - XCTAssertFalse(result.success, "Should fail with null SDK") - if let error = result.error { - XCTAssertEqual(error.pointee.code, InvalidParameter, "Should be InvalidParameter error") - swift_dash_error_free(error) - } - - // Test with null token contract ID - result = swift_dash_token_burn(sdk, nil, existingIdentityId, 1000) - XCTAssertFalse(result.success, "Should fail with null token contract ID") - if let error = result.error { - XCTAssertEqual(error.pointee.code, InvalidParameter, "Should be InvalidParameter error") - swift_dash_error_free(error) - } - - // Test with null from identity ID - result = swift_dash_token_burn(sdk, tokenContractId, nil, 1000) - XCTAssertFalse(result.success, "Should fail with null from identity ID") - if let error = result.error { - XCTAssertEqual(error.pointee.code, InvalidParameter, "Should be InvalidParameter error") - swift_dash_error_free(error) - } - } -} diff --git a/packages/swift-sdk/SwiftTests/run_tests.sh b/packages/swift-sdk/SwiftTests/run_tests.sh deleted file mode 100755 index 786db56f0f3..00000000000 --- a/packages/swift-sdk/SwiftTests/run_tests.sh +++ /dev/null @@ -1,72 +0,0 @@ -#!/bin/bash - -# Swift SDK Test Runner Script -# This script runs the Swift SDK tests using Swift Package Manager - -set -e - -SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" - -echo "๐Ÿงช Running Swift SDK Tests..." -echo "==========================" - -# Change to the test directory -cd "$SCRIPT_DIR" - -# Clean build artifacts -echo "๐Ÿงน Cleaning build artifacts..." -swift package clean - -# Build the test package -echo "๐Ÿ”จ Building test package..." -swift build - -# Run tests with verbose output -echo "๐Ÿƒ Running tests..." -swift test --verbose - -# Check test results -if [ $? -eq 0 ]; then - echo "" - echo "โœ… All tests passed!" - echo "" - - # Optionally run with coverage - if [[ "$1" == "--coverage" ]]; then - echo "๐Ÿ“Š Generating code coverage..." - swift test --enable-code-coverage - - # Find the coverage data - COV_BUILD_DIR=$(swift build --show-bin-path) - COV_DATA="${COV_BUILD_DIR}/codecov/default.profdata" - - if [ -f "$COV_DATA" ]; then - echo "Coverage data generated at: $COV_DATA" - fi - fi -else - echo "" - echo "โŒ Tests failed!" - exit 1 -fi - -# Optional: Run specific test suites -if [[ "$1" == "--filter" && -n "$2" ]]; then - echo "" - echo "๐Ÿ” Running filtered tests: $2" - swift test --filter "$2" -fi - -# Show test summary -echo "" -echo "๐Ÿ“‹ Test Summary:" -echo "===============" -swift test list | grep -E "test[A-Z]" | wc -l | xargs echo "Total test methods:" - -# Group by test class -echo "" -echo "Tests by class:" -swift test list | grep -E "^[A-Za-z]+Tests" | sort | uniq -c - -echo "" -echo "๐ŸŽ‰ Test run complete!" diff --git a/packages/swift-sdk/Tests/SwiftDashSDKTests/IdentityManagerTests.swift b/packages/swift-sdk/Tests/SwiftDashSDKTests/IdentityManagerTests.swift new file mode 100644 index 00000000000..755a7fa5765 --- /dev/null +++ b/packages/swift-sdk/Tests/SwiftDashSDKTests/IdentityManagerTests.swift @@ -0,0 +1,30 @@ +import XCTest +@testable import SwiftDashSDK + +class IdentityManagerTests: XCTestCase { + + var identityManager: IdentityManager! + + override func setUp() { + super.setUp() + + do { + identityManager = try IdentityManager.create() + } catch { + XCTFail("Failed to set up test: \(error)") + } + } + + // MARK: - Identity Getters Tests + + func testInitialIdentityGetters() throws { + let count = try identityManager.getIdentityCount() + XCTAssertEqual(count, 0, "New manager should have 0 identities") + + let ids = try identityManager.getAllIdentityIds() + XCTAssertEqual(ids.count, 0, "New manager should have no identities") + + let primaryId = try identityManager.getPrimaryIdentityId() + XCTAssertNil(primaryId, "Should return nil when no primary identity") + } +} diff --git a/packages/swift-sdk/Tests/SwiftDashSDKTests/PlatformWalletIntegrationTests.swift b/packages/swift-sdk/Tests/SwiftDashSDKTests/PlatformWalletIntegrationTests.swift new file mode 100644 index 00000000000..ffcc7fb0656 --- /dev/null +++ b/packages/swift-sdk/Tests/SwiftDashSDKTests/PlatformWalletIntegrationTests.swift @@ -0,0 +1,127 @@ +import XCTest +@testable import SwiftDashSDK + +/// Integration tests for Platform Wallet with real identity data and contact flows +/// These tests require the full FFI stack to be built and linked +class PlatformWalletIntegrationTests: XCTestCase { + + var wallet: PlatformWallet! + var identityManager: IdentityManager! + + override func setUp() { + super.setUp() + + do { + // Create a test wallet from mnemonic + let mnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about" + wallet = try PlatformWallet.fromMnemonic(mnemonic) + identityManager = try wallet.getIdentityManager(for: .testnet) + } catch { + XCTFail("Failed to set up integration test: \(error)") + } + } + + // MARK: - Wallet and Identity Manager Integration + + func testWalletToIdentityManagerFlow() throws { + // Verify we can create wallet and get identity manager + XCTAssertNotNil(wallet) + XCTAssertNotNil(identityManager) + + // Verify initial state + let count = try identityManager.getIdentityCount() + XCTAssertGreaterThanOrEqual(count, 0, "Should have zero or more identities") + + let ids = try identityManager.getAllIdentityIds() + XCTAssertEqual(ids.count, count, "ID count should match identity count") + } + + func testMultipleNetworkIdentityManagers() throws { + let mainnetManager = try wallet.getIdentityManager(for: .mainnet) + let testnetManager = try wallet.getIdentityManager(for: .testnet) + let devnetManager = try wallet.getIdentityManager(for: .devnet) + + XCTAssertNotEqual(mainnetManager.handle, testnetManager.handle) + XCTAssertNotEqual(testnetManager.handle, devnetManager.handle) + XCTAssertNotEqual(mainnetManager.handle, devnetManager.handle) + } + + // MARK: - BlockTime Integration + + func testBlockTimeRoundTrip() throws { + let originalBlockTime = BlockTime( + height: 1000, + coreHeight: 2000, + timestamp: 1234567890 + ) + + let ffiBlockTime = originalBlockTime.ffiValue + let convertedBlockTime = BlockTime(ffiBlockTime: ffiBlockTime) + + XCTAssertEqual(convertedBlockTime.height, originalBlockTime.height) + XCTAssertEqual(convertedBlockTime.coreHeight, originalBlockTime.coreHeight) + XCTAssertEqual(convertedBlockTime.timestamp, originalBlockTime.timestamp) + } + + // MARK: - Memory Management Stress Tests + + func testWalletCreationStressTest() throws { + // Create and destroy many wallets to test memory management + for i in 0..<100 { + let mnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about" + let wallet = try PlatformWallet.fromMnemonic(mnemonic, passphrase: "test\(i)") + let manager = try wallet.getIdentityManager(for: .testnet) + let count = try manager.getIdentityCount() + + XCTAssertGreaterThanOrEqual(count, 0) + } + + // If this completes without crashing, memory management is working + XCTAssertTrue(true, "Stress test completed") + } + + // MARK: - Error Handling Integration + + func testWalletCreationErrorHandling() { + // Test invalid mnemonic + XCTAssertThrowsError(try PlatformWallet.fromMnemonic("invalid mnemonic phrase")) { error in + XCTAssertTrue(error is PlatformWalletError) + } + + // Test invalid seed size + let invalidSeed = Data(count: 10) + XCTAssertThrowsError(try PlatformWallet.fromSeed(invalidSeed)) { error in + if case PlatformWalletError.invalidParameter = error { + // Expected + } else { + XCTFail("Expected invalidParameter error, got \(error)") + } + } + } + + // MARK: - Thread Safety Tests (if applicable) + + @MainActor + func testConcurrentWalletCreation() throws { + let expectation = self.expectation(description: "Concurrent wallet creation") + expectation.expectedFulfillmentCount = 10 + + let queue = DispatchQueue(label: "test.concurrent", attributes: .concurrent) + + for i in 0..<10 { + queue.async { + do { + let mnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about" + let wallet = try PlatformWallet.fromMnemonic(mnemonic, passphrase: "test\(i)") + let manager = try wallet.getIdentityManager(for: .testnet) + _ = try manager.getIdentityCount() + expectation.fulfill() + } catch { + XCTFail("Concurrent creation failed: \(error)") + } + } + } + + waitForExpectations(timeout: 10.0) + } +} diff --git a/packages/swift-sdk/SwiftTests/Tests/SwiftDashSDKTests/PlatformWalletTests.swift b/packages/swift-sdk/Tests/SwiftDashSDKTests/PlatformWalletTests.swift similarity index 89% rename from packages/swift-sdk/SwiftTests/Tests/SwiftDashSDKTests/PlatformWalletTests.swift rename to packages/swift-sdk/Tests/SwiftDashSDKTests/PlatformWalletTests.swift index ad2fa23c413..68adf7e6c9a 100644 --- a/packages/swift-sdk/SwiftTests/Tests/SwiftDashSDKTests/PlatformWalletTests.swift +++ b/packages/swift-sdk/Tests/SwiftDashSDKTests/PlatformWalletTests.swift @@ -83,19 +83,4 @@ class PlatformWalletTests: XCTestCase { XCTAssertNotEqual(mainnetManager.handle, testnetManager.handle, "Different networks should have different managers") XCTAssertNotEqual(testnetManager.handle, devnetManager.handle, "Different networks should have different managers") } - - // MARK: - Memory Management Tests - - func testWalletDeinit() throws { - var wallet: PlatformWallet? = try PlatformWallet.fromSeed(testSeed) - let handle = wallet?.handle - - XCTAssertNotNil(handle) - - // Release wallet - should call deinit - wallet = nil - - // If this doesn't crash, memory management is working - XCTAssertNil(wallet) - } } diff --git a/packages/swift-sdk/Tests/SwiftDashSDKTests/PlatformWalletTypesTests.swift b/packages/swift-sdk/Tests/SwiftDashSDKTests/PlatformWalletTypesTests.swift new file mode 100644 index 00000000000..1a883ee7357 --- /dev/null +++ b/packages/swift-sdk/Tests/SwiftDashSDKTests/PlatformWalletTypesTests.swift @@ -0,0 +1,84 @@ +import XCTest +@testable import SwiftDashSDK + +class PlatformWalletTypesTests: XCTestCase { + // MARK: - BlockTime Tests + + func testBlockTimeInit() { + let blockTime = BlockTime(height: 100, coreHeight: 200, timestamp: 1234567890) + + XCTAssertEqual(blockTime.height, 100) + XCTAssertEqual(blockTime.coreHeight, 200) + XCTAssertEqual(blockTime.timestamp, 1234567890) + } + + func testBlockTimeFFIConversion() { + let swiftBlockTime = BlockTime(height: 100, coreHeight: 200, timestamp: 1234567890) + let ffiBlockTime = swiftBlockTime.ffiValue + + XCTAssertEqual(ffiBlockTime.height, 100) + XCTAssertEqual(ffiBlockTime.core_height, 200) + XCTAssertEqual(ffiBlockTime.timestamp, 1234567890) + + // Convert back + let convertedBack = BlockTime(ffiBlockTime: ffiBlockTime) + XCTAssertEqual(convertedBack.height, swiftBlockTime.height) + XCTAssertEqual(convertedBack.coreHeight, swiftBlockTime.coreHeight) + XCTAssertEqual(convertedBack.timestamp, swiftBlockTime.timestamp) + } + + // MARK: - Data Hex Extension Tests + + func testDataFromHexString() { + let hexString = "48656c6c6f" // "Hello" in hex + let data = Data(hexString: hexString) + + XCTAssertNotNil(data) + XCTAssertEqual(data?.count, 5) + + if let data = data { + let string = String(data: data, encoding: .utf8) + XCTAssertEqual(string, "Hello") + } + } + + func testDataFromInvalidHexString() { + let invalidHex = "xyz" + let data = Data(hexString: invalidHex) + + XCTAssertNil(data) + } + + func testDataFromOddLengthHexString() { + let oddHex = "123" // Odd number of characters + let data = Data(hexString: oddHex) + + // Should handle gracefully (depends on implementation) + // Current implementation treats this as 1 byte + XCTAssertNotNil(data) + } + + // MARK: - PlatformWalletError Tests + + func testPlatformWalletErrorMapping() { + // Test that error mapping from FFI results works correctly + // This is tested indirectly through other tests, but we can verify the enum exists + + let errors: [PlatformWalletError] = [ + .nullPointer, + .invalidHandle, + .invalidParameter, + .invalidIdentifier, + .invalidNetwork, + .walletOperation("test"), + .identityNotFound, + .contactNotFound, + .utf8Conversion, + .serialization, + .deserialization, + .unknown("test") + ] + + XCTAssertEqual(errors.count, 12, "All error cases should be defined") + } +} diff --git a/packages/swift-sdk/Tests/SwiftDashSDKTests/KeyWallet/WalletSerializationTests.swift b/packages/swift-sdk/Tests/SwiftDashSDKTests/WalletSerializationTests.swift similarity index 96% rename from packages/swift-sdk/Tests/SwiftDashSDKTests/KeyWallet/WalletSerializationTests.swift rename to packages/swift-sdk/Tests/SwiftDashSDKTests/WalletSerializationTests.swift index a978fbd69df..2875197d376 100644 --- a/packages/swift-sdk/Tests/SwiftDashSDKTests/KeyWallet/WalletSerializationTests.swift +++ b/packages/swift-sdk/Tests/SwiftDashSDKTests/WalletSerializationTests.swift @@ -14,7 +14,6 @@ final class WalletSerializationTests: XCTestCase { let (walletId1, serializedWallet) = try manager1.addWalletAndSerialize( mnemonic: mnemonic, passphrase: nil, - network: .testnet, birthHeight: 0, accountOptions: .default, downgradeToPublicKeyWallet: false, @@ -42,8 +41,8 @@ final class WalletSerializationTests: XCTestCase { XCTAssertTrue(wallets2.contains(walletId2), "Manager 2 should contain the imported wallet") // Verify addresses match - let address1 = try manager1.getReceiveAddress(walletId: walletId1, network: .testnet) - let address2 = try manager2.getReceiveAddress(walletId: walletId2, network: .testnet) + let address1 = try manager1.getReceiveAddress(walletId: walletId1) + let address2 = try manager2.getReceiveAddress(walletId: walletId2) XCTAssertEqual(address1, address2, "Addresses should match after import") } @@ -57,7 +56,6 @@ final class WalletSerializationTests: XCTestCase { let (walletId, serializedWallet) = try manager.addWalletAndSerialize( mnemonic: mnemonic, passphrase: nil, - network: .testnet, birthHeight: 100000, accountOptions: .default, downgradeToPublicKeyWallet: true, @@ -74,7 +72,7 @@ final class WalletSerializationTests: XCTestCase { XCTAssertEqual(walletId, importedWalletId, "Wallet IDs should match") // Verify we can get addresses (watch-only wallets can still derive addresses) - let address = try manager2.getReceiveAddress(walletId: importedWalletId, network: .testnet) + let address = try manager2.getReceiveAddress(walletId: importedWalletId) XCTAssertFalse(address.isEmpty, "Should be able to get address from watch-only wallet") } @@ -87,7 +85,6 @@ final class WalletSerializationTests: XCTestCase { let (walletId, serializedWallet) = try manager.addWalletAndSerialize( mnemonic: mnemonic, passphrase: "test-passphrase", - network: .mainnet, birthHeight: 50000, accountOptions: .default, downgradeToPublicKeyWallet: true, @@ -145,7 +142,6 @@ final class WalletSerializationTests: XCTestCase { for mnemonic in mnemonics { let (walletId, serialized) = try manager.addWalletAndSerialize( mnemonic: mnemonic, - network: .testnet ) serializedWallets.append((walletId: walletId, serialized: serialized)) } diff --git a/packages/swift-sdk/example/SwiftSDKExample.swift b/packages/swift-sdk/example/SwiftSDKExample.swift deleted file mode 100644 index 1ba11656a4b..00000000000 --- a/packages/swift-sdk/example/SwiftSDKExample.swift +++ /dev/null @@ -1,253 +0,0 @@ -import Foundation - -// This example demonstrates how to use the Swift Dash SDK -// The actual implementation would import the compiled library - -class SwiftDashSDKExample { - - func runExample() { - // Initialize the SDK - swift_dash_sdk_init() - - // Create SDK configuration for testnet - let config = swift_dash_sdk_config_testnet() - - // Create SDK instance - guard let sdk = swift_dash_sdk_create(config) else { - print("Failed to create SDK instance") - return - } - - defer { - // Always clean up SDK when done - swift_dash_sdk_destroy(sdk) - } - - // Create a test signer for development - guard let signer = swift_dash_signer_create_test() else { - print("Failed to create test signer") - return - } - - defer { - swift_dash_signer_destroy(signer) - } - - // Example: Working with identities - identityExample(sdk: sdk, signer: signer) - - // Example: Working with data contracts - dataContractExample(sdk: sdk, signer: signer) - - // Example: Working with documents - documentExample(sdk: sdk, signer: signer) - } - - func identityExample(sdk: OpaquePointer, signer: OpaquePointer) { - print("\n--- Identity Example ---") - - // Fetch an identity by ID - let identityId = "GWRSAVFMjXx8HpQFaNJMqBV7MBgMK4br5UESsB4S31Ec" - - guard let identity = swift_dash_identity_fetch(sdk, identityId) else { - print("Failed to fetch identity") - return - } - - // Get identity information - if let info = swift_dash_identity_get_info(identity) { - defer { - swift_dash_identity_info_free(info) - } - - let idString = String(cString: info.pointee.id) - print("Identity ID: \(idString)") - print("Balance: \(info.pointee.balance) credits") - print("Revision: \(info.pointee.revision)") - print("Public Keys: \(info.pointee.public_keys_count)") - } - - // Example: Put identity to platform with instant lock - var settings = swift_dash_put_settings_default() - settings.timeout_ms = 60000 // 60 seconds - settings.wait_timeout_ms = 120000 // 2 minutes - - if let result = swift_dash_identity_put_to_platform_with_instant_lock( - sdk, identity, 0, signer, &settings - ) { - defer { - swift_dash_binary_data_free(result) - } - - print("State transition size: \(result.pointee.len) bytes") - - // Convert to Data for further processing - let data = Data(bytes: result.pointee.data, count: result.pointee.len) - print("State transition created successfully") - } - - // Example: Transfer credits - let recipientId = "4EfA9Jrvv3nnCFdSf7fad59851iiTRZ6Wcu6YVJ8ihhL" - let amount: UInt64 = 1000000 // 1 million credits - - if let transferResult = swift_dash_identity_transfer_credits( - sdk, identity, recipientId, amount, 0, signer, &settings - ) { - defer { - swift_dash_transfer_credits_result_free(transferResult) - } - - print("Transferred \(transferResult.pointee.amount) credits") - let recipient = String(cString: transferResult.pointee.recipient_id) - print("To recipient: \(recipient)") - } - } - - func dataContractExample(sdk: OpaquePointer, signer: OpaquePointer) { - print("\n--- Data Contract Example ---") - - // Create a simple data contract - let ownerId = "GWRSAVFMjXx8HpQFaNJMqBV7MBgMK4br5UESsB4S31Ec" - let contractSchema = """ - { - "$formatVersion": "0", - "ownerId": "\(ownerId)", - "documents": { - "message": { - "type": "object", - "properties": { - "content": { - "type": "string", - "maxLength": 280 - }, - "author": { - "type": "string" - }, - "timestamp": { - "type": "integer" - } - }, - "required": ["content", "author", "timestamp"], - "additionalProperties": false - } - } - } - """ - - guard let contract = swift_dash_data_contract_create(sdk, ownerId, contractSchema) else { - print("Failed to create data contract") - return - } - - // Get contract info - if let infoJson = swift_dash_data_contract_get_info(contract) { - defer { - swift_dash_string_free(infoJson) - } - - let info = String(cString: infoJson) - print("Contract info: \(info)") - } - - // Put contract to platform - var settings = swift_dash_put_settings_default() - settings.user_fee_increase = 10 // 10% fee increase for priority - - if let result = swift_dash_data_contract_put_to_platform( - sdk, contract, 0, signer, &settings - ) { - defer { - swift_dash_binary_data_free(result) - } - - print("Data contract state transition created") - print("Size: \(result.pointee.len) bytes") - } - } - - func documentExample(sdk: OpaquePointer, signer: OpaquePointer) { - print("\n--- Document Example ---") - - // First, fetch the data contract - let contractId = "GWRSAVFMjXx8HpQFaNJMqBV7MBgMK4br5UESsB4S31Ec" - guard let contract = swift_dash_data_contract_fetch(sdk, contractId) else { - print("Failed to fetch data contract") - return - } - - // Create a new document - let ownerId = "4EfA9Jrvv3nnCFdSf7fad59851iiTRZ6Wcu6YVJ8ihhL" - let documentType = "message" - let documentData = """ - { - "content": "Hello from Swift Dash SDK!", - "author": "Swift Developer", - "timestamp": \(Int(Date().timeIntervalSince1970 * 1000)) - } - """ - - guard let document = swift_dash_document_create( - sdk, contract, ownerId, documentType, documentData - ) else { - print("Failed to create document") - return - } - - // Get document info - if let info = swift_dash_document_get_info(document) { - defer { - swift_dash_document_info_free(info) - } - - let docId = String(cString: info.pointee.id) - let docType = String(cString: info.pointee.document_type) - print("Document ID: \(docId)") - print("Document Type: \(docType)") - print("Revision: \(info.pointee.revision)") - } - - // Put document to platform and wait for confirmation - var settings = swift_dash_put_settings_default() - settings.retries = 5 - settings.ban_failed_address = true - - if let confirmedDoc = swift_dash_document_put_to_platform_and_wait( - sdk, document, 0, signer, &settings - ) { - print("Document successfully published to platform!") - - // Get info of confirmed document - if let confirmedInfo = swift_dash_document_get_info(confirmedDoc) { - defer { - swift_dash_document_info_free(confirmedInfo) - } - - let docId = String(cString: confirmedInfo.pointee.id) - print("Confirmed document ID: \(docId)") - } - } - - // Example: Purchase a document - let docToPurchase = "someDocumentId123" - if let docToBuy = swift_dash_document_fetch( - sdk, contract, documentType, docToPurchase - ) { - if let purchaseResult = swift_dash_document_purchase_to_platform( - sdk, docToBuy, 0, signer, &settings - ) { - defer { - swift_dash_binary_data_free(purchaseResult) - } - - print("Document purchase state transition created") - } - } - } -} - -// Helper function to safely free C strings -func swift_dash_string_free(_ string: UnsafeMutablePointer?) { - guard let string = string else { return } - // This would call the actual C function - // ios_sdk_string_free(string) -} diff --git a/packages/swift-sdk/run_tests.sh b/packages/swift-sdk/run_tests.sh new file mode 100755 index 00000000000..06bf5d48762 --- /dev/null +++ b/packages/swift-sdk/run_tests.sh @@ -0,0 +1,14 @@ +#!/bin/bash +set -euo pipefail + +SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" + +echo "Running Swift SDK Tests" + +cd "$SCRIPT_DIR" || exit 1 + +bash build_ios.sh --target mac --profile dev + +swift package clean +swift build +swift test --verbose