另一个结构中的结构 Solidity

Struct within another struct Solidity

我刚开始学习 solidity,我正在研究允许投标人对活动进行投标的投标合同。 我有一个活动结构。投标人有详细信息(地址、姓名),我想在活动中存储投标人及其信息。一项活动可以有多个投标人

这是我的活动和投标人结构

struct Campaign {
    uint256 campaignID;
    uint256 budget;
    uint256 bidCount;

}
 struct Bidder {
    bool bided;
    uint256 bid;
    string name;
    address bidderAddress;

}
mapping(address => Bidder) public bidders;
Campaign[] public campaigns;

我在这里写下了一个出价函数,它获取活动和出价的索引,然后填充 bidCount。

function bid(uint256 _bidIndex, uint256 _twitterID) public {
    require(!bidders[msg.sender].bided);

    bidders[msg.sender].bid = _bidIndex;
    campaigns[_bidIndex].bidCount += 1;
    totalBids += 1;
}

所以活动可以看起来像这样(如果可能的话)

0: campaignID 1
1: budget 2ETH
2: bidCount 3
3: Bidder {0: name Bidder1, 1: address 0xahaaahha}
          {0: name Bidder2, 2: address 0x2334jddd}

任何帮助将不胜感激。谢谢

根据我的说法,在这种情况下,您可以使用嵌套映射到 Campaign 结构中,以便 'connect' 对单个广告系列进行不同的出价。我为您的案例专门创建了一个智能合约,您可以在以下几行中看到它:

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

contract Auction {
    address owner;

    constructor() {
        owner = msg.sender;
    }

    struct Campaign {
        uint256 campaignID;
        uint256 budget;
        uint256 bidCount;
        mapping(uint => Bidder[]) bidders;
    }

    struct Bidder {
        bool bided;
        uint256 bid;
        string name;
        address bidderAddress;
    }

    Campaign[] public campaigns;
    uint totalCampaign = 0;

    modifier onlyOwner {
        require(msg.sender == owner, "Error! You're not the smart contract owner!");
        _;
    }

    // Create campaigns
    function createCampaing(uint _budgetCampaign) public onlyOwner {
        Campaign storage _firstCampaigns = campaigns.push();
        _firstCampaigns.campaignID = totalCampaign;
        _firstCampaigns.budget = _budgetCampaign;
        totalCampaign++;
    }

    // Bid 
    function bid(uint _indexCampaign, string memory _nameBidder) public {
        Campaign storage _bidCampaign = campaigns[_indexCampaign];
        _bidCampaign.bidCount += 1;
        uint _bidIndex = _bidCampaign.bidCount;
        _bidCampaign.bidders[_indexCampaign].push(Bidder(true, _bidIndex, _nameBidder, msg.sender));
    }

    // Getter Bids
    function getBids(uint _indexCampaign) onlyOwner external view returns(Bidder[] memory) {
        return campaigns[_indexCampaign].bidders[_indexCampaign];
    }
}

使用 getBids() 函数,您可以检索它用索引标识的特定广告系列的所有出价。我放置了一个 onlyOwner 修饰符,它允许特定功能,他们只能从智能合约所有者(而不是第一次将智能合约部署到区块链中的人)调用。