【问题标题】:How to make user email address unique in solidity如何使用户电子邮件地址具有唯一性
【发布时间】:2021-09-03 04:11:00
【问题描述】:

我想注册用户,并希望每个用户都有唯一的电子邮件地址。如果有人输入了已经从其他用户那里获得的电子邮件地址,则会显示错误消息。

【问题讨论】:

    标签: ethereum solidity web3js


    【解决方案1】:

    gas-wise 最便宜的选择是创建映射,其中键是字符串(电子邮件地址),值是布尔值(显示它是否已注册)。

    然后您可以根据映射验证键的值是true 还是false

    pragma solidity ^0.8.5;
    
    contract MyContract {
        mapping (string => bool) isRegistered;
        
        function register(string memory _email) external {
            require(!isRegistered[_email], 'This e-mail is already registered');
            
            // TODO perform the registration
            
            isRegistered[_email] = true; // mark it as registered
        }
    }
    

    试试看:

    1. 使用参数john@example.com 执行register() 函数。它通过了require() 语句,因为isRegistered['john@example.com']false。然后它将isRegistered['john@example.com'] 映射值设置为true
    2. 第二次执行它。它使require() 语句失败,因为isRegistered['john@example.com'] 已经是true,并使用This e-mail is already registered 消息引发异常。

    【讨论】:

    • 我建议使用电子邮件哈希而不是原始字符串,因为对于这个用例,不需要将整个字符串存储在公共区块链中。
    • @MikkoOhtamaa 关于如何在solidity 中创建散列的任何想法?
    • @AndrewMiracle 你可以使用内置的keccak256()函数(docs)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-23
    • 2018-07-08
    • 1970-01-01
    • 2014-03-26
    • 2020-03-12
    • 1970-01-01
    相关资源
    最近更新 更多