使结构、枚举、构造函数和映射协同工作



所以我想在Solidity中实现一个简单的CarShop合同。合同应该由一个构造函数启动,我在那里输入我商店里已经有的汽车的当前库存金额。我在构造函数中调用这些(ToyotaCount、AudiCount、BmwCount(。。。

然后我想我需要创建一个结构来存储CarCount和CarType。所以我创建了一个枚举(丰田,奥迪,宝马(。。。

最后,我想用构造函数中的值CarCount(作为初始状态(和枚举中car的carType来创建这个结构。。。然而,我很困惑我应该如何实施它,以及我哪里出了问题。

此外,作为下一步,我想实现一个名为";AddCar";当我添加一些汽车时,更新结构中的值。。。例如,我想增加3辆奥迪汽车。。。

你能告诉我如何更正我的代码吗?这样构造函数、结构和枚举就可以一起工作了。如果你能给我介绍一些类似的项目或实现,我也会非常感激。

这是我当前的代码。我认为我正确地启动了构造函数。然而,结构、枚举和构造函数的相互作用出现了问题。

''

contract CarShop {
address owner;
uint256 toyotaCount;
uint256 audiCount;
uint256 bmwCount;
constructor(uint256 _toyotaCount, uint256 _audiCount, uint256 _bmwCount) {
owner = msg.sender;
toyotaCount = _toyotaCount;
audiCount = _audiCount;
bmwCount = _bmwCount;
}
enum CarType {None, Toyota, Audi, Bmw}

struct Cars {
CarType carType;
uint count;
}
Cars public item;
Cars memory toyota = Cars(carType, toyotaCount)

}

''

我对您的合同做了一些更改并添加了一些注释。请注意,您应该更改汽车的存储方式,因为我们为三辆不同的汽车使用了三个汽车结构。

contract CarShop {
address owner;
uint256 toyotaCount;
uint256 audiCount;
uint256 bmwCount;
Cars public toyota;
Cars public audi;
Cars public bmw;
enum CarType {Toyota, Audi, Bmw}
struct Cars {
CarType carType;
uint count;
}
constructor(uint256 _toyotaCount, uint256 _audiCount, uint256 _bmwCount) {
owner = msg.sender;
toyotaCount = _toyotaCount;
audiCount = _audiCount;
bmwCount = _bmwCount;
// initialize the three cars with their count
toyota = Cars(CarType.Toyota, _toyotaCount);
audi = Cars(CarType.Audi, _audiCount);
bmw = Cars(CarType.Bmw, _bmwCount);
}
/**
* @dev Add car count function
* @param _carType type of the car: 0 for Toyota, 1 for Audi, 2 for Bmw
* @return _count increment car count
*/
function addCarCount(CarType _carType, uint256 _count) public {
require(msg.sender == owner, "Only owner can add car count");
if(_carType == CarType.Toyota) {
toyota.count += _count;
} else if(_carType == CarType.Audi) {
audi.count += _count;
} else if(_carType == CarType.Bmw) {
bmw.count += _count;
}
}
}

我部署了合同,每10辆车在商店里。我创建了一个脚本,将3辆汽车添加到奥迪结构中。

import { ethers } from "hardhat";
async function main() {
const [owner] = await ethers.getSigners();
const contractAddress = process.env.CAR_CONTRACT_ADDRESS;
const contract = await ethers.getContractFactory("CarShop");
const contractInstance = await contract.attach(`${contractAddress}`);
const audi = await contractInstance.audi();
console.log(audi);
await contractInstance.connect(owner).addCarCount(1, 3);
const audiAfter = await contractInstance.audi();
console.log(audiAfter);
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});

结果:

[
1,
BigNumber { value: "10" },
carType: 1,
count: BigNumber { value: "10" }
]
[
1,
BigNumber { value: "13" },
carType: 1,
count: BigNumber { value: "13" }
]

不能仅在函数中在约定级别声明内存变量

Cars memory toyota = Cars(carType, toyotaCount)

最新更新