on cd91628 help sign in
bridge/src/lib/invite.js
287 lines 7.8 kB history raw
1import { Just } from 'folktale/maybe';
2import Tx from 'ethereumjs-tx';
4import * as azimuth from 'azimuth-js';
5import * as kg from 'urbit-key-generation/dist';
6import * as wg from './walletgen';
7import * as tank from './tank';
9import JSZip from 'jszip';
10import saveAs from 'file-saver';
12import { sendSignedTransaction, hexify } from './txn';
13import { attemptNetworkSeedDerivation } from './keys';
14import { addHexPrefix, WALLET_TYPES } from './wallet';
16const INVITE_STAGES = {
17 INVITE_LOGIN: 'invite login',
18 INVITE_WALLET: 'invite wallet',
19 INVITE_VERIFY: 'invite verify',
20 INVITE_TRANSACTIONS: 'invite transactions',
21};
23const WALLET_STATES = {
24 UNLOCKING: 'Unlocking invite wallet',
25 GENERATING: 'Generating your wallet',
26 RENDERING: 'Creating paper collateral',
27 PAPER_READY: 'Download your wallet',
28 DOWNLOADED: 'Wallet downloaded',
29 TRANSACTIONS: 'Sending transactions',
30};
32const TRANSACTION_STATES = {
33 GENERATING: {
34 label: 'Generating Transactions...',
35 progress: 0.0,
36 },
37 SIGNING: {
38 label: 'Signing Transactions...',
39 progress: 0.15,
40 },
41 FUNDING_INVITE: {
42 label: 'Funding Invite Wallet...',
43 progress: 0.3,
44 },
45 CLAIMING: {
46 label: 'Claiming Invite...',
47 progress: 0.55,
48 },
49 FUNDING_RECIPIENT: {
50 label: 'Funding Recipient Wallet...',
51 progress: 0.65,
52 },
53 CONFIGURING: {
54 label: 'Configuring Point...',
55 progress: 0.85,
56 },
57 CLEANING: {
58 label: 'Cleaning Up...',
59 progress: 0.95,
60 },
61 DONE: {
62 label: 'Done',
63 progress: 1.0,
64 },
65};
67async function generateWallet(point) {
68 const ticket = await wg.makeTicket(point);
69 const wallet = await wg.generateWallet(point, ticket);
70 return wallet;
73//TODO should be moved to lib/walletgen
74async function downloadWallet(paper) {
75 return new Promise((resolve, reject) => {
76 const zip = new JSZip();
77 //TODO the categories here aren't explained in bridge at all...
79 const bin0 = paper.filter(item => item.bin === '0');
80 const bin1 = paper.filter(item => item.bin === '1');
81 const bin2 = paper.filter(item => item.bin === '2');
82 const bin3 = paper.filter(item => item.bin === '3');
83 const bin4 = paper.filter(item => item.bin === '4');
85 const bin0Folder = zip.folder('0. Public');
86 const bin1Folder = zip.folder('1. Very High Friction Custody');
87 const bin2Folder = zip.folder('2. High Friction Custody');
88 const bin3Folder = zip.folder('3. Medium Friction Custody');
89 const bin4Folder = zip.folder('4. Low Friction Custody');
91 bin0.forEach(item => bin0Folder.file(`${item.pageTitle}.png`, item.png));
92 bin1.forEach(item => bin1Folder.file(`${item.pageTitle}.png`, item.png));
93 bin2.forEach(item => bin2Folder.file(`${item.pageTitle}.png`, item.png));
94 bin3.forEach(item => bin3Folder.file(`${item.pageTitle}.png`, item.png));
95 bin4.forEach(item => bin4Folder.file(`${item.pageTitle}.png`, item.png));
97 zip.generateAsync({ type: 'blob' }).then(content => {
98 saveAs(content, 'urbit-wallet.zip');
99 resolve(true);
100 });
101 });
104async function claimPointFromInvite({
105 inviteWallet,
106 wallet,
107 point,
108 web3,
109 contracts,
110 onUpdate,
111}) {
112 const askForFunding = (address, minBalance, balance) =>
113 onUpdate({
114 type: 'askFunding',
115 value: { address, minBalance, balance },
116 });
118 const gotFunding = () => onUpdate({ type: 'gotFunding' });
119 const progress = state => onUpdate({ type: 'progress', state });
121 const inviteAddress = inviteWallet.address;
123 progress(TRANSACTION_STATES.GENERATING);
125 // transfer from invite wallet to new wallet
126 const transferTx = azimuth.ecliptic.transferPoint(
127 contracts,
128 point,
129 wallet.ownership.keys.address
130 );
131 transferTx.gas = 500000; //TODO can maybe be lower?
133 // ping gas tank with txs if needed
134 let inviteNonce = await web3.eth.getTransactionCount(inviteAddress);
135 transferTx.nonce = inviteNonce++;
136 transferTx.gasPrice = 20000000000; //NOTE we pay the premium for faster ux
137 transferTx.from = inviteAddress;
139 progress(TRANSACTION_STATES.SIGNING);
140 // NOTE: using web3.eth.accounts.signTransaction is broken (1.0.0-beta51)
141 const transferStx = new Tx(transferTx);
142 transferStx.sign(inviteWallet.privateKey);
143 const rawTransferStx = hexify(transferStx.serialize());
144 const transferCost = transferTx.gas * transferTx.gasPrice;
146 progress(TRANSACTION_STATES.FUNDING_INVITE);
148 let usedTank = await tank.ensureFundsFor(
149 web3,
150 point,
151 inviteAddress,
152 transferCost,
153 [rawTransferStx],
154 askForFunding,
155 gotFunding
156 );
158 progress(TRANSACTION_STATES.CLAIMING);
160 // send transaction
161 await sendAndAwaitConfirm(web3, [Just(transferStx)], usedTank);
163 //
164 // we're gonna be operating as the new wallet from here on out, so change
165 // the relevant values
166 //
167 const newAddress = wallet.ownership.keys.address;
169 // configure management proxy
170 const managementTx = azimuth.ecliptic.setManagementProxy(
171 contracts,
172 point,
173 wallet.management.keys.address
174 );
175 managementTx.gas = 200000;
176 managementTx.nonce = 0;
178 // configure networking public keys
179 //TODO feels like more of this logic should live in a lib?
180 const seed = await attemptNetworkSeedDerivation(true, {
181 walletType: WALLET_TYPES.TICKET,
182 urbitWallet: Just(wallet),
183 pointCursor: Just(point),
184 pointCache: { [point]: { keyRevisionNumber: 0 } },
185 });
187 const networkSeed = seed.matchWith({
188 Nothing: () => {
189 throw new Error('network seed not derived');
190 },
191 Just: p => p.value,
192 });
194 const networkKeys = kg.deriveNetworkKeys(networkSeed);
196 let keysTx = azimuth.ecliptic.configureKeys(
197 contracts,
198 point,
199 addHexPrefix(networkKeys.crypt.public),
200 addHexPrefix(networkKeys.auth.public),
201 1,
202 false
203 );
204 keysTx.gas = 150000;
205 keysTx.nonce = 1;
207 //TODO refactor this process into function
208 let totalCost = 0;
209 let txs = [managementTx, keysTx];
210 txs = txs.map(tx => {
211 tx.gasPrice = 20000000000;
212 tx.from = newAddress;
213 totalCost = totalCost + tx.gasPrice * tx.gas;
214 return tx;
215 });
217 let txPairs = txs.map(tx => {
218 let stx = new Tx(tx);
219 stx.sign(Buffer.from(wallet.ownership.keys.private, 'hex'));
220 return {
221 raw: '0x' + stx.serialize().toString('hex'),
222 signed: stx,
223 };
224 });
226 progress(TRANSACTION_STATES.FUNDING_RECIPIENT);
228 usedTank = await tank.ensureFundsFor(
229 web3,
230 point,
231 newAddress,
232 totalCost,
233 txPairs.map(p => p.raw),
234 askForFunding
235 );
237 progress(TRANSACTION_STATES.CONFIGURING);
239 await sendAndAwaitConfirm(web3, txPairs.map(p => Just(p.signed)), usedTank);
241 progress(TRANSACTION_STATES.CLEANING);
243 // if non-trivial eth left in invite wallet, transfer to new ownership
244 let balance = await web3.eth.getBalance(inviteAddress);
245 const gasPrice = 20000000000;
246 const gasLimit = 21000;
247 const sendEthCost = gasPrice * gasLimit;
248 if (balance > sendEthCost) {
249 const value = balance - sendEthCost;
250 console.log('sending', value);
251 const tx = {
252 to: newAddress,
253 value: value,
254 gasPrice: gasPrice,
255 gas: gasLimit,
256 nonce: inviteNonce++,
257 };
258 let stx = new Tx(tx);
259 stx.sign(inviteWallet.privateKey);
260 const rawTx = hexify(stx.serialize());
261 web3.eth.sendSignedTransaction(rawTx).catch(err => {
262 console.log('error sending value tx, who cares', err);
263 });
264 console.log('sent old balance');
265 }
267 progress(TRANSACTION_STATES.DONE);
270async function sendAndAwaitConfirm(web3, signedTxs, usedTank) {
271 await Promise.all(
272 signedTxs.map(tx => {
273 return new Promise((resolve, reject) => {
274 sendSignedTransaction(web3, tx, usedTank, resolve);
275 });
276 })
277 );
280export {
281 generateWallet,
282 downloadWallet,
283 claimPointFromInvite,
284 INVITE_STAGES,
285 WALLET_STATES,
286 TRANSACTION_STATES,
287};