Mission 2
Establish Comms with the Lunar Base
Congratulations on joining the Academy! Your first job as a junior cadet is to establish communications with the lunar base. To do this you will need to first take ownership of a special comms smart contract. Once you have done that you will need to establish a connection with the base by randomly generating the proper communication code. After that task is complete you will index all of the data into The Graph for the basecamp to see your success.
Smart Contract
In this part of the mission you will be creating a smart contract to establish communications with the lunar base.
1Environment Setup
Before you begin, make sure you are in the proper branch.
Clone the repository:
git clone https://github.com/kmjones1979/graphbuilders-basecamp mission-2-comms
Navigate into the project directory:
cd mission-2-comms
Checkout the branch:
git checkout mission-2-comms
Install the dependencies:
yarn install
Start your local blockchain:
yarn chain
Deploy your contract (in a new terminal):
yarn deploy
Start your frontend (in a new terminal):
yarn start
2Starting Contract Code
The starting smart contract code for this mission is as follows:
contract Comms {
uint8 public channel;
uint8 public attempt;
bool public isCommsEstablished = false;
event CommsEstablished(address indexed _address, bool isCommsEstablished);
constructor() {
channel = uint8(block.prevrandao % 6) + 1;
}
function establishComms() public {
require(!isCommsEstablished, "Comms already established");
attempt = uint8(block.prevrandao % 6) + 1;
console.log("Attempt: %s", attempt);
require(attempt == channel, "Attempt failed: Invalid channel, try again");
isCommsEstablished = true;
emit CommsEstablished(msg.sender, isCommsEstablished);
}
receive() external payable {}
}
This smart contract uses block.prevrandao
to generate a random number at the time of deployment. Then by calling the establishComms
function we can attempt to generate another random number and compare it to the number generated during the contract deployment. If they match we can establish communications with the base.
1Take ownership of the contract with OpenZeppelin Ownable
To complete this task, follow these steps:
- Import the Ownable contract from OpenZeppelin
- Inherit the contract from Ownable
- Pass your address to the Ownable constructor
- Deploy the contract
Deploy your changes:
yarn deploy --reset
✅ Success will look like this:
deployed at 0x0165878A594ca255338adfa4d48449f69242Eb8F with 378023 gas
Once you deploy your changes navigate to the "Debug Contracts" tab and call the establishComms
function to test the functionality. You will need to attempt to call the function multiple times until the channel matches your attempt. When testing on your local network you can use the Faucet button to simulate a new block. You will know you are successful when the isCommsEstablished
variable is set to true.