Skip to content

Commit

Permalink
fix: don't swallow errors without checking its type and message
Browse files Browse the repository at this point in the history
  • Loading branch information
davidyuk committed Aug 3, 2022
1 parent 0478eed commit 7456b0f
Show file tree
Hide file tree
Showing 8 changed files with 33 additions and 13 deletions.
4 changes: 2 additions & 2 deletions src/aepp-wallet-communication/rpc/RpcClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,8 @@ export default class RpcClient <
}

const request = msg as JsonRpcRequest;
let result; let
error;
let result;
let error;
try {
if (!(request.method in this.#methods)) throw new RpcMethodNotFoundError();
const methodName = request.method as keyof LocalApi;
Expand Down
7 changes: 5 additions & 2 deletions src/chain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
*/
import { AE_AMOUNT_FORMATS, formatAmount } from './utils/amount-formatter';
import verifyTransaction, { ValidatorResult } from './tx/validator';
import { pause } from './utils/other';
import { isAccountNotFoundError, pause } from './utils/other';
import { isNameValid, produceNameId } from './tx/builder/helpers';
import { DRY_RUN_ACCOUNT } from './tx/builder/schema';
import { AensName } from './tx/builder/constants';
Expand Down Expand Up @@ -267,7 +267,10 @@ export async function getBalance(
{ format = AE_AMOUNT_FORMATS.AETTOS, ...options }:
{ format?: AE_AMOUNT_FORMATS } & Parameters<typeof getAccount>[1],
): Promise<string> {
const { balance } = await getAccount(address, options).catch(() => ({ balance: 0n }));
const { balance } = await getAccount(address, options).catch((error) => {
if (!isAccountNotFoundError(error)) throw error;
return { balance: 0n };
});

return formatAmount(balance, { targetDenomination: format });
}
Expand Down
10 changes: 7 additions & 3 deletions src/contract/aci.ts
Original file line number Diff line number Diff line change
Expand Up @@ -390,9 +390,13 @@ export default async function getContractInstance({

const callerId = await Promise.resolve()
.then(() => opt.onAccount.address(opt))
.catch((error: any) => {
if (opt.callStatic === true) return DRY_RUN_ACCOUNT.pub;
throw error;
.catch((error) => {
const messageToSwallow = 'Account should be an address (ak-prefixed string), keypair, or instance of AccountBase, got undefined instead';
if (
opt.callStatic !== true || !(error instanceof TypeError)
|| error.message !== messageToSwallow
) throw error;
return DRY_RUN_ACCOUNT.pub;
}) as Encoded.AccountAddress;
const callData = instance.calldata.encode(instance._name, fn, params);

Expand Down
1 change: 1 addition & 0 deletions src/contract/ga.ts
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,7 @@ export async function createMetaTx(
authData: authCallData,
gasLimit,
vsn: 2,
nonce: 0,
};
// @ts-expect-error createMetaTx needs to be integrated into tx builder
const { fee } = await prepareTxParams(Tag.GaMetaTx, { ...params, onNode });
Expand Down
7 changes: 5 additions & 2 deletions src/tx/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ import {
import Node from '../Node';
import { Encoded } from '../utils/encoder';
import { buildTx as syncBuildTx, unpackTx } from './builder/index';
import { isKeyOfObject } from '../utils/other';
import { isAccountNotFoundError, isKeyOfObject } from '../utils/other';
import { AE_AMOUNT_FORMATS } from '../utils/amount-formatter';

type Int = number | string | BigNumber;
Expand Down Expand Up @@ -91,7 +91,10 @@ export async function prepareTxParams(
}: PrepareTxParamsOptions,
): Promise<{ ttl: number; nonce: number }> {
nonce ??= (
await onNode.getAccountNextNonce(senderId, { strategy }).catch(() => ({ nextNonce: 1 }))
await onNode.getAccountNextNonce(senderId, { strategy }).catch((error) => {
if (!isAccountNotFoundError(error)) throw error;
return { nextNonce: 1 };
})
).nextNonce;

if (ttl !== 0) {
Expand Down
7 changes: 5 additions & 2 deletions src/tx/validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
import { Tag } from './builder/constants';
import { TxUnpacked, unpackTx } from './builder';
import { UnsupportedProtocolError } from '../utils/errors';
import { concatBuffers, isKeyOfObject } from '../utils/other';
import { concatBuffers, isAccountNotFoundError, isKeyOfObject } from '../utils/other';
import {
decode, encode, Encoded, Encoding,
} from '../utils/encoder';
Expand Down Expand Up @@ -91,7 +91,10 @@ export default async function verifyTransaction(
address == null
? undefined
: node.getAccountByPubkey(address)
.catch(() => ({ id: address, balance: 0n, nonce: 0 }))
.catch((error) => {
if (!isAccountNotFoundError(error)) throw error;
return { id: address, balance: 0n, nonce: 0 };
})
// TODO: remove after fixing https://github.com/aeternity/aepp-sdk-js/issues/1537
.then((acc) => ({ ...acc, id: acc.id as Encoded.AccountAddress })),
node.getCurrentKeyBlockHeight(),
Expand Down
7 changes: 7 additions & 0 deletions src/utils/other.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { RestError } from '@azure/core-rest-pipeline';

export const pause = async (duration: number): Promise<void> => new Promise((resolve) => {
setTimeout(resolve, duration);
});
Expand Down Expand Up @@ -42,3 +44,8 @@ export function isKeyOfObject<T>(key: string | number | symbol, object: T): key
export function isItemOfArray<T>(item: any, array: readonly T[]): item is T {
return array.includes(item);
}

export function isAccountNotFoundError(error: Error): boolean {
return error instanceof RestError && error.statusCode === 404
&& error.message.includes('Account not found');
}
3 changes: 1 addition & 2 deletions test/integration/aens.ts
Original file line number Diff line number Diff line change
Expand Up @@ -189,8 +189,7 @@ describe('Aens', () => {
.aensBid(nameShort, bidFee, { onAccount });
bid.should.be.an('object');

const isAuctionFinished = await aeSdk.getName(nameShort).catch(() => false);
isAuctionFinished.should.be.equal(false);
await expect(aeSdk.getName(nameShort)).to.be.rejectedWith('error: Name not found');

if (bid.blockHeight == null) throw new UnexpectedTsError();
const auctionEndBlock = computeAuctionEndBlock(nameShort, bid.blockHeight);
Expand Down

0 comments on commit 7456b0f

Please sign in to comment.