In Canada, capital gains are calculated using an adjusted cost base (ACB). The ACB is the weighted average cost of the Bitcoins, including any transaction fees or commissions.
Assuming that all the costs in your question include transaction fees and commissions, then the weighted average cost of your Bitcoins is:
[(2 BTC * $4,000) + (2 BTC * $10,000) + (4 BTC * $28,000)] / (2 BTC + 2 BTC + 4 BTC) = $17,500
You sold 1 BTC for $40,000, so:
Capital gain = $40,000 - $17,500 = $22,500
I hope you are aware that gains from Bitcoins are not always considered capital gains. Depending on your specific activities, they may be considered business income instead, in which case the calculations above may not apply. Refer to the Guide for cryptocurrency users and tax professionals.