on 8adeea8 help sign in
bridge/src/lib/reticket.js
243 lines 6.2 kB history raw
1import * as azimuth from 'azimuth-js';
2import * as tank from './tank';
4import { hexify } from './txn';
5import {
6 deriveNetworkSeedFromUrbitWallet,
7 deriveNetworkKeys,
8 CRYPTO_SUITE_VERSION,
9} from './keys';
10import { addHexPrefix } from './wallet';
11import {
12 sendAndAwaitAllSerial,
13 signTransaction,
14 sendSignedTransaction,
15} from './txn';
16import getSuggestedGasPrice from './getSuggestedGasPrice';
17import { GAS_LIMITS } from './constants';
18import { toWei, toBN } from 'web3-utils';
20// the initial network key revision is always 1
21const INITIAL_NETWORK_KEY_REVISION = 1;
23export const TRANSACTION_PROGRESS = {
24 GENERATING: 0.01,
25 SIGNING: 0.15,
26 FUNDING: 0.3,
27 TRANSFERRING: 0.55,
28 CLEANING: 0.95,
29 DONE: 1.0,
30};
32export async function reticketPointBetweenWallets({
33 fromWallet,
34 fromWalletType,
35 fromWalletHdPath,
36 toWallet,
37 point,
38 web3,
39 contracts,
40 networkType,
41 onUpdate,
42 transferEth = false,
43 nextRevision = INITIAL_NETWORK_KEY_REVISION,
44}) {
45 const askForFunding = (address, minBalance, balance) =>
46 onUpdate({
47 type: 'askFunding',
48 value: { address, minBalance, balance },
49 });
51 const gotFunding = () => onUpdate({ type: 'gotFunding' });
52 const progress = state => onUpdate({ type: 'progress', state });
54 //
55 // generate transactions
56 //
58 progress(TRANSACTION_PROGRESS.GENERATING);
60 // transfer to invite wallet, so it can configure
61 //NOTE doing this in the invite wallet instead of the final wallet makes
62 // failure cases "solvable" by just telling the user to fully retry.
63 // in other words, the invite flow is effectively idempotent.
65 //TODO no harm done if we already owned it, but should still get a bool arg
66 // for skipping this, if it isn't too big a burden for callers
67 const transferTmpTx = azimuth.ecliptic.transferPoint(
68 contracts,
69 point,
70 fromWallet.address,
71 false
72 );
73 transferTmpTx.gas = GAS_LIMITS.TRANSFER;
75 // configure networking public keys
76 const seed = await deriveNetworkSeedFromUrbitWallet(toWallet, nextRevision);
78 const networkSeed = seed.matchWith({
79 Nothing: () => {
80 throw new Error('network seed not derived');
81 },
82 Just: p => p.value,
83 });
85 const networkKeys = deriveNetworkKeys(networkSeed);
87 const keysTx = azimuth.ecliptic.configureKeys(
88 contracts,
89 point,
90 addHexPrefix(networkKeys.crypt.public),
91 addHexPrefix(networkKeys.auth.public),
92 CRYPTO_SUITE_VERSION,
93 /* discontinuous */ false
94 );
95 keysTx.gas = GAS_LIMITS.CONFIGURE_KEYS;
97 // configure management proxy
99 const managementTx = azimuth.ecliptic.setManagementProxy(
100 contracts,
101 point,
102 toWallet.management.keys.address
103 );
104 managementTx.gas = GAS_LIMITS.SET_PROXY;
106 // set spawn & voting proxies situationally
108 let txs = [transferTmpTx, keysTx, managementTx];
109 if (
110 azimuth.azimuth.getPointSize(point) !== azimuth.azimuth.PointSize.Planet
111 ) {
112 const spawnTx = azimuth.ecliptic.setSpawnProxy(
113 contracts,
114 point,
115 toWallet.spawn.keys.address
116 );
117 spawnTx.gas = GAS_LIMITS.SET_PROXY;
118 txs.push(spawnTx);
120 if (
121 azimuth.azimuth.getPointSize(point) === azimuth.azimuth.PointSize.Galaxy
122 ) {
123 const votingTx = azimuth.ecliptic.setVotingProxy(
124 contracts,
125 point,
126 toWallet.voting.keys.address
127 );
128 votingTx.gas = GAS_LIMITS.SET_PROXY;
129 txs.push(votingTx);
130 }
131 }
133 // transfer configured point to user's new wallet
135 const transferFinalTx = azimuth.ecliptic.transferPoint(
136 contracts,
137 point,
138 toWallet.ownership.keys.address,
139 false
140 );
141 transferFinalTx.gas = GAS_LIMITS.TRANSFER;
142 txs.push(transferFinalTx);
144 //
145 // finalizing & signing transactions
146 //
148 progress(TRANSACTION_PROGRESS.SIGNING);
150 const suggestedGasPrice = await getSuggestedGasPrice(networkType);
151 const chainId = await web3.eth.net.getId();
152 const gasPrice = toWei(suggestedGasPrice.toFixed(), 'gwei');
153 const gasPriceBN = toBN(gasPrice);
154 let inviteNonce = await web3.eth.getTransactionCount(fromWallet.address);
155 const totalCost = txs.reduce(
156 (acc, tx) => acc.add(gasPriceBN.mul(toBN(tx.gas))),
157 toBN(0)
158 );
160 let txPairs = [];
162 // Must be done in serial else hardware will give nonce errors
163 for (let i = 0; i < txs.length; i++) {
164 const stx = await signTransaction({
165 wallet: fromWallet,
166 walletType: fromWalletType,
167 walletHdPath: fromWalletHdPath,
168 networkType,
169 txn: txs[i],
170 nonce: inviteNonce + i,
171 chainId,
172 gasPrice: suggestedGasPrice.toFixed(),
173 gasLimit: txs[i].gas,
174 });
175 txPairs.push({
176 raw: hexify(stx.serialize()),
177 signed: stx,
178 });
179 }
181 inviteNonce = inviteNonce + txs.length;
183 //
184 // ensuring funding for transactions
185 //
187 progress(TRANSACTION_PROGRESS.FUNDING);
189 const usedTank = await tank.ensureFundsFor(
190 web3,
191 point,
192 fromWallet.address,
193 fromWalletType,
194 totalCost,
195 txPairs.map(p => p.raw),
196 askForFunding,
197 gotFunding
198 );
200 //
201 // sending and awaiting transactions
202 //
204 progress(TRANSACTION_PROGRESS.TRANSFERRING);
206 await sendAndAwaitAllSerial(web3, txPairs.map(p => p.signed), usedTank);
208 //
209 // move leftover eth
210 //
212 progress(TRANSACTION_PROGRESS.CLEANING);
214 // if non-trivial eth left in invite wallet, transfer to new ownership
215 let balance = toBN(await web3.eth.getBalance(fromWallet.address));
216 const gasLimit = GAS_LIMITS.SEND_ETH;
217 const sendEthCost = gasPriceBN.mul(toBN(gasLimit));
218 if (transferEth && balance.gt(sendEthCost)) {
219 const value = balance.sub(sendEthCost);
220 const txn = {
221 to: toWallet.ownership.keys.address,
222 value: value,
223 };
224 const stx = signTransaction({
225 wallet: fromWallet,
226 walletType: fromWalletType,
227 walletHdPath: fromWalletHdPath,
228 txn,
229 chainId,
230 networkType,
231 gasPrice: gasPriceBN,
232 gasLimit,
233 nonce: inviteNonce++,
234 });
235 // let stx = new Tx(tx);
236 // stx.sign(fromWallet.privateKey);
237 sendSignedTransaction(web3, stx).catch(err => {
238 console.log('error sending value tx, who cares', err);
239 });
240 }
242 progress(TRANSACTION_PROGRESS.DONE);