This is why magic mushrooms have psilocybin.

Psilocybin is a naturally occurring psychedelic compound found in 200 species of mushrooms that grow across Earth. It’s the so-called magic in “magic mushrooms,” that, when consumed, sends the brain on a hallucinatory trip. But while scientists understand what psilocybin does to the would-be trippers that consume it, what has only recently become clear is why mushrooms have it in the first place.

In a new paper published in the journal bioRxiv, researchers who conducted one of the first genomic analyses of hallucinogenic fungi report their hypothesis for psilocybin’s existence. It all comes back to survival: Psilocybin most likely repels insects away from the fungi, allowing the mushrooms to thrive on the wood and animal dung the bugs would normally consume. Magic mushrooms typically grow on decaying mulch as well as on the decaying grass roots around poop.

“Patterns of gene distribution and transmission suggest that psilocybin provides a fitness advantage in the dung and late wood-decay niches, which may be reservoirs of fungal indole-based metabolites that alter the behavior of mycophagous and wood-eating invertebrates,” the scientists write.

 Fruit bodies of the hallucinogenic mushroom Psilocybe semilanceata.

In other words, bugs and magic mushrooms compete for the same resources and mushrooms developed psilocybin in order to drug their competitors. The team behind the research, led by Jason Slot, Ph.D., of Ohio State University, came to this conclusion by identifying the cluster of genes in mushrooms linked to the creation of psilocybin. These genes, in turn, are the ones that specialize in breaking down wood and dung — hence, the theory that insects would be the natural enemy.

The genes necessary for creating psilocybin, the researchers argue, have been passed through the fungi through horizontal gene transfers. This means that the genes that make the psychedelic compound were transferred directly between different species of fungi, rather than direct parent to offspring lineage. New Scientist points out that this is the first time a compound like this — one that’s not completely necessary for survival — has been found to move through mushroom genes.

While the idea that magic mushrooms developed psilocybin to drug insect predators is new, the concept that a fungi or plant would develop a special compound in order to survive isn’t. Peppers, for example, developed the chemical capsaicin so that birds but not mammals could eat them. Mammals have capsaicin receptors, which means that peppers are unappealing spicy to them, but birds do not. That’s good news for peppers, because they rely on birds to eat them and poop out the seeds (when mammals poop out pepper seeds, they emerge unfertile).

Consumption, evolutionarily driven compounds, and poop — it’s the circle of life.