- 🎯 Type-Safe Design: Swift types generated directly from OpenAPI specification
- ⚡ Native Swift Performance: Built with modern Swift concurrency (async/await)
- 🎬 Actor-Based Client: Thread-safe actor model for concurrent request handling
- 🛡️ Comprehensive Type System: Codable types for all RPC requests and responses
- 🔀 Discriminated Union Types: Helper enums for complex requests like
queryandchanges - 📦 Zero Dependencies: Pure Swift implementation with no external dependencies
- 🧪 Extensive Test Coverage: Comprehensive test suites with mock data
- 🔄 Auto-Generated Code: Types, methods, and tests generated from NEAR's OpenAPI spec
- 📱 Multi-Platform: Support for iOS 13+ and macOS 10.15+
- 🎭 Mock Data Generation: Python-based mock JSON generation for testing
A type-safe, high-performance Swift Package Manager library for interacting with NEAR Protocol JSON-RPC API. Built with Swift concurrency features and automatically generated from the official OpenAPI specification.
| Module | Description |
|---|---|
NearJsonRpcClient |
JSON-RPC client with all RPC method wrappers |
NearJsonRpcTypes |
Swift Codable types for requests and responses |
Add to your Package.swift:
dependencies: [
.package(url: "https://github.com/space-rock/near-jsonrpc-swift.git", from: "1.0.0")
]Then you can add the NearJsonRpcClient and NearJsonRpcTypes module products as dependency to the targets of your choosing, by adding it to the dependencies value of your targets.
dependencies: [
.product(name: "NearJsonRpcClient", package: "near-jsonrpc-swift"),
.product(name: "NearJsonRpcTypes", package: "near-jsonrpc-swift")
]Or in Xcode:
- File → Add Package Dependencies
- Enter:
https://github.com/space-rock/near-jsonrpc-swift.git
import NearJsonRpcClient
import NearJsonRpcTypes
// Initialize client
let client = try NearRpcClient(baseURLString: "https://rpc.testnet.near.org")
// Query block information
let blockRequest = RpcBlockRequest.finality(.final)
let blockResponse = try await client.block(blockRequest)
print("Block hash: \(blockResponse.header.hash)")
// Query account details
let queryRequest = RpcQueryRequest.viewAccountByFinality(
ViewAccountByFinality(
finality: .final,
accountId: "example.testnet",
requestType: .viewAccount
)
)
let queryResponse = try await client.query(queryRequest)
// Check node health
let healthRequest = RpcHealthRequest()
let healthResponse = try await client.health(healthRequest)- Swift 6.1 or later
- Xcode 15.0+ (for iOS/macOS development)
- Python 3.8+ (for code generation)
# Clone the repository
git clone https://github.com/space-rock/near-jsonrpc-swift.git
cd near-jsonrpc-swift
# Setup Python environment for code generation
cd Scripts
./setup.sh
cd ..
# Build the package
swift build
# Run tests
swift testThe project uses Python scripts to generate Swift code from NEAR's OpenAPI specification:
-
Types & Methods (
Scripts/generate_types.py)- Generates
Sources/NearJsonRpcTypes/Types.swiftwith all Codable types - Generates
Sources/NearJsonRpcClient/Methods.swiftwith RPC method wrappers - Parses OpenAPI spec and creates Swift enums, structs, and protocols
- Generates
-
Mock Data (
Scripts/generate_mock.py)- Generates JSON mock files in
Tests/*/Mock/directories - Creates valid test data for all type structures
- Generates JSON mock files in
-
Test Suites (
Scripts/generate_tests.py)- Generates comprehensive unit tests
- Creates decoding tests for all types
- Ensures type safety across the entire API surface
# Generate all code (types, mocks, and tests)
cd Scripts
./codegen.sh
# Or run individual generators
python3 generate_types.py # Generate Swift types and methods
python3 generate_mock.py # Generate mock JSON data
python3 generate_tests.py # Generate test files# Download the latest OpenAPI spec
curl -L -o Scripts/openapi.json https://raw.githubusercontent.com/near/near-jsonrpc-client-rs/master/openapi.json
# Regenerate all code
cd Scripts
./codegen.sh# Run all tests
swift test
# Run with verbose output
swift test --verbose
# Run specific test suite
swift test --filter NearJsonRpcClientTests
swift test --filter NearJsonRpcTypesTests- Unit Tests: Test individual components and methods
- Integration Tests: Test actual RPC calls (when enabled)
- Decoding Tests: Verify all types decode correctly from mock JSON
- Mock Data: Comprehensive JSON fixtures for all response types
See Examples/Sources/Example.swift for a comprehensive demonstration of all RPC methods.
# Run the example
cd Examples
swift runThe client uses typed throws for precise error handling. All RPC methods throw NearJsonRpcError, which encapsulates all possible error cases.
do {
let response = try await client.block(request)
// Handle success
} catch {
switch error {
case .invalidURL(let url):
print("Invalid URL: \(url)")
case .httpError(let code):
print("HTTP error: \(code)")
case .rpcError(let rpcError):
print("RPC error: \(rpcError.message)")
case .decodingError(let decodingError):
print("Decoding failed: \(decodingError)")
case .invalidResponse:
print("Invalid response from server")
}
}The NearJsonRpcError enum provides comprehensive error cases:
invalidURL(String): The provided URL string is malformedinvalidResponse: The server response is not a valid HTTP responsehttpError(Int): HTTP request failed with the given status coderpcError(RpcError): NEAR RPC returned an error responsedecodingError(Error): Failed to decode the response data
-
Type-Safe Swift
- Generated from OpenAPI spec
- Comprehensive Codable conformance
- Swift enums for variants
-
Modern Concurrency
- Actor-based client for thread safety
- Async/await for all network calls
- Structured concurrency support
-
Zero Dependencies
- Built on Foundation and URLSession
- No external dependencies
- Minimal runtime overhead
-
Generated Code
- Types auto-generated from spec
- Methods auto-generated with proper signatures
- Tests auto-generated for coverage
For more detailed information, check out:
- CONTRIBUTING.md - Guidelines for contributing to the project
- SETUP.md - Complete development environment setup guide
- DEPLOYMENT.md - Release and deployment procedures
Contributions are welcome! Please read our Contributing Guide for details on our development process, coding standards, and how to submit pull requests.
Quick checklist before submitting a PR:
- All tests pass (
swift test) - Code is formatted with
swiftformat - New features include tests
- Generated code is updated if needed
# Before submitting a PR
swift test # Run all tests
swiftformat Sources/ Tests/ Examples/ # Format code
cd Scripts && ./codegen.sh # Regenerate if neededSee CONTRIBUTING.md for complete contribution guidelines.
MIT License - see LICENSE for details.
Built with ❤️ for the NEAR Swift community