Skip to content

Commit 1909396

Browse files
committed
Added extension nft meta data pointer example
1 parent 4366669 commit 1909396

File tree

359 files changed

+51789
-0
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

359 files changed

+51789
-0
lines changed
Lines changed: 307 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,307 @@
1+
# Solana Game Preset
2+
3+
This game is ment as a starter game for on chain games.
4+
There is a js and a unity client for this game and both are talking to a solana anchor program.
5+
6+
This game uses gum session keys for auto approval of transactions.
7+
Note that neither the program nor session keys are audited. Use at your own risk.
8+
9+
# How to run this example
10+
11+
## Quickstart
12+
13+
The unity client and the js client are both connected to the same program and should work out of the box connecting to the already deployed program.
14+
15+
### Unity
16+
Open the Unity project with Unity Version 2021.3.32.f1 (or similar), open the GameScene or LoginScene and hit play.
17+
Use the editor login button in the bottom left. If you cant get devnet sol you can copy your address from the console and use the faucet here: https://faucet.solana.com/ to request some sol.
18+
19+
### Js Client
20+
To start the js client open the project in visual studio code and run:
21+
22+
```bash
23+
cd app
24+
yarn install
25+
yarn dev
26+
```
27+
28+
To start changing the program and connecting to your own program follow the steps below.
29+
30+
## Installing Solana dependencies
31+
32+
Follow the installation here: https://www.anchor-lang.com/docs/installation
33+
Install the latest 1.16 solana version (1.17 is not supported yet)
34+
sh -c "$(curl -sSfL https://release.solana.com/v1.16.18/install)"
35+
36+
Anchor program
37+
1. Install the [Anchor CLI](https://project-serum.github.io/anchor/getting-started/installation.html)
38+
2. `cd program` to end the program directory
39+
3. Run `anchor build` to build the program
40+
4. Run `anchor deploy` to deploy the program
41+
5. Copy the program id from the terminal into the lib.rs, anchor.toml and within the unity project in the AnchorService and if you use js in the anchor.ts file
42+
6. Build and deploy again
43+
44+
Next js client
45+
1. Install [Node.js](https://nodejs.org/en/download/)
46+
2. Copy the program id into app/utils/anchor.ts
47+
2. `cd app` to end the app directory
48+
3. Run `yarn install` to install node modules
49+
4. Run `yarn dev` to start the client
50+
5. After doing changes to the anchor program make sure to copy over the types from the program into the client so you can use them. You can find the js types in the target/idl folder.
51+
52+
Unity client
53+
1. Install [Unity](https://unity.com/)
54+
2. Open the MainScene
55+
3. Hit play
56+
4. After doing changes to the anchor program make sure to regenerate the C# client: https://solanacookbook.com/gaming/porting-anchor-to-unity.html#generating-the-client
57+
Its done like this (after you have build the program):
58+
59+
```bash
60+
cd program
61+
dotnet tool install Solana.Unity.Anchor.Tool <- run once
62+
dotnet anchorgen -i target/idl/extension_nft.json -o target/idl/ExtensionNft.cs
63+
```
64+
65+
(Replace extension_nft with the name of your program)
66+
67+
then copy the c# code into the unity project.
68+
69+
## Connect to local host (optional)
70+
To connect to local host from Unity add these links on the wallet holder game object:
71+
http://localhost:8899
72+
ws://localhost:8900
73+
74+
## Video walkthroughs
75+
Here are two videos explaining the energy logic and session keys:
76+
Session keys:
77+
https://www.youtube.com/watch?v=oKvWZoybv7Y&t=17s&ab_channel=Solana
78+
Energy system:
79+
https://www.youtube.com/watch?v=YYQtRCXJBgs&t=4s&ab_channel=Solana
80+
81+
# Project structure
82+
The anchor project is structured like this:
83+
84+
The entry point is in the lib.rs file. Here we define the program id and the instructions.
85+
The instructions are defined in the instructions folder.
86+
The state is defined in the state folder.
87+
88+
So the calls arrive in the lib.rs file and are then forwarded to the instructions.
89+
The instructions then call the state to get the data and update it.
90+
91+
```shell
92+
├── src
93+
│ ├── instructions
94+
│ │ ├── chop_tree.rs
95+
│ │ ├── init_player.rs
96+
│ │ └── update_energy.rs
97+
│ ├── state
98+
│ │ ├── game_data.rs
99+
│ │ ├── mod.rs
100+
│ │ └── player_data.rs
101+
│ ├── lib.rs
102+
│ └── constants.rs
103+
│ └── errors.rs
104+
105+
```
106+
107+
The project uses session keys (maintained by Magic Block) for auto approving transactions using an expiring token.
108+
109+
# Energy System
110+
111+
Many casual games in traditional gaming use energy systems. This is how you can build it on chain.
112+
113+
If you have no prior knowledge in solan and rust programming it is recommended to start with the Solana cookbook [Hello world example]([https://unity.com/](https://solanacookbook.com/gaming/hello-world.html#getting-started-with-your-first-solana-game)).
114+
115+
## Anchor program
116+
117+
Here we will build a program which refills energy over time which the player can then use to perform actions in the game.
118+
In our example it will be a lumber jack which chops trees. Every tree will reward on wood and cost one energy.
119+
120+
### Creating the player account
121+
122+
First the player needs to create an account which saves the state of our player. Notice the last_login time which will save the current unix time stamp of the player he interacts with the program.
123+
Like this we will be able to calculate how much energy the player has at a certain point in time.
124+
We also have a value for wood which will store the wood the lumber jack chucks in the game.
125+
126+
```rust
127+
128+
pub fn init_player(ctx: Context<InitPlayer>) -> Result<()> {
129+
ctx.accounts.player.energy = MAX_ENERGY;
130+
ctx.accounts.player.last_login = Clock::get()?.unix_timestamp;
131+
ctx.accounts.player.authority = ctx.accounts.signer.key();
132+
Ok(())
133+
}
134+
135+
#[derive(Accounts)]
136+
pub struct InitPlayer<'info> {
137+
#[account(
138+
init,
139+
payer = signer,
140+
space = 1000, // 8+32+x+1+8+8+8 But taking 1000 to have space to expand easily.
141+
seeds = [b"player".as_ref(), signer.key().as_ref()],
142+
bump,
143+
)]
144+
pub player: Account<'info, PlayerData>,
145+
146+
#[account(
147+
init_if_needed,
148+
payer = signer,
149+
space = 1000, // 8 + 8 for anchor account discriminator and the u64. Using 1000 to have space to expand easily.
150+
seeds = [b"gameData".as_ref()],
151+
bump,
152+
)]
153+
pub game_data: Account<'info, GameData>,
154+
155+
#[account(mut)]
156+
pub signer: Signer<'info>,
157+
pub system_program: Program<'info, System>,
158+
}
159+
```
160+
161+
### Chopping trees
162+
163+
Then whenever the player calls the chop_tree instruction we will check if the player has enough energy and reward him with one wood.
164+
165+
```rust
166+
#[error_code]
167+
pub enum ErrorCode {
168+
#[msg("Not enough energy")]
169+
NotEnoughEnergy,
170+
}
171+
172+
pub fn chop_tree(mut ctx: Context<ChopTree>) -> Result<()> {
173+
let account = &mut ctx.accounts;
174+
update_energy(account)?;
175+
176+
if ctx.accounts.player.energy == 0 {
177+
return err!(ErrorCode::NotEnoughEnergy);
178+
}
179+
180+
ctx.accounts.player.wood = ctx.accounts.player.wood + 1;
181+
ctx.accounts.player.energy = ctx.accounts.player.energy - 1;
182+
msg!("You chopped a tree and got 1 log. You have {} wood and {} energy left.", ctx.accounts.player.wood, ctx.accounts.player.energy);
183+
Ok(())
184+
}
185+
```
186+
187+
### Calculating the energy
188+
189+
The interesting part happens in the update_energy function. We check how much time has passed and calculate the energy that the player will have at the given time.
190+
The same thing we will also do in the client. So we basically lazily update the energy instead of polling it all the time.
191+
The is a common technic in game development.
192+
193+
```rust
194+
195+
const TIME_TO_REFILL_ENERGY: i64 = 60;
196+
const MAX_ENERGY: u64 = 10;
197+
198+
pub fn update_energy(&mut self) -> Result<()> {
199+
// Get the current timestamp
200+
let current_timestamp = Clock::get()?.unix_timestamp;
201+
202+
// Calculate the time passed since the last login
203+
let mut time_passed: i64 = current_timestamp - self.last_login;
204+
205+
// Calculate the time spent refilling energy
206+
let mut time_spent = 0;
207+
208+
while time_passed >= TIME_TO_REFILL_ENERGY && self.energy < MAX_ENERGY {
209+
self.energy += 1;
210+
time_passed -= TIME_TO_REFILL_ENERGY;
211+
time_spent += TIME_TO_REFILL_ENERGY;
212+
}
213+
214+
if self.energy >= MAX_ENERGY {
215+
self.last_login = current_timestamp;
216+
} else {
217+
self.last_login += time_spent;
218+
}
219+
220+
Ok(())
221+
}
222+
```
223+
224+
## Js client
225+
226+
### Subscribe to account updates
227+
228+
It is possible to subscribe to account updates via a websocket. This get updates to this account pushed directly back to the client without the need to poll this data. This allows fast gameplay because the updates usually arrive after around 500ms.
229+
230+
```js
231+
useEffect(() => {
232+
if (!publicKey) {return;}
233+
const [pda] = PublicKey.findProgramAddressSync(
234+
[Buffer.from("player", "utf8"),
235+
publicKey.toBuffer()],
236+
new PublicKey(ExtensionNft_PROGRAM_ID)
237+
);
238+
try {
239+
program.account.playerData.fetch(pda).then((data) => {
240+
setGameState(data);
241+
});
242+
} catch (e) {
243+
window.alert("No player data found, please init!");
244+
}
245+
246+
connection.onAccountChange(pda, (account) => {
247+
setGameState(program.coder.accounts.decode("playerData", account.data));
248+
});
249+
250+
}, [publicKey]);
251+
```
252+
253+
### Calculate energy and show countdown
254+
255+
In the java script client we can then perform the same logic and show a countdown timer for the player so that he knows when the next energy will be available:
256+
257+
```js
258+
const interval = setInterval(async () => {
259+
if (gameState == null || gameState.lastLogin == undefined || gameState.energy >= 10) {
260+
return;
261+
}
262+
263+
const lastLoginTime = gameState.lastLogin * 1000;
264+
const currentTime = Date.now();
265+
const timePassed = (currentTime - lastLoginTime) / 1000;
266+
267+
while (timePassed > TIME_TO_REFILL_ENERGY && gameState.energy < MAX_ENERGY) {
268+
gameState.energy++;
269+
gameState.lastLogin += TIME_TO_REFILL_ENERGY;
270+
timePassed -= TIME_TO_REFILL_ENERGY;
271+
}
272+
273+
setTimePassed(timePassed);
274+
275+
const nextEnergyIn = Math.floor(TIME_TO_REFILL_ENERGY - timePassed);
276+
setEnergyNextIn(nextEnergyIn > 0 ? nextEnergyIn : 0);
277+
}, 1000);
278+
279+
return () => clearInterval(interval);
280+
}, [gameState, timePassed]);
281+
282+
...
283+
284+
{(gameState && <div className="flex flex-col items-center">
285+
{("Wood: " + gameState.wood + " Energy: " + gameState.energy + " Next energy in: " + nextEnergyIn )}
286+
</div>)}
287+
288+
```
289+
290+
## Unity client
291+
292+
In the Unity client everything interesting happens in the AnchorService.
293+
To generate the client code you can follow the instructions here: https://solanacookbook.com/gaming/porting-anchor-to-unity.html#generating-the-client
294+
295+
```bash
296+
cd program
297+
dotnet tool install Solana.Unity.Anchor.Tool <- run once
298+
dotnet anchorgen -i target/idl/extension_nft.json -o target/idl/ExtensionNft.cs
299+
```
300+
301+
### Session keys
302+
303+
Session keys is an optional component. What it does is creating a local key pair which is toped up with some sol which can be used to autoapprove transactions. The session token is only allowed on certain functions of the program and has an expiry of 23 hours. Then the player will get the sol back and can create a new session.
304+
305+
With this you can now build any energy based game and even if someone builds a bot for the game the most he can do is play optimally, which maybe even easier to achieve when playing normally depending on the logic of your game.
306+
307+
This game becomes even better when combined with the Token example from Solana Cookbook and you actually drop some spl token to the players.
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
{
2+
"extends": "next/core-web-vitals"
3+
}
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2+
3+
# dependencies
4+
/node_modules
5+
/.pnp
6+
.pnp.js
7+
8+
# testing
9+
/coverage
10+
11+
# next.js
12+
/.next/
13+
/out/
14+
15+
# production
16+
/build
17+
18+
# misc
19+
.DS_Store
20+
*.pem
21+
22+
# debug
23+
npm-debug.log*
24+
yarn-debug.log*
25+
yarn-error.log*
26+
27+
# local env files
28+
.env*.local
29+
30+
# vercel
31+
.vercel
32+
33+
# typescript
34+
*.tsbuildinfo
35+
next-env.d.ts
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app).
2+
3+
## Getting Started
4+
5+
First, run the development server:
6+
7+
```bash
8+
npm run dev
9+
# or
10+
yarn dev
11+
# or
12+
pnpm dev
13+
```
14+
15+
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
16+
17+
You can start editing the page by modifying `pages/index.tsx`. The page auto-updates as you edit the file.
18+
19+
[API routes](https://nextjs.org/docs/api-routes/introduction) can be accessed on [http://localhost:3000/api/hello](http://localhost:3000/api/hello). This endpoint can be edited in `pages/api/hello.ts`.
20+
21+
The `pages/api` directory is mapped to `/api/*`. Files in this directory are treated as [API routes](https://nextjs.org/docs/api-routes/introduction) instead of React pages.
22+
23+
This project uses [`next/font`](https://nextjs.org/docs/basic-features/font-optimization) to automatically optimize and load Inter, a custom Google Font.
24+
25+
## Learn More
26+
27+
To learn more about Next.js, take a look at the following resources:
28+
29+
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
30+
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
31+
32+
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js/) - your feedback and contributions are welcome!
33+
34+
## Deploy on Vercel
35+
36+
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
37+
38+
Check out our [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details.

0 commit comments

Comments
 (0)