Refactor protocol code