From 5b3f6f6f924aac7104bcad90ba7b6ba68a360d2b Mon Sep 17 00:00:00 2001 From: Andrew Stewart Date: Sun, 8 Dec 2019 11:38:12 -0700 Subject: [PATCH] Start getting two wallets to communicate --- src/runtime.ts | 88 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 src/runtime.ts diff --git a/src/runtime.ts b/src/runtime.ts new file mode 100644 index 0000000..f9bd210 --- /dev/null +++ b/src/runtime.ts @@ -0,0 +1,88 @@ +import { AnyEventObject, interpret, Interpreter } from 'xstate'; +import { getChannelID, pretty } from '.'; +import { messageService } from './messaging'; +import { Wallet } from './protocols'; +import { AddressableMessage } from './wire-protocol'; + +import { CreateChannelEvent } from './protocols/wallet/protocol'; +import { Store } from './store'; + +const store = name => { + const privateKeys = { [name]: name }; + const _store = new Store({ privateKeys }); + messageService.on('message', (m: AddressableMessage) => { + if (m.to === name) { + switch (m.type) { + case 'SendStates': + _store.receiveStates(m.signedStates); + } + } + }); + + return _store; +}; + +const first = 'first'; +const second = 'second'; +const stores = { + first: store(first), + second: store(second), +}; + +const logEvents = name => event => + console.log(`${name} received ${event.type}`); + +const wallet = name => { + return interpret(Wallet.machine(stores[name])) + .onEvent(logEvents(name)) + .start(); +}; + +const wallets: Record> = { + first: wallet(first), + second: wallet(second), +}; + +// This is sort of the "dispatcher" +messageService.on('message', ({ to, ...event }: AddressableMessage) => { + switch (event.type) { + case 'SendStates': { + stores[to].receiveStates(event.signedStates); + const channelId = getChannelID(event.signedStates[0].state.channel); + + wallets[to].send({ + type: 'CHANNEL_UPDATED', + channelId, + }); + break; + } + case 'OPEN_CHANNEL': { + wallets[to].send(event); + break; + } + } +}); + +const createChannel: CreateChannelEvent = { + type: 'CREATE_CHANNEL', + participants: [ + { + participantId: first, + signingAddress: first, + destination: first, + }, + { + participantId: second, + signingAddress: second, + destination: second, + }, + ], + allocations: [ + { destination: first, amount: '3' }, + { destination: second, amount: '1' }, + ], + appDefinition: '0x', + appData: '0x', +}; + +wallets[first].send(createChannel);