on a8a2d64 help sign in
bridge/src/lib/starRelease.js
85 lines 2.4 kB history raw
1import { linearSR, conditionalSR } from 'azimuth-js';
3function mapRange(amount, cb) {
4 return [...Array(amount).keys()].map(cb);
5}
7// Preferentially withdraw from conditional contracts and use linear
8// to mop up the rest
9export function generateWithdrawTxs(contracts, batchLimits, amount, to) {
10 const [left, ...csrTxs] = generateConditionalWithdrawTxs(
11 contracts,
12 batchLimits,
13 amount,
14 to
15 );
16 const lsrTxs = generateLinearWithdrawTxs(contracts, left, to);
17 return [...csrTxs, ...lsrTxs];
20function generateConditionalWithdrawTxs(
21 contracts,
22 batchLimits,
23 amount,
24 to,
25 offset = 0
26) {
27 // Successfully withdraw all requesed
28 if (amount <= 0) {
29 return [0];
30 }
31 // Return missing amount in car
32 if (batchLimits.length === 0) {
33 return [amount];
34 }
35 const [next, ...rest] = batchLimits;
36 const currentAmount = Math.min(amount, next);
37 return [
38 ...generateConditionalWithdrawTxs(
39 contracts,
40 rest,
41 amount - currentAmount,
42 to,
43 offset + 1
44 ),
45 ...mapRange(currentAmount, () =>
46 conditionalSR.withdrawTo(contracts, offset, to)
47 ),
48 ];
51function generateLinearWithdrawTxs(contracts, amount, to) {
52 return mapRange(amount, () => linearSR.withdrawTo(contracts, to));
55export async function getConditional(contracts, address) {
56 const [commitment, batches] = await Promise.all([
57 conditionalSR.getCommitment(contracts, address),
58 conditionalSR.getBatches(contracts, address),
59 ]);
61 const { total } = commitment;
62 const withdrawLimits = await Promise.all(
63 batches.map((_, idx) =>
64 conditionalSR.getWithdrawLimit(contracts, address, idx)
65 )
66 );
67 const available = withdrawLimits.reduce((acc, val) => acc + val, 0);
69 const withdrawnAmounts = await conditionalSR.getWithdrawn(contracts, address);
71 const withdrawn = withdrawnAmounts.reduce((acc, val) => acc + val, 0);
72 const batchLimits = withdrawLimits.map(
73 (limit, idx) => limit - withdrawnAmounts[idx]
74 );
76 return { total, available, withdrawn, batchLimits };
79export async function getLinear(contracts, address) {
80 const { amount, withdrawn } = await linearSR.getBatch(contracts, address);
82 const available = // Contract errors on withdrawing from a user that does not have any
83 amount > 0 ? await linearSR.getWithdrawLimit(contracts, address) : 0;
84 return { available, withdrawn, total: amount };