We study a dynamic-contracting problem involving risk sharing between two parties — the Proposer and the Responder — who invest in a risky asset until an exogenous but random termination time. In any time period they must invest all their wealth in the risky asset, but they can share the underlying investment and termination risk. When the project ends they consume their final accumulated wealth. The Proposer and the Responder have constant relative risk aversion R and r respectively, with R > r > 0. We show that the optimal contract has three components: a non-contingent flow payment, a share in investment risk and a termination payment. We derive approximations for the optimal share in investment risk and the optimal termination payment, and we use numerical simulations to show that these approximations offer a close fit to the exact rules. The approximations take the form of a myopic benchmark plus a dynamic correction. In the case of the approximation for the optimal share in investment risk, the myopic benchmark is simply the classical formula for optimal risk sharing. This benchmark is endogenous because it depends on the wealths of the two parties. The dynamic correction is driven by counterparty risk. If both parties are fairly risk tolerant, in the sense that 2 > R > r, then the Proposer takes on more risk than she would under the myopic benchmark. If both parties are fairly risk averse, in the sense that R > r > 2, then the Proposer takes on less risk than she would under the myopic benchmark. In the mixed case, in which R > 2 > r, the Proposer takes on more risk when the Responder's share in total wealth is low and less risk when the Responder's share in total wealth is high. In the case of the approximation for the optimal termination payment, the myopic benchmark is zero. The dynamic correction tells us, among other things, that: (i) if the asset has a high return then, following termination, the Responder compensates the Proposer for the loss of a valuable investment opportunity; and (ii) if the asset has a low return then, prior to termination, the Responder compensates the Proposer for the low returns obtained. Finally, we exploit our representation of the optimal contract to derive simple and easily interpretable sufficient conditions for the existence of an optimal contract.