Skip to content

Commit

Permalink
Bugfixes
Browse files Browse the repository at this point in the history
  • Loading branch information
DogLooksGood committed Feb 4, 2024
1 parent a22e950 commit 2e7e151
Show file tree
Hide file tree
Showing 31 changed files with 315 additions and 199 deletions.
5 changes: 5 additions & 0 deletions api/src/effect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,11 @@ impl Effect {
self.timestamp
}

/// Cancel current dispatched event.
pub fn cancel_dispatch(&mut self) {
self.cancel_dispatch = true;
}

/// Dispatch waiting timeout event after certain milliseconds.
pub fn wait_timeout(&mut self, timeout: u64) {
self.wait_timeout = Some(timeout);
Expand Down
2 changes: 1 addition & 1 deletion api/src/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ impl std::fmt::Display for Event {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Event::Custom { sender, raw } => write!(f, "Custom from {}, inner: {:?}", sender, raw),
Event::Bridge { dest, raw } => write!(f, "Bridge to {}, inner: {:?}", dest, raw),
Event::Bridge { dest, raw } => write!(f, "Bridge to {}, inner: [{}...]", dest, raw[0]),
Event::Ready => write!(f, "Ready"),
Event::ShareSecrets { sender, shares } => {
let repr = shares
Expand Down
2 changes: 1 addition & 1 deletion core/src/types/broadcast_frame.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ pub enum BroadcastFrame {
game_addr: String,
event: Event,
timestamp: u64,
is_history: bool,
remain: u16,
},
// Arbitrary message
Message {
Expand Down
3 changes: 1 addition & 2 deletions dev/scripts/create-mtt-game.sh
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,7 @@ DATA=$(cd ./js/borsh; npx ts-node ./bin/cli.ts \
-u8 50 \
-u8 30 \
-u8 20 \
-u8 1 \
-s GvMiN5CouVeELHbvyzZXfAqa21TU2rMSRTdiHwCHUTz5)
-u8 0)
echo "DATA is $DATA"

JSON=$(cat <<EOF
Expand Down
13 changes: 12 additions & 1 deletion js/sdk-core/src/app-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {
import { GameContext } from './game-context';
import { ITransport, TransactionResult } from './transport';
import { IWallet } from './wallet';
import { Handler } from './handler';
import { Handler, InitAccount } from './handler';
import { Encryptor, IEncryptor } from './encryptor';
import { SdkError } from './error';
import { Client } from './client';
Expand Down Expand Up @@ -172,6 +172,16 @@ export class AppClient extends BaseClient {
const gameBundle = await getGameBundle(this.__transport, this.__storage, bundleCacheKey, bundleAddr);
const handler = await Handler.initialize(gameBundle, this.__encryptor, client, decryptionCache);
const gameContext = this.__gameContext.subContext(subGame);
const initAccount = new InitAccount({
addr,
accessVersion: this.__gameContext.accessVersion,
settleVersion: this.__gameContext.settleVersion,
data: subGame.initData,
players: subGame.players,
maxPlayers: 0,
checkpoint: subGame.checkpoint,
entryType: new EntryTypeCash({ minDeposit: 0n, maxDeposit: 0n }),
});

return new SubClient({
gameAddr: addr,
Expand All @@ -189,6 +199,7 @@ export class AppClient extends BaseClient {
decryptionCache,
gameContext,
subId,
initAccount,
});
} finally {
console.groupEnd();
Expand Down
32 changes: 13 additions & 19 deletions js/sdk-core/src/base-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,7 @@ export class BaseClient {
this.__onConnectionState(connState);
}
}

/**
* Connect to the transactor and retrieve the event stream.
*/
Expand All @@ -179,6 +180,7 @@ export class BaseClient {
const initAccount = InitAccount.createFromGameAccount(gameAccount, this.gameContext.accessVersion, this.gameContext.settleVersion);
this.__gameContext = new GameContext(gameAccount);
this.__gameContext.applyCheckpoint(gameAccount.checkpointAccessVersion, this.__gameContext.settleVersion);

for (const p of gameAccount.players) this.__onLoadProfile(p.accessVersion, p.addr);
await this.__connection.connect(new SubscribeEventParams({ settleVersion: this.__gameContext.settleVersion }));
await this.__initializeState(initAccount);
Expand All @@ -200,25 +202,28 @@ export class BaseClient {
async __initializeState(initAccount: InitAccount): Promise<void> {
console.log('Initialize state with', initAccount);
await this.__handler.initState(this.__gameContext, initAccount);
console.log('State initialized');
await this.__invokeEventCallback(undefined, true);
}

async __getGameAccount(): Promise<GameAccount> {
let retries = 0;
while (true) {
if (retries === MAX_RETRIES) {
throw new Error(`Game account not found, after ${retries} retries`);
}
try {
const gameAccount = await this.__transport.getGameAccount(this.gameAddr);
if (gameAccount === undefined) continue;
if (gameAccount === undefined) {
retries += 1;
continue;
}
return gameAccount;
} catch (e: any) {
console.warn(e, 'Failed to fetch game account, will retry in 3s');
await new Promise(r => setTimeout(r, 3000));
if (retries === MAX_RETRIES) {
throw new Error(`Game account not found, after ${retries} retries`);
} else {
retries += 1;
continue;
}
retries += 1;
continue;
}
}
}
Expand Down Expand Up @@ -285,23 +290,12 @@ export class BaseClient {
this.__gameContext.prepareForNextEvent(timestamp);
try {
let context = new GameContext(this.__gameContext);
if (event instanceof Join) {
while (true) {
let gameAccount = await this.__transport.getGameAccount(this.__gameAddr);
if (gameAccount === undefined) {
console.warn('Failed to get game account, will retry');
await new Promise(r => setTimeout(r, 3000));
continue;
}
break;
}
}
await this.__handler.handleEvent(context, event);
this.__gameContext = context;
} catch (err: any) {
console.error(err);
}
await this.__invokeEventCallback(event, frame.isHistory);
await this.__invokeEventCallback(event, frame.remain !== 0);
} catch (e: any) {
console.log("Game context in error:", this.__gameContext);
throw e;
Expand Down
13 changes: 4 additions & 9 deletions js/sdk-core/src/connection.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { IEncryptor, PublicKeyRaws } from './encryptor';
import { TxState } from './tx-state';
import { GameEvent } from './events';
import { deserialize, array, enums, field, option, serialize, struct, variant } from '@race-foundation/borsh';
import { deserialize, array, enums, field, serialize, struct, variant } from '@race-foundation/borsh';
import { arrayBufferToBase64, base64ToUint8Array } from './utils';
import { PlayerJoin, ServerJoin } from './accounts';

Expand All @@ -26,11 +26,6 @@ interface ISubmitMessageParams {
content: string;
}

interface ICheckTxStateParams {
newPlayers: string[];
accessVersion: bigint;
}

export type ConnectionSubscriptionItem = BroadcastFrame | ConnectionState | undefined;

export type ConnectionSubscription = AsyncGenerator<ConnectionSubscriptionItem>;
Expand Down Expand Up @@ -95,8 +90,8 @@ export class BroadcastFrameEvent extends BroadcastFrame {
event!: GameEvent;
@field('u64')
timestamp!: bigint;
@field('bool')
isHistory!: boolean;
@field('u16')
remain!: number;
constructor(fields: any) {
super();
Object.assign(this, fields);
Expand Down Expand Up @@ -222,7 +217,7 @@ export class Connection implements IConnection {
}

async connect(params: SubscribeEventParams) {
console.log('Establishing server connection, settle version:', params.settleVersion);
console.log(`Establishing server connection, target: ${this.target}, settle version: ${params.settleVersion}`)
this.socket = new WebSocket(this.endpoint);

this.clearCheckTimer();
Expand Down
2 changes: 1 addition & 1 deletion js/sdk-core/src/game-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -492,6 +492,6 @@ export class GameContext {
}

findSubGame(subId: number): LaunchSubGame | undefined {
return this.launchSubGames.find(g => g.subId === subId);
return this.launchSubGames.find(g => g.subId === Number(subId));
}
}
1 change: 1 addition & 0 deletions js/sdk-core/src/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ export class InitAccount {
this.checkpoint = fields.checkpoint;
this.entryType = fields.entryType;
}

static createFromGameAccount(
gameAccount: GameAccount,
transactorAccessVersion: bigint,
Expand Down
33 changes: 28 additions & 5 deletions js/sdk-core/src/sub-client.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { BaseClient } from './base-client';
import { Client } from './client';
import { IConnection } from './connection';
import { IConnection, SubscribeEventParams } from './connection';
import { DecryptionCache } from './decryption-cache';
import { IEncryptor } from './encryptor';
import { GameContext } from './game-context';
import { Handler } from './handler';
import { Handler, IInitAccount, InitAccount } from './handler';
import { ITransport } from './transport';
import { GameInfo, ConnectionStateCallbackFunction, EventCallbackFunction, MessageCallbackFunction, TxStateCallbackFunction } from './types';
import { IWallet } from './wallet';
Expand All @@ -25,21 +25,44 @@ export type SubClientCtorOpts = {
encryptor: IEncryptor;
info: GameInfo;
decryptionCache: DecryptionCache;
initAccount: InitAccount;
}

export class SubClient extends BaseClient {

#subId: number;
__subId: number;
__initAccount: InitAccount;

constructor(opts: SubClientCtorOpts) {
super({
onLoadProfile: (_id: bigint, _addr: string) => {},
...opts
})
this.#subId = opts.subId;
this.__subId = opts.subId;
this.__initAccount = opts.initAccount;
}

get subId(): number {
return this.#subId;
return this.__subId;
}

/**
* Connect to the transactor and retrieve the event stream.
*/
async attachGame() {
console.groupCollapsed('Attach to game');
let sub;
try {
await this.__client.attachGame();
sub = this.__connection.subscribeEvents();
await this.__connection.connect(new SubscribeEventParams({ settleVersion: this.__gameContext.settleVersion }));
await this.__initializeState(this.__initAccount);
} catch (e) {
console.error('Attaching game failed', e);
throw e;
} finally {
console.groupEnd();
}
await this.__processSubscription(sub);
}
}
1 change: 1 addition & 0 deletions transactor/src/component.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ pub use event_bus::CloseReason;
pub use broadcaster::Broadcaster;
pub use common::Component;
pub use common::PortsHandle;
pub use common::ComponentEnv;
pub use connection::{LocalConnection, RemoteConnection};
pub use event_bus::EventBus;
pub use event_loop::EventLoop;
Expand Down
Loading

0 comments on commit 2e7e151

Please sign in to comment.