In a supply-following "smart" grid scenario, buildings can exploit remotely controllable thermostats and "smart" meters to communicate with energy providers, trade energy in real-time and offer frequency regulation services, by leveraging the flexibility in the energy consumption of their heating, ventilation and air conditioning (HVAC) systems. The realization of such a scenario is, however, strongly dependent on our ability to radically re-think the way both the grid and the building control algorithms are designed. In this work, we regard the grid as an integrated, distributed, cyber-physical system, and propose a compositional framework for the deployment of an optimal supply-following strategy. We use the concept of assume-guarantee contracts to formalize the requirements of the grid and the building subsystem as well as their interface. At the building level, such formalization leads to the development of an optimal control mechanism to determine the HVAC energy flexibility while maximizing the monetary incentive for it. At the grid level, it allows formulating a model predictive control scheme to optimally control the ancillary service power flow from buildings, while integrating constraints such as ramping rates of ancillary service providers, maximum available ancillary power, and load forecast information. Simulation results illustrate the effectiveness of the proposed design methodology and the improvements brought by the proposed control strategy with respect to the state of the art.