Saraf
A crypto and gold trading app for the Iranian market, moved onto a modular MVVM-C architecture while it kept shipping. Twenty-five feature modules, a documented DI container and 534 tests, migrated one flow at a time next to the old code.
- Role
- Senior iOS Engineer
- When
- May 2025 to Jul 2026
- Stack
- Swift · SwiftUI · Combine · Swift Concurrency · WidgetKit
- Scale
- 25 feature modules · 534 tests · 514 new files
A trading app that could not stop shipping
Saraf is an iOS app for buying, holding and selling crypto and gold-backed assets priced in Toman. It has KYC-gated trading, bank and card management, and a home-screen price widget. A second flow, AlSaraf, serves an Arabic-speaking market and guest users from the same app.
I joined as Senior iOS Engineer in May 2025 and stayed until July 2026. My main job was to move the app off its original architecture and onto a modular one while the team kept shipping features. Nobody was going to give us a freeze to do it, and on a live trading app, nobody should.
The work earned an internal Outstanding Performance award.
One object that knew everything
The original app put most of its state in one place: a 370-line AppManagerViewModel, a shared singleton the team itself had already labeled "Legacy". It held login status, sheet flags, the selected tab, a splash flag and a manual reloadID used to force views to refresh. Around it were 226 Swift files in a flat Model/View/ViewModel split.
Michael Feathers says in Working Effectively with Legacy Code that legacy code is code without tests, and by that definition most of this was legacy. A global ObservableObject gives you nowhere to put a test double. So the first goal was not "clean architecture". It was seams.
Constraints
- iOS 15 for the app, iOS 14 for the widget. The widget extension ran one version lower than the app, which limited what it could assume.
- KYC before trading.
KYCL1UseCasechecks a national ID and birth date against the backend, with separate errors for each kind of mismatch. Legal-name fields accept Persian and Arabic script only. - Language picked from context. User preference first, then device time zone: Tehran gets Persian, Dubai gets Arabic, everything else English. Layout direction follows.
- Two markets in one codebase. The main flow and AlSaraf both had login, home, portfolio and coin details, and both had to keep behaving the same way.
- Six analytics SDKs at once. WebEngage, Adtrace, Sentry, Clarity, Heap and Firebase Analytics all ran together, which is a real cost in binary size and launch time.
Twenty-five modules, one service locator
MVVM-C with Repository and Use Case layers. Core/ holds the shared parts and Features/ holds 25 modules, each with its own Coordinator, ViewModels and Views. The old tree kept compiling next to it.
Opening the Market screen goes through the whole stack. MarketViewModel is resolved through the service locator and subscribes to PricePollingService, which runs a Task loop every ten seconds. That loop calls GetListedPricesUseCase, then MarketRepository, then NetworkService against a typed APIEndpoint. Tapping an asset opens the product detail page, which runs its own quote timer and validates the amount before Buy is enabled. If the user is not L1-verified yet, they get a pending or declined sheet instead of a trade confirmation.
This is the dependency rule from Robert C. Martin's Clean Architecture, applied without ceremony: views know view models, view models know use cases, use cases know repository protocols, and nothing in Core/Domain knows about URLSession.
What we chose, and what we paid for it
Strangler fig, not a rewrite
The 226-file legacy tree kept shipping while 514 new files grew next to it. Flows moved over one at a time: Login, then Home, then the bank-account flows.
For the whole project, we had to reason about two networking styles and two DI styles: Alamofire and singletons in the old code, async URLSession and the service locator in the new code.
A documented service locator instead of pure constructor injection
ServiceLocator wraps a container with singleton and transient lifetimes and detects circular dependencies. We could migrate 25 modules gradually instead of touching every construction site at once. It has its own written guide in the repo.
It is a service locator. A few resolution failures show up as fatalError() at runtime instead of a compile error. We wrote that trade down on purpose.
Plain URLSession for new code
NetworkService uses async/await, one typed endpoint enum and one place that maps HTTP status to errors.
Alamofire stayed in the Podfile. 41 legacy files still imported it when I left, all of them outside Core/ and Features/.
Polling prices every ten seconds
No socket server to run for market data, and the real trade price is checked again by the server at execution anyway. Ten seconds is fine for a display price.
It is not real-time. The one WebSocket client in the app is used for login and session notifications, not prices.
A module per feature, drawn early
Buy can change without touching Login, and each module owns its own navigation.
Some modules arrived before they had enough content to justify them. SarafCard is one file.
Where it pushed back
A polling loop that survives the app lifecycle
A naive Task-based poller leaks loops or starts duplicates when the app goes to the background and comes back. PricePollingService guards start and stop with a lock and listens for foreground and background notifications so there is exactly one loop running at any time.
Errors that mean something to the user
NetworkService decodes a shared error body with a message and an error key. Use cases switch on the key, so a birth-date mismatch and a phone mismatch read differently to the user instead of collapsing into "something went wrong".
Two auth models touching each other
The socket service only connects when the device is in the Tehran time zone, and it still read its token from an old global instead of the new DI-managed auth state. It was a known seam between old and new, and I would rather name it than pretend it was closed.
Guest mode, added in the middle of a migration
When the international guest flow went in, guest and logged-in state were not passed consistently through the new coordinators. A missing argument in PDP navigation and a sell button that guests could see both reached a build. We found and fixed both the same day. The lesson was clear: adding a second product surface during a migration multiplies the seams that can break.
What the migration built
Who is allowed to trade
Saraf deals with real KYC documents and bank accounts, so most of the security work was about who can trade and how session state is stored:
- A tested Keychain wrapper replaced the old habit of keeping the session token in a global string.
- OTP state follows what the backend reports about delivery, not only a client-side countdown.
- Identity matching happens on the server. The client only validates format before sending.
- API calls use an ephemeral URLSession configuration with no on-disk cache.
What I would tell myself in 2025
- Seams first, patterns second. The Keychain wrapper and the network service landed before any big architecture change, and everything after was easier because of them.
- Write the DI rules down once you pass about a dozen modules. The DI guide was the most useful document in the repo.
- Don't start a second product inside an unfinished migration. If I had to do the guest flow again, I would make the coordinator contract guest-aware first.