on 466bf89 help sign in
bridge/src/lib/flowCommand.ts
113 lines 2.5 kB history raw
1import { useMemo } from 'react';
2import { isValidAddress } from './utils/address';
4// looks into the GET parameters and attempts to construct a "flow" object,
5// which would indicate bridge is to be used for one specific flow.
6// expects to find any of the following sets of parameters, varying by kind.
7//
8// ? kind = takeLockup
9// & lock = linear | conditional // which lockup contract, defaults to linear
10// & from = 0x1234abcd // ethereum address to accept transfer from
11//
12// ? kind = btc
13// & utx = somebase64string
14//
15// ? kind = xpub
16//
18const COMMANDS = {
19 TAKE_LOCKUP: 'takeLockup',
20 BITCOIN: 'btc',
21 XPUB: 'xpub',
22};
24interface LockupFlowKind {
25 kind: 'takeLockup';
26 lock: 'linear' | 'conditional';
27 from: string;
28 [k: string]: string | boolean;
31interface BitcoinFlowKind {
32 kind: 'btc';
33 utx: string;
34 [k: string]: string | boolean;
37interface XpubFlowKind {
38 kind: 'xpub';
39 [k: string]: string | boolean;
42interface DefaultFlowKind {
43 kind?: string;
44 [k: string]: string | boolean | undefined;
47export type FlowType =
48 | LockupFlowKind
49 | BitcoinFlowKind
50 | XpubFlowKind
51 | DefaultFlowKind
52 | null;
54const useFlowCommand = () => {
55 const flow = useMemo(() => {
56 let flow: FlowType = {};
58 window.location.search
59 .substring(1)
60 .split('&')
61 .forEach(arg => {
62 if ('' === arg) return;
63 const pam = arg.split('=');
64 if (flow) {
65 flow[pam[0]] = pam.length <= 1 ? true : decodeURIComponent(pam[1]);
66 }
67 });
69 if (flow && typeof flow === 'object') {
70 switch (flow.kind) {
71 case COMMANDS.TAKE_LOCKUP:
72 flow.lock = flow.lock || 'linear';
73 if (
74 (flow.lock !== 'linear' && flow.lock !== 'conditional') ||
75 !isValidAddress(flow.from)
76 ) {
77 flow = null;
78 }
79 break;
80 //
81 case COMMANDS.BITCOIN:
82 try {
83 if (flow.utx && typeof flow.utx === 'string') {
84 atob(flow.utx);
85 } else {
86 throw Error();
87 }
88 } catch (e) {
89 flow = null;
90 }
91 break;
92 //
93 case COMMANDS.XPUB:
94 break;
95 //
96 case undefined:
97 flow = null;
98 break;
99 default:
100 console.log('unrecognized kind of flow:', flow.kind);
101 flow = null;
102 }
103 } else {
104 flow = null;
105 }
107 return flow;
108 }, []);
110 return flow;
111};
113export { COMMANDS, useFlowCommand };