-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapprove-budget-and-fund.ts
More file actions
398 lines (370 loc) · 12.2 KB
/
approve-budget-and-fund.ts
File metadata and controls
398 lines (370 loc) · 12.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
import {
StateSchema,
StateMachine,
ActionObject,
createMachine,
Guard,
assign,
DoneInvokeEvent,
Interpreter
} from 'xstate';
import {
DomainBudget,
Participant,
SimpleAllocation,
AssetBudget,
State as ChannelState,
statesEqual,
checkThat,
exists,
simpleEthAllocation,
BN,
Uint256,
serializeDomainBudget
} from '@statechannels/wallet-core';
import {filter, map, first} from 'rxjs/operators';
import {ChannelChainInfo} from '../chain';
import {Store} from '../store';
import {MessagingServiceInterface} from '../messaging';
import {sendUserDeclinedResponse, hideUI, displayUI} from '../utils/workflow-utils';
import {CHALLENGE_DURATION, ETH_ASSET_HOLDER_ADDRESS} from '../config';
const {add} = BN;
interface ChainEvent {
type: 'CHAIN_EVENT';
blockNum: number;
balance: Uint256;
}
type Event =
| {type: 'USER_APPROVES_BUDGET'}
| {type: 'USER_REJECTS_BUDGET'}
| {type: 'USER_APPROVES_RETRY'}
| {type: 'USER_REJECTS_RETRY'}
| {type: 'SUFFICIENT_FUNDS_DETECTED'}
| {type: 'INSUFFICIENT_FUNDS_DETECTED'}
| ChainEvent;
interface Initial {
budget: DomainBudget;
player: Participant;
hub: Participant;
requestId: number;
}
interface LedgerExists extends Initial {
ledgerId: string;
ledgerState: ChannelState;
}
interface Deposit {
depositAt: Uint256;
totalAfterDeposit: Uint256;
fundedAt: Uint256;
}
interface Chain {
ledgerTotal: Uint256;
lastChangeBlockNum: number;
currentBlockNum: number;
}
interface Transaction {
transactionId: string;
}
type Typestate =
| {value: 'waitForUserApproval'; context: Initial}
| {value: {waitForSufficientFunds: 'init'}; context: Initial}
| {value: {waitForSufficientFunds: 'waitForFunds'}; context: Initial}
| {value: 'createLedger'; context: Initial}
| {value: 'createBudget'; context: Initial}
| {value: 'waitForPreFS'; context: LedgerExists}
| {value: {deposit: 'init'}; context: LedgerExists & Deposit}
| {value: {deposit: 'waitTurn'}; context: LedgerExists & Deposit & Chain}
| {value: {deposit: 'submitTransaction'}; context: LedgerExists & Deposit & Chain}
| {value: {deposit: 'retry'}; context: LedgerExists & Deposit & Chain}
| {value: {deposit: 'waitMining'}; context: LedgerExists & Deposit & Chain & Transaction}
| {value: {deposit: 'waitFullyFunded'}; context: LedgerExists & Deposit & Chain}
| {value: 'done'; context: LedgerExists}
| {value: 'failure'; context: Initial};
type Context = Typestate['context'];
export interface Schema extends StateSchema<Context> {
states: {
waitForSufficientFunds: {};
createLedger: {};
createBudget: {};
waitForPreFS: {};
deposit: {
states: {
init: {};
waitTurn: {};
submitTransaction: {};
retry: {};
waitMining: {};
waitFullyFunded: {};
};
};
done: {};
failure: {};
};
}
export const machine = (
store: Store,
messagingService: MessagingServiceInterface,
context: Initial
): StateMachine<Context, Schema, Event, Typestate> =>
createMachine<Context, Event, Typestate>({
id: 'approve-budget-and-fund',
context,
initial: 'waitForUserApproval',
entry: displayUI(messagingService),
states: {
waitForUserApproval: {
on: {
USER_APPROVES_BUDGET: {target: 'waitForSufficientFunds'},
USER_REJECTS_BUDGET: {target: 'failure'}
}
},
createLedger: {
invoke: {
id: 'createLedger',
src: createLedger(store),
onDone: {target: 'waitForPreFS', actions: setLedgerInfo}
}
},
waitForPreFS: {
invoke: {
id: 'subscribeToLedgerUpdates',
src: notifyWhenPreFSSupported(store),
onDone: {target: 'deposit', actions: assignDepositingInfo}
}
},
createBudget: {
invoke: {
id: 'createBudget',
src: createBudget(store, messagingService),
onDone: {target: 'done'}
}
},
waitForSufficientFunds: {
initial: 'init',
invoke: {
id: 'subscribeToBalanceUpdates',
src: notifyWhenSufficientFunds(store)
},
states: {
init: {},
waitForFunds: {}
},
on: {
INSUFFICIENT_FUNDS_DETECTED: {target: '.waitForFunds'},
SUFFICIENT_FUNDS_DETECTED: {target: 'createLedger'}
}
},
deposit: {
initial: 'init',
invoke: {
id: 'observeChain',
src: observeLedgerOnChainBalance(store)
},
on: {
CHAIN_EVENT: [
{target: 'createBudget', actions: assignChainData, cond: fullAmountConfirmed},
{target: '.waitFullyFunded', actions: assignChainData, cond: myAmountConfirmed}
]
},
states: {
init: {
on: {
CHAIN_EVENT: [
{target: 'submitTransaction', actions: assignChainData, cond: myTurnNow},
{target: 'waitTurn', actions: assignChainData, cond: notMyTurnYet}
]
}
},
waitTurn: {
on: {
CHAIN_EVENT: [
{target: 'submitTransaction', actions: assignChainData, cond: myTurnNow}
]
}
},
submitTransaction: {
invoke: {
id: 'submitTransaction',
src: submitDepositTransaction(store),
onDone: {target: 'waitMining', actions: setTransactionId}
// onError: {target: 'retry'}
}
},
retry: {
on: {
USER_APPROVES_RETRY: {target: 'submitTransaction'},
USER_REJECTS_RETRY: {target: '#failure'}
}
},
waitMining: {},
waitFullyFunded: {}
}
},
done: {
id: 'done',
type: 'final',
entry: [hideUI(messagingService), sendResponse(messagingService)]
},
failure: {
type: 'final',
id: 'failure',
entry: [hideUI(messagingService), sendUserDeclinedResponse(messagingService)]
}
}
});
interface LedgerInitRetVal {
ledgerId: string;
ledgerState: ChannelState;
}
const createBudget = (store: Store, messagingService: MessagingServiceInterface) => async (
context: Initial
): Promise<void> => {
// create budget
await store.createBudget(context.budget);
await messagingService.sendBudgetNotification(context.budget);
};
const createLedger = (store: Store) => async (context: Initial): Promise<LedgerInitRetVal> => {
// create ledger
const initialOutcome = convertPendingBudgetToAllocation(context);
const participants = [context.player, context.hub];
const stateVars = {outcome: initialOutcome, turnNum: 0, isFinal: false, appData: '0x00'};
const entry = await store.createChannel(participants, CHALLENGE_DURATION, stateVars);
const ledgerId = entry.channelId;
await store.setFunding(entry.channelId, {type: 'Direct'});
await store.setLedger(entry.channelId);
await store.setapplicationDomain(ledgerId, context.budget.domain);
await store.addObjective({
type: 'FundLedger',
participants: participants,
data: {ledgerId}
});
return {
ledgerId,
ledgerState: entry.latestState
};
};
const setLedgerInfo = assign<Context, DoneInvokeEvent<LedgerInitRetVal>>({
ledgerId: (context, event) => event.data.ledgerId,
ledgerState: (context, event) => event.data.ledgerState
});
function convertPendingBudgetToAllocation({hub, player, budget}: Context): SimpleAllocation {
// TODO: Eventually we will need to support more complex budgets
if (Object.keys(budget.forAsset).length !== 1) {
throw new Error('Cannot handle mixed budget');
}
// todo: this throws if the budget is undefined and casts it to a AssetBudget otherwise
// maybe this should be called assertBudgetExists ??
const ethBudget = checkThat<AssetBudget>(budget.forAsset[ETH_ASSET_HOLDER_ADDRESS], exists);
const playerItem = {
destination: player.destination,
amount: ethBudget.availableSendCapacity
};
const hubItem = {
destination: hub.destination,
amount: ethBudget.availableReceiveCapacity
};
return simpleEthAllocation([hubItem, playerItem]);
}
const sendResponse = (
messagingService: MessagingServiceInterface
): ActionObject<Context, Event> => ({
type: 'sendResponse',
exec: context =>
messagingService.sendResponse(context.requestId, serializeDomainBudget(context.budget))
});
const assignDepositingInfo = assign<Context>({
// this is inefficient, but if use the other style of xstate assign, the devtools break ...
depositAt: context => calculateDepositInfo(context).depositAt,
totalAfterDeposit: context => calculateDepositInfo(context).totalAfterDeposit,
fundedAt: context => calculateDepositInfo(context).fundedAt
});
const calculateDepositInfo = (context: Context) => {
const ethBudget = checkThat<AssetBudget>(
context.budget.forAsset[ETH_ASSET_HOLDER_ADDRESS],
exists
);
const ourAmount = ethBudget.availableSendCapacity;
const hubAmount = ethBudget.availableSendCapacity;
const totalAmount = add(ourAmount, hubAmount);
const depositAt = hubAmount; // hub goes first
const totalAfterDeposit = totalAmount;
const fundedAt = totalAmount;
return {depositAt, totalAfterDeposit, fundedAt};
};
const notifyWhenPreFSSupported = (store: Store) => ({ledgerState, ledgerId}: LedgerExists) =>
store
.channelUpdatedFeed(ledgerId)
.pipe(
filter(({isSupported}) => isSupported),
filter(({supported}) => statesEqual(ledgerState, supported)), //store the hash?
map(() => 'SUPPORTED'),
first()
)
.toPromise();
const notifyWhenSufficientFunds = (store: Store) => ({budget}: Initial) => {
const ethBudget = checkThat<AssetBudget>(budget.forAsset[ETH_ASSET_HOLDER_ADDRESS], exists);
if (!store.chain.selectedAddress) {
throw new Error('No selected address');
}
const depositAmount = ethBudget.availableSendCapacity;
return store.chain.balanceUpdatedFeed(store.chain.selectedAddress).pipe(
map(b => ({
type: BN.gte(b, depositAmount) ? 'SUFFICIENT_FUNDS_DETECTED' : 'INSUFFICIENT_FUNDS_DETECTED'
}))
);
};
const observeLedgerOnChainBalance = (store: Store) => ({ledgerId}: LedgerExists) =>
store.chain.chainUpdatedFeed(ledgerId).pipe(
map<ChannelChainInfo, ChainEvent>(({amount: balance, blockNum}) => ({
type: 'CHAIN_EVENT',
balance,
blockNum
}))
);
// // for now don't wait for any number of blocks (until the chain is reporting blockNum)
const fullAmountConfirmed: Guard<Deposit, ChainEvent> = {
type: 'xstate.guard',
name: 'fullAmountConfirmed',
predicate: (context, event) => BN.gte(event.balance, context.fundedAt)
};
const myTurnNow: Guard<Deposit, ChainEvent> = {
type: 'xstate.guard',
name: 'myTurnNow',
predicate: (context, event) =>
BN.gte(event.balance, context.depositAt) && BN.lt(event.balance, context.totalAfterDeposit)
};
const notMyTurnYet: Guard<Deposit, ChainEvent> = {
type: 'xstate.guard',
name: 'notMyTurnYet',
predicate: (context, event) => BN.lt(event.balance, context.depositAt)
};
const myAmountConfirmed: Guard<Deposit, ChainEvent> = {
type: 'xstate.guard',
name: 'myAmountConfirmed',
predicate: (context, event) =>
BN.gte(event.balance, context.totalAfterDeposit) && BN.lt(event.balance, context.fundedAt)
};
const assignChainData = assign<Context, ChainEvent>({
ledgerTotal: (context, event: ChainEvent) => event.balance,
currentBlockNum: (context, event: ChainEvent) => event.blockNum,
lastChangeBlockNum: (context, event: ChainEvent) =>
context.ledgerTotal && context.ledgerTotal === event.balance
? context.lastChangeBlockNum
: event.blockNum
});
const setTransactionId = assign<Context, DoneInvokeEvent<string>>({
transactionId: (context, event) => event.data
});
const submitDepositTransaction = (store: Store) => async (
ctx: LedgerExists & Deposit & Chain
): Promise<string | undefined> => {
const amount = BN.sub(ctx.totalAfterDeposit, ctx.ledgerTotal);
if (BN.lte(amount, 0)) {
// sanity check: we shouldn't be in this state, if this is the case
throw new Error(
`Something is wrong! Shouldn't be trying to deposit when the remaining amount is ${amount.toString()}.`
);
}
return store.chain.deposit(ctx.ledgerId, BN.from(ctx.ledgerTotal), amount);
};
export type ApproveBudgetAndFundService = Interpreter<Context, any, Event, Typestate>;