Solidity

從另一個合約中獲取映射中的數組

  • February 9, 2022

我有契約使用者,其中包含使用者列表和 nftInstance:

contract Users {
   struct UserData{
       User user;
       bool exists;
   }

   mapping (address => UserData) public users;
   NFT public nftInstance;

   constructor() {
       nftInstance = new NFT();
   }

   event UserConnect(User user);

   function connectUser() public  {
       address userAddress = msg.sender;

       if(users[userAddress].exists) emit UserConnect(users[userAddress].user);
       else {
           User user = new User(userAddress, nftInstance);
           users[userAddress].user = user;
           users[userAddress].exists = true;
           emit UserConnect(user);
       }
   }

   function getUser(address _userAddress) public view returns (User){
       return users[_userAddress].user;
   }
}

而且我有User契約。在建構子中,我得到 nftInstance 以便能夠在User. 並將 NFT 儲存在一個儲存中。這是我的User contract

contract User {
   address public userAddress;
   NFT private nftInstance;

   constructor (address _userAddress, NFT _nftInstance) {
       userAddress = _userAddress;
       nftInstance = _nftInstance;
   }

   event Collect(string tokenURI);

   function collect() public{
       uint256 tokenId = nftInstance.createNFT(userAddress);
       emit Collect(nftInstance.tokenURI(tokenId));
   }

   function getMyNFTs() public {
       mapping(address => uint256) storage tokenIdsCount = nftInstance.userAddressToTokenId; // 1 VARIANT
       uint256[] memory tokenIds = nftInstance.userAddressToTokenId[userAddress]; // 2 VARIANT
   }
}

在 NFT 合約中,我有這樣的映射:mapping(address => uint256[]) public userAddressToTokenId; 我嘗試在User. 但這是錯誤的

1 - TypeError:類型函式(地址,uint256)視圖外部返回(uint256)不能隱式轉換為預期的類型映射(地址=> uint256)。

2 - ypeError:索引表達式必須是類型、映射或數組(是函式(地址,uint256)查看外部返回(uint256))

那麼,如何從合約實例tokenIds的映射中獲取數組呢?NFT

我在合約中寫了一個getterNFT來獲取映射

function getTokenIdsFromAddress(address _userAddress) public view 
returns(uint256[] memory) {
   return userAddressToTokenId[_userAddress];
}

引用自:https://ethereum.stackexchange.com/questions/120964