Your friend's death is a tragedy. Preventing as many deaths like this as possible is what I hope for the future.
Suppose your friend were in a country like Singapore, where drug punishments are extremely harsh. When his prescription ran out, he would have been faced with the choice to either kick opioids or engage in serious criminal activity. Finding a dealer would be very hard, because dealers are executed if caught. Even if he found a dealer, he would know that, if caught, he would be facing jail time. There's a very good chance that someone in your friend's position would decide to go through the extremely difficult process of kicking.
In SF, even for someone who is trying to kick, it is so easy in a moment of weakness to just to go down to the Tenderloin and buy fentanyl, like your friend did. Buying fentanyl there is pretty easy, not too expensive, everyone knows where to go, and there is zero chance of being arrested. The only problem is that you might get more than you bargained for and overdose and die.
I also have a friend who got addicted to stimulants and was going insane from them. I tried hard but ultimately wasn't able to help him. I talked to a lot of people who deal with addiction professionally, and what I kept hearing was that in this situation someone has to hit rock bottom before they can start to recover.
In the end, he was arrested for forging prescriptions and had to spend some time in jail, where he didn't have access to drugs. He would say that this was the first step towards his recovery and the best thing that ever happened to him. He got clean and went on to get a master's degree, get married, and now has a good job and a couple of kids.
Rock bottom in San Francisco though isn't a jail cell, it's overdosing on the sidewalk and dying.