|
1 | 1 | import { Transaction } from '@solana/web3.js' |
2 | 2 | import { System } from './System' |
| 3 | +import { storage } from '../storage' |
| 4 | +import bs58 from 'bs58' |
| 5 | + |
| 6 | +const key = 'hyp:solana:auths' |
| 7 | +const template = 'Connect to world:\n{address}' |
3 | 8 |
|
4 | 9 | export class ClientSolana extends System { |
5 | 10 | constructor(world) { |
6 | 11 | super(world) |
| 12 | + this.wallet = null |
| 13 | + this.modal = null |
| 14 | + this.auths = storage.get(key, []) // [...{ address, signature }] |
| 15 | + this.connected = false |
7 | 16 | } |
8 | 17 |
|
9 | | - connect() { |
10 | | - const player = this.world.entities.player |
11 | | - if (player.wallet.connected) return console.warn('[solana] already connected') |
12 | | - player.wallet.openModal() |
| 18 | + async bind({ wallet, modal }) { |
| 19 | + this.wallet = wallet |
| 20 | + this.modal = modal |
| 21 | + if (this.wallet.connected && !this.connected) { |
| 22 | + const address = this.wallet.publicKey.toString() |
| 23 | + let auth = this.auths.find(auth => auth.address === address) |
| 24 | + if (!auth) { |
| 25 | + const text = template.replace('{address}', address) |
| 26 | + const message = new TextEncoder().encode(text) |
| 27 | + const signature_ = await this.wallet.signMessage(message) |
| 28 | + const signature = bs58.encode(signature_) |
| 29 | + auth = { address, signature } |
| 30 | + this.auths.push(auth) |
| 31 | + storage.set(key, this.auths) |
| 32 | + } |
| 33 | + this.connected = true |
| 34 | + this.world.network.send('walletConnect', auth) |
| 35 | + } |
| 36 | + if (!this.wallet.connected && this.connected) { |
| 37 | + this.connected = false |
| 38 | + this.world.network.send('walletDisconnect') |
| 39 | + } |
13 | 40 | } |
14 | 41 |
|
15 | | - disconnect() { |
16 | | - const player = this.world.entities.player |
17 | | - if (!player.wallet.connected) return console.warn('[solana] already disconnected') |
18 | | - player.wallet.disconnect() |
| 42 | + connect(player) { |
| 43 | + if (player && player.data.id !== this.world.network.id) { |
| 44 | + throw new Error('[solana] cannot connect a remote player from client') |
| 45 | + } |
| 46 | + if (!this.wallet) return |
| 47 | + if (this.wallet.connected) return |
| 48 | + this.modal.setVisible(true) |
| 49 | + } |
| 50 | + |
| 51 | + disconnect(player) { |
| 52 | + if (player && player.data.id !== this.world.network.id) { |
| 53 | + throw new Error('[solana] cannot disconnect a remote player from client') |
| 54 | + } |
| 55 | + if (!this.wallet) return |
| 56 | + if (!this.wallet.connected) return |
| 57 | + this.wallet.disconnect() |
19 | 58 | } |
20 | 59 |
|
21 | 60 | deposit(playerId, amount) { |
|
0 commit comments