I think it should go like this:
- you buy Sir Destry, losing $5
- on-buy triggers before gaining (and I believe gaining is the thing which moves the card): your opponent gains Sir Destry.
- you try to gain Sir Destry, failing to do so because you lost track
This is mostly right, but not quite right—the lose-track rule isn't what causes you to fail to gain Sir Destry, it's just the fact that there isn't a Sir Destry available in the supply to gain at the moment.
Actually, you could just gain another Knight. The card in the OP says "...you gain
an attack card," not that you gain a copy of that attack card. That means you could gain a Cutpurse, a Goons, or another Knight, assuming those are in the Supply.