Skip to content

Commit

Permalink
Merge branch 'feature/use-scoreboard-for-antcopter'
Browse files Browse the repository at this point in the history
  • Loading branch information
felipefg committed Feb 29, 2024
2 parents b7a79c6 + bd6d2cd commit 7040827
Show file tree
Hide file tree
Showing 15 changed files with 250 additions and 161 deletions.
3 changes: 2 additions & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -78,10 +78,11 @@ COPY main.py .
COPY app app
COPY misc/Rives-Logo.png misc/Rives-Logo.png
COPY misc/snake.sqfs misc/snake.sqfs
COPY misc/2048.sqfs misc/2048.sqfs
# COPY misc/2048.sqfs misc/2048.sqfs
COPY misc/freedoom.sqfs misc/freedoom.sqfs
COPY misc/antcopter.sqfs misc/antcopter.sqfs
COPY misc/monky.sqfs misc/monky.sqfs
COPY misc/breakout.sqfs misc/breakout.sqfs
COPY misc/test.rivlog misc/test.rivlog

COPY misc/font misc/font
Expand Down
9 changes: 9 additions & 0 deletions app/cartridge.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,15 @@ def initialize_data():
except Exception as e:
LOGGER.warning(e)

try:
cartridge_example_file = open('misc/breakout.sqfs','rb')
cartridge_example_data = cartridge_example_file.read()
cartridge_example_file.close()
create_cartridge(cartridge_example_data,msg_sender="0xd33Dfbfb0D0961284656e0225CFfB561090762D3")
if AppSettings.rivemu_path is None: os.remove('misc/breakout.sqfs')
except Exception as e:
LOGGER.warning(e)

# try:
# cartridge_example_file = open('misc/2048.sqfs','rb')
# cartridge_example_data = cartridge_example_file.read()
Expand Down
4 changes: 2 additions & 2 deletions app/riv.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ def replay_log(cartridge_id,log,riv_args,in_card):
if in_card is not None and len(in_card):
run_args.append(f"-load-incard={incard_temp.name}")
if riv_args is not None and len(riv_args) > 0:
run_args.extend(riv_args.split())
run_args.append(f"-args='{riv_args}'")

result = subprocess.run(run_args, cwd=cwd)
if result.returncode != 0:
Expand Down Expand Up @@ -237,7 +237,7 @@ def riv_get_cartridge_outcard(cartridge_id,frame,riv_args,in_card):
run_args.append(f"-load-incard={incard_temp.name}")
run_args.append(f"-stop-frame={frame}")
if riv_args is not None and len(riv_args) > 0:
run_args.extend(riv_args.split())
run_args.append(f"-args='{riv_args}'")

result = subprocess.run(run_args, cwd=cwd)
if result.returncode != 0:
Expand Down
15 changes: 8 additions & 7 deletions app/scoreboard.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@

class Scoreboard(Entity):
id = helpers.PrimaryKey(str, 64)
name = helpers.Required(str, index=True, unique=True)
name = helpers.Required(str, index=True)
cartridge_id = helpers.Required(str, 64, index=True)
created_by = helpers.Required(str, 42)
created_at = helpers.Required(int)
Expand Down Expand Up @@ -168,8 +168,8 @@ def create_scoreboard(payload: CreateScoreboardPayload) -> bool:
add_output(msg,tags=['error'])
return False

if helpers.count(s.id for s in Scoreboard if s.name == payload.name) > 0:
msg = f"Scoreboard {payload.name} already exists"
if helpers.count(s.id for s in Scoreboard if s.name == payload.name and s.cartridge_id == payload.cartridge_id.hex()) > 0:
msg = f"Scoreboard {payload.name} already exists for this game"
LOGGER.error(msg)
add_output(msg,tags=['error'])
return False
Expand All @@ -185,8 +185,8 @@ def create_scoreboard(payload: CreateScoreboardPayload) -> bool:
return False

# process outcard
outcard_hash = sha256(outcard_raw).digest()
outcard_format = outcard_raw[:4]
print(outcard_format)
if outcard_format != b"JSON":
msg = f"Outcard format is not json"
LOGGER.error(msg)
Expand Down Expand Up @@ -217,7 +217,7 @@ def create_scoreboard(payload: CreateScoreboardPayload) -> bool:
return False

# str2bytes(metadata.msg_sender) + metadata.timestamp.to_bytes(32, byteorder='big')
scoreboard_id = sha256(str2bytes(payload.name)).digest()
scoreboard_id = sha256(payload.cartridge_id + str2bytes(payload.name)).digest()

LOGGER.info(f"Creating scoreboard {payload.name} (id={scoreboard_id.hex()}) with function {payload.score_function}")

Expand Down Expand Up @@ -332,7 +332,7 @@ def scoreboard_replay(replay: ScoreboardReplayPayload) -> bool:
add_output(msg,tags=['error'])
return False

user_alias = replay.user_alias if len(replay.user_alias) else f"{metadata.msg_sender[:6]}...{metadata.msg_sender[:-4]}"
user_alias = replay.user_alias if len(replay.user_alias) else f"{metadata.msg_sender[:6]}...{metadata.msg_sender[-4:]}"

s = Score(
user_address = metadata.msg_sender,
Expand All @@ -353,11 +353,12 @@ def scoreboard_replay(replay: ScoreboardReplayPayload) -> bool:
score = default_score,
extra_score = score,
scoreboard_id = replay.scoreboard_id.hex(),
screenshot_cid = cid,
gameplay_hash = gameplay_hash.digest()
)

add_output(replay.log,tags=['replay',scoreboard.cartridge_id,replay.scoreboard_id.hex()])
add_output(final_screenshot,tags=['screenshot',replay.cartridge_id.hex()])
add_output(final_screenshot,tags=['screenshot',scoreboard.cartridge_id])
emit_event(replay_score,tags=['score',scoreboard.cartridge_id,replay.scoreboard_id.hex()])

GameplayHash.add(scoreboard.cartridge_id,gameplay_hash.hexdigest())
Expand Down
2 changes: 2 additions & 0 deletions frontend/.env
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,5 @@ NEXT_PUBLIC_DAPP_ADDR="0x70ac08179605AF2D9e75782b8DEcDD3c22aA4D0C"
NEXT_PUBLIC_CARTESI_NODE_URL="http://127.0.0.1:8080"
NEXT_PUBLIC_NETWORK_CHAIN_ID="0x7A69"
NEXT_PUBLIC_NFT_ADDR="0xc6e7DF5E7b4f2A278906862b61205850344D4e7d"
NEXT_PUBLIC_SCOREBOARD_ID=f919b9f089e4a105e7e9f530c896a1979744d0fa107a63c5cd44eae5fc28c484
NEXT_PUBLIC_SCOREBOARD_CARTRIDGE_ID=76d516fe6fdfd59c338c0c5288b1dac4ee0dabe80033984c842837d35082afed
2 changes: 2 additions & 0 deletions frontend/.env.sepolia
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,5 @@ NEXT_PUBLIC_DAPP_ADDR="0x573F9E8457B4bDCCDef62F07cf9AFF0a3802f1C8"
NEXT_PUBLIC_CARTESI_NODE_URL="https://rives.io"
NEXT_PUBLIC_NETWORK_CHAIN_ID="0xAA36A7"
NEXT_PUBLIC_NFT_ADDR="0x5b8C976fb283bc575f15C868a98F04c68a2Ea204"
NEXT_PUBLIC_SCOREBOARD_ID=f919b9f089e4a105e7e9f530c896a1979744d0fa107a63c5cd44eae5fc28c484
NEXT_PUBLIC_SCOREBOARD_CARTRIDGE_ID=76d516fe6fdfd59c338c0c5288b1dac4ee0dabe80033984c842837d35082afed
21 changes: 20 additions & 1 deletion frontend/app/cartridges/selectedCartridgeProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@

import { createContext, useState } from 'react';
import { CartridgeInfo as Cartridge } from "../backend-libs/app/ifaces"
import { envClient } from '../utils/clientEnv';

import { scoreboards, ScoreboardsOutput } from '../backend-libs/app/lib';

export const selectedCartridgeContext = createContext<{
selectedCartridge: PlayableCartridge|null, changeCartridge:Function, playCartridge:Function,
Expand Down Expand Up @@ -44,7 +46,24 @@ export function SelectedCartridgeProvider({ children }:{ children: React.ReactNo
const aux = {...cartridge, play:false, downloading:false, cartridgeData:undefined, inCard:undefined,
args:undefined, scoreFunction:undefined, replay:undefined, gameplayLog:undefined,
outcard:undefined, outhash:undefined, initCanvas:selectedCartridge?.initCanvas};
setSelectedCartridge(aux as PlayableCartridge);

if (cartridge.id == envClient.SCOREBOARD_CARTRIDGE_ID) {
scoreboards({cartridge_id:cartridge.id},{cartesiNodeUrl: envClient.CARTESI_NODE_URL,cache:"force-cache"}).then(
(reportOutput) => {
const scoreboardsOutput = new ScoreboardsOutput(reportOutput);
if (scoreboardsOutput.total > 0) {
const lastInd = scoreboardsOutput.total - 1;
aux.args = scoreboardsOutput.data[lastInd].args;
aux.inCard = scoreboardsOutput.data[lastInd].inCard;
aux.scoreFunction = scoreboardsOutput.data[lastInd].scoreFunction;
}
setSelectedCartridge(aux as PlayableCartridge);
}
);
} else {
setSelectedCartridge(aux as PlayableCartridge);

}
}

const playCartridge = () => {
Expand Down
19 changes: 15 additions & 4 deletions frontend/app/components/CartridgeInfo.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ import QRCode from "react-qr-code";
import Cartridge from "../models/cartridge";
import {SciFiPedestal} from "../models/scifi_pedestal";
import Loader from "../components/Loader";
import { ReplayScore, getOutputs, replay } from '../backend-libs/app/lib';
import { Replay } from '../backend-libs/app/ifaces';
import { ReplayScore, getOutputs, replay, scoreboardReplay } from '../backend-libs/app/lib';
import { Replay, ScoreboardReplayPayload } from '../backend-libs/app/ifaces';
import CartridgeDescription from './CartridgeDescription';
import Link from 'next/link';
import CartridgeScoreboard from './CartridgeScoreboard';
Expand Down Expand Up @@ -238,7 +238,18 @@ function CartridgeInfo() {
// setSubmitLogStatus({status: STATUS.SUBMIT});
try {
setSubmitLogStatus({status: STATUS.SUBMITING});
const receipt = await replay(signer, envClient.DAPP_ADDR, inputData, {sync:false, cartesiNodeUrl: envClient.CARTESI_NODE_URL}) as ContractReceipt;
let receipt: ContractReceipt;
if (selectedCartridge.id != envClient.SCOREBOARD_CARTRIDGE_ID) {
receipt = await replay(signer, envClient.DAPP_ADDR, inputData, {sync:false, cartesiNodeUrl: envClient.CARTESI_NODE_URL}) as ContractReceipt;
} else {
const inputData: ScoreboardReplayPayload = {
user_alias:userAliasToSubmit,
scoreboard_id: '0x' + envClient.SCOREBOARD_ID,
outcard_hash: '0x' + selectedCartridge.outhash,
log: ethers.utils.hexlify(selectedCartridge.gameplayLog)
}
receipt = await scoreboardReplay(signer, envClient.DAPP_ADDR, inputData, {sync:false, cartesiNodeUrl: envClient.CARTESI_NODE_URL}) as ContractReceipt;
}

if (receipt == undefined || receipt.events == undefined)
throw new Error("Couldn't send transaction");
Expand Down Expand Up @@ -489,7 +500,7 @@ function CartridgeInfo() {
{/* lg: width is equal to the max-w-3xl */}
<Tab.Panel className="game-tab-content">
<div className="w-full flex">
<button className="ms-auto scoreboard-btn" onClick={() => setReloadScoreboardCount(reloadScoreboardCount+1)}><span><CachedIcon/></span></button>
<button title="Reload Scores (cached for 3 mins)" className="ms-auto scoreboard-btn" onClick={() => setReloadScoreboardCount(reloadScoreboardCount+1)}><span><CachedIcon/></span></button>
</div>
<Suspense fallback={scoreboardFallback()}>
<CartridgeScoreboard cartridge_id={selectedCartridge.id} reload={reloadScoreboardCount} replay_function={prepareReplay}/>
Expand Down
6 changes: 5 additions & 1 deletion frontend/app/components/CartridgeScoreboard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,11 @@ import React from 'react';


const getGeneralScoreboard = async (cartridge_id:string):Promise<Array<ReplayScore>> => {
const scores:Array<ReplayScore> = await getOutputs({tags: ["score", cartridge_id]}, {cartesiNodeUrl: envClient.CARTESI_NODE_URL});
const tags = ["score", cartridge_id];
if (cartridge_id == envClient.SCOREBOARD_CARTRIDGE_ID) {
tags.push(envClient.SCOREBOARD_ID);
}
const scores:Array<ReplayScore> = await getOutputs({tags}, {cartesiNodeUrl: envClient.CARTESI_NODE_URL});
return scores;
}

Expand Down
322 changes: 177 additions & 145 deletions frontend/app/contracts/RivesScoreNFT.sol/RivesScoreNFT.json

Large diffs are not rendered by default.

8 changes: 8 additions & 0 deletions frontend/app/utils/clientEnv.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,13 @@ export const envClient = envsafe({
NFT_ADDR: str({
input: process.env.NEXT_PUBLIC_NFT_ADDR,
desc: "Rives Score NFT ETH address."
}),
SCOREBOARD_CARTRIDGE_ID: str({
input: process.env.NEXT_PUBLIC_SCOREBOARD_CARTRIDGE_ID,
desc: "Cartridge id to consider scoreboard."
}),
SCOREBOARD_ID: str({
input: process.env.NEXT_PUBLIC_SCOREBOARD_ID,
desc: "Scoreboard id."
})
})
Binary file modified misc/antcopter.sqfs
Binary file not shown.
Binary file added misc/breakout.sqfs
Binary file not shown.
Binary file modified misc/freedoom.sqfs
Binary file not shown.
Binary file modified misc/snake.sqfs
Binary file not shown.

0 comments on commit 7040827

Please sign in to comment.