on ed565d9 help sign in
bridge/src/lib/invite.js
311 lines 8.2 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';
15import { GAS_LIMITS } from './constants';
17const INVITE_STAGES = {
18 INVITE_LOGIN: 'invite login',
19 INVITE_WALLET: 'invite wallet',
20 INVITE_VERIFY: 'invite verify',
21 INVITE_TRANSACTIONS: 'invite transactions',
22};
24const WALLET_STATES = {
25 UNLOCKING: 'Unlocking invite wallet',
26 GENERATING: 'Generating your wallet',
27 RENDERING: 'Creating paper collateral',
28 PAPER_READY: 'Download your wallet',
29 DOWNLOADED: 'Wallet downloaded',
30 TRANSACTIONS: 'Sending transactions',
31};
33const TRANSACTION_STATES = {
34 GENERATING: {
35 label: 'Generating Transactions...',
36 progress: 0.0,
37 },
38 SIGNING: {
39 label: 'Signing Transactions...',
40 progress: 0.15,
41 },
42 FUNDING: {
43 label: 'Funding Transactions...',
44 progress: 0.3,
45 },
46 CLAIMING: {
47 label: 'Claiming Invite...',
48 progress: 0.55,
49 },
50 CLEANING: {
51 label: 'Cleaning Up...',
52 progress: 0.95,
53 },
54 DONE: {
55 label: 'Done',
56 progress: 1.0,
57 },
58};
60async function generateWallet(point) {
61 const ticket = await wg.makeTicket(point);
62 const wallet = await wg.generateWallet(point, ticket);
63 return wallet;
66//TODO should be moved to lib/walletgen
67async function downloadWallet(paper) {
68 return new Promise((resolve, reject) => {
69 const zip = new JSZip();
70 //TODO the categories here aren't explained in bridge at all...
72 const bin0 = paper.filter(item => item.bin === '0');
73 const bin1 = paper.filter(item => item.bin === '1');
74 const bin2 = paper.filter(item => item.bin === '2');
75 const bin3 = paper.filter(item => item.bin === '3');
76 const bin4 = paper.filter(item => item.bin === '4');
78 const bin0Folder = zip.folder('0. Public');
79 const bin1Folder = zip.folder('1. Very High Friction Custody');
80 const bin2Folder = zip.folder('2. High Friction Custody');
81 const bin3Folder = zip.folder('3. Medium Friction Custody');
82 const bin4Folder = zip.folder('4. Low Friction Custody');
84 bin0.forEach(item => bin0Folder.file(`${item.pageTitle}.png`, item.png));
85 bin1.forEach(item => bin1Folder.file(`${item.pageTitle}.png`, item.png));
86 bin2.forEach(item => bin2Folder.file(`${item.pageTitle}.png`, item.png));
87 bin3.forEach(item => bin3Folder.file(`${item.pageTitle}.png`, item.png));
88 bin4.forEach(item => bin4Folder.file(`${item.pageTitle}.png`, item.png));
90 zip.generateAsync({ type: 'blob' }).then(content => {
91 saveAs(content, 'urbit-wallet.zip');
92 resolve(true);
93 });
94 });
97async function claimPointFromInvite({
98 inviteWallet,
99 wallet,
100 point,
101 web3,
102 contracts,
103 onUpdate,
104 transferEth = false,
105}) {
106 const askForFunding = (address, minBalance, balance) =>
107 onUpdate({
108 type: 'askFunding',
109 value: { address, minBalance, balance },
110 });
112 const gotFunding = () => onUpdate({ type: 'gotFunding' });
113 const progress = state => onUpdate({ type: 'progress', state });
115 const inviteAddress = inviteWallet.address;
117 //
118 // generate transactions
119 //
121 progress(TRANSACTION_STATES.GENERATING);
123 // transfer to invite wallet, so it can configure
124 //NOTE doing this in the invite wallet instead of the final wallet makes
125 // failure cases "solvable" by just telling the user to fully retry.
126 // in other words, the invite flow is effectively idempotent.
128 //TODO no harm done if we already owned it, but should still get a bool arg
129 // for skipping this, if it isn't too big a burden for callers
130 const transferTmpTx = azimuth.ecliptic.transferPoint(
131 contracts,
132 point,
133 inviteAddress,
134 false
135 );
136 transferTmpTx.gas = GAS_LIMITS.TRANSFER;
138 // configure networking public keys
140 //TODO feels like more of this logic should live in a lib?
141 const seed = await attemptNetworkSeedDerivation(true, {
142 walletType: WALLET_TYPES.TICKET,
143 urbitWallet: Just(wallet),
144 pointCursor: Just(point),
145 pointCache: { [point]: { keyRevisionNumber: 0 } },
146 });
148 const networkSeed = seed.matchWith({
149 Nothing: () => {
150 throw new Error('network seed not derived');
151 },
152 Just: p => p.value,
153 });
155 const networkKeys = kg.deriveNetworkKeys(networkSeed);
157 const keysTx = azimuth.ecliptic.configureKeys(
158 contracts,
159 point,
160 addHexPrefix(networkKeys.crypt.public),
161 addHexPrefix(networkKeys.auth.public),
162 1,
163 false
164 );
165 keysTx.gas = GAS_LIMITS.CONFIGURE_KEYS;
167 // configure management proxy
169 const managementTx = azimuth.ecliptic.setManagementProxy(
170 contracts,
171 point,
172 wallet.management.keys.address
173 );
174 managementTx.gas = GAS_LIMITS.SET_PROXY;
176 // set spawn & voting proxies situationally
178 let txs = [transferTmpTx, keysTx, managementTx];
179 if (
180 azimuth.azimuth.getPointSize(point) !== azimuth.azimuth.PointSize.Planet
181 ) {
182 const spawnTx = azimuth.ecliptic.setSpawnProxy(
183 contracts,
184 point,
185 wallet.spawn.keys.address
186 );
187 spawnTx.gas = GAS_LIMITS.SET_PROXY;
188 txs.push(spawnTx);
190 if (
191 azimuth.azimuth.getPointSize(point) === azimuth.azimuth.PointSize.Galaxy
192 ) {
193 const votingTx = azimuth.ecliptic.setVotingProxy(
194 contracts,
195 point,
196 wallet.voting.keys.address
197 );
198 votingTx.gas = GAS_LIMITS.SET_PROXY;
199 txs.push(votingTx);
200 }
201 }
203 // transfer configured point to user's new wallet
205 const transferFinalTx = azimuth.ecliptic.transferPoint(
206 contracts,
207 point,
208 wallet.ownership.keys.address,
209 false
210 );
211 transferFinalTx.gas = GAS_LIMITS.TRANSFER;
212 txs.push(transferFinalTx);
214 //
215 // finalizing & signing transactions
216 //
218 progress(TRANSACTION_STATES.SIGNING);
220 let totalCost = 0;
221 let inviteNonce = await web3.eth.getTransactionCount(inviteAddress);
222 txs = txs.map(tx => {
223 tx.from = inviteAddress;
224 tx.nonce = inviteNonce++;
225 tx.gasPrice = 20000000000; //NOTE we pay the premium for faster ux
226 totalCost = totalCost + tx.gasPrice * tx.gas;
227 return tx;
228 });
230 let txPairs = txs.map(tx => {
231 let stx = new Tx(tx);
232 stx.sign(Buffer.from(inviteWallet.privateKey, 'hex'));
233 return {
234 raw: hexify(stx.serialize()),
235 signed: stx,
236 };
237 });
239 //
240 // ensuring funding for transactions
241 //
243 progress(TRANSACTION_STATES.FUNDING);
245 const usedTank = await tank.ensureFundsFor(
246 web3,
247 point,
248 inviteAddress,
249 totalCost,
250 txPairs.map(p => p.raw),
251 askForFunding,
252 gotFunding
253 );
255 //
256 // sending and awaiting transactions
257 //
259 progress(TRANSACTION_STATES.CLAIMING);
261 await sendAndAwaitConfirm(web3, txPairs.map(p => Just(p.signed)), usedTank);
263 //
264 // move leftover eth
265 //
267 progress(TRANSACTION_STATES.CLEANING);
269 // if non-trivial eth left in invite wallet, transfer to new ownership
270 let balance = await web3.eth.getBalance(inviteAddress);
271 const gasPrice = 20000000000;
272 const gasLimit = 21000;
273 const sendEthCost = gasPrice * gasLimit;
274 if (transferEth && balance > sendEthCost) {
275 const value = balance - sendEthCost;
276 const tx = {
277 to: wallet.ownership.keys.address,
278 value: value,
279 gasPrice: gasPrice,
280 gas: gasLimit,
281 nonce: inviteNonce++,
282 };
283 let stx = new Tx(tx);
284 stx.sign(inviteWallet.privateKey);
285 const rawTx = hexify(stx.serialize());
286 web3.eth.sendSignedTransaction(rawTx).catch(err => {
287 console.log('error sending value tx, who cares', err);
288 });
289 }
291 progress(TRANSACTION_STATES.DONE);
294async function sendAndAwaitConfirm(web3, signedTxs, usedTank) {
295 await Promise.all(
296 signedTxs.map(tx => {
297 return new Promise((resolve, reject) => {
298 sendSignedTransaction(web3, tx, usedTank, resolve);
299 });
300 })
301 );
304export {
305 generateWallet,
306 downloadWallet,
307 claimPointFromInvite,
308 INVITE_STAGES,
309 WALLET_STATES,
310 TRANSACTION_STATES,
311};