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

Add support for sendTransaction error fetching #59

Merged
merged 6 commits into from
Sep 6, 2023
Merged
Show file tree
Hide file tree
Changes from 3 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
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@gnolang/tm2-js-client",
"version": "1.0.4",
"version": "1.0.5",
"description": "Tendermint2 JS / TS Client",
"main": "./bin/index.js",
"repository": {
Expand Down
52 changes: 40 additions & 12 deletions src/provider/jsonrpc/jsonrpc.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import {
ABCIResponse,
BlockInfo,
BlockResult,
BroadcastTxResult,
BroadcastTxSyncResult,
ConsensusParams,
NetworkInfo,
RPCRequest,
Expand Down Expand Up @@ -69,20 +69,48 @@ describe('JSON-RPC Provider', () => {
expect(result).toEqual(mockResult);
});

test('sendTransaction', async () => {
const mockResult: BroadcastTxResult = mock<BroadcastTxResult>();
mockResult.hash = 'hash123';
describe('sendTransaction', () => {
const validResult: BroadcastTxSyncResult = {
error: null,
data: null,
Log: '',
hash: 'hash123',
};

mockedAxios.post.mockResolvedValue({
data: newResponse<BroadcastTxResult>(mockResult),
});
const mockError = '/std.UnauthorizedError';
const mockLog = 'random error message';
const invalidResult: BroadcastTxSyncResult = {
error: {
ABCIErrorKey: mockError,
},
data: null,
Log: mockLog,
hash: '',
};

// Create the provider
const provider = new JSONRPCProvider(mockURL);
const hash = await provider.sendTransaction('encoded tx');
test.each([
[validResult, validResult.hash, ''], // no error
[invalidResult, invalidResult.hash, `${mockError}: ${mockLog}`], // error out
])('case %#', async (response, expectedHash, expectedErr) => {
mockedAxios.post.mockResolvedValue({
data: newResponse<BroadcastTxSyncResult>(response),
});

expect(axios.post).toHaveBeenCalled();
expect(hash).toEqual(mockResult.hash);
try {
// Create the provider
const provider = new JSONRPCProvider(mockURL);
const hash = await provider.sendTransaction('encoded tx');

expect(axios.post).toHaveBeenCalled();
expect(hash).toEqual(expectedHash);

if (expectedErr != '') {
fail('expected error');
}
} catch (e) {
expect((e as Error).message).toContain(expectedErr);
}
});
});

test('waitForTransaction', async () => {
Expand Down
69 changes: 64 additions & 5 deletions src/provider/jsonrpc/jsonrpc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@ import {
ABCIResponse,
BlockInfo,
BlockResult,
BroadcastTxResult,
BroadcastTxCommitResult,
BroadcastTxSyncResult,
ConsensusParams,
NetworkInfo,
RPCRequest,
Status,
} from '../types';
import { RestService } from '../../services';
Expand Down Expand Up @@ -143,12 +145,69 @@ export class JSONRPCProvider implements Provider {
});
}

async sendTransaction(tx: string): Promise<string> {
const response: BroadcastTxResult =
await RestService.post<BroadcastTxResult>(this.baseURL, {
request: newRequest(TransactionEndpoint.BROADCAST_TX_SYNC, [tx]),
async sendTransaction(
tx: string,
endpoint?:
| TransactionEndpoint.BROADCAST_TX_SYNC
| TransactionEndpoint.BROADCAST_TX_COMMIT
): Promise<string> {
const queryEndpoint = endpoint
? endpoint
: TransactionEndpoint.BROADCAST_TX_SYNC;

const request: RPCRequest = newRequest(queryEndpoint, [tx]);

if (queryEndpoint == TransactionEndpoint.BROADCAST_TX_SYNC) {
return this.broadcastTxSync(request);
}

// The endpoint is a commit broadcast
// (it waits for the transaction to be committed) to the chain before returning
return this.broadcastTxCommit(request);
}

private async broadcastTxSync(request: RPCRequest): Promise<string> {
const response: BroadcastTxSyncResult =
await RestService.post<BroadcastTxSyncResult>(this.baseURL, {
request,
});

// Check if there is an immediate tx-broadcast error
// (originating from basic transaction checks like CheckTx)
if (response.error) {
const errType: string = response.error.ABCIErrorKey;
const log: string = response.Log;

throw new Error(`${errType}: ${log}`);
}

return response.hash;
}

private async broadcastTxCommit(request: RPCRequest): Promise<string> {
const response: BroadcastTxCommitResult =
await RestService.post<BroadcastTxCommitResult>(this.baseURL, {
request,
});

const { check_tx, deliver_tx } = response;

// Check if there is an immediate tx-broadcast error (in CheckTx)
if (check_tx.ResponseBase.Error) {
const errType: string = check_tx.ResponseBase.Error.ABCIErrorKey;
const log: string = check_tx.ResponseBase.Log;

throw new Error(`${errType}: ${log}`);
}

// Check if there is a parsing error with the transaction (in DeliverTx)
if (deliver_tx.ResponseBase.Error) {
const errType: string = deliver_tx.ResponseBase.Error.ABCIErrorKey;
const log: string = deliver_tx.ResponseBase.Log;

throw new Error(`${errType}: ${log}`);
}

return response.hash;
}

Expand Down
10 changes: 9 additions & 1 deletion src/provider/provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
Status,
} from './types';
import { Tx } from '../proto';
import { TransactionEndpoint } from './endpoints';

/**
* Read-only abstraction for accessing blockchain data
Expand Down Expand Up @@ -96,8 +97,15 @@ export interface Provider {
* The transaction needs to be signed beforehand.
* Returns the transaction hash
* @param {string} tx the base64-encoded signed transaction
* @param {TransactionEndpoint} endpoint the transaction broadcast type (sync / commit).
* Defaults to broadcast_sync
*/
sendTransaction(tx: string): Promise<string>;
sendTransaction(
tx: string,
endpoint?:
| TransactionEndpoint.BROADCAST_TX_SYNC
| TransactionEndpoint.BROADCAST_TX_COMMIT
): Promise<string>;

/**
* Waits for the transaction to be committed on the chain.
Expand Down
9 changes: 8 additions & 1 deletion src/provider/types/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,7 @@ export interface BeginBlock {
ResponseBase: ABCIResponseBase;
}

export interface BroadcastTxResult {
export interface BroadcastTxSyncResult {
error: {
// ABCIErrorKey
[key: string]: string;
Expand All @@ -267,3 +267,10 @@ export interface BroadcastTxResult {

hash: string;
}

export interface BroadcastTxCommitResult {
check_tx: DeliverTx;
deliver_tx: DeliverTx;
hash: string;
height: string; // decimal number
}
40 changes: 33 additions & 7 deletions src/provider/websocket/ws.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {
BeginBlock,
BlockInfo,
BlockResult,
BroadcastTxResult,
BroadcastTxSyncResult,
ConsensusParams,
EndBlock,
NetworkInfo,
Expand All @@ -17,6 +17,8 @@ import WS from 'jest-websocket-mock';
import { Tx } from '../../proto';
import { sha256 } from '@cosmjs/crypto';
import { CommonEndpoint } from '../endpoints';
import { JSONRPCProvider } from '../jsonrpc';
import axios from 'axios/index';

describe('WS Provider', () => {
const wsPort = 8545;
Expand Down Expand Up @@ -250,19 +252,43 @@ describe('WS Provider', () => {
expect(blockNumber).toBe(expectedBlockNumber);
});

test('sendTransaction', async () => {
const mockResult: BroadcastTxResult = {
describe('sendTransaction', () => {
const validResult: BroadcastTxSyncResult = {
error: null,
data: null,
Log: '',
hash: 'hash123',
};

// Set the response
await setHandler<BroadcastTxResult>(mockResult);
const mockError = '/std.UnauthorizedError';
const mockLog = 'random error message';
const invalidResult: BroadcastTxSyncResult = {
error: {
ABCIErrorKey: mockError,
},
data: null,
Log: mockLog,
hash: '',
};

const hash: string = await wsProvider.sendTransaction('encoded tx');
expect(hash).toBe(mockResult.hash);
test.each([
[validResult, validResult.hash, ''], // no error
[invalidResult, invalidResult.hash, `${mockError}: ${mockLog}`], // error out
])('case %#', async (response, expectedHash, expectedErr) => {
await setHandler<BroadcastTxSyncResult>(response);

try {
const hash = await wsProvider.sendTransaction('encoded tx');

expect(hash).toEqual(expectedHash);

if (expectedErr != '') {
fail('expected error');
}
} catch (e) {
expect((e as Error).message).toContain(expectedErr);
}
});
});

const getEmptyBlockInfo = (): BlockInfo => {
Expand Down
73 changes: 67 additions & 6 deletions src/provider/websocket/ws.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ import {
ABCIResponse,
BlockInfo,
BlockResult,
BroadcastTxResult,
BroadcastTxCommitResult,
BroadcastTxSyncResult,
ConsensusParams,
NetworkInfo,
RPCRequest,
Expand Down Expand Up @@ -255,12 +256,72 @@ export class WSProvider implements Provider {
return this.parseResponse<Status>(response);
}

async sendTransaction(tx: string): Promise<string> {
const response = await this.sendRequest<BroadcastTxResult>(
newRequest(TransactionEndpoint.BROADCAST_TX_SYNC, [tx])
);
async sendTransaction(
tx: string,
endpoint?:
| TransactionEndpoint.BROADCAST_TX_SYNC
| TransactionEndpoint.BROADCAST_TX_COMMIT
): Promise<string> {
const queryEndpoint = endpoint
? endpoint
: TransactionEndpoint.BROADCAST_TX_SYNC;

const request: RPCRequest = newRequest(queryEndpoint, [tx]);

if (queryEndpoint == TransactionEndpoint.BROADCAST_TX_SYNC) {
return this.broadcastTxSync(request);
}

// The endpoint is a commit broadcast
// (it waits for the transaction to be committed) to the chain before returning
return this.broadcastTxCommit(request);
}

private async broadcastTxSync(request: RPCRequest): Promise<string> {
const response: RPCResponse<BroadcastTxSyncResult> =
await this.sendRequest<BroadcastTxSyncResult>(request);

const broadcastResponse: BroadcastTxSyncResult =
this.parseResponse<BroadcastTxSyncResult>(response);

// Check if there is an immediate tx-broadcast error
// (originating from basic transaction checks like CheckTx)
if (broadcastResponse.error) {
const errType: string = broadcastResponse.error.ABCIErrorKey;
const log: string = broadcastResponse.Log;

throw new Error(`${errType}: ${log}`);
}

return broadcastResponse.hash;
}

private async broadcastTxCommit(request: RPCRequest): Promise<string> {
const response: RPCResponse<BroadcastTxCommitResult> =
await this.sendRequest<BroadcastTxCommitResult>(request);

const broadcastResponse: BroadcastTxCommitResult =
this.parseResponse<BroadcastTxCommitResult>(response);

const { check_tx, deliver_tx } = broadcastResponse;

// Check if there is an immediate tx-broadcast error (in CheckTx)
if (check_tx.ResponseBase.Error) {
const errType: string = check_tx.ResponseBase.Error.ABCIErrorKey;
const log: string = check_tx.ResponseBase.Log;

throw new Error(`${errType}: ${log}`);
}

// Check if there is a parsing error with the transaction (in DeliverTx)
if (deliver_tx.ResponseBase.Error) {
const errType: string = deliver_tx.ResponseBase.Error.ABCIErrorKey;
const log: string = deliver_tx.ResponseBase.Log;

throw new Error(`${errType}: ${log}`);
}

return this.parseResponse<BroadcastTxResult>(response).hash;
return broadcastResponse.hash;
}

waitForTransaction(
Expand Down