on dffcebf help sign in
bridge/src/lib/reticket.js
217 lines 5.5 kB history raw
1import Tx from 'ethereumjs-tx';
2import * as azimuth from 'azimuth-js';
3import * as tank from './tank';
5import { hexify } from './txn';
6import {
7 deriveNetworkSeedFromUrbitWallet,
8 deriveNetworkKeys,
9 CRYPTO_SUITE_VERSION,
10} from './keys';
11import { addHexPrefix } from './wallet';
12import { sendAndAwaitAll } from './txn';
13import { GAS_LIMITS, DEFAULT_GAS_PRICE_GWEI } from './constants';
14import { toWei } from 'web3-utils';
16// the initial network key revision is always 1
17const INITIAL_NETWORK_KEY_REVISION = 1;
19export const TRANSACTION_PROGRESS = {
20 GENERATING: 0.01,
21 SIGNING: 0.15,
22 FUNDING: 0.3,
23 TRANSFERRING: 0.55,
24 CLEANING: 0.95,
25 DONE: 1.0,
26};
28export async function reticketPointBetweenWallets({
29 fromWallet,
30 toWallet,
31 point,
32 web3,
33 contracts,
34 onUpdate,
35 transferEth = false,
36}) {
37 const askForFunding = (address, minBalance, balance) =>
38 onUpdate({
39 type: 'askFunding',
40 value: { address, minBalance, balance },
41 });
43 const gotFunding = () => onUpdate({ type: 'gotFunding' });
44 const progress = state => onUpdate({ type: 'progress', state });
46 //
47 // generate transactions
48 //
50 progress(TRANSACTION_PROGRESS.GENERATING);
52 // transfer to invite wallet, so it can configure
53 //NOTE doing this in the invite wallet instead of the final wallet makes
54 // failure cases "solvable" by just telling the user to fully retry.
55 // in other words, the invite flow is effectively idempotent.
57 //TODO no harm done if we already owned it, but should still get a bool arg
58 // for skipping this, if it isn't too big a burden for callers
59 const transferTmpTx = azimuth.ecliptic.transferPoint(
60 contracts,
61 point,
62 fromWallet.address,
63 false
64 );
65 transferTmpTx.gas = GAS_LIMITS.TRANSFER;
67 // configure networking public keys
68 const seed = await deriveNetworkSeedFromUrbitWallet(
69 toWallet,
70 INITIAL_NETWORK_KEY_REVISION
71 );
73 const networkSeed = seed.matchWith({
74 Nothing: () => {
75 throw new Error('network seed not derived');
76 },
77 Just: p => p.value,
78 });
80 const networkKeys = deriveNetworkKeys(networkSeed);
82 const keysTx = azimuth.ecliptic.configureKeys(
83 contracts,
84 point,
85 addHexPrefix(networkKeys.crypt.public),
86 addHexPrefix(networkKeys.auth.public),
87 CRYPTO_SUITE_VERSION,
88 /* discontinuous */ false
89 );
90 keysTx.gas = GAS_LIMITS.CONFIGURE_KEYS;
92 // configure management proxy
94 const managementTx = azimuth.ecliptic.setManagementProxy(
95 contracts,
96 point,
97 toWallet.management.keys.address
98 );
99 managementTx.gas = GAS_LIMITS.SET_PROXY;
101 // set spawn & voting proxies situationally
103 let txs = [transferTmpTx, keysTx, managementTx];
104 if (
105 azimuth.azimuth.getPointSize(point) !== azimuth.azimuth.PointSize.Planet
106 ) {
107 const spawnTx = azimuth.ecliptic.setSpawnProxy(
108 contracts,
109 point,
110 toWallet.spawn.keys.address
111 );
112 spawnTx.gas = GAS_LIMITS.SET_PROXY;
113 txs.push(spawnTx);
115 if (
116 azimuth.azimuth.getPointSize(point) === azimuth.azimuth.PointSize.Galaxy
117 ) {
118 const votingTx = azimuth.ecliptic.setVotingProxy(
119 contracts,
120 point,
121 toWallet.voting.keys.address
122 );
123 votingTx.gas = GAS_LIMITS.SET_PROXY;
124 txs.push(votingTx);
125 }
126 }
128 // transfer configured point to user's new wallet
130 const transferFinalTx = azimuth.ecliptic.transferPoint(
131 contracts,
132 point,
133 toWallet.ownership.keys.address,
134 false
135 );
136 transferFinalTx.gas = GAS_LIMITS.TRANSFER;
137 txs.push(transferFinalTx);
139 //
140 // finalizing & signing transactions
141 //
143 progress(TRANSACTION_PROGRESS.SIGNING);
145 let totalCost = 0;
146 let inviteNonce = await web3.eth.getTransactionCount(fromWallet.address);
147 txs = txs.map(tx => {
148 tx.from = fromWallet.address;
149 tx.nonce = inviteNonce++;
150 tx.gasPrice = parseInt(toWei(DEFAULT_GAS_PRICE_GWEI.toFixed(), 'gwei'), 10);
151 totalCost = totalCost + tx.gasPrice * tx.gas;
152 return tx;
153 });
155 let txPairs = txs.map(tx => {
156 let stx = new Tx(tx);
157 stx.sign(Buffer.from(fromWallet.privateKey, 'hex'));
158 return {
159 raw: hexify(stx.serialize()),
160 signed: stx,
161 };
162 });
164 //
165 // ensuring funding for transactions
166 //
168 progress(TRANSACTION_PROGRESS.FUNDING);
170 const usedTank = await tank.ensureFundsFor(
171 web3,
172 point,
173 fromWallet.address,
174 totalCost,
175 txPairs.map(p => p.raw),
176 askForFunding,
177 gotFunding
178 );
180 //
181 // sending and awaiting transactions
182 //
184 progress(TRANSACTION_PROGRESS.TRANSFERRING);
186 await sendAndAwaitAll(web3, txPairs.map(p => p.signed), usedTank);
188 //
189 // move leftover eth
190 //
192 progress(TRANSACTION_PROGRESS.CLEANING);
194 // if non-trivial eth left in invite wallet, transfer to new ownership
195 let balance = await web3.eth.getBalance(fromWallet.address);
196 const gasPrice = parseInt(toWei(DEFAULT_GAS_PRICE_GWEI.toFixed(), 'gwei'));
197 const gasLimit = GAS_LIMITS.SEND_ETH;
198 const sendEthCost = gasPrice * gasLimit;
199 if (transferEth && balance > sendEthCost) {
200 const value = balance - sendEthCost;
201 const tx = {
202 to: toWallet.ownership.keys.address,
203 value: value,
204 gasPrice: gasPrice,
205 gas: gasLimit,
206 nonce: inviteNonce++,
207 };
208 let stx = new Tx(tx);
209 stx.sign(fromWallet.privateKey);
210 const rawTx = hexify(stx.serialize());
211 web3.eth.sendSignedTransaction(rawTx).catch(err => {
212 console.log('error sending value tx, who cares', err);
213 });
214 }
216 progress(TRANSACTION_PROGRESS.DONE);