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

Cherrypick - Extract and Log Contract Revert Reason (#1043) #1070

Merged
merged 1 commit into from
Apr 15, 2023
Merged
Show file tree
Hide file tree
Changes from all 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
13 changes: 12 additions & 1 deletion packages/relay/src/formatters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,4 +54,15 @@ const decodeErrorMessage = (message?: string): string => {
return hexToASCII(resultCodeHex);
};

export { hashNumber, formatRequestIdMessage, hexToASCII, decodeErrorMessage };
const formatTransactionId = (transactionId: string): string | null => {
if (!constants.TRANSACTION_ID_REGEX.test(transactionId)) {
return null;
}

var transactionSplit = transactionId.split("@");
const payer = transactionSplit[0];
const timestamp = transactionSplit[1].replace(".","-");
return `${payer}-${timestamp}`;
}

export { hashNumber, formatRequestIdMessage, hexToASCII, decodeErrorMessage, formatTransactionId };
16 changes: 15 additions & 1 deletion packages/relay/src/lib/clients/mirrorNodeClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import { MirrorNodeClientError } from './../errors/MirrorNodeClientError';
import { Logger } from "pino";
import constants from './../constants';
import { Histogram, Registry } from 'prom-client';
import { formatRequestIdMessage } from '../../formatters';
import { formatRequestIdMessage, formatTransactionId } from '../../formatters';
import axiosRetry from 'axios-retry';
import { predefined } from "../errors/JsonRpcError";
const LRU = require('lru-cache');
Expand Down Expand Up @@ -543,6 +543,20 @@ export class MirrorNodeClient {
return this.post(MirrorNodeClient.CONTRACT_CALL_ENDPOINT, callData, MirrorNodeClient.CONTRACT_CALL_ENDPOINT, [], requestId);
}

public async getTransactionById(transactionId: string, nonce: number | undefined, requestId?: string) {
const formattedId = formatTransactionId(transactionId);
if (formattedId == null) {
return formattedId;
}
const queryParamObject = {};
this.setQueryParam(queryParamObject, 'nonce', nonce);
const queryParams = this.getQueryParams(queryParamObject);
return this.get(`${MirrorNodeClient.GET_TRANSACTIONS_ENDPOINT}/${formattedId}${queryParams}`,
MirrorNodeClient.GET_STATE_ENDPOINT,
[400, 404],
requestId);
}

getQueryParams(params: object) {
let paramString = '';
for (const [key, value] of Object.entries(params)) {
Expand Down
6 changes: 3 additions & 3 deletions packages/relay/src/lib/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,6 @@ enum CACHE_KEY {
GAS_PRICE = 'gas_price',
FEE_HISTORY = 'fee_history',
GET_CONTRACT_RESULT = 'getContractResult'


}

enum CACHE_TTL {
Expand Down Expand Up @@ -67,5 +65,7 @@ export default {
MAX_MIRROR_NODE_PAGINATION: 20,
MIRROR_NODE_QUERY_LIMIT: 100,
NEXT_LINK_PREFIX: '/api/v1/',
QUERY_COST_INCREMENTATION_STEP: 1.1
QUERY_COST_INCREMENTATION_STEP: 1.1,

TRANSACTION_ID_REGEX: /\d{1}\.\d{1}\.\d{1,10}\@\d{1,10}\.\d{1,9}/
};
4 changes: 4 additions & 0 deletions packages/relay/src/lib/errors/SDKClientError.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,10 @@ export class SDKClientError extends Error {
return this.statusCode === Status.InsufficientTxFee._code;
}

public isContractRevertExecuted(): boolean {
return this.statusCode == Status.ContractRevertExecuted._code;
}

public isGrpcTimeout(): boolean {
// The SDK uses the same code for Grpc Timeout as INVALID_TRANSACTION_ID
return this.statusCode === Status.InvalidTransactionId._code;
Expand Down
23 changes: 23 additions & 0 deletions packages/relay/src/lib/eth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -894,6 +894,9 @@ export class EthImpl implements Eth {

return EthImpl.prepend0x(Buffer.from(record.ethereumHash).toString('hex'));
} catch (e) {

await this.extractContractRevertReason(e, requestId, requestIdPrefix);

this.logger.error(e,
`${requestIdPrefix} Failed sendRawTransaction during record retrieval for transaction ${transaction}, returning computed hash`);
//Return computed hash if unable to retrieve EthereumHash from record due to error
Expand All @@ -909,6 +912,26 @@ export class EthImpl implements Eth {
}
}

/**
* Check if transaction fail is because of contract revert and try to fetch and log the reason.
*
* @param e
* @param requestId
* @param requestIdPrefix
*/
private async extractContractRevertReason(e: any, requestId: string | undefined, requestIdPrefix: string) {
if (e instanceof SDKClientError && e.isContractRevertExecuted()) {
const transactionId = e.message.match(constants.TRANSACTION_ID_REGEX);
if (transactionId) {
const tx = await this.mirrorNodeClient.getTransactionById(transactionId[0], undefined, requestId);
if (tx.transactions.length > 1) {
const result = tx.transactions[1].result;
this.logger.error(`${requestIdPrefix} Transaction failed with result: ${result}`);
}
}
}
}

/**
* Execute a free contract call query.
*
Expand Down
16 changes: 15 additions & 1 deletion packages/relay/tests/lib/formatters.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { expect } from 'chai';
import { hexToASCII, decodeErrorMessage } from '../../src/formatters';
import { hexToASCII, decodeErrorMessage, formatTransactionId } from '../../src/formatters';

describe('Formatters', () => {
describe('hexToASCII', () => {
Expand Down Expand Up @@ -43,4 +43,18 @@ describe('Formatters', () => {
}
});
});

describe('formatTransactionId', () => {
const validInputTimestamp = '[email protected]';
const validOutputTimestamp = '0.0.2-1234567890-123456789';
const invalidInputTimestamp = '[email protected]';

it('should return correct formated transaction id', () => {
expect(formatTransactionId(validInputTimestamp)).to.eq(validOutputTimestamp);
});

it('should return null', () => {
expect(formatTransactionId(invalidInputTimestamp)).to.eq(null);
})
})
});
71 changes: 71 additions & 0 deletions packages/relay/tests/lib/mirrorNodeClient.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -698,6 +698,77 @@ describe('MirrorNodeClient', async function () {
});
});

describe('getTransactionById', async() => {
const defaultTransactionId = '[email protected]';
const defaultTransactionIdFormatted = '0.0.2-1681130064-409933500';
const invalidTransactionId = '[email protected]';
const defaultTransaction = {
transactions: [
{
bytes: null,
charged_tx_fee: 56800000,
consensus_timestamp: '1681130077.127938923',
entity_id: null,
max_fee: '1080000000',
memo_base64: '',
name: 'ETHEREUMTRANSACTION',
node: '0.0.3',
nonce: 0,
parent_consensus_timestamp: null,
result: 'CONTRACT_REVERT_EXECUTED',
scheduled: false,
staking_reward_transfers: [],
transaction_hash: 'uUHtwzFBlpHzp20OCJtjk4m6yFi93TZem7pKYrjgaF0v383um84g/Jo+uP2IrRd7',
transaction_id: '0.0.2-1681130064-409933500',
transfers: [],
valid_duration_seconds: '120',
valid_start_timestamp: '1681130064.409933500'
},
{
bytes: null,
charged_tx_fee: 0,
consensus_timestamp: '1681130077.127938924',
entity_id: null,
max_fee: '0',
memo_base64: '',
name: 'TOKENCREATION',
node: null,
nonce: 1,
parent_consensus_timestamp: '1681130077.127938923',
result: 'INVALID_FULL_PREFIX_SIGNATURE_FOR_PRECOMPILE',
scheduled: false,
staking_reward_transfers: [],
transaction_hash: 'EkQUvik9b4QUvymTNX90ybTz1SNobpQ5huQmMCKkP3fjOxirLT0nRel+w4bweXyX',
transaction_id: '0.0.2-1681130064-409933500',
transfers: [],
valid_duration_seconds: null,
valid_start_timestamp: '1681130064.409933500'
}
]
};

it('should be able to fetch transaction by transaction id', async() => {
mock.onGet(`transactions/${defaultTransactionIdFormatted}`).reply(200, defaultTransaction);
const transaction = await mirrorNodeInstance.getTransactionById(defaultTransactionId);
expect(transaction).to.exist;
expect(transaction.transactions.length).to.equal(defaultTransaction.transactions.length);
});

it('should be able to fetch transaction by transaction id and nonce', async() => {
mock.onGet(`transactions/${defaultTransactionIdFormatted}?nonce=1`).reply(200, defaultTransaction.transactions[1]);
const transaction = await mirrorNodeInstance.getTransactionById(defaultTransactionId, 1);
expect(transaction).to.exist;
expect(transaction.transaction_id).to.equal(defaultTransaction.transactions[1].transaction_id);
expect(transaction.result).to.equal(defaultTransaction.transactions[1].result);
});

it('should fail to fetch transaction by wrong transaction id', async() => {
mock.onGet(`transactions/${invalidTransactionId}`).reply(404, mockData.notFound);
const transaction = await mirrorNodeInstance.getTransactionById(invalidTransactionId);
expect(transaction).to.be.null;
});
})

describe('getPaginatedResults', async() => {

const mockPages = (pages) => {
Expand Down