Skip to content

Commit

Permalink
fix(tx-builder): avoid extra requests in tx validator
Browse files Browse the repository at this point in the history
  • Loading branch information
davidyuk committed Aug 6, 2022
1 parent 29e20ea commit 03c77e5
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 3 deletions.
14 changes: 12 additions & 2 deletions src/tx/validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { concatBuffers, isAccountNotFoundError, isKeyOfObject } from '../utils/o
import { encode, Encoded, Encoding } from '../utils/encoder';
import Node, { TransformNodeType } from '../Node';
import { Account } from '../apis/node';
import { genAggressiveCacheGetResponsesPolicy } from '../utils/autorest';

export interface ValidatorResult {
message: string;
Expand Down Expand Up @@ -68,16 +69,25 @@ const getSenderAddress = (
* to make sure it can be posted it to the chain
* @category transaction builder
* @param transaction - Base64Check-encoded transaction
* @param node - Node to validate transaction against
* @param nodeNotCached - Node to validate transaction against
* @param parentTxTypes - Types of parent transactions
* @returns Array with verification errors
* @example const errors = await verifyTransaction(transaction, node)
*/
export default async function verifyTransaction(
transaction: Encoded.Transaction | Encoded.Poi,
node: Node,
nodeNotCached: Node,
parentTxTypes: Tag[] = [],
): Promise<ValidatorResult[]> {
let node = nodeNotCached;
if (
!node.pipeline.getOrderedPolicies()
.some(({ name }) => name === 'aggressive-cache-get-responses')
) {
node = new Node(nodeNotCached.$host, { ignoreVersion: true });
node.pipeline.addPolicy(genAggressiveCacheGetResponsesPolicy());
}

const { tx, txType } = unpackTx<Tag.SignedTx>(transaction);
const address = getSenderAddress(tx)
?? (txType === Tag.SignedTx ? getSenderAddress(tx.encodedTx.tx) : undefined);
Expand Down
17 changes: 16 additions & 1 deletion src/utils/autorest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export const genCombineGetRequestsPolicy = (): AdditionalPolicyConfig => {

return {
policy: {
name: 'combine-requests',
name: 'combine-get-requests',
async sendRequest(request, next) {
if (request.method !== 'GET') return next(request);
const key = JSON.stringify([request.url, request.body]);
Expand All @@ -48,6 +48,21 @@ export const genCombineGetRequestsPolicy = (): AdditionalPolicyConfig => {
};
};

export const genAggressiveCacheGetResponsesPolicy = (): PipelinePolicy => {
const getRequests = new Map<string, Promise<PipelineResponse>>();

return {
name: 'aggressive-cache-get-responses',
async sendRequest(request, next) {
if (request.method !== 'GET') return next(request);
const key = JSON.stringify([request.url, request.body]);
const response = getRequests.get(key) ?? next(request);
getRequests.set(key, response);
return response;
},
};
};

export const genErrorFormatterPolicy = (
getMessage: (b: any) => string,
): AdditionalPolicyConfig => ({
Expand Down
15 changes: 15 additions & 0 deletions test/integration/chain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,21 @@ describe('Node Chain', () => {
isConfirmed2.should.be.equal(true);
});

it('doesn\'t make extra requests', async () => {
const httpSpy = spy(http, 'request');
await aeSdk.spend(100, publicKey, { waitMined: false, verify: false });
expect(httpSpy.args.length).to.be.equal(2); // nonce, post tx
httpSpy.resetHistory();

await aeSdk.spend(100, publicKey, { waitMined: false, verify: false });
expect(httpSpy.args.length).to.be.equal(2); // nonce, post tx
httpSpy.resetHistory();

await aeSdk.spend(100, publicKey, { waitMined: false });
expect(httpSpy.args.length).to.be.equal(5); // nonce, validator(acc, height, status), post tx
httpSpy.restore();
});

const accounts = new Array(10).fill(undefined).map(() => MemoryAccount.generate());
const transactions: Encoded.TxHash[] = [];

Expand Down

0 comments on commit 03c77e5

Please sign in to comment.