Skip to content

Commit

Permalink
feat(starter-game-template): Add ability to listen to transaction rec…
Browse files Browse the repository at this point in the history
…eipts from Nakama (#2)

* feat(starter-game-template): Add ability to listen to transaction receipts from Nakama

* add js client to demonstrate transaction receipts

* moved jsclient to the hidden .jsclient, removed yarn-error.log, added some documentation

* Moved txReceiptRequest to a named struct
  • Loading branch information
jerargus committed Aug 15, 2023
1 parent 5c9ca2d commit a4337bc
Show file tree
Hide file tree
Showing 18 changed files with 513 additions and 34 deletions.
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
# Dependency directories (remove the comment below to include it)
/cardinal/vendor
/nakama/vendor
/testsuite/vendor

### Linux ###
*~
Expand Down Expand Up @@ -112,3 +113,7 @@ $RECYCLE.BIN/

# Windows shortcuts
*.lnk

# Node
/.jsclient/node_modules
yarn-error.log
13 changes: 13 additions & 0 deletions .jsclient/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
This is a simple js client that demonstrates transaction receipts.

after run `mage start` in the parent directory (to start cardinal and nakama), run:

`
npm install
node main.mjs
`

The js client will attempt to join the singleton match and then will print any transaciton receipts that cardinal generates.

Transactions can be sent in via the Nakama API Explorer (localhost:7351/#/apiexplorer)

50 changes: 50 additions & 0 deletions .jsclient/main.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import {Client} from '@heroiclabs/nakama-js';
import {WebSocket} from 'ws';
Object.assign(global, { WebSocket: WebSocket });

console.log(WebSocket);

var client = new Client("defaultkey", "127.0.0.1", 7350);

console.log(client);

var randomString = function() {
let str = ""
for (let i = 0; i < 13; i++) {
str += Math.floor(10 * Math.random())
}
return str
}

var device_id = randomString();
var username = device_id;

var create = true
var session = await client.authenticateDevice(device_id, create, username)
console.log("auth success", session);

const account = await client.getAccount(session);
console.log("account is", account)

const secure = false; // Enable if server is run with an SSL certificate
const trace = false;
const socket = client.createSocket(secure, trace);
socket.ondisconnect = (evt) => {
console.info("Disconnected", evt);
};

var appearOnline = true
session = await socket.connect(session, appearOnline);

console.log("session is", session)

let result = await client.listMatches(session)

let dec = new TextDecoder()
socket.onmatchdata = (result) => {
console.log("tx receipt: ", dec.decode(result.data));
}

let match_id = result.matches[0].match_id
let match = await socket.joinMatch(match_id)
console.log("i joined the match: ", match)
73 changes: 73 additions & 0 deletions .jsclient/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions .jsclient/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"type": "module",
"dependencies": {
"@heroiclabs/nakama-js": "^2.6.1",
"ws": "^8.13.0"
}
}
38 changes: 38 additions & 0 deletions .jsclient/yarn.lock
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
# yarn lockfile v1


"@heroiclabs/nakama-js@^2.6.1":
version "2.6.1"
resolved "https://registry.npmjs.org/@heroiclabs/nakama-js/-/nakama-js-2.6.1.tgz"
integrity sha512-akuHr42rUdKGli0un6+ok7HDC2KarHs3lGRF1pIn5Mc7ALRZ46Cnx0kRX7jqj4mj5FuMD5wBtIY8CEcJGP+Oaw==
dependencies:
"@scarf/scarf" "^1.1.1"
base64-arraybuffer "^1.0.2"
js-base64 "^3.7.4"
whatwg-fetch "^3.6.2"

"@scarf/scarf@^1.1.1":
version "1.1.1"
resolved "https://registry.npmjs.org/@scarf/scarf/-/scarf-1.1.1.tgz"
integrity sha512-VGbKDbk1RFIaSmdVb0cNjjWJoRWRI/Weo23AjRCC2nryO0iAS8pzsToJfPVPtVs74WHw4L1UTADNdIYRLkirZQ==

base64-arraybuffer@^1.0.2:
version "1.0.2"
resolved "https://registry.npmjs.org/base64-arraybuffer/-/base64-arraybuffer-1.0.2.tgz"
integrity sha512-I3yl4r9QB5ZRY3XuJVEPfc2XhZO6YweFPI+UovAzn+8/hb3oJ6lnysaFcjVpkCPfVWFUDvoZ8kmVDP7WyRtYtQ==

js-base64@^3.7.4:
version "3.7.5"
resolved "https://registry.npmjs.org/js-base64/-/js-base64-3.7.5.tgz"
integrity sha512-3MEt5DTINKqfScXKfJFrRbxkrnk2AxPWGBL/ycjz4dK8iqiSJ06UxD8jh8xuh6p10TX4t2+7FsBYVxxQbMg+qA==

whatwg-fetch@^3.6.2:
version "3.6.17"
resolved "https://registry.npmjs.org/whatwg-fetch/-/whatwg-fetch-3.6.17.tgz"
integrity sha512-c4ghIvG6th0eudYwKZY5keb81wtFz9/WeAHAoy8+r18kcWlitUIrmGFQ2rWEl4UCKUilD3zCLHOIPheHx5ypRQ==

ws@^8.13.0:
version "8.13.0"
resolved "https://registry.npmjs.org/ws/-/ws-8.13.0.tgz"
integrity sha512-x9vcZYTrFPC7aSIbj7sRCYo7L/Xb8Iy+pW0ng0wt2vCJv7M9HOMy0UoN3rr+IFC7hb7vXoqS+P9ktyLLLhO+LA==
5 changes: 2 additions & 3 deletions cardinal/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,8 @@ replace (
)

require (
github.com/argus-labs/world-engine/cardinal v0.1.20-alpha
github.com/ericlagergren/decimal v0.0.0-20221120152707-495c53812d05
github.com/argus-labs/world-engine/cardinal v0.1.22-alpha
github.com/rs/zerolog v1.29.1
golang.org/x/exp v0.0.0-20230711153332-06a737ee72cb
)

require (
Expand Down Expand Up @@ -107,6 +105,7 @@ require (
github.com/yuin/gopher-lua v1.1.0 // indirect
go.etcd.io/bbolt v1.3.7 // indirect
golang.org/x/crypto v0.11.0 // indirect
golang.org/x/exp v0.0.0-20230711153332-06a737ee72cb // indirect
golang.org/x/net v0.12.0 // indirect
golang.org/x/sys v0.10.0 // indirect
golang.org/x/text v0.11.0 // indirect
Expand Down
6 changes: 2 additions & 4 deletions cardinal/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -429,8 +429,8 @@ github.com/alicebob/gopher-json v0.0.0-20200520072559-a9ecdc9d1d3a/go.mod h1:SGn
github.com/alicebob/miniredis/v2 v2.30.2 h1:lc1UAUT9ZA7h4srlfBmBt2aorm5Yftk9nBjxz7EyY9I=
github.com/alicebob/miniredis/v2 v2.30.2/go.mod h1:b25qWj4fCEsBeAAR2mlb0ufImGC6uH3VlUfb/HS5zKg=
github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY=
github.com/argus-labs/world-engine/cardinal v0.1.20-alpha h1:V9QZskGK91YXx8v7D5+cM8BKwI693v136gD3W4AxofM=
github.com/argus-labs/world-engine/cardinal v0.1.20-alpha/go.mod h1:FeW3pj9xuzmgEr+gu95Lv2Qnpmaq+ALkXnbvqpLzvbY=
github.com/argus-labs/world-engine/cardinal v0.1.22-alpha h1:1zOF5yOqX1gtYtpGaBrYZ2p2AFbHaprxs+/rZ6D0WnA=
github.com/argus-labs/world-engine/cardinal v0.1.22-alpha/go.mod h1:lErdQQkL3Ao6nXe4E05UjYPMHHQyOi9q5ox2jfSCjV4=
github.com/argus-labs/world-engine/chain v0.1.1-alpha h1:J9DhMEm/I0HCttzdyoLYabAbQJTVfBcJezXrO4aCY+c=
github.com/argus-labs/world-engine/chain v0.1.1-alpha/go.mod h1:Zm/G+e03QpGCmZmgbtar9PqNBEjlHoKryuZSVXHVxok=
github.com/argus-labs/world-engine/sign v0.1.4-alpha h1:IlMZDnTjJRuvcGMRWIDE3t12oWXy+DXU4b3NLXsUPOY=
Expand Down Expand Up @@ -566,8 +566,6 @@ github.com/envoyproxy/go-control-plane v0.10.3/go.mod h1:fJJn/j26vwOu972OllsvAgJ
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
github.com/envoyproxy/protoc-gen-validate v0.6.7/go.mod h1:dyJXwwfPK2VSqiB9Klm1J6romD608Ba7Hij42vrOBCo=
github.com/envoyproxy/protoc-gen-validate v0.9.1/go.mod h1:OKNgG7TCp5pF4d6XftA0++PMirau2/yoOwVac3AbF2w=
github.com/ericlagergren/decimal v0.0.0-20221120152707-495c53812d05 h1:S92OBrGuLLZsyM5ybUzgc/mPjIYk2AZqufieooe98uw=
github.com/ericlagergren/decimal v0.0.0-20221120152707-495c53812d05/go.mod h1:M9R1FoZ3y//hwwnJtO51ypFGwm8ZfpxPT/ZLtO1mcgQ=
github.com/fatih/color v1.15.0 h1:kOqh6YHBtK8aywxGerMG2Eq3H6Qgoqeo13Bk2Mv/nBs=
github.com/felixge/httpsnoop v1.0.2 h1:+nS9g82KMXccJ/wp0zyRW9ZBHFETmMGtkk+2CTTrW4o=
github.com/filecoin-project/go-jsonrpc v0.3.1 h1:qwvAUc5VwAkooquKJmfz9R2+F8znhiqcNHYjEp/NM10=
Expand Down
3 changes: 2 additions & 1 deletion cardinal/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@ package main

import (
"context"
"time"

"github.com/argus-labs/starter-game-template/cardinal/component"
"github.com/argus-labs/starter-game-template/cardinal/read"
"github.com/argus-labs/starter-game-template/cardinal/system"
"github.com/argus-labs/starter-game-template/cardinal/tx"
"github.com/argus-labs/world-engine/cardinal/server"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"time"
)

func main() {
Expand Down
11 changes: 10 additions & 1 deletion cardinal/system/system_attack.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package system

import (
"fmt"

comp "github.com/argus-labs/starter-game-template/cardinal/component"
"github.com/argus-labs/starter-game-template/cardinal/tx"
"github.com/argus-labs/world-engine/cardinal/ecs"
Expand Down Expand Up @@ -31,21 +33,28 @@ func AttackSystem(world *ecs.World, tq *ecs.TransactionQueue) error {
// or otherwise the rest of the transaction will not be processed & get dropped.
// In the future, you will be able to add error receipts to transaction receipts.
for _, attack := range attackTxs {
targetPlayerID, ok := playerTagToID[attack.TargetNickname]
target := attack.Value.TargetNickname
targetPlayerID, ok := playerTagToID[target]
// If the target player doesn't exist, skip this transaction
if !ok {
tx.AttackPlayer.AddError(world, attack.ID,
fmt.Errorf("target %q does not exist", target))
continue
}

// Get the health component for the target player
health, err := comp.Health.Get(world, targetPlayerID)
if err != nil {
tx.AttackPlayer.AddError(world, attack.ID,
fmt.Errorf("can't get health for %q: %w", target, err))
continue
}

// Inflict damage and update the component
health.HP -= 10
if err := comp.Health.Set(world, targetPlayerID, health); err != nil {
tx.AttackPlayer.AddError(world, attack.ID,
fmt.Errorf("failed to set health on %q: %w", target, err))
continue
}
}
Expand Down
13 changes: 9 additions & 4 deletions cardinal/system/system_player_spawner.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package system

import (
"fmt"

comp "github.com/argus-labs/starter-game-template/cardinal/component"
"github.com/argus-labs/starter-game-template/cardinal/tx"
"github.com/argus-labs/world-engine/cardinal/ecs"
Expand All @@ -20,21 +21,25 @@ func PlayerSpawnerSystem(world *ecs.World, tq *ecs.TransactionQueue) error {
for _, create := range createTxs {
id, err := world.Create(comp.Player, comp.Health)
if err != nil {
fmt.Println("Error creating player")
tx.CreatePlayer.AddError(world, create.ID,
fmt.Errorf("error creating player: %w", err))
continue
}

err = comp.Player.Set(world, id, comp.PlayerComponent{Nickname: create.Nickname})
err = comp.Player.Set(world, id, comp.PlayerComponent{Nickname: create.Value.Nickname})
if err != nil {
fmt.Println("Error setting player nickname")
tx.CreatePlayer.AddError(world, create.ID,
fmt.Errorf("error setting player nickname: %w", err))
continue
}

err = comp.Health.Set(world, id, comp.HealthComponent{HP: 100})
if err != nil {
fmt.Println("Error setting player health")
tx.CreatePlayer.AddError(world, create.ID,
fmt.Errorf("error setting player health: %w", err))
continue
}
tx.CreatePlayer.SetResult(world, create.ID, tx.CreatePlayerMsgReply{true})
}

return nil
Expand Down
4 changes: 3 additions & 1 deletion cardinal/tx/tx_attack_player.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,6 @@ type AttackPlayerMsg struct {
TargetNickname string `json:"target"`
}

var AttackPlayer = ecs.NewTransactionType[AttackPlayerMsg]("attack-player")
type AttackPlayerMsgReply struct{}

var AttackPlayer = ecs.NewTransactionType[AttackPlayerMsg, AttackPlayerMsgReply]("attack-player")
6 changes: 5 additions & 1 deletion cardinal/tx/tx_create_player.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,8 @@ type CreatePlayerMsg struct {
Nickname string `json:"nickname"`
}

var CreatePlayer = ecs.NewTransactionType[CreatePlayerMsg]("create-player")
type CreatePlayerMsgReply struct {
Success bool `json:"success"`
}

var CreatePlayer = ecs.NewTransactionType[CreatePlayerMsg, CreatePlayerMsgReply]("create-player")
13 changes: 10 additions & 3 deletions magefiles/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,19 @@ func Check() error {
return checkPrereq(true)
}

// Test runs the test suite
func Test() error {
mg.Deps(exitMagefilesDir)
// Clear deletes all the docker volumes
func Clear() error {
if err := sh.RunV("docker", "compose", "down", "--volumes"); err != nil {
return err
}
return nil
}


// Test runs the test suite
func Test() error {
mg.Deps(exitMagefilesDir)
mg.Deps(Clear)

if err := prepareDirs("testsuite", "cardinal", "nakama"); err != nil {
return err
Expand Down
Loading

0 comments on commit a4337bc

Please sign in to comment.