|
| 1 | +import { AnyEventObject, interpret, Interpreter } from 'xstate'; |
| 2 | +import { getChannelID, pretty } from '.'; |
| 3 | +import { messageService } from './messaging'; |
| 4 | +import { Wallet } from './protocols'; |
| 5 | +import { AddressableMessage } from './wire-protocol'; |
| 6 | + |
| 7 | +import { CreateChannelEvent } from './protocols/wallet/protocol'; |
| 8 | +import { Store } from './store'; |
| 9 | + |
| 10 | +const store = name => { |
| 11 | + const privateKeys = { [name]: name }; |
| 12 | + const _store = new Store({ privateKeys }); |
| 13 | + messageService.on('message', (m: AddressableMessage) => { |
| 14 | + if (m.to === name) { |
| 15 | + switch (m.type) { |
| 16 | + case 'SendStates': |
| 17 | + _store.receiveStates(m.signedStates); |
| 18 | + } |
| 19 | + } |
| 20 | + }); |
| 21 | + |
| 22 | + return _store; |
| 23 | +}; |
| 24 | + |
| 25 | +const first = 'first'; |
| 26 | +const second = 'second'; |
| 27 | +const stores = { |
| 28 | + first: store(first), |
| 29 | + second: store(second), |
| 30 | +}; |
| 31 | + |
| 32 | +const logEvents = name => event => |
| 33 | + console.log(`${name} received ${event.type}`); |
| 34 | + |
| 35 | +const wallet = name => { |
| 36 | + return interpret(Wallet.machine(stores[name])) |
| 37 | + .onEvent(logEvents(name)) |
| 38 | + .start(); |
| 39 | +}; |
| 40 | + |
| 41 | +const wallets: Record<string, Interpreter<Wallet.Init, any, AnyEventObject>> = { |
| 42 | + first: wallet(first), |
| 43 | + second: wallet(second), |
| 44 | +}; |
| 45 | + |
| 46 | +// This is sort of the "dispatcher" |
| 47 | +messageService.on('message', ({ to, ...event }: AddressableMessage) => { |
| 48 | + switch (event.type) { |
| 49 | + case 'SendStates': { |
| 50 | + stores[to].receiveStates(event.signedStates); |
| 51 | + const channelId = getChannelID(event.signedStates[0].state.channel); |
| 52 | + |
| 53 | + wallets[to].send({ |
| 54 | + type: 'CHANNEL_UPDATED', |
| 55 | + channelId, |
| 56 | + }); |
| 57 | + break; |
| 58 | + } |
| 59 | + case 'OPEN_CHANNEL': { |
| 60 | + wallets[to].send(event); |
| 61 | + break; |
| 62 | + } |
| 63 | + } |
| 64 | +}); |
| 65 | + |
| 66 | +const createChannel: CreateChannelEvent = { |
| 67 | + type: 'CREATE_CHANNEL', |
| 68 | + participants: [ |
| 69 | + { |
| 70 | + participantId: first, |
| 71 | + signingAddress: first, |
| 72 | + destination: first, |
| 73 | + }, |
| 74 | + { |
| 75 | + participantId: second, |
| 76 | + signingAddress: second, |
| 77 | + destination: second, |
| 78 | + }, |
| 79 | + ], |
| 80 | + allocations: [ |
| 81 | + { destination: first, amount: '3' }, |
| 82 | + { destination: second, amount: '1' }, |
| 83 | + ], |
| 84 | + appDefinition: '0x', |
| 85 | + appData: '0x', |
| 86 | +}; |
| 87 | + |
| 88 | +wallets[first].send(createChannel); |
0 commit comments