Move code from script to wallet

Continues #4754