Solidity

從外部合約訪問和儲存結構

  • February 13, 2022

我試圖從外部契約訪問和儲存一個結構。有沒有辦法做到這一點。這將是一個簡單的 PoC,我試圖在 ClassRoom 契約中從學生契約訪問 Struct,但不斷得到:

TypeError: Type tuple(string memory,uint256,bool) is not implicitly convertible to expected type struct stu storage ref.
 --> contracts/TestContract.sol:32:16:
  |
32 |         test = student.studentNames(ID);
  |     

契約:

SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
struct stu {
   string name;
   uint age;
   bool tookTest;
}
contract Student{
   mapping(uint => stu) public studentNames;
   function addStudent (uint ID, string memory _name, uint _age) public {
       studentNames[ID] = stu(_name, _age, false);
   }
   function updateStudent (uint ID) public {
       studentNames[ID].tookTest = true;
   }
}
contract ClassRoom {
   address studentAddr;
   Student student;
   stu public test;
   function classRoom(address addr) public {
       studentAddr = addr;
       student = Student(addr);
   }

   //some function that performs a check on student obj and updates the tookTest status to true
   function updateTookTest (uint ID) public {
       student.updateStudent(ID);
   }
   //if you want to access the public mapping
   function readStudentStruct (uint ID) public {
       test = student.studentNames(ID);
   }
}

我可以看到呼叫正確解析,因此訪問映射和結構不是問題,只需儲存它即可。有任何想法嗎?

問題是結構是元組,因此您必須將它們視為元組。以下程式碼將起作用。

contract ClassRoom{

Student studentContract;
stu public test;

constructor(address _addr) {
   studentContract = Student(_addr);
}

function updateTookTest (uint ID) public {
}

function readStudentStruct (uint ID) public view returns(string memory, 
uint, bool) {

   stu memory student;
   (student.name, student.age, student.tookTest) = 
   studentContract.studentNames(ID);
   return (student.name, student.age, student.tookTest);
}
}

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