-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathstructs-exercise.sol
68 lines (56 loc) · 1.9 KB
/
structs-exercise.sol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
https://docs.base.org/base-camp/docs/structs/structs-exercise/
CODE:
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.13;
contract GarageManager {
// Custom error declaration
error BadCarIndex(uint256 index);
// Struct to represent a car
struct Car {
string make;
string model;
string color;
uint256 numberOfDoors;
}
// Mapping from address to array of cars
mapping(address => Car[]) private garage;
// Function to add a new car to the sender's garage
function addCar(
string calldata _make,
string calldata _model,
string calldata _color,
uint256 _numberOfDoors
) external {
garage[msg.sender].push(Car(_make, _model, _color, _numberOfDoors));
}
// Function to get all cars belonging to the sender
function getMyCars() external view returns (Car[] memory) {
return garage[msg.sender];
}
// Function to get all cars belonging to a specific user
function getUserCars(address _user) external view returns (Car[] memory) {
return garage[_user];
}
// Function to update the details of a car in the sender's garage
function updateCar(
uint256 _index,
string calldata _make,
string calldata _model,
string calldata _color,
uint256 _numberOfDoors
) external {
Car[] storage cars = garage[msg.sender];
// Ensure that the car index is valid
require(_index < cars.length, "BadCarIndex");
// Update the details of the specified car
Car storage carToUpdate = cars[_index];
carToUpdate.make = _make;
carToUpdate.model = _model;
carToUpdate.color = _color;
carToUpdate.numberOfDoors = _numberOfDoors;
}
// Function to reset the sender's garage by deleting all cars
function resetMyGarage() external {
delete garage[msg.sender];
}
}