I'm learning Solidity, and referring given example of Voting in a doc. But I'm not able to understand one thing about delegate function.
Here is the Delegate method:

/// Delegate your vote to the voter `to`.
function delegate(address to) public {
    // assigns reference
    Voter storage sender = voters[msg.sender];
    require(!sender.voted, "You already voted.");

    require(to != msg.sender, "Self-delegation is disallowed.");

    // Forward the delegation as long as
    // `to` also delegated.
    // In general, such loops are very dangerous,
    // because if they run too long, they might
    // need more gas than is available in a block.
    // In this case, the delegation will not be executed,
    // but in other situations, such loops might
    // cause a contract to get "stuck" completely.
    while (voters[to].delegate != address(0)) {
        to = voters[to].delegate;

        // We found a loop in the delegation, not allowed.
        require(to != msg.sender, "Found loop in delegation.");

What is use of while loop here? they already checked with self delegation with

require(to != msg.sender, "Self-delegation is disallowed."); 

And we can check initial address condition with if condition.

  if (voters[to].delegate != address(0)) {
            to = voters[to].delegate;

What is special about While loop here?


The while loop is for checking that no delegation loop exists like this:

voter A === delegate ===> voter B === delegate ===> ... === delegate ===> voter A

Whereas the line require(to != msg.sender, "Self-delegation is disallowed."); only checks for a direct self-delegate:

voter A === delegate ===> voter A

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for?Browse other questions tagged or ask your own question.