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

Implement payment routes #1711

Merged
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
79 changes: 72 additions & 7 deletions raiden-cli/src/routes/payments.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,81 @@
import { Router, Request, Response } from 'express';
import { Router, Request, Response, NextFunction } from 'express';
import { ErrorCodes, RaidenError, RaidenTransfer } from 'raiden-ts';
import { timer } from 'rxjs';
import { toArray, takeUntil, first } from 'rxjs/operators';
import { Cli } from '../types';
import { validateAddressParameter, isInvalidParameterError } from '../utils/validation';
import { transformSdkTransferToApiPayment } from '../utils/payments';

function isConflictError(error: RaidenError): boolean {
return [
ErrorCodes.PFS_INVALID_INFO,
ErrorCodes.PFS_NO_ROUTES_FOUND,
ErrorCodes.PFS_ERROR_RESPONSE,
ErrorCodes.PFS_DISABLED,
ErrorCodes.PFS_UNKNOWN_TOKEN_NETWORK,
ErrorCodes.PFS_TARGET_OFFLINE,
ErrorCodes.PFS_TARGET_NO_RECEIVE,
ErrorCodes.PFS_LAST_IOU_REQUEST_FAILED,
ErrorCodes.PFS_IOU_SIGNATURE_MISMATCH,
ErrorCodes.PFS_NO_ROUTES_BETWEEN_NODES,
].includes(error.message);
}

async function getPaymentsForTokenAndTarget(this: Cli, request: Request, response: Response) {
const allTransfers = await this.raiden.transfers$
.pipe(takeUntil(timer(0)), toArray())
.toPromise();
const filteredTransfers = allTransfers.filter(
(transfer) =>
transfer.token === request.params.tokenAddress &&
transfer.target === request.params.targetAddress,
);
const payments = filteredTransfers.map((transfer) => transformSdkTransferToApiPayment(transfer));
response.json(payments);
}

async function doTransfer(this: Cli, request: Request, response: Response, next: NextFunction) {
try {
// TODO: We ignore the provided `lock_timeout` until #1710 provides a better solution
const transferKey = await this.raiden.transfer(
request.params.tokenAddress,
request.params.targetAddress,
request.body.amount,
{ paymentId: request.body.identifier },
);
await this.raiden.waitTransfer(transferKey);
const newTransfer = await this.raiden.transfers$
.pipe(first(({ key }: RaidenTransfer) => key === transferKey))
.toPromise();
response.send(transformSdkTransferToApiPayment(newTransfer));
} catch (error) {
if (isInvalidParameterError(error)) {
response.status(400).send(error.message);
} else if (isConflictError(error)) {
const pfsErrorDetail = error.details?.errors ? ` (${error.details.errors})` : '';
response.status(409).send(error.message + pfsErrorDetail);
} else {
next(error);
}
}
}

export function makePaymentsRouter(this: Cli): Router {
const router = Router();

router.get('/:tokenAddress/:targetAddress', (_request: Request, response: Response) => {
response.status(404).send('Not implemented yet');
});
router.get(
'/:tokenAddress/:targetAddress',
validateAddressParameter.bind('tokenAddress'),
validateAddressParameter.bind('targetAddress'),
getPaymentsForTokenAndTarget.bind(this),
);

router.post('/:tokenAddress/:targetAddress', (_request: Request, response: Response) => {
response.status(404).send('Not implemented yet');
});
router.post(
'/:tokenAddress/:targetAddress',
validateAddressParameter.bind('tokenAddress'),
validateAddressParameter.bind('targetAddress'),
doTransfer.bind(this),
);

return router;
}
10 changes: 10 additions & 0 deletions raiden-cli/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,13 @@ export interface ApiChannel {
settle_timeout: number;
reveal_timeout: number;
}

export interface ApiPayment {
initiator_address: string;
target_address: string;
token_address: string;
amount: string;
identifier: number;
secret: string;
secret_hash: string;
}
14 changes: 14 additions & 0 deletions raiden-cli/src/utils/payments.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { RaidenTransfer } from 'raiden-ts';
import { ApiPayment } from '../types';

export function transformSdkTransferToApiPayment(transfer: RaidenTransfer): ApiPayment {
return {
initiator_address: transfer.initiator,
target_address: transfer.target,
token_address: transfer.token,
amount: transfer.value.toString(),
identifier: transfer.paymentId.toNumber(),
secret: '', // FIXME: must be first exposed by SDK (#1708)
Copy link
Contributor

Choose a reason for hiding this comment

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

secret is already exposed

secret_hash: transfer.secrethash,
};
}
4 changes: 4 additions & 0 deletions raiden-cli/src/utils/validation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,10 @@ export function isInvalidParameterError(error: RaidenError): boolean {
ErrorCodes.DTA_INVALID_ADDRESS,
ErrorCodes.DTA_INVALID_DEPOSIT,
ErrorCodes.DTA_INVALID_TIMEOUT,
ErrorCodes.DTA_INVALID_AMOUNT,
ErrorCodes.DTA_INVALID_PAYMENT_ID,
ErrorCodes.DTA_INVALID_PATH,
ErrorCodes.DTA_INVALID_PFS,
].includes(error.message);
}

Expand Down
3 changes: 2 additions & 1 deletion raiden-ts/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@
- [#1421] Adds support for withdrawing tokens from the UDC
- [#1642] Check token's allowance before deposit and skip approve
- [#1701] Allow parameter decoding to throw and log customized errors
- [#1701] Add and extend error codes for user parameter validation
- [#1701] Add and extend error codes for user parameter validation for open channel
- [#1711] Add and extend error codes for user parameter validation for transfer

### Changed
- [#837] Changes the action tags from camel to path format. This change affects the event types exposed through the public API.
Expand Down
4 changes: 4 additions & 0 deletions raiden-ts/src/errors.json
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,10 @@
"DTA_INVALID_ADDRESS": "Invalid address parameter.",
"DTA_INVALID_DEPOSIT": "Invalid deposit parameter.",
"DTA_INVALID_TIMEOUT": "Invalid timeout parameter.",
"DTA_INVALID_AMOUNT": "Invalid amount parameter.",
"DTA_INVALID_PAYMENT_ID": "Invalid payment identifier parameter.",
"DTA_INVALID_PATH": "Invalid path parameter.",
"DTA_INVALID_PFS": "Invalid path finding service parameter.",

"UDC_PLAN_WITHDRAW_FAILED" : "An error occurred while planning to withdraw from the User Deposit contract.",
"UDC_PLAN_WITHDRAW_GT_ZERO" : "The planned withdraw amount has to be greater than zero.",
Expand Down
14 changes: 10 additions & 4 deletions raiden-ts/src/raiden.ts
Original file line number Diff line number Diff line change
Expand Up @@ -806,10 +806,16 @@ export class Raiden {
const tokenNetwork = this.state.tokens[token];
assert(tokenNetwork, ErrorCodes.RDN_UNKNOWN_TOKEN_NETWORK, this.log.info);

const decodedValue = decode(UInt(32), value);
const paymentId = options.paymentId ? decode(UInt(8), options.paymentId) : makePaymentId();
const paths = options.paths ? decode(Paths, options.paths) : undefined;
const pfs = options.pfs ? decode(PFS, options.pfs) : undefined;
const decodedValue = decode(UInt(32), value, ErrorCodes.DTA_INVALID_AMOUNT, this.log.info);
const paymentId = options.paymentId
? decode(UInt(8), options.paymentId, ErrorCodes.DTA_INVALID_PAYMENT_ID, this.log.info)
: makePaymentId();
const paths = !options.paths
? undefined
: decode(Paths, options.paths, ErrorCodes.DTA_INVALID_PATH, this.log.info);
const pfs = !options.pfs
? undefined
: decode(PFS, options.pfs, ErrorCodes.DTA_INVALID_PFS, this.log.info);

assert(
options.secret === undefined || Secret.is(options.secret),
Expand Down
6 changes: 3 additions & 3 deletions raiden-ts/tests/e2e/raiden.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -713,7 +713,7 @@ describe('Raiden', () => {
test('invalid amount', async () => {
expect.assertions(1);
await expect(raiden.transfer(token, partner, -1)).rejects.toThrowError(
/Invalid value.*UInt/i,
/Invalid amount parameter./i,
);
});

Expand Down Expand Up @@ -743,7 +743,7 @@ describe('Raiden', () => {
test('invalid provided paymentId', async () => {
expect.assertions(1);
await expect(raiden.transfer(token, partner, 23, { paymentId: -1 })).rejects.toThrowError(
/Invalid value.*UInt/i,
/Invalid payment identifier parameter./i,
);
});

Expand All @@ -753,7 +753,7 @@ describe('Raiden', () => {
raiden.transfer(token, partner, 23, {
paths: [{ path: ['0xnotAnAddress'], fee: 0 }],
}),
).rejects.toThrowError(/Invalid value.*Address/i);
).rejects.toThrowError(/Invalid path parameter./i);
});

test('target not available', async () => {
Expand Down