We present a counting of microstates of a class of dyonic BPS black holes in AdS4 which precisely reproduces their Bekenstein–Hawking entropy. The counting is performed in the dual boundary description, that provides a non-perturbative definition of quantum gravity, in terms of a twisted and mass-deformed ABJM theory. We evaluate its twisted index and propose an extremization principle to extract the entropy, which reproduces the attractor mechanism in gauged supergravity.