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 7 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": patch
"@near-js/utils": patch
---

Display user-friendly messages for JSON RPC errors:

- MethodNotFound
- CodeDoesNotExist
- AccessKeyDoesNotExist
- AccountDoesNotExist
denbite marked this conversation as resolved.
Show resolved Hide resolved
114 changes: 114 additions & 0 deletions packages/accounts/test/providers_errors.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
const { JsonRpcProvider } = require('@near-js/providers');
const testUtils = require('./test-utils');
let ERRORS_JSON = require('../../utils/lib/errors/error_messages.json');
const { KeyPair } = require('@near-js/crypto');

jest.setTimeout(30000);

const withProvider = (fn) => {
const config = Object.assign(
require('./config')(process.env.NODE_ENV || 'test')
);
const provider = new JsonRpcProvider({ url: config.nodeUrl });
return () => fn(provider);
};

test(
'JSON RPC Error: MethodNotFound',
withProvider(async (provider) => {
const near = await testUtils.setUpTestConnection();
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: 'final',
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',
withProvider(async (provider) => {
try {
const response = await provider.query({
request_type: 'call_function',
finality: 'final',
account_id: 'test.near',
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',
withProvider(async (provider) => {
const accountName = 'abc.near';
try {
const response = await provider.query({
request_type: 'call_function',
finality: 'final',
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',
withProvider(async (provider) => {
const near = await testUtils.setUpTestConnection();
const { accountId } = await testUtils.createAccount(near);

try {
const response = await provider.query({
request_type: 'view_access_key',
finality: 'final',
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
4 changes: 2 additions & 2 deletions packages/utils/fetch_error_schema.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ const https = require('https');
const fs = require('fs');

const ERROR_SCHEMA_URL =
'https://raw.githubusercontent.com/nearprotocol/nearcore/4c1149974ccf899dbcb2253a3e27cbab86dc47be/chain/jsonrpc/res/rpc_errors_schema.json';
const TARGET_SCHEMA_FILE_PATH = `${process.argv[2] || process.cwd()}/src/errors/rpc_error_schema.json'`;
'https://raw.githubusercontent.com/near/nearcore/master/chain/jsonrpc/res/rpc_errors_schema.json';
const TARGET_SCHEMA_FILE_PATH = `${process.argv[2] || process.cwd()}/src/errors/rpc_error_schema.json`;

https
.get(ERROR_SCHEMA_URL, resp => {
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
Loading