Hydrokinetic turbines extract kinetic energy from moving water to generate renewable electricity, thus contributing to sustainable energy production and reducing reliance on fossil fuels. It has been hypothesized that a duct can accelerate and condition the fluid flow passing the turbine blades, improving the overall energy extraction efficiency. However, no substantial evidence has been provided so far for hydrokinetic turbines. To investigate this problem, we perform a CFD-based optimization study with a blade-resolved Reynolds-averaged Navier--Stokes (RANS) solver to explore the design of a ducted hydrokinetic turbine that maximizes the efficiency of energy extraction. To handle the high-dimensional design space of the blade and duct geometry, we use a gradient-based optimization approach where the gradients are computed using the adjoint method. The final design is re-evaluated through higher-fidelity unsteady RANS (URANS) simulations. Our optimized ducted turbine achieves an efficiency of about 54% over a range of operating conditions, higher than the typical 46% efficiency of unducted turbines such as the well-known Bahaj model.