spacetraders-v1
My first implementation against the spacetraders api is an entirely browser-based UI and automation tool · source · play spacetraders-v1 · spacetraders api · posts
-
v0.38 - System monitor
Extracted
systemMonitorMachineto handle background system monitoring tasks. This machine runs alongside the player machine and handles periodic updates like fetching flight plans and refreshing system data.Added last profit tracking for ships - each ship now saves its most recent trade profit for quick reference. Improved request caching in the ship requests view with better display of cached vs fresh requests.
Fixed several ship state issues: properly expire flight plans when they complete, resolve stale ship locations by triggering a getShip call, and handle cases where ships have no flight plan or location. The trade route determination was also fixed to handle edge cases better.
Removed the old trade component and cleaned up debug code. Various buy and upgrade flow fixes.
-
v0.37 - Player machine tests
Added comprehensive tests for the player machine. The
playerMachine.test.tsfile covers the core state transitions and event handling, improving confidence in the central state management logic.Extracted
buyAndUpgradeShipMachinefrom the player machine into its own module. This machine handles the combined buy-and-upgrade flow, making the player machine simpler and the upgrade logic more testable.Reorganized data modules by extracting
probes,ships, andstrategiesinto separate files. MovedpersistStrategyfrom components to the data layer where it belongs.Improved the trade routes list with better display and more information. Removed more global state dependencies to improve testability.
-
v0.36.2 - Code extraction
Refactoring day focused on code organization. Extracted the
Databaseclass from the data index into its own module for better separation of concerns. Similarly extractedmakeRequestfrom the API module to isolate HTTP request logic.Added
objectMothertest utility for creating test fixtures. This pattern makes tests more readable by providing factory functions for common test objects.Removed global state dependencies to improve testability and reduce coupling between modules. Fixed existing tests to work with the new structure.
-
v0.36.1 - Trade route fixes
Fixed the closest location calculation in
determineBestTradeRoute. The algorithm was incorrectly selecting routes in some cases - now properly considers distance when ranking trade options.Improved the trade routes table display with better formatting and additional columns. Empty trade routes are now automatically deleted from the database to prevent clutter.
Added logging improvements for better debugging of trade route selection.
-
v0.36 - Trade route analysis
Improved the best trades calculation to account for fuel costs and fuel availability at each location. Routes where fuel isn’t available are now deprioritized, and the profit calculation subtracts estimated fuel costs for more accurate profitability ranking.
Created a dedicated
TradeRoutescomponent that displays detailed trade route information in a table format. This replaces the simpler trades display with richer data including route details, profitability metrics, and ship assignments.Enhanced the DataTable component with more configuration options for flexible column display. Added flight time to CSV exports and included quantity and ship type in trade records for better analysis.
-
v0.35 - Manual cargo sales
Added the ability to sell cargo directly from the ship view. This provides manual control when you want to liquidate cargo immediately rather than waiting for the automated trading system.
Added a “focus single trade route” debug feature that restricts ships to a specific route, useful for testing and optimizing particular trade paths. The best trades view now supports selecting a route to focus on.
Improved good icons with avatar-style display. Added graph animations for smoother visual updates when data changes.
Fixed several issues: goto machine now properly switches back to trade strategy after reaching the destination, ships wait if they don’t have enough credits for fuel instead of erroring, and stale ship data is now properly cleaned up. Also fixed ship spawning after purchase.
-
v0.34 - Ship requests
Added ship request tracking to monitor API calls per ship. The
Requestscomponent in the ship view shows recent API requests made by each ship, helpful for debugging and understanding ship behavior. CreatedIRequestResponsetype for structured request data.Improved chart responsiveness with grow and shrink animations. The chart now smoothly adjusts when data series are added or removed. The markets chart got significant improvements to handle dynamic data better.
Reorganized the Ship component into its own folder with separate
RequestsandTradessub-components. Removed locations from the player context to reduce memory usage - they’re now fetched from localStorage as needed.Fixed trade completion detection to properly mark trades as complete when all cargo is sold. Added error handling for buy fuel failures to prevent ships from getting stuck.
-
v0.33 - Leaderboard
Added a leaderboard view to the intel section. The
Leaderboardcomponent fetches and displays player rankings from the API, showing net worth and other stats for top players.Created
saveTradeDatato persist detailed trade information for analytics. Trade records now include more context about the route and profitability. AddedITradeRouteDatatype for structured trade route information.Implemented
shipCachefor caching ship data in localStorage, reducing API calls when ship information is needed. The travel machine now updates the cache when ships complete flights.Added a
Tradescomponent tab for viewing saved trade data with filtering options. -
v0.32 - Goto strategy
Added a new “goto” strategy that sends ships to specific locations on demand. The
gotoMachinehandles navigation to a user-selected destination, useful for repositioning ships or manual control.Created
SelectLocationDialogto provide a UI for choosing destination locations. The strategy change component now supports selecting the goto strategy with a location picker.Started improving the charts with a dedicated
Colorsmodule containing 400+ color definitions for consistent, distinguishable chart series. The chart component was enhanced to better handle multiple data series.Fixed a context assignment bug in the goto flow within the trade machine.
-
v0.31.2 - Trade machine refactor
Simplified the trade machine by removing the redundant
InFlightstate. Flight handling is now fully delegated totravelToLocationMachine, reducing duplication and complexity.Fixed several edge cases in the trading flow: handling ships that are mid-way through a route when the app restarts, proper trade completion detection, and fuel calculation accuracy. Ships now update their fuel state when creating flight plans.
Improved performance by keeping locations in memory instead of constantly reading from localStorage. Added a
sleeputility for controlled delays.Enhanced debugging with the ability to toggle debug mode without restarting the app. Improved error logging throughout the ship machines.
-
v0.31.1 - Markets and upgrades
Improved the markets display with better data organization and added new localStorage keys for market data caching.
Re-enabled the FlyToShipyard functionality in the upgrade ship machine. Ships upgrading to a new type will now properly fly to a shipyard location before attempting the purchase.
Minor UI fixes including label improvements and index updates.
-
v0.31 - Structures
Added support for viewing available structures. Created
StructureandStructurescomponents to display buildable structures at locations. The API layer now fetches available structure data and caches it in localStorage.Improved trade route determination to use the pathfinding graph directly. The
determineBestTradeRoutefunction now considers multi-hop routes when calculating profitability. Added aRoutetype to better structure path data.Organized localStorage usage with a central
Keysmodule for consistent key naming. Added error count display in the UI to track API failures.Various stability fixes including null checks, routing fixes, and initialization improvements. Increased max cargo per trade to 500 and created a custom
useIntervalhook to replace the external dependency. -
v0.30 - Warp jumps
Added warp jump support for inter-system travel. The
travelToLocationMachinenow handles warp jumps when the destination is in a different system. Updated fuel calculations to account for warp fuel costs.Significantly improved the pathfinding system. Added comprehensive tests with 800+ lines of test data covering various routing scenarios. The graph module now properly handles multi-system navigation and calculates optimal paths considering both regular travel and warp jumps.
Enhanced probe assignments to show the target location in the UI. Various display improvements including updated fusion reactors icon and better location information display.
Removed redundant system code and added debug helpers for troubleshooting pathfinding issues.
-
v0.29 - Pathfinding
Implemented A* pathfinding using the ngraph library. Created a graph data structure in
graph.tsthat models the star system as nodes and edges, with distances as edge weights. This enables finding optimal multi-hop routes between locations.The pathfinding integrates with
determineBestTradeRouteand probe assignments to consider routes that may require multiple jumps. Added TypeScript type definitions for ngraph.graph and ngraph.path.Added the ability to change ship strategy directly from the ship screen. Extracted
StrategyChangeas a reusable component that can be embedded in different views. This makes it much faster to adjust individual ship behaviors.Various layout and location display improvements. Fixed a crash bug and cleaned up redundant code.
-
v0.28.1 - Fuel handling
Improved fuel handling edge cases. Ships now properly halt when they have no fuel instead of getting stuck in an error loop. The
confirmStrategymodule checks fuel status before allowing strategy changes.Fixed issues in the upgrade ship machine related to ship purchasing and location handling. The API layer was updated with better error handling for upgrade operations.
-
v0.28 - Trade route ranking
Improved trade route selection with a ranking system. The
determineBestTradeRoutefunction now scores routes based on multiple factors and selects the highest-ranked option. Added aTradeRoutetype to better structure route data.Significantly improved ship filtering and strategy selection in the UI. The strategy view was refactored to provide better filtering options and a cleaner interface for managing ship strategies. Ships can now show their current strategy directly in the ship view.
Added
revertToTradefunctionality so ships can automatically switch back to trading after completing other tasks. The halt machine now has proper debug logging.Various ship view enhancements: icons on ship cards, more trades displayed, linked focused ship navigation, and flight progress improvements. Fixed rate limit handling and added a rate limit indicator icon. Also fixed an edge case where ships had no fuel.
-
v0.27.1 - Strategy select
Improved the strategy selection UI. Refactored
StrategyToggleand the strategy index component to use a cleaner select-based interface viaCustomSelect. This simplifies the code and provides a more consistent user experience.Added error handling in
spawnShipMachineto gracefully handle API bugs instead of throwing exceptions. This prevents the entire application from crashing when the API returns unexpected data. -
v0.27 - Market charts
Added market price charts using Chart.js. The
Chartcomponent visualizes price history for goods over time, grouped by location. This helps identify price trends and optimal trading windows. Uses the Luxon adapter for proper datetime handling on the x-axis.Improved the intel user detail view with more information about individual players. Added a users tab panel for better organization of intel data.
Added quick strategy change buttons to make it faster to switch ship behaviors without navigating to the full strategy screen. Moved credits storage to localStorage for persistence.
Fixed GitHub issues #1 (charts) and #2. Renamed the “Workers” icon to “Drones” to match the game’s terminology. Various debug and lint cleanups.
-
v0.26 - Trade analytics
Added trade analytics views. The
Bestcomponent shows the most profitable trade routes based on current market data, helping identify optimal trading opportunities. TheCurrentcomponent displays active trade routes with visual good icons for each commodity type.Added icons for all tradeable goods - chemicals, construction materials, consumer goods, electronics, exotic plasma, food, fuel, and more. Created a
GoodIconcomponent to display these throughout the UI.Merged the map and locations views into a single
Locationscomponent with tabs, reducing navigation complexity. The map now shows location names properly.Fixed the sell fuel logic that was causing ships to incorrectly offload fuel. Various travel fixes and dynamic debug improvements. Also closed GitHub issue #4.
-
v0.25 - Ship scrapping
Added ship scrapping functionality via the API. Ships can now be sold back to recoup some credits, which is essential for the upgrade flow - sell the old ship, buy the new one.
Significantly expanded the
upgradeShipMachineto handle the full upgrade workflow. It now manages selling cargo, scrapping the old ship, buying the new ship at the appropriate location, and transferring the ship name. AddedgetUpgradingShiphelper to track which ships are mid-upgrade.Fixed the fuel calculation formula that was causing ships to miscalculate fuel needs for journeys. Also fixed various buy/sell edge cases in the trading logic.
-
v0.24 - Upgrade machine
Created
upgradeShipMachineto handle the ship upgrade process as a proper state machine. This moves the upgrade logic out of the player machine into a dedicated machine that manages selling the old ship and buying the new one atomically.Improved the
shouldUpgradelogic in the automation settings. TheAutoUpgradecomponent was refactored to better handle upgrade rule configuration, removing the separateUpgradecomponent and consolidating the UI.Added clickable ship links in the trades data table, making it easier to navigate from a trade record to the ship that executed it. Also cleaned up strategy persistence by renaming the file extension and improving type safety.
-
v0.23 - Auto-upgrade
Added auto-upgrade functionality to automatically replace ships with better models. The
AutoUpgradecomponent lets you configure upgrade paths - selecting which ship type should be upgraded to which better ship type, with a credit threshold for when upgrades should trigger.Created an
Upgradecomponent for individual upgrade rules, showing the source and target ship types with their specs. The automation settings were expanded withIUpgradeto store upgrade configurations.Reorganized the automation components into their own folder under
Ships/Automation. Also refactored global events in the player machine for cleaner event handling. -
v0.22 - Auto-buy configuration
Added configurable auto-buy settings for ship purchasing. The new
AutoBuycomponent in the ships view lets you set the credit threshold for automatic purchases, choose which ship type to buy, and toggle the feature on/off. Settings are persisted in theIAutomationdata structure.Restructured several components into folders for better organization.
Shipsnow has its own folder withShip,AutoBuy, andAutomationcomponents.Tradeswas similarly reorganized with a separateTradesDataTablecomponent.Extracted a reusable
TabPanelcomponent for tabbed interfaces. Fixed routing redirect issues and resolved GitHub issues #13 and #15 related to cargo display and ship information. -
v0.21.1 - Stability improvements
Big day of bug fixes and stability improvements. Added automatic retry logic for 429 (rate limit) responses from the API, with exponential backoff. Improved caching and throttling to reduce API calls and stay within rate limits.
Ships now sell excess cargo before starting new trade routes - fixing an issue where leftover goods from failed trades would block cargo space. Added
shouldCheckStrategyto properly handle strategy switches mid-operation.Fixed the reset flow to properly clear all database tables, and persist flight plans across sessions. Probes now visit locations by shortest distance instead of random selection. Excluded research goods from trading until proper handling is implemented.
Increased max ships to 70-80 for larger fleets. Various UI fixes including activity visibility, row keys, and layout improvements. Added wait-on-error behavior to prevent machines from spinning on repeated failures.
-
v0.21 - Trade route optimization
Replaced the old
determineCargoalgorithm with a newdetermineBestTradeRoutemodule. Instead of just picking what to buy at the current location, it now evaluates all possible routes to find the most profitable trade considering travel distance, fuel costs, and market prices at both ends.Added a dynamic debugging system with
debugStatesthat can be toggled at runtime. Ship machines now log state transitions and context changes when debug mode is enabled, making it much easier to trace issues in the trading logic.Refactored
travelToLocationMachineand extracted common travel logic into atravelToLocationhelper. Also createdinitShipMachineto standardize ship machine initialization across strategies.Fixed a bug with fuel overage calculations that was causing ships to buy more fuel than needed. Various probe fixes to handle edge cases when all locations have been recently scouted.
-
v0.20 - Probe strategy
Added a new “probe” strategy for ships to scout locations and gather market data. The
probeMachinesends ships to unvisited or stale locations to refresh market intelligence. CreatedgetProbeAssignmentto determine which location each probe should visit based on data freshness.Built a
travelToLocationMachineas a reusable sub-machine for handling flight plans. It manages creating flight plans, waiting for arrival, and handling the in-flight state. This machine is now shared between the trade and probe strategies, reducing duplication.Added a
Usercomponent to the intel view that shows detailed activity for individual players - their ships, recent flights, and trading patterns. CreatedgroupByLocationto aggregate flight data for the map display.Refactored strategy confirmation into a
confirmStrategymodule and added aProbescomponent to show probe assignments and status. The strategy table now persists selections properly with the newpersistStrategyhelper. -
v0.19.1 - Table performance
Created a
useTableCaphook to automatically prune old records from Dexie tables. The hook runs on mount and periodically (every 5 minutes), deleting records older than a configurable number of hours. This prevents the trades table from growing unbounded and slowing down the UI.Applied the table cap to the trades view and improved the table rendering performance. Also fixed some TypeScript warnings and added proper indexing to the database tables for faster queries.
Minor cleanup including removing unused debug code and fixing warning messages in the strategy toggle component.
-
v0.19 - Ship names
Added ship naming functionality. Ships are now assigned names from a predefined list when purchased, making it easier to identify individual ships in the fleet. The names are stored in the database alongside ship data and displayed in the strategy view and trades list.
Created a location scout table in Dexie to track which locations have been visited and when. This prepares for future scouting strategies where ships explore the system to gather market data.
Fixed the trading algorithm - there was an issue with how market prices were being compared that was causing suboptimal trade route selection. Also added
useMediaQueryfor responsive design adjustments on smaller screens.Changed ship state terminology from “idle” to “ready” to better reflect what the state represents.
-
v0.18 - Strategy switching
Implemented dynamic strategy switching for ships. Ships can now change between trade and halt strategies at runtime without needing to restart. Created an
updateStrategymodule that handles the transition logic between machine states.Refactored the strategy UI into its own folder with separate components:
StrategyTogglefor the toggle switch,SingleShipStrategyfor per-ship controls, and a mainStrategyindex component that ties it together. The toggle provides a clean interface for switching ship behaviors.Both the
tradeMachineandhaltMachinenow listen for strategy change events and can transition to the appropriate state. The player machine coordinates these changes by sending events to the ship actors when strategies are updated in the database. -
v0.17 - Intel and caching
Added an intel system to track other players’ activities. The
Intelcomponent displays flight plans from other players, showing their ships, routes, and timing. This data is fetched from the API and stored in Dexie for historical tracking.Implemented caching for API calls to reduce rate limiting issues. Market data and flight plans are now cached with configurable TTLs. Extracted a reusable
getCachedResponsepattern for consistent caching across different endpoints.Enhanced the strategy system - ships now spawn with the correct machine based on their configured strategy. The
spawnShipMachinehandles dynamic machine selection between trade and halt behaviors.Added profit metrics tracking with cost and profit columns in the trades view. The toolbar now shows an intel icon with quick access to the intel view. Various UI fixes including column widths and delayed updates to reduce flickering.
-
v0.16 - Ship strategies
Started implementing ship strategies to allow different behaviors per ship. Created a
Strategycomponent in the settings to configure ship behavior. Ships can now be set to either “trade” (the existing automated trading) or “halt” (stop all activity).Reorganized the ship machines into a
Shipfolder with separate files:tradeMachine.tsfor trading logic,haltMachine.tsfor idle ships, andspawnShipMachine.tsfor the spawning logic. Added aShipBaseContexttype for shared context between strategies.Added spread calculation to the markets view - showing the difference between buy and sell prices for each good. Fixed a bug where ships would try to buy research goods that can’t be traded.
Various tuning: reduced
MAX_CARGO_MOVEto 300, set ship purchase threshold to 100,000 credits, and added error handling for failed ship purchases. Also fixed trades table display on small screens. -
v0.15 - System map
Added a visual map of the star system. The
Mapcomponent renders locations as positioned elements based on their coordinates. AdrawMapfunction handles the geometry calculations to scale and position locations within the viewport. Each location is clickable and shows details on hover.Created a
CustomSelectcomponent for choosing which system to view on the map. Locations are now indexed by system in the player context for efficient lookups.Reorganized the component structure - moved App-related components into an
Appfolder and extracted reusablegetMenuslogic. Also extracted a common data table pattern from the trades and other list views.Cleaned up by removing old test files and the unused Pixi.js-based map implementation. Fixed the volume display to use the proper cubic metre symbol (㎥).
-
v0.14 - Dark mode and settings
Added dark mode support with theme persistence. The theme selection is saved to localStorage so it persists across sessions. The toggle is in the new settings page along with other configuration options.
Built out several new views. The
Marketscomponent displays market data from all known locations with pricing information.AvailableShipsshows ships that can be purchased with their prices and locations. TheSettingspage centralizes configuration options.Added filtering to the trades view so you can narrow down by good type, ship, or location. Also improved the net worth calculation display with better breakdown of assets.
Various UI polish including tooltips on icons and setting a proper default route.
-
v0.13 - Data persistence
Added Dexie for IndexedDB persistence. The database stores API errors and trades with proper indexing for queries. This enables tracking historical data across browser sessions.
Implemented React Router to add navigation between views. The app now has separate routes for ships, trades, markets, and errors. The
Appcomponent was restructured to handle routing and the main layout.Created a
Tradescomponent that displays all recorded trades in a table - showing good type, quantity, price, profit, ship, and location. Trades are recorded whenever the ship machine completes a buy or sell operation.Also added a markets table placeholder and increased the buy/sell quantity limit to 1000 for faster trading. Error handling was improved with API errors now being persisted to the database for later review.
-
v0.12 - UI overhaul
Major UI restructuring today. I created a
MainToolbarcomponent using Material-UI’s AppBar that consolidates the player info, status, credits, net worth, and ship count into a clean toolbar layout. The oldPlayercomponent was removed entirely.Added an
IconAndValuecomponent for consistent display of metrics with icons, and created a customSpaceshipIconcomponent from an SVG for the ship count display. The toolbar shows username, credits with a dollar icon, net worth with a trending icon, and ship count.Set a maximum fleet size of 20 ships to prevent runaway purchasing. Also improved error handling in the ship machine and fixed some TypeScript type issues. The ship cards now show a warning color when in error states for better visibility.
-
v0.11 - Multi-ship support
Extended the actor system to properly support multiple ships. Ships are now spawned from both the
getShipsresponse and when buying new ships. ThespawnShiplogic was extracted to be reusable from either path.Added automatic ship purchasing - when the player has enough credits, the system will automatically buy additional ships to expand the fleet. The UI now shows ship count alongside net worth.
Improved error handling throughout the ship machine. Failed
buyGoodoperations now recover gracefully by refetching market data, and errors are properly logged for debugging. Also cleaned up console warnings and removed excessive logging.Finished up with some TypeScript improvements, adding stronger typing to the player machine context and events.
-
v0.10 - Ship actors
Refactored the ship machine from an invoked service to a spawned actor. Instead of invoking a single
shipMachinein thereadystate, ships are now spawned using XState’sspawnfunction and stored in aship_actorsarray in the player context. This sets up the architecture for managing multiple ships independently.The
ShipActortype usesActorRefFromto properly type the actor references. TheShipcomponent now receives an actor and reads state directly fromactor.state.context- displaying ship type, cargo, and current state. When in flight, it shows the flight plan progress; otherwise it displays the current state name.This change also improves the UI by showing a loading spinner while actor state is initializing, and cleans up some debug logging. The
FlightPlancomponent was simplified to receive the flight plan directly rather than searching through an array. -
v0.9 - Net worth tracking
Added net worth calculation to track overall progress. The
calculateNetWorthfunction computes total value from credits, ship resale values (at 25% of purchase price), and cargo worth based on current market prices. It returns line items categorized as assets or debts for detailed breakdown.Improved the ship context handling in the player machine - ships now properly share context with the parent machine for better state coordination. Fixed an issue with location handling when ships are in flight by falling back to the flight plan’s origin location for market lookups.
Cleaned up the UI across multiple components -
FlightPlan,Ship,Cargo, andPlayerall got visual improvements. Also fixed a null cache bug in the location cache with a proper test, and updated the README. -
v0.8 - Trading logic
Big day of work on the trading system. I added flight plan functionality - ships can now create flight plans to destinations and the UI shows a progress indicator with time remaining using a
CircularProgressWithLabelcomponent.The main feature is the cargo determination algorithm in
determineCargo.ts. It looks at market prices at the current location and destination, calculates potential profit for each good, and determines what to buy. TheshipMachinenow has a full trading loop: check fuel, determine destination, determine cargo, buy goods, create flight plan, wait for arrival, repeat.I also added a
Locationscomponent that displays all known locations with their market data, and aCargocomponent to show what’s in the ship’s hold. Market data is now cached to localStorage via alocationCachemodule so we don’t refetch unnecessarily.Finally, I wrote tests for both the
shipMachineanddetermineCargologic using anobjectMotherpattern for test fixtures. The tests verify the state machine transitions and cargo calculation edge cases. -
v0.7 - Ship automation
Added a
shipMachineto automate ship operations. The machine starts in an idle state and checks if the ship needs fuel - if so, it transitions to abuyFuelstate that purchases fuel from the current location’s market. It usessendParentto notify theplayerMachineof credit changes after purchases.The
playerMachinenow has a proper initialisation flow. After fetching user data, it goes through aninitialisingstate that checks conditions in order: get a loan if none, buy a ship if none, fetch market data for the ship’s location if not cached, then finally transition toready. The market data is now cached in the player context by location symbol.The UI also got updated to distinguish between
initialisingandreadystates - the refresh button only appears when fully ready, but the player info displays during both states. -
v0.6 - Automated onboarding
Added automated onboarding for new players using XState child machines. When a player has no loans, the
playerMachinenow transitions to agetLoanstate that invokes agetLoanMachine. This child machine fetches available loans from the API and automatically requests a startup loan.Similarly, I created a
buyShipMachinethat fetches available ships, sorts them by price, and purchases the cheapest one. TheplayerMachinechains these together - after getting a loan, if the player has no ships, it automatically buys one.I also added
react-number-formatto display the player’s credits with proper formatting in the UI. The player’s credits now show with a dollar sign and thousand separators. -
v0.5 - Player state machine
Built out the player management system using XState. I created a
playerMachinethat handles the full lifecycle: checking localStorage for cached credentials, fetching a new token if needed, caching the result, and then fetching user details from the API.I also reorganized the codebase, moving all the state machines into a dedicated
machinesfolder. TheapiMachinewas refactored to usesendParentfor communicating results back to parent machines, and I split outapiPollMachineinto its own file for the polling use case.The Player component now properly shows a loading state until the machine reaches the “loaded” state, and the “new player” button works again - it sends a
CLEAR_PLAYERevent that removes the cached credentials and restarts the authentication flow. -
v0.4 - XState migration
Made a significant architectural change today, switching from Redux to XState for state management. I removed Redux Toolkit, react-redux, and all the associated store files (
gameSlice,gameMiddleware,shipSlice, etc.) and replaced them with XState state machines.I created an
apiMachinethat handles API calls with proper loading, success, and failure states. There’s also a polling variant that uses a timer machine to automatically retry after a delay. The timer machine itself manages elapsed time and duration for scheduled refetches.The Status component now uses the new XState-based approach, and the App component is much simpler without the Redux Provider wrapper. Had to fix a deprecated XState pattern too - switching from empty string event transitions to the
alwaysproperty for transient transitions. -
v0.3 - User management
Added the ability to fetch user information from the SpaceTraders API with a new
getUserendpoint. This pulls back the player’s credits, ships, and loans in a single call.I also created a reusable
ConfirmDialogcomponent and wired it up to the Player component, allowing users to create a new account. The dialog warns that the current API key will be lost before proceeding. This involved updating the Redux slice to handle the new user state and clearing the player during token requests. -
v0.2 - trading and travel
I added the core trading mechanics to the SpaceTraders client today. Ships can now purchase and sell cargo at different locations, which is the fundamental gameplay loop of the game.
I also implemented flight plans so ships can actually travel between locations. This involved extending the API client with the relevant endpoints and adding a new ship slice to Redux to manage ship-specific state separately from the main game state.
The location model got expanded to include more detail about what’s available at each waypoint, which will be useful for making informed trading decisions.
-
v0.1 - spacetraders react client
I kicked off a new project to build a browser-based client for the SpaceTraders API. The idea is to create a React app that lets me interact with the game’s space trading mechanics through a web interface.
I started with Create React App and immediately set up a GitHub Actions workflow to deploy to Netlify. Getting CI/CD working early means I can iterate quickly and always have a live version running.
The core of the app is built around Redux for state management. I implemented a custom middleware to handle the async API calls, including a
wrappedThunkhelper to manage loading states and error handling consistently. There’s also some basic Jest test coverage for the middleware logic.On the API side, I created TypeScript types for ships, loans, systems, locations, and the user account. The client can now create a new player, fetch available loans, request a loan, and display the user’s ships. I added a fun random name generator for new players.
For the UI, I built a simple status display showing the user’s credits and loans, plus a Player component that ties everything together. I also added a GitHub fork ribbon because why not.