目标:验证交易具有事务性
结果:具有事务性
-
部署合约
部署成功后,查询初始化数据:
image.png -
测试交易
-
name 传参为空,然后调用getUsers。
结果:交易回滚了,data合约里也没有存储数据。
image.png -
name 传参,然后调用getUsers。
结果:data和voting合约都存储了数据。
image.png
合约demo示例
- 逻辑合约
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
import "./data.sol";
import "./voting.sol";
contract Logic {
Data private _data;
voting private _voting;
constructor(address dataAddr, address votingAddr){
_data = Data(dataAddr);
_voting = voting(votingAddr);
}
function getUsers(string memory name) public view returns(Data.User[] memory){
if(bytes(name).length >0){
Data.User[] memory _users = new Data.User[](1) ;
_users[0] =_data.getUsers()[0];
return _users;
}
return _data.getUsers();
}
function addUserAndProposal(string memory name, uint age) public{
Data.User memory newUser;
newUser.name=name;
newUser.age=age;
//
_data.addUser(newUser);
//
_voting.addProposal(name);
}
}
- 数据合约
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
contract Data {
struct User {
string name;
uint age;
}
//
User[] private users;
constructor() {
users.push(User("zxl",1));
users.push(User("zxl2",2));
users.push(User("zxl3",3));
}
function getUsers() public view returns(User[] memory){
return users;
}
function addUser(User memory newUser) public{
users.push(newUser);
}
}
- 投票合约
pragma solidity >=0.7.0 <0.9.0;
contract voting{
string public proposalCode;
function addProposal(string memory code) public{
require(bytes(code).length>0,"voting: code can not be empty.");
proposalCode = code;
}
}
网友评论