@@ -34,26 +34,47 @@ export const jsonRpcComplianceLayer = async (
3434 status : number | undefined ;
3535 } & ParameterizedContext ,
3636) => {
37- if ( ! ctx . body ) {
37+ const fallback = FALLBACK_RESPONSE_BODY ;
38+
39+ const setBadRequest = ( ) => {
3840 ctx . status = 400 ;
39- ctx . body = FALLBACK_RESPONSE_BODY ;
41+ ctx . body = fallback ;
42+ } ;
43+
44+ const ensureBaseFields = ( ) => {
45+ ctx . body . jsonrpc ||= fallback . jsonrpc ;
46+ ctx . body . id ||= fallback . id ;
47+ } ;
48+
49+ const normalizeErrorStatus = ( ) => {
50+ const isBadReq = ctx . status === 400 ;
51+ const missingError = ! ctx . body . error || ! ctx . body . error . code ;
52+
53+ if ( isBadReq && missingError ) ctx . body . error = fallback . error ;
54+ if ( isBadReq && VALID_JSON_RPC_HTTP_REQUESTS_STATUS_CODE ) ctx . status = 200 ;
55+ } ;
56+
57+ if ( ! ctx . body ) {
58+ setBadRequest ( ) ;
4059 return ;
4160 }
4261
43- // Always return 200 for array requests.
4462 if ( Array . isArray ( ctx . body ) ) {
4563 ctx . status = 200 ;
4664 return ;
4765 }
66+
4867 if ( typeof ctx . body !== 'object' ) {
49- ctx . status = 400 ;
50- ctx . body = FALLBACK_RESPONSE_BODY ;
68+ setBadRequest ( ) ;
5169 return ;
5270 }
5371
54- if ( ! ctx . body . jsonrpc ) ctx . body . jsonrpc = FALLBACK_RESPONSE_BODY . jsonrpc ;
55- if ( ! ctx . body . id ) ctx . body . id = FALLBACK_RESPONSE_BODY . id ;
56- if ( ctx . status === 200 && ! ctx . body . result ) ctx . body . result = '0x' ;
57- if ( ctx . status === 400 && ( ! ctx . body . error || ! ctx . body . error . code ) ) ctx . body . error = FALLBACK_RESPONSE_BODY . error ;
58- if ( ctx . status === 400 && VALID_JSON_RPC_HTTP_REQUESTS_STATUS_CODE ) ctx . status = 200 ;
72+ ensureBaseFields ( ) ;
73+
74+ if ( ctx . status === 200 && ! ctx . body . result ) {
75+ ctx . body . result = '0x' ;
76+ }
77+
78+ normalizeErrorStatus ( ) ;
5979} ;
80+
0 commit comments