on d67c869 help sign in
bridge/src/lib/reticket.js
218 lines 5.6 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 nextNetworkKeyRevision = INITIAL_NETWORK_KEY_REVISION,
37}) {
38 const askForFunding = (address, minBalance, balance) =>
39 onUpdate({
40 type: 'askFunding',
41 value: { address, minBalance, balance },
42 });
44 const gotFunding = () => onUpdate({ type: 'gotFunding' });
45 const progress = state => onUpdate({ type: 'progress', state });
47 //
48 // generate transactions
49 //
51 progress(TRANSACTION_PROGRESS.GENERATING);
53 // transfer to invite wallet, so it can configure
54 //NOTE doing this in the invite wallet instead of the final wallet makes
55 // failure cases "solvable" by just telling the user to fully retry.
56 // in other words, the invite flow is effectively idempotent.
58 //TODO no harm done if we already owned it, but should still get a bool arg
59 // for skipping this, if it isn't too big a burden for callers
60 const transferTmpTx = azimuth.ecliptic.transferPoint(
61 contracts,
62 point,
63 fromWallet.address,
64 false
65 );
66 transferTmpTx.gas = GAS_LIMITS.TRANSFER;
68 // configure networking public keys
69 const seed = await deriveNetworkSeedFromUrbitWallet(
70 toWallet,
71 nextNetworkKeyRevision
72 );
74 const networkSeed = seed.matchWith({
75 Nothing: () => {
76 throw new Error('network seed not derived');
77 },
78 Just: p => p.value,
79 });
81 const networkKeys = deriveNetworkKeys(networkSeed);
83 const keysTx = azimuth.ecliptic.configureKeys(
84 contracts,
85 point,
86 addHexPrefix(networkKeys.crypt.public),
87 addHexPrefix(networkKeys.auth.public),
88 CRYPTO_SUITE_VERSION,
89 /* discontinuous */ false
90 );
91 keysTx.gas = GAS_LIMITS.CONFIGURE_KEYS;
93 // configure management proxy
95 const managementTx = azimuth.ecliptic.setManagementProxy(
96 contracts,
97 point,
98 toWallet.management.keys.address
99 );
100 managementTx.gas = GAS_LIMITS.SET_PROXY;
102 // set spawn & voting proxies situationally
104 let txs = [transferTmpTx, keysTx, managementTx];
105 if (
106 azimuth.azimuth.getPointSize(point) !== azimuth.azimuth.PointSize.Planet
107 ) {
108 const spawnTx = azimuth.ecliptic.setSpawnProxy(
109 contracts,
110 point,
111 toWallet.spawn.keys.address
112 );
113 spawnTx.gas = GAS_LIMITS.SET_PROXY;
114 txs.push(spawnTx);
116 if (
117 azimuth.azimuth.getPointSize(point) === azimuth.azimuth.PointSize.Galaxy
118 ) {
119 const votingTx = azimuth.ecliptic.setVotingProxy(
120 contracts,
121 point,
122 toWallet.voting.keys.address
123 );
124 votingTx.gas = GAS_LIMITS.SET_PROXY;
125 txs.push(votingTx);
126 }
127 }
129 // transfer configured point to user's new wallet
131 const transferFinalTx = azimuth.ecliptic.transferPoint(
132 contracts,
133 point,
134 toWallet.ownership.keys.address,
135 false
136 );
137 transferFinalTx.gas = GAS_LIMITS.TRANSFER;
138 txs.push(transferFinalTx);
140 //
141 // finalizing & signing transactions
142 //
144 progress(TRANSACTION_PROGRESS.SIGNING);
146 let totalCost = 0;
147 let inviteNonce = await web3.eth.getTransactionCount(fromWallet.address);
148 txs = txs.map(tx => {
149 tx.from = fromWallet.address;
150 tx.nonce = inviteNonce++;
151 tx.gasPrice = parseInt(toWei(DEFAULT_GAS_PRICE_GWEI.toFixed(), 'gwei'), 10);
152 totalCost = totalCost + tx.gasPrice * tx.gas;
153 return tx;
154 });
156 let txPairs = txs.map(tx => {
157 let stx = new Tx(tx);
158 stx.sign(Buffer.from(fromWallet.privateKey, 'hex'));
159 return {
160 raw: hexify(stx.serialize()),
161 signed: stx,
162 };
163 });
165 //
166 // ensuring funding for transactions
167 //
169 progress(TRANSACTION_PROGRESS.FUNDING);
171 const usedTank = await tank.ensureFundsFor(
172 web3,
173 point,
174 fromWallet.address,
175 totalCost,
176 txPairs.map(p => p.raw),
177 askForFunding,
178 gotFunding
179 );
181 //
182 // sending and awaiting transactions
183 //
185 progress(TRANSACTION_PROGRESS.TRANSFERRING);
187 await sendAndAwaitAll(web3, txPairs.map(p => p.signed), usedTank);
189 //
190 // move leftover eth
191 //
193 progress(TRANSACTION_PROGRESS.CLEANING);
195 // if non-trivial eth left in invite wallet, transfer to new ownership
196 let balance = await web3.eth.getBalance(fromWallet.address);
197 const gasPrice = parseInt(toWei(DEFAULT_GAS_PRICE_GWEI.toFixed(), 'gwei'));
198 const gasLimit = GAS_LIMITS.SEND_ETH;
199 const sendEthCost = gasPrice * gasLimit;
200 if (transferEth && balance > sendEthCost) {
201 const value = balance - sendEthCost;
202 const tx = {
203 to: toWallet.ownership.keys.address,
204 value: value,
205 gasPrice: gasPrice,
206 gas: gasLimit,
207 nonce: inviteNonce++,
208 };
209 let stx = new Tx(tx);
210 stx.sign(fromWallet.privateKey);
211 const rawTx = hexify(stx.serialize());
212 web3.eth.sendSignedTransaction(rawTx).catch(err => {
213 console.log('error sending value tx, who cares', err);
214 });
215 }
217 progress(TRANSACTION_PROGRESS.DONE);