When a shopper places an order with a code, the amount is held on the code straight away, so two people cannot spend the same balance at the same time.
If the order is cancelled, refunded or left Incomplete (for example the online payment for the rest failed), the amount goes back onto the code automatically.
If you later move that order back to a live status, the amount is taken from the code again.
A gateway refund only refunds what the customer paid by card or UPI; the certificate part goes back to the code as above.