typestar

orchard_votes.sol en Solidity

Un miembro un voto: proponer, votar al plazo, contar.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

// One member, one vote: propose, vote until the deadline, tally.
contract OrchardVotes {
    struct Proposal {
        string text;
        uint256 deadline;
        uint256 yes;
        uint256 no;
        bool executed;
    }

    Proposal[] public proposals;
    mapping(uint256 => mapping(address => bool)) public voted;

    event Proposed(uint256 indexed id, string text);
    event Voted(uint256 indexed id, address indexed voter, bool yes);
    event Decided(uint256 indexed id, bool passed);

    function propose(string calldata text, uint256 votingSeconds)
        external returns (uint256 id)
    {
        proposals.push(Proposal(
            text, block.timestamp + votingSeconds, 0, 0, false));
        id = proposals.length - 1;
        emit Proposed(id, text);
    }

    function vote(uint256 id, bool inFavor) external {
        Proposal storage p = proposals[id];
        require(block.timestamp < p.deadline, "voting closed");
        require(!voted[id][msg.sender], "already voted");
        voted[id][msg.sender] = true;
        if (inFavor) p.yes += 1;
        else p.no += 1;
        emit Voted(id, msg.sender, inFavor);
    }

    function execute(uint256 id) external returns (bool passed) {
        Proposal storage p = proposals[id];
        require(block.timestamp >= p.deadline, "still voting");
        require(!p.executed, "already tallied");
        p.executed = true;
        passed = p.yes > p.no;
        emit Decided(id, passed);
    }
}

Cómo funciona

  1. Las propuestas cargan texto, plazo y ambos conteos.
  2. El mapping anidado impide el voto doble por propuesta.
  3. execute espera el reloj y decide una sola vez.

Palabras clave y builtins usados aquí

El intento, en números

Líneas
48
Caracteres a escribir
1291
Tokens
296
Ritmo de tres estrellas
55 tpm

Al ritmo de tres estrellas de 55 tokens por minuto, este intento toma unos 323 segundos.

Escribe este fragmento

Paso 3 de 3 en Bis; paso 28 de 28 en Fundamentos del lenguaje.

← Anterior