Magnesium acts as a natural CA2+ (voltage gated calcium) channel inhibitor. Basically the way the brains reward system works (on stimulants or not) is that you get what's called an "action potential". Or more professionally known as a "depolarized membrane potential". A voltage signal is sent into the Axon Terminal within the pre-synaptic neurons, this causes the CA2+ channels to open up and release positively charged Calcium Ions into the Axon Terminal. These Calcium Ions then bind to the pre-synaptic vesicles containing the neurotransmitters (Dopamine, Norepinephrine, Epinephrine, Serotonin...etc). Which then signals the vesicles to bind to the membrane of the pre-synaptic neuron, causing the neurotransmitters to be released from the storage vesicles and into the Synaptic Cleft (the brains reward path way). Here the neurotransmitters bind the corresponding receptors on the outer membrane of the post-synaptic neurons before they make their way back up through the reuptake channels.
Problem is, Calcium Ions are also released into the Synaptic Cleft, but not all of these Ions are re-uptaken, but instead are absorbed through the receptors and make their way down through the post-synaptic neurons and down into the arteries. This causes the arteries to constrict which increases the chances of blood clotting which can result in a Heart Attack or Stroke, depending on which arteries get blocked.
Magnesium (which should be taken in chelated/glycinate form as it has the highest bioavailability) partially blocks the CA2+ channels, meaning that Calcium Ions enter the Axon Terminal at a slower/regulated rate as opposed to cascading in too quickly. This slows downs the pre-synaptic vesicle action making the overall effect of stimulants "smoother" and without any sudden hard crash 5-6 hours later, but rather a pleasant smoothen off.
But most importantly, it slows down the amount of Calcium Ions making their way down into the arteries, helping to prevent them from over restricting, thus reducing the risk of Heart Attack or Stroke.
Now I'm not saying that Magnesium is completely fail safe. These conditions can still of course occur, but it does greatly reduce the chances of it happening. You'll have less chance of experiencing chest pain, palpitations, arrhythmias and so on.
Another supplement that i'd highly recommend with any stimulant (even just Caffeine) is L-Theanine. L-Theanine is a glutamate transporter antagonist, which allows GABA levels to naturally increase in their neurons. A far more effective and safer alternative to Benzo use in my personal opinion. L-Theanine doesn't have any sedative effects, but it can prevent anxiety and panic attacks from occurring, which decreases the odds of having a psychologically induced seizure.