The cause and effect is the other way around.
Over the course of history, many city-states have appeared – whether by being built, by separating from an existing entity, arising from a collapse, or in some other way. Most of them quickly get assimilated into a larger entity, whether by military conquest or by economic pressure. Only the wealthy or otherwise powerful ones manage to survive.
So, why are those microstates wealthy? Because the non-wealthy ones don’t exist anymore.
Small countries are easier to run manpower wise than big ones. Hire your friends / qualified people to run your country, keep the numbers small but quality high.
If a country gets big might be hard to control quality.
Singapore government operates on a technocrat system, young students are sent on government scholarships to study at top schools, and after coming back then will serve a bond. Those given top scholarships are almost guaranteed a permanent place in government service.
Tax dodging, and financial centres.
Hong Kong and Singapore (the later, created out of nothing) were made by the British Empire as commercial ports – places where banking, trade, etc. could all happen with proper contracts, rule of law – an a part of the world where there was not much of that.
Monaco, Lux, Swiss, San Marino tend to leverage themselves by attracting money with fewer questions asked, lower tax rates etc..
Taxheaven status aside, one aspect that gets overlooked is the fact that often cities tend to be richer than rural areas.
If you look across Europe at a sub-national level at various measures of GDP or wealth per capita it is usually the big cities and capitals that stand out as richer than the the rest of the country around them. (Ignore Berlin in Germany going against this trend.)
A country that is all or mostly capital city with none or little of the poorer sectors dragging it down will be rich in comparison to to others.
If a place like London or Warsaw were its own separate country without any special tax heaven status they would be richer than the country they are currently part of and the rest of the country around them would be poorer.
This at least explains places like Singapore, but not San Marino. For those the tax heaven part needs to be considered.
Latest Answers