Skip to content

Commit

Permalink
Converted raiden, transport and channel errors
Browse files Browse the repository at this point in the history
  • Loading branch information
nephix committed Feb 14, 2020
1 parent 55f45b6 commit 2abe85b
Show file tree
Hide file tree
Showing 5 changed files with 49 additions and 22 deletions.
5 changes: 4 additions & 1 deletion raiden-ts/src/channels/epics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -493,7 +493,10 @@ export const channelOpenEpic = (
).pipe(
mergeMap(async tx => ({ receipt: await tx.wait(), tx })),
map(({ receipt, tx }) => {
if (!receipt.status) throw new Error(`openChannel transaction "${tx.hash}" failed`);
if (!receipt.status)
throw new RaidenError(ErrorCodes.CNL_OPENCHANNEL_FAILED, [
{ transactionHash: tx.hash! },
]);
return tx.hash;
}),
// if succeeded, return a empty/completed observable
Expand Down
15 changes: 9 additions & 6 deletions raiden-ts/src/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import goerliDeploy from './deployment/deployment_goerli.json';
import ropstenServicesDeploy from './deployment/deployment_services_ropsten.json';
import rinkebyServicesDeploy from './deployment/deployment_services_rinkeby.json';
import goerliServicesDeploy from './deployment/deployment_services_goerli.json';
import RaidenError, { ErrorCodes } from './utils/error';

/**
* Returns contract information depending on the passed [[Network]]. Currently, only
Expand Down Expand Up @@ -48,9 +49,7 @@ export const getContracts = (network: Network): ContractsInfo => {
...goerliServicesDeploy.contracts,
} as unknown) as ContractsInfo;
default:
throw new Error(
`No deploy info provided nor recognized network: ${JSON.stringify(network)}`,
);
throw new RaidenError(ErrorCodes.RDN_UNRECOGNIZED_NETWORK, [{ network }]);
}
};

Expand Down Expand Up @@ -102,7 +101,9 @@ export const getSigner = async (
} else if (account instanceof Wallet) {
signer = account.connect(provider);
} else {
throw new Error(`Signer ${account} not connected to ${provider}`);
throw new RaidenError(ErrorCodes.RDN_SIGNER_NOT_CONNECTED, [
{ account: account.toString(), provider: provider.toString() },
]);
}
address = (await signer.getAddress()) as Address;
} else if (typeof account === 'number') {
Expand All @@ -113,7 +114,9 @@ export const getSigner = async (
// address
const accounts = await provider.listAccounts();
if (!accounts.includes(account)) {
throw new Error(`Account "${account}" not found in provider, got=${accounts}`);
throw new RaidenError(ErrorCodes.RDN_ACCOUNT_NOT_FOUND, [
{ account, accounts: JSON.stringify(accounts) },
]);
}
signer = provider.getSigner(account);
address = account;
Expand All @@ -122,7 +125,7 @@ export const getSigner = async (
signer = new Wallet(account, provider);
address = signer.address as Address;
} else {
throw new Error('String account must be either a 0x-encoded address or private key');
throw new RaidenError(ErrorCodes.RDN_STRING_ACCOUNT_INVALID);
}

if (subkey) {
Expand Down
12 changes: 7 additions & 5 deletions raiden-ts/src/raiden.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ import {
chooseOnchainAccount,
getContractWithSigner,
} from './helpers';
import RaidenError, { ErrorCodes } from './utils/error';

export class Raiden {
private readonly store: Store<RaidenState, RaidenAction>;
Expand Down Expand Up @@ -886,7 +887,8 @@ export class Raiden {
const customTokenContract = CustomTokenFactory.connect(token, signer);
const tx = await customTokenContract.functions.mint(decode(UInt(32), amount));
const receipt = await tx.wait();
if (!receipt.status) throw new Error('Failed to mint token.');
if (!receipt.status)
throw new RaidenError(ErrorCodes.RDN_MINT_FAILED, [{ transactionHash: tx.hash! }]);

return tx.hash as Hash;
}
Expand Down Expand Up @@ -955,15 +957,15 @@ export class Raiden {
depositAmount,
);
const approveReceipt = await approveTx.wait();
if (!approveReceipt.status) throw new Error('Approve transaction failed.');
if (!approveReceipt.status) throw new RaidenError(ErrorCodes.RDN_APPROVE_TRANSACTION_FAILED);

const currentUDCBalance = await userDepositContract.functions.balances(this.address);
const depositTx = await userDepositContract.functions.deposit(
this.address,
currentUDCBalance.add(depositAmount),
);
const depositReceipt = await depositTx.wait();
if (!depositReceipt.status) throw new Error('Deposit transaction failed.');
if (!depositReceipt.status) throw new RaidenError(ErrorCodes.RDN_DEPOSIT_TRANSACTION_FAILED);

return depositTx.hash as Hash;
}
Expand Down Expand Up @@ -998,7 +1000,7 @@ export class Raiden {
const tx = await signer.sendTransaction({ to, value: bigNumberify(value) });
const receipt = await tx.wait();

if (!receipt.status) throw new Error('Failed to transfer balance');
if (!receipt.status) throw new RaidenError(ErrorCodes.RDN_TRANSFER_ONCHAIN_BALANCE_FAILED);
return tx.hash! as Hash;
}

Expand Down Expand Up @@ -1030,7 +1032,7 @@ export class Raiden {
const tx = await tokenContract.functions.transfer(to, bigNumberify(value));
const receipt = await tx.wait();

if (!receipt.status) throw new Error('Failed to transfer tokens');
if (!receipt.status) throw new RaidenError(ErrorCodes.RDN_TRANSFER_ONCHAIN_TOKENS_FAILED);
return tx.hash! as Hash;
}
}
Expand Down
20 changes: 10 additions & 10 deletions raiden-ts/src/transport/epics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ import {
} from 'matrix-js-sdk';
import matrixLogger from 'matrix-js-sdk/lib/logger';

import RaidenError, { ErrorCodes } from '../utils/error';
import { Address, Signed, isntNil, assert, Signature } from '../utils/types';
import { isActionOf } from '../utils/actions';
import { RaidenEpicDeps } from '../types';
Expand Down Expand Up @@ -226,8 +227,7 @@ function searchAddressPresence$(matrix: MatrixClient, address: Address) {
// fetch it here directly, and from now on, that other epic will monitor its
// updates, and sort by most recently seen user
map(presences => {
if (!presences.length)
throw new Error(`Could not find any user with valid signature for ${address}`);
if (!presences.length) throw new RaidenError(ErrorCodes.TRNS_NO_VALID_USER, [{ address }]);
return minBy(presences, 'last_active_ago')!;
}),
);
Expand Down Expand Up @@ -393,7 +393,7 @@ function setupMatrixClient$(
},
) {
const serverName = getServerName(server);
if (!serverName) throw new Error(`Could not get serverName from "${server}"`);
if (!serverName) throw new RaidenError(ErrorCodes.TRNS_NO_SERVERNAME, [{ server }]);

return defer(() => {
if (setup) {
Expand Down Expand Up @@ -676,13 +676,13 @@ export const matrixPresenceUpdateEpic = (
return displayName$.pipe(
map(displayName => {
// errors raised here will be logged and ignored on catchError below
if (!displayName) throw new Error(`Could not get displayName of "${userId}"`);
if (!displayName) throw new RaidenError(ErrorCodes.TRNS_NO_DISPLAYNAME, [{ userId }]);
// ecrecover address, validating displayName is the signature of the userId
const recovered = verifyMessage(userId, displayName) as Address | undefined;
if (!recovered || recovered !== address)
throw new Error(
`Could not verify displayName signature of "${userId}": got "${recovered}"`,
);
throw new RaidenError(ErrorCodes.TRNS_USERNAME_VERIFICATION_FAILED, [
{ userId, receivedSignature: recovered },
]);
return recovered;
}),
// TODO: edge case: don't emit unavailable if address is available somewhere else
Expand Down Expand Up @@ -1212,9 +1212,9 @@ export const matrixMessageReceivedEpic = (
message = decodeJsonMessage(line);
const signer = getMessageSigner(message);
if (signer !== presence.meta.address)
throw new Error(
`Signature mismatch: sender=${presence.meta.address} != signer=${signer}`,
);
throw new RaidenError(ErrorCodes.TRNS_MESSAGE_SIGNATURE_MISMATCH, [
{ sender: presence.meta.address, signer },
]);
} catch (err) {
console.warn(`Could not decode message: ${line}: ${err}`);
message = undefined;
Expand Down
19 changes: 19 additions & 0 deletions raiden-ts/src/utils/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ export enum ErrorCodes {
CNL_NO_OPEN_OR_CLOSING_CHANNEL_FOUND = 'No open or closing channel has been found.',
CNL_NO_SETTLEABLE_OR_SETTLING_CHANNEL_FOUND = 'No settleable or settling channel has been found.',
CNL_APPROVE_TRANSACTION_FAILED = 'Token approve transaction failed.',
CNL_OPENCHANNEL_FAILED = 'Token networks openChannel transaction failed.',
CNL_SETTOTALDEPOSIT_FAILED = 'Token networks setTotalDeposit transaction failed.',
CNL_CLOSECHANNEL_FAILED = 'Token networks closeChannel transaction failed.',
CNL_SETTLECHANNEL_FAILED = 'Token networks settleChannel transaction failed.',
Expand All @@ -31,6 +32,24 @@ export enum ErrorCodes {
XFER_EXPIRED = 'Transfer expired.',
XFER_CHANNEL_CLOSED_PREMATURELY = 'Channel was closed before secret got reveiled or transfer unlocked.',
XFER_REFUNDED = 'Transfer has been refunded.',

// Transport errors
TRNS_NO_VALID_USER = 'Could not find a user with a valid signature.',
TRNS_NO_SERVERNAME = 'Could not get server name from Matrix server.',
TRNS_NO_DISPLAYNAME = 'Could not get display name from Matrix server.',
TRNS_USERNAME_VERIFICATION_FAILED = 'Could not verify the signature of a display name.',
TRNS_MESSAGE_SIGNATURE_MISMATCH = 'Unable to decode message due to signature mismatch.',

// Raiden main class errors
RDN_MINT_FAILED = 'Failed to mint tokens.',
RDN_APPROVE_TRANSACTION_FAILED = 'Approve transaction has failed.',
RDN_DEPOSIT_TRANSACTION_FAILED = 'Deposit transaction has failed.',
RDN_TRANSFER_ONCHAIN_BALANCE_FAILED = 'Failed to transfer on-chain balance.',
RDN_TRANSFER_ONCHAIN_TOKENS_FAILED = 'Failed to transfer on-chain tokens.',
RDN_UNRECOGNIZED_NETWORK = 'No deploy info provided nor recognized network.',
RDN_SIGNER_NOT_CONNECTED = 'The signing account is not connected to the provider.',
RDN_ACCOUNT_NOT_FOUND = 'Account not found in provider.',
RDN_STRING_ACCOUNT_INVALID = 'String account must be either a 0x-encoded address or private key',
}

export const ErrorDetails = t.array(t.record(t.string, t.union([t.string, t.number])));
Expand Down

0 comments on commit 2abe85b

Please sign in to comment.