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

Display user-friendly messages for JSON RPC errors #1275

Merged
merged 16 commits into from
Feb 8, 2024
Merged
Show file tree
Hide file tree
Changes from 14 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
11 changes: 11 additions & 0 deletions .changeset/red-mice-argue.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
"@near-js/providers": minor
"@near-js/utils": minor
---

Display user-friendly messages for JSON RPC errors:

- MethodNotFound
- CodeDoesNotExist
- AccessKeyDoesNotExist
- AccountDoesNotExist
109 changes: 101 additions & 8 deletions packages/accounts/test/providers.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,20 @@ const BN = require('bn.js');
const base58 = require('bs58');

const testUtils = require('./test-utils');
const { KeyPair } = require('@near-js/crypto');
let ERRORS_JSON = require('../../utils/lib/errors/error_messages.json');

jest.setTimeout(20000);
jest.setTimeout(60000);

describe('providers', () => {
let provider;
let near;
let provider;
let near;

beforeAll(async () => {
near = await testUtils.setUpTestConnection();
provider = near.connection.provider;
});
beforeAll(async () => {
near = await testUtils.setUpTestConnection();
provider = near.connection.provider;
});

describe('providers', () => {
test('txStatus with string hash and buffer hash', async () => {
const sender = await testUtils.createAccount(near);
const receiver = await testUtils.createAccount(near);
Expand Down Expand Up @@ -188,3 +190,94 @@ describe('providers', () => {
await expect(provider.lightClientProof(lightClientRequest)).rejects.toThrow(/.+ block .+ is ahead of head block .+/);
});
});

describe('providers errors', () => {
test('JSON RPC Error - MethodNotFound', async () => {
const account = await testUtils.createAccount(near);
const contract = await testUtils.deployContract(
account,
testUtils.generateUniqueString('test')
);

await contract.setValue({ args: { value: 'hello' } });

try {
const response = await provider.query({
request_type: 'call_function',
finality: 'optimistic',
account_id: contract.contractId,
method_name: 'methodNameThatDoesNotExist',
args_base64: '',
});
expect(response).toBeUndefined();
} catch (e) {
const errorType = 'MethodNotFound';
expect(e.type).toEqual(errorType);
expect(e.message).toEqual(ERRORS_JSON[errorType]);
}
});

test('JSON RPC Error - CodeDoesNotExist', async () => {
const { accountId } = await testUtils.createAccount(near);

try {
const response = await provider.query({
request_type: 'call_function',
finality: 'optimistic',
account_id: accountId,
method_name: 'methodNameThatDoesNotExistOnContractNotDeployed',
args_base64: '',
});
expect(response).toBeUndefined();
} catch (e) {
const errorType = 'CodeDoesNotExist';
expect(e.type).toEqual(errorType);
expect(e.message.split(' ').slice(0, 5)).toEqual(
ERRORS_JSON[errorType].split(' ').slice(0, 5)
);
}
});

test('JSON RPC Error - AccountDoesNotExist', async () => {
const accountName = 'abc.near';
try {
const response = await provider.query({
request_type: 'call_function',
finality: 'optimistic',
account_id: accountName,
method_name: 'methodNameThatDoesNotExistOnContractNotDeployed',
args_base64: '',
});
expect(response).toBeUndefined();
} catch (e) {
const errorType = 'AccountDoesNotExist';
expect(e.type).toEqual(errorType);
expect(e.message.split(' ').slice(0, 5)).toEqual(
ERRORS_JSON[errorType].split(' ').slice(0, 5)
);
}
});

test('JSON RPC Error - AccessKeyDoesNotExist', async () => {
const { accountId } = await testUtils.createAccount(near);

try {
const response = await provider.query({
request_type: 'view_access_key',
finality: 'optimistic',
account_id: accountId,
public_key: KeyPair.fromRandom('ed25519')
.getPublicKey()
.toString(),
});
expect(response).toBeUndefined();
} catch (e) {
const errorType = 'AccessKeyDoesNotExist';
expect(e.type).toEqual(errorType);
expect(e.message.split(' ').slice(0, 5)).toEqual(
ERRORS_JSON[errorType].split(' ').slice(0, 5)
);
}
});
});

14 changes: 13 additions & 1 deletion packages/providers/src/json-rpc-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@
*/
import {
baseEncode,
formatError,
getErrorTypeFromErrorMessage,
Logger,
parseRpcError,
ServerError,
} from '@near-js/utils';
import {
AccessKeyWithPublicKey,
Expand Down Expand Up @@ -366,7 +368,17 @@ export class JsonRpcProvider extends Provider {
throw new TypedError(errorMessage, 'TimeoutError');
}

throw new TypedError(errorMessage, getErrorTypeFromErrorMessage(response.error.data, response.error.name));
const errorType = getErrorTypeFromErrorMessage(response.error.data, '');
if (errorType) {
throw new TypedError(formatError(errorType, params), errorType);
}
throw new TypedError(errorMessage, response.error.name);
}
} else if (typeof response.result?.error === 'string') {
const errorType = getErrorTypeFromErrorMessage(response.result.error, '');

if (errorType) {
throw new ServerError(formatError(errorType, params), errorType);
}
}
// Success when response.error is not exist
Expand Down
1 change: 1 addition & 0 deletions packages/utils/src/errors/error_messages.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
"AccountAlreadyExists": "Can't create a new account {{account_id}}, because it already exists",
"InvalidChain": "Transaction parent block hash doesn't belong to the current chain",
"AccountDoesNotExist": "Can't complete the action because account {{account_id}} doesn't exist",
"AccessKeyDoesNotExist": "Can't complete the action because access key {{public_key}} doesn't exist",
"MethodNameMismatch": "Transaction method name {{method_name}} isn't allowed by the access key",
"DeleteAccountHasRent": "Account {{account_id}} can't be deleted. It has {{#formatNear}}{{balance}}{{/formatNear}}, which is enough to cover the rent",
"DeleteAccountHasEnoughBalance": "Account {{account_id}} can't be deleted. It has {{#formatNear}}{{balance}}{{/formatNear}}, which is enough to cover it's storage",
Expand Down
4 changes: 4 additions & 0 deletions packages/utils/src/errors/rpc_errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,11 @@ export function getErrorTypeFromErrorMessage(errorMessage, errorType) {
case /^access key .*? does not exist while viewing$/.test(errorMessage):
return 'AccessKeyDoesNotExist';
case /wasm execution failed with error: FunctionCallError\(CompilationError\(CodeDoesNotExist/.test(errorMessage):
case /wasm execution failed with error: CompilationError\(CodeDoesNotExist/.test(errorMessage):
return 'CodeDoesNotExist';
case /wasm execution failed with error: FunctionCallError\(MethodResolveError\(MethodNotFound/.test(errorMessage):
case /wasm execution failed with error: MethodResolveError\(MethodNotFound/.test(errorMessage):
return 'MethodNotFound';
case /Transaction nonce \d+ must be larger than nonce of the used access key \d+/.test(errorMessage):
return 'InvalidNonce';
default:
Expand Down
16 changes: 8 additions & 8 deletions packages/utils/test/rpc-errors.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,8 @@ describe('rpc-errors', () => {
}
};
let error = parseRpcError(rpc_error);
expect(error.type === 'InvalidIteratorIndex').toBe(true);
expect(error.iterator_index).toBe(42);
expect(formatError(error.type, error)).toBe('Iterator index 42 does not exist');
expect(error.type).toBe('ActionError');
expect(error.message).toBe('{"kind":{"FunctionCallError":{"HostError":{"InvalidIteratorIndex":{"iterator_index":42}}}}}');
});

test('test ActionError::FunctionCallError::GasLimitExceeded error', async () => {
Expand All @@ -69,28 +68,29 @@ describe('rpc-errors', () => {
}
};
let error = parseRpcError(rpc_error);
expect(error.type === 'GasLimitExceeded').toBe(true);

expect(formatError(error.type, error)).toBe('Exceeded the maximum amount of gas allowed to burn per contract');
expect(error.type).toBe('ActionError');
expect(error.message).toBe('{"index":0,"kind":{"index":0,"kind":{"FunctionCallError":{"HostError":"GasLimitExceeded"}}}}');
});

test('test parse error object', async () => {
const errorStr = '{"status":{"Failure":{"ActionError":{"index":0,"kind":{"FunctionCallError":{"EvmError":"ArgumentParseError"}}}}},"transaction":{"signer_id":"test.near","public_key":"ed25519:D5HVgBE8KgXkSirDE4UQ8qwieaLAR4wDDEgrPRtbbNep","nonce":110,"receiver_id":"evm","actions":[{"FunctionCall":{"method_name":"transfer","args":"888ZO7SvECKvfSCJ832LrnFXuF/QKrSGztwAAA==","gas":300000000000000,"deposit":"0"}}],"signature":"ed25519:7JtWQ2Ux63ixaKy7bTDJuRTWnv6XtgE84ejFMMjYGKdv2mLqPiCfkMqbAPt5xwLWwFdKjJniTcxWZe7FdiRWpWv","hash":"E1QorKKEh1WLJwRQSQ1pdzQN3f8yeFsQQ8CbJjnz1ZQe"},"transaction_outcome":{"proof":[],"block_hash":"HXXBPjGp65KaFtam7Xr67B8pZVGujZMZvTmVW6Fy9tXf","id":"E1QorKKEh1WLJwRQSQ1pdzQN3f8yeFsQQ8CbJjnz1ZQe","outcome":{"logs":[],"receipt_ids":["ZsKetkrZQGVTtmXr2jALgNjzcRqpoQQsk9HdLmFafeL"],"gas_burnt":2428001493624,"tokens_burnt":"2428001493624000000000","executor_id":"test.near","status":{"SuccessReceiptId":"ZsKetkrZQGVTtmXr2jALgNjzcRqpoQQsk9HdLmFafeL"}}},"receipts_outcome":[{"proof":[],"block_hash":"H6fQCVpxBDv9y2QtmTVHoxHibJvamVsHau7fDi7AmFa2","id":"ZsKetkrZQGVTtmXr2jALgNjzcRqpoQQsk9HdLmFafeL","outcome":{"logs":[],"receipt_ids":["DgRyf1Wv3ZYLFvM8b67k2yZjdmnyUUJtRkTxAwoFi3qD"],"gas_burnt":2428001493624,"tokens_burnt":"2428001493624000000000","executor_id":"evm","status":{"Failure":{"ActionError":{"index":0,"kind":{"FunctionCallError":{"EvmError":"ArgumentParseError"}}}}}}},{"proof":[],"block_hash":"9qNVA235L9XdZ8rZLBAPRNBbiGPyNnMUfpbi9WxbRdbB","id":"DgRyf1Wv3ZYLFvM8b67k2yZjdmnyUUJtRkTxAwoFi3qD","outcome":{"logs":[],"receipt_ids":[],"gas_burnt":0,"tokens_burnt":"0","executor_id":"test.near","status":{"SuccessValue":""}}}]}';
const error = parseRpcError(JSON.parse(errorStr).status.Failure);
expect(error).toEqual(new ServerError('{"index":0,"kind":{"EvmError":"ArgumentParseError"}}'));
expect(error).toEqual(new ServerError('{"index":0,"kind":{"index":0,"kind":{"FunctionCallError":{"EvmError":"ArgumentParseError"}}}}'));
});

test('test getErrorTypeFromErrorMessage', () => {
const err1 = 'account random.near does not exist while viewing';
const err2 = 'Account random2.testnet doesn\'t exist';
const err3 = 'access key ed25519:DvXowCpBHKdbD2qutgfhG6jvBMaXyUh7DxrDSjkLxMHp does not exist while viewing';
const err4 = 'wasm execution failed with error: FunctionCallError(CompilationError(CodeDoesNotExist { account_id: "random.testnet" }))';
const err4 = 'wasm execution failed with error: CompilationError(CodeDoesNotExist { account_id: "random.testnet" })';
const err5 = '[-32000] Server error: Invalid transaction: Transaction nonce 1 must be larger than nonce of the used access key 1';
const err6 = 'wasm execution failed with error: MethodResolveError(MethodNotFound)';
expect(getErrorTypeFromErrorMessage(err1)).toEqual('AccountDoesNotExist');
expect(getErrorTypeFromErrorMessage(err2)).toEqual('AccountDoesNotExist');
expect(getErrorTypeFromErrorMessage(err3)).toEqual('AccessKeyDoesNotExist');
expect(getErrorTypeFromErrorMessage(err4)).toEqual('CodeDoesNotExist');
expect(getErrorTypeFromErrorMessage(err5)).toEqual('InvalidNonce');
expect(getErrorTypeFromErrorMessage(err6)).toEqual('MethodNotFound');
});

test('test NotEnoughBalance message uses human readable values', () => {
Expand Down
Loading