on 20e49fc help sign in
bridge/src/lib/reticket.js
250 lines 6.3 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 console.log(suggestedGasPrice.toFixed());
154 const gasPriceBN = toBN(gasPrice);
155 console.log(gasPrice);
156 let inviteNonce = await web3.eth.getTransactionCount(fromWallet.address);
157 console.log(txs);
158 const totalCost = txs.reduce(
159 (acc, tx) => acc.add(gasPriceBN.mul(toBN(tx.gas))),
160 toBN(0)
161 );
163 console.log(txs);
165 let txPairs = await Promise.all(
166 txs.map(async (tx, idx) => {
167 const stx = await signTransaction({
168 wallet: fromWallet,
169 walletType: fromWalletType,
170 walletHdPath: fromWalletHdPath,
171 networkType,
172 txn: tx,
173 nonce: inviteNonce + idx,
174 chainId,
175 gasPrice: suggestedGasPrice.toFixed(),
176 gasLimit: tx.gas,
177 });
178 if (!stx) {
179 debugger;
180 }
181 return {
182 raw: hexify(stx.serialize()),
183 signed: stx,
184 };
185 })
186 );
188 inviteNonce = inviteNonce + txs.length;
190 //
191 // ensuring funding for transactions
192 //
194 progress(TRANSACTION_PROGRESS.FUNDING);
196 const usedTank = await tank.ensureFundsFor(
197 web3,
198 point,
199 fromWallet.address,
200 totalCost,
201 txPairs.map(p => p.raw),
202 askForFunding,
203 gotFunding
204 );
206 //
207 // sending and awaiting transactions
208 //
210 progress(TRANSACTION_PROGRESS.TRANSFERRING);
212 console.log(txPairs);
213 await sendAndAwaitAllSerial(web3, txPairs.map(p => p.signed), usedTank);
215 //
216 // move leftover eth
217 //
219 progress(TRANSACTION_PROGRESS.CLEANING);
221 // if non-trivial eth left in invite wallet, transfer to new ownership
222 let balance = toBN(await web3.eth.getBalance(fromWallet.address));
223 const gasLimit = GAS_LIMITS.SEND_ETH;
224 const sendEthCost = gasPriceBN.mul(toBN(gasLimit));
225 if (transferEth && balance.gt(sendEthCost)) {
226 const value = balance.sub(sendEthCost);
227 const txn = {
228 to: toWallet.ownership.keys.address,
229 value: value,
230 };
231 const stx = signTransaction({
232 wallet: fromWallet,
233 walletType: fromWalletType,
234 walletHdPath: fromWalletHdPath,
235 txn,
236 chainId,
237 networkType,
238 gasPrice: gasPriceBN,
239 gasLimit,
240 nonce: inviteNonce++,
241 });
242 // let stx = new Tx(tx);
243 // stx.sign(fromWallet.privateKey);
244 sendSignedTransaction(web3, stx).catch(err => {
245 console.log('error sending value tx, who cares', err);
246 });
247 }
249 progress(TRANSACTION_PROGRESS.DONE);