Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix mismatch between UDC totalDeposit and effectiveBalance #2277

Merged
merged 2 commits into from
Oct 20, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion raiden-ts/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@

## [Unreleased]
### Fixed
- [#2078] Check for overflows before sending transfers
- [#2094] Fix TransferState's timestamps missing
- [#2174] Fix a few transport issues triggered on high-load scenarios
- [#2078] Check for overflows before sending transfers
- [#2275] Fix mismatch between UDC totalDeposit and effectiveBalance

### Added
- [#2044] Introduce PouchDB (IndexedDB/leveldown) as new persistent state storage backend
Expand All @@ -21,6 +22,7 @@
[#2174]: https://github.com/raiden-network/light-client/pull/2174
[#2204]: https://github.com/raiden-network/light-client/issues/2204
[#2205]: https://github.com/raiden-network/light-client/issues/2205
[#2275]: https://github.com/raiden-network/light-client/issues/2225

## [0.11.1] - 2020-08-18
### Changed
Expand Down
2 changes: 1 addition & 1 deletion raiden-ts/src/epics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ export function getLatest$(
): Observable<Latest> {
const udcBalance$ = action$.pipe(
filter(udcDeposit.success.is),
pluck('meta', 'totalDeposit'),
pluck('payload', 'balance'),
// starts with max, to prevent receiving starting as disabled before actual balance is fetched
startWith(MaxUint256 as UInt<32>),
);
Expand Down
10 changes: 6 additions & 4 deletions raiden-ts/src/raiden.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1199,17 +1199,19 @@ export class Raiden {

const deposit = decode(UInt(32), amount, ErrorCodes.DTA_INVALID_DEPOSIT, this.log.info);
assert(deposit.gt(Zero), ErrorCodes.DTA_NON_POSITIVE_NUMBER, this.log.info);
const balance = await getUdcBalance(this.deps.latest$);
const meta = { totalDeposit: balance.add(deposit) as UInt<32> };
const deposited = await this.deps.userDepositContract.functions.total_deposit(this.address);
const meta = { totalDeposit: deposited.add(deposit) as UInt<32> };

const mined = asyncActionToPromise(udcDeposit, meta, this.action$).then((res) => res?.txHash);
const mined = asyncActionToPromise(udcDeposit, meta, this.action$, false).then(
(res) => res.txHash,
);
this.store.dispatch(udcDeposit.request({ deposit, subkey }, meta));

let txHash = await mined;
onChange?.({ type: EventTypes.DEPOSITED, payload: { txHash: txHash! } });

const confirmed = asyncActionToPromise(udcDeposit, meta, this.action$, true).then(
(res) => res!.txHash,
(res) => res.txHash,
);
txHash = await confirmed;
onChange?.({ type: EventTypes.CONFIRMED, payload: { txHash } });
Expand Down
9 changes: 7 additions & 2 deletions raiden-ts/src/services/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,13 @@ export const udcDeposit = createAsyncAction(
'udc/deposit/failure',
t.intersection([t.type({ deposit: UInt(32) }), t.partial({ subkey: t.boolean })]),
t.union([
t.undefined,
t.type({ txHash: Hash, txBlock: t.number, confirmed: t.union([t.undefined, t.boolean]) }),
t.type({ balance: UInt(32) }),
t.type({
balance: UInt(32),
txHash: Hash,
txBlock: t.number,
confirmed: t.union([t.undefined, t.boolean]),
}),
]),
);
export namespace udcDeposit {
Expand Down
37 changes: 24 additions & 13 deletions raiden-ts/src/services/epics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -459,13 +459,16 @@ export function monitorUdcBalanceEpic(
* etc), but merged on the top-level observable, therefore connectivity issues can cause
* exceptions which would shutdown the SDK. Let's swallow the error here, since this will be
* retried on next block, which should only be emitted after connectivity is reestablished */
defer(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Regarding line 455: We should open an issue for the contracts to add events.

async () => userDepositContract.functions.effectiveBalance(address) as Promise<UInt<32>>,
defer(async () =>
Promise.all([
userDepositContract.functions.effectiveBalance(address) as Promise<UInt<32>>,
userDepositContract.functions.total_deposit(address) as Promise<UInt<32>>,
]),
).pipe(catchError(constant(EMPTY))),
),
withLatestFrom(latest$),
filter(([balance, { udcBalance }]) => !udcBalance.eq(balance)),
map(([balance]) => udcDeposit.success(undefined, { totalDeposit: balance })),
filter(([[balance], { udcBalance }]) => !udcBalance.eq(balance)),
map(([[balance, totalDeposit]]) => udcDeposit.success({ balance }, { totalDeposit })),
);
}

Expand All @@ -480,7 +483,7 @@ function makeUdcDeposit$(
Promise.all([
tokenContract.functions.balanceOf(sender) as Promise<UInt<32>>,
tokenContract.functions.allowance(sender, userDepositContract.address) as Promise<UInt<32>>,
userDepositContract.functions.effectiveBalance(address),
userDepositContract.functions.total_deposit(address),
]),
).pipe(
mergeMap(([balance, allowance, deposited]) => {
Expand Down Expand Up @@ -547,14 +550,22 @@ export function udcDepositEpic(
{ log },
);
}),
map(([, receipt]) =>
udcDeposit.success(
{
txHash: receipt.transactionHash,
txBlock: receipt.blockNumber,
confirmed: undefined, // let confirmationEpic confirm this action
},
action.meta,
mergeMap(([, receipt]) =>
defer(
async () =>
userDepositContract.functions.effectiveBalance(address) as Promise<UInt<32>>,
).pipe(
map((balance) =>
udcDeposit.success(
{
balance,
txHash: receipt.transactionHash,
txBlock: receipt.blockNumber,
confirmed: undefined, // let confirmationEpic confirm this action
},
action.meta,
),
),
),
),
catchError((error) => of(udcDeposit.failure(error, action.meta))),
Expand Down
49 changes: 44 additions & 5 deletions raiden-ts/src/utils/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@
import * as t from 'io-ts';
import isMatchWith from 'lodash/isMatchWith';
import { Observable } from 'rxjs';
import { first, map } from 'rxjs/operators';
import { filter, first, map } from 'rxjs/operators';

import { assert } from '../utils';
import { RaidenError, ErrorCodes } from '../utils/error';
import { BigNumberC } from './types';
import { BigNumberC, Hash } from './types';

/**
* The type of a generic action
Expand Down Expand Up @@ -511,13 +511,46 @@ export function isConfirmationResponseOf<
return _isResponseOf;
}

export function asyncActionToPromise<
AAC extends AsyncActionCreator<t.Mixed, any, any, any, any, t.Mixed, t.Mixed>
>(
asyncAction: AAC,
meta: ActionType<AAC['request']>['meta'],
action$: Observable<Action>,
): Promise<ActionType<AAC['success']>['payload']>;
export function asyncActionToPromise<
AAC extends AsyncActionCreator<t.Mixed, any, any, any, any, t.Mixed, t.Mixed>
>(
asyncAction: AAC,
meta: ActionType<AAC['request']>['meta'],
action$: Observable<Action>,
confirmed: false,
): Promise<
ActionType<AAC['success']>['payload'] & {
txBlock: number;
txHash: Hash;
confirmed: undefined | boolean;
}
>;
export function asyncActionToPromise<
AAC extends AsyncActionCreator<t.Mixed, any, any, any, any, t.Mixed, t.Mixed>
>(
asyncAction: AAC,
meta: ActionType<AAC['request']>['meta'],
action$: Observable<Action>,
confirmed: true,
): Promise<
ActionType<AAC['success']>['payload'] & { txBlock: number; txHash: Hash; confirmed: true }
>;

/**
* Watch a stream of actions and resolves on meta-matching success or rejects on failure
*
* @param asyncAction - async actions object to wait for
* @param meta - meta object of a request to wait for the respective response
* @param action$ - actions stream to watch for responses
* @param confirmed - set if should ignore non-confirmed success response
* @param confirmed - undefined for any response action, false to filter confirmable actions,
* true for confirmed ones
* @returns Promise which rejects with payload in case of failure, or resolves payload otherwise
*/
export async function asyncActionToPromise<
Expand All @@ -526,15 +559,21 @@ export async function asyncActionToPromise<
asyncAction: AAC,
meta: ActionType<AAC['request']>['meta'],
action$: Observable<Action>,
confirmed = false,
confirmed?: boolean,
) {
return action$
.pipe(
first(
filter(
confirmed
? isConfirmationResponseOf<AAC>(asyncAction, meta)
: isResponseOf<AAC>(asyncAction, meta),
),
first(
(action) =>
confirmed === undefined ||
!asyncAction.success.is(action) ||
'confirmed' in action.payload,
),
map((action) => {
if (asyncAction.failure.is(action))
throw action.payload as ActionType<AAC['failure']>['payload'];
Expand Down
17 changes: 13 additions & 4 deletions raiden-ts/tests/integration/raiden.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1299,14 +1299,17 @@ describe('Raiden', () => {
});

test('deposit success', async () => {
expect.assertions(1);
await raiden.mint(await raiden.userDepositTokenAddress(), 10);
expect.assertions(3);
await raiden.mint(await raiden.userDepositTokenAddress(), 20);
await expect(raiden.depositToUDC(10)).resolves.toMatch(/^0x[0-9a-fA-F]{64}$/);
await expect(raiden.depositToUDC(5)).resolves.toMatch(/^0x[0-9a-fA-F]{64}$/);
await expect(raiden.getUDCCapacity()).resolves.toEqual(bigNumberify(15));
});

test('withdraw success', async () => {
expect.assertions(5);
test('withdraw success!', async () => {
expect.assertions(7);
const deposit = bigNumberify(100) as UInt<32>;
const newDeposit = bigNumberify(30) as UInt<32>;
const withdraw = bigNumberify(80) as UInt<32>;
await raiden.mint(await raiden.userDepositTokenAddress(), deposit);
await expect(raiden.depositToUDC(deposit)).resolves.toMatch(/^0x[0-9a-fA-F]{64}$/);
Expand All @@ -1325,6 +1328,12 @@ describe('Raiden', () => {
amount: withdraw,
}),
]);

await expect(raiden.depositToUDC(newDeposit)).resolves.toMatch(/^0x[0-9a-fA-F]{64}$/);
await provider.mine(confirmationBlocks * 2);
await expect(raiden.getUDCCapacity()).resolves.toEqual(
deposit.sub(withdraw).add(newDeposit),
);
});

test('withdraw success with restart', async () => {
Expand Down
17 changes: 13 additions & 4 deletions raiden-ts/tests/unit/epics/monitor.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,21 +45,23 @@ test('monitorUdcBalanceEpic', async () => {
const raiden = await makeRaiden(undefined, false);
const { userDepositContract } = raiden.deps;
userDepositContract.functions.effectiveBalance.mockResolvedValue(Zero);
userDepositContract.functions.total_deposit.mockResolvedValue(Zero);

await raiden.start();
await sleep();
expect(raiden.output).toContainEqual(
udcDeposit.success(undefined, { totalDeposit: Zero as UInt<32> }),
udcDeposit.success({ balance: Zero as UInt<32> }, { totalDeposit: Zero as UInt<32> }),
);
await expect(
raiden.deps.latest$.pipe(pluck('udcBalance'), first()).toPromise(),
).resolves.toEqual(Zero);

const balance = bigNumberify(23) as UInt<32>;
userDepositContract.functions.effectiveBalance.mockResolvedValue(balance);
userDepositContract.functions.total_deposit.mockResolvedValue(balance);
await waitBlock();

expect(raiden.output).toContainEqual(udcDeposit.success(undefined, { totalDeposit: balance }));
expect(raiden.output).toContainEqual(udcDeposit.success({ balance }, { totalDeposit: balance }));
await expect(
raiden.deps.latest$.pipe(pluck('udcBalance'), first()).toPromise(),
).resolves.toEqual(balance);
Expand Down Expand Up @@ -182,10 +184,12 @@ describe('monitorRequestEpic', () => {
);

userDepositContract.functions.effectiveBalance.mockResolvedValue(monitoringReward.sub(1));
userDepositContract.functions.total_deposit.mockResolvedValue(monitoringReward.sub(1));
await waitBlock();

const balance = monitoringReward.sub(1) as UInt<32>;
expect(raiden.output).toContainEqual(
udcDeposit.success(undefined, { totalDeposit: monitoringReward.sub(1) as UInt<32> }),
udcDeposit.success({ balance }, { totalDeposit: balance }),
);

await ensureChannelIsDeposited([raiden, partner], deposit);
Expand Down Expand Up @@ -389,6 +393,7 @@ describe('udcDepositEpic', () => {
const raiden = await makeRaiden(undefined, false);
const { userDepositContract } = raiden.deps;
userDepositContract.functions.effectiveBalance.mockResolvedValue(Zero);
userDepositContract.functions.total_deposit.mockResolvedValue(Zero);

const tokenContract = raiden.deps.getTokenContract(
await raiden.deps.userDepositContract.functions.token(),
Expand All @@ -413,6 +418,7 @@ describe('udcDepositEpic', () => {
const raiden = await makeRaiden(undefined, false);
const { userDepositContract } = raiden.deps;
userDepositContract.functions.effectiveBalance.mockResolvedValue(Zero);
userDepositContract.functions.total_deposit.mockResolvedValue(Zero);

const tokenContract = raiden.deps.getTokenContract(
await raiden.deps.userDepositContract.functions.token(),
Expand Down Expand Up @@ -452,6 +458,7 @@ describe('udcDepositEpic', () => {
const raiden = await makeRaiden(undefined, false);
const { userDepositContract } = raiden.deps;
userDepositContract.functions.effectiveBalance.mockResolvedValue(Zero);
userDepositContract.functions.total_deposit.mockResolvedValue(Zero);

const tokenContract = raiden.deps.getTokenContract(
await raiden.deps.userDepositContract.functions.token(),
Expand Down Expand Up @@ -483,6 +490,7 @@ describe('udcDepositEpic', () => {
const raiden = await makeRaiden(undefined, false);
const { userDepositContract } = raiden.deps;
userDepositContract.functions.effectiveBalance.mockResolvedValue(prevDeposit);
userDepositContract.functions.total_deposit.mockResolvedValue(prevDeposit);

const tokenContract = raiden.deps.getTokenContract(
await raiden.deps.userDepositContract.functions.token(),
Expand All @@ -501,6 +509,7 @@ describe('udcDepositEpic', () => {

const depositTx = makeTransaction(undefined, { to: userDepositContract.address });
userDepositContract.functions.deposit.mockResolvedValue(depositTx);
userDepositContract.functions.effectiveBalance.mockResolvedValue(balance);

await raiden.start();
raiden.store.dispatch(udcDeposit.request({ deposit }, { totalDeposit: balance }));
Expand All @@ -515,7 +524,7 @@ describe('udcDepositEpic', () => {
);
expect(raiden.output).toContainEqual(
udcDeposit.success(
{ txHash: depositTx.hash! as Hash, txBlock: expect.any(Number), confirmed: true },
{ balance, txHash: depositTx.hash! as Hash, txBlock: expect.any(Number), confirmed: true },
{ totalDeposit: balance },
),
);
Expand Down