Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions examples/chat-siwe/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
.hathora
node_modules
dist
.env
/api
/data/*
!/data/saves
/client/prototype-ui/*
!/client/prototype-ui/plugins
15 changes: 15 additions & 0 deletions examples/chat-siwe/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
FROM node:16

WORKDIR /app

RUN npm i -g hathora@0.10.2

ENV NODE_ENV=production

ARG APP_SECRET
ENV APP_SECRET=${APP_SECRET}

COPY . .
RUN hathora build --only server

CMD ["node", "server/dist/index.mjs"]
11 changes: 11 additions & 0 deletions examples/chat-siwe/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
Try it at: https://hathora-chat.surge.sh/

![image](https://user-images.githubusercontent.com/5400947/149680221-98474638-e88c-47db-a3bd-8bca56a611aa.png)

To run locally:

- install hathora (`npm install -g hathora`)
- clone or download this repo
- cd into this directory
- run `hathora dev`
- visit http://localhost:3000 in your browser
25 changes: 25 additions & 0 deletions examples/chat-siwe/hathora.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
types:
Message:
text: string
sentAt: int
sentBy: UserId
sentTo: UserId?
RoomState:
users: UserId[]
messages: Message[]

methods:
joinRoom:
leaveRoom:
sendPublicMessage:
text: string
sendPrivateMessage:
text: string
to: UserId

auth:
siwe:
statement: "Sign in to Hathora"

userState: RoomState
error: string
48 changes: 48 additions & 0 deletions examples/chat-siwe/server/impl.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { Methods, Context } from "./.hathora/methods";
import { Response } from "../api/base";
import { UserId, RoomState, ISendPublicMessageRequest, ISendPrivateMessageRequest } from "../api/types";

export class Impl implements Methods<RoomState> {
initialize(): RoomState {
return { users: [], messages: [] };
}
joinRoom(state: RoomState, userId: string): Response {
if (state.users.includes(userId)) {
return Response.error("Already joined!");
}
state.users.push(userId);
return Response.ok();
}
leaveRoom(state: RoomState, userId: string): Response {
if (!state.users.includes(userId)) {
return Response.error("Not joined");
}
state.users.splice(state.users.indexOf(userId), 1);
return Response.ok();
}
sendPublicMessage(state: RoomState, userId: UserId, ctx: Context, request: ISendPublicMessageRequest): Response {
if (!state.users.includes(userId)) {
return Response.error("Not joined");
}
state.messages.push({ text: request.text, sentAt: ctx.time, sentBy: userId });
return Response.ok();
}
sendPrivateMessage(state: RoomState, userId: UserId, ctx: Context, request: ISendPrivateMessageRequest): Response {
if (!state.users.includes(userId)) {
return Response.error("Not joined");
}
if (!state.users.includes(request.to)) {
return Response.error("Recpient not joined");
}
state.messages.push({ text: request.text, sentAt: ctx.time, sentBy: userId, sentTo: request.to });
return Response.ok();
}
getUserState(state: RoomState, userId: UserId): RoomState {
return {
users: state.users,
messages: state.messages.filter(
(msg) => msg.sentBy === userId || msg.sentTo === userId || msg.sentTo === undefined
),
};
}
}
36 changes: 36 additions & 0 deletions examples/chat-siwe/server/package-lock.json

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

8 changes: 8 additions & 0 deletions examples/chat-siwe/server/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"name": "chat-server",
"version": "0.0.1",
"type": "module",
"devDependencies": {
"typescript": "^4.5.2"
}
}
10 changes: 10 additions & 0 deletions examples/chat-siwe/server/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"compilerOptions": {
"esModuleInterop": true,
"module": "esnext",
"strict": true,
"target": "esnext",
"moduleResolution": "node",
"isolatedModules": true
}
}
4 changes: 4 additions & 0 deletions src/generate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ const HathoraConfig = z
anonymous: z.optional(z.object({ separator: z.optional(z.string()).default("-") }).strict()),
nickname: z.optional(z.object({}).strict()),
google: z.optional(z.object({ clientId: z.string() }).strict()),
siwe: z.optional(z.object({ statement: z.optional(z.string()).default("Sign in with Ethereum"),
chainId: z.optional(z.number().int()).default(11155111),
publicAddress: z.optional(z.string()),
}).strict()),
})
.strict(),
userState: z.string(),
Expand Down
4 changes: 4 additions & 0 deletions templates/base/api/base.ts.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@ export interface {{capitalize @key}}UserData {
email: string;
locale: string;
picture: string;
{{else if (eq @key "siwe")}}
publicAddress: string;
{{/if}}
}
{{/each}}
Expand All @@ -74,6 +76,8 @@ export function getUserDisplayName(user: UserData) {
return user.name;
{{else if (eq @key "google")}}
return user.name;
{{else if (eq @key "siwe")}}
return user.publicAddress;
{{else if (eq @key "email")}}
return user.email;
{{/if}}
Expand Down
4 changes: 4 additions & 0 deletions templates/base/client/.hathora/client.ts.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,10 @@ export class HathoraClient {
return this._client.loginGoogle(idToken);
}

{{else if (eq @key "siwe")}}
public async loginSiwe(message: string, signature: string, nonceToken: string): Promise<string> {
return this._client.loginSiwe(message, signature, nonceToken);
}
{{/if}}
{{/each}}
public async create(token: string, request: IInitializeRequest): Promise<string> {
Expand Down
20 changes: 20 additions & 0 deletions templates/base/client/prototype-ui/Login.tsx.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ import { toast } from "react-toastify";
{{#if auth.google}}
import { GoogleLogin } from "react-google-login";
{{/if}}
{{#if auth.siwe}}
import { SiweLogin } from "./SiweLogin";
{{/if}}
import { HathoraClient } from "../.hathora/client";

export function Login({ client, setToken }: { client: HathoraClient; setToken: (token: string) => void }) {
Expand Down Expand Up @@ -72,6 +75,23 @@ export function Login({ client, setToken }: { client: HathoraClient; setToken: (
onFailure={(error) => toast.error("Authentication error: " + error.details)}
/>
</div>
{{else if (eq @key "siwe")}}
<div className="mb-4">
<SiweLogin
onSuccess={({ message, signature, nonceToken }: { message: string; signature: string; nonceToken: string; }) =>
{
client
.loginSiwe(message, signature, nonceToken)
.then(token => {
sessionStorage.setItem(client.appId, token)
setToken(token)
})
.catch(e => toast.error(`Authentication error: ${JSON.stringify(e)}`))
}
}
onFailure={(e) => {toast.error(`Authentication error: ${JSON.stringify(e)}`)}}
/>
</div>
{{/if}}
{{/each}}
</div>
Expand Down
61 changes: 61 additions & 0 deletions templates/base/client/prototype-ui/SiweLogin.tsx.hbs
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import React, { useCallback, useMemo } from "react";
import ReactDOM from "react-dom";
import { ethers } from 'ethers';
import { SiweMessage } from 'siwe';
import { JsonRpcSigner } from '@ethersproject/providers';
import axios from "axios";

export type SiweLoginProps = {
statement?: string;
onSuccess: (payload: { message: string; signature: string; nonceToken: string; }) => Promise<void> | void;
onFailure: (error: unknown) => Promise<void> | void;
}

const useConnectWallet = () => {
const provider = useMemo(() => new ethers.providers.Web3Provider((window as any).ethereum), [])
const signer = useMemo(() => provider.getSigner(), [])
const connectWallet = useCallback(async () => provider.send('eth_requestAccounts', []), [provider])
return useMemo(() => ({ connectWallet, signer, provider }), [connectWallet, signer, provider])
}

const useAuthServer = () => {
const getNonce = useCallback(async () => {
//make request to auth server for nonce using axios
return axios.get('http://localhost:3001/nonce')
}, []);
return useMemo(() => ({ getNonce }), [getNonce])
}

const getSiweMessage = (address: string, nonce: string, statement?: string): Partial<SiweMessage> => (
{
domain: window.location.host,
address: address,
statement: statement || 'Sign in to Hathora',
uri: window.location.origin,
version: '1',
chainId: 1,
nonce
}
);

export const SiweLogin = ({ statement, onFailure, onSuccess }: SiweLoginProps) => {
const { connectWallet, signer } = useConnectWallet()
const { getNonce } = useAuthServer();
const handleLogin = useCallback(async () => {
try {
await connectWallet()
const address = await signer.getAddress();
const { nonce, nonceToken } = (await getNonce())?.data
const siweMessagePartial = getSiweMessage(address, nonce, statement)
const message = new SiweMessage(siweMessagePartial)
const messagePrepared = message.prepareMessage();
const signature = await signer.signMessage(messagePrepared)
await onSuccess({ message: messagePrepared, signature, nonceToken })
} catch (error) {
onFailure(error)
}
}, [connectWallet, onFailure, onSuccess, signer])
return (
<button onClick={handleLogin} className="inline-flex items-center rounded-full border px-6 py-2 text-base font-medium shadow-sm transition duration-300 ease-out focus:outline-none focus:ring-2 focus:ring-brand-500 border-transparent bg-brand-500 text-neutralgray-700 hover:bg-secondary-500 text-neutralgray-700 border border-neutralgray-700">Login</button>
)
}
4 changes: 4 additions & 0 deletions templates/base/client/prototype-ui/package.json.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@
{{#if auth.google}}
"react-google-login": "5.2.2",
{{/if}}
{{#if auth.siwe}}
"ethers": "5.5.1",
"siwe": "1.1.6",
{{/if}}
"react-router-dom": "6.2.1",
"react-toastify": "8.1.0"
},
Expand Down
2 changes: 2 additions & 0 deletions templates/base/server/.hathora/store.ts.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,8 @@ const coordinator = await register({
nickname: {},
{{else if (eq @key "google")}}
google: { clientId: "{{clientId}}" },
{{else if (eq @key "siwe")}}

{{/if}}
{{/each}}
},
Expand Down