Chapter 3: Bringing it all together
Now that we’ve built the core logic for interacting with the Walnut contract, it’s time to tie everything together into a CLI that runs a multiplayer game session with two players - Alice and Bob. In this chapter, you’ll set up the environment variables for multiple players and write index.ts
to simulate gameplay. Estimated time: ~20 minutes
Set Up Environment Variables
Before running the Walnut game, we need to define environment variables that store important configurations such as the RPC URL, chain ID, and player private keys.
Create a .env
in packages/cli
:
Open .env
and paste the following:
What’s Happening Here?
• CHAIN_ID=31337
: 31337
is the default chain ID for sanvil
(your local Seismic node).
• RPC_URL=http://127.0.0.1:8545
: This is the RPC URL for interacting with the local Seismic node.
• ALICE_PRIVKEY
and BOB_PRIVKEY
: These are Alice and Bob’s private keys, allowing them to play the game. (These again are standard test keys provided by sanvil
)
Write index.ts
Now, we’ll create the main entry point for our game session. This file will simulate gameplay, initializing players and having them interact with the Walnut contract. Open packages/cli/src/index.ts
and follow these steps:
Import Dependencies
Import the required libraries to read environment variables, define network configurations, and interact with the Walnut contract.
Define the main() function
This function initializes the contract and player wallets, then runs the game session.
Read Contract Details
The contract’s ABI and deployed address are read from files generated during deployment.
Select the blockchain network
Determine whether to use the local sanvil
node (31337) or the Seismic devnet.
Define players
Assign Alice and Bob as players with private keys stored in .env
.
Initialize the Game App
Create an App
instance to interact with the Walnut contract.
Simulate the game round by round
The following logic executes two rounds of gameplay between Alice and Bob.
Round 1 - Alice Plays
Round 2 - Bob Plays
Alice Tries to Look in Round 2 (we expect this to fail since she has contributed in round 1 but not round 2)
Execute the main() function
This ensures that the script runs when executed.
Running the CLI
Now, run the CLI from packages/cli
by running:
You should see something like this as the output:
This output logs the events during two rounds of gameplay in the Walnut contract, showing interactions by Alice and Bob, along with a revert error when Alice attempts to call look()
in Round 2.
Last updated