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

feat: add response check for Paraswap API #99

Merged
merged 4 commits into from
Nov 26, 2024
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
1 change: 1 addition & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ module.exports = {
'^.+\\.(js|jsx)$': 'babel-jest',
},
transformIgnorePatterns: [`/node_modules/(?!micro-eth-signer)`],
modulePathIgnorePatterns: ['<rootDir>/dist/'],
globals: {
EVM_PROVIDER_INFO_NAME: 'EVM_PROVIDER_INFO_NAME',
EVM_PROVIDER_INFO_UUID: 'EVM_PROVIDER_INFO_UUID',
Expand Down
124 changes: 124 additions & 0 deletions src/contexts/SwapProvider/SwapProvider.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -481,10 +481,22 @@ describe('contexts/SwapProvider', () => {
let requestMock;

const mockedTx = {
gas: '0x2710', // 10000n
data: 'approval-tx-data',
};

beforeEach(() => {
jest.spyOn(global, 'fetch').mockResolvedValue({
json: jest.fn().mockResolvedValue({
data: 'data',
to: '0xParaswapContractAddress',
from: '0x123',
value: '0x0',
gas: '1223',
chainId: 123,
}),
} as any);

allowanceMock = jest.fn().mockResolvedValue(0);
requestMock = jest.fn().mockResolvedValue('0xALLOWANCE_HASH');

Expand Down Expand Up @@ -528,6 +540,10 @@ describe('contexts/SwapProvider', () => {
json: jest.fn().mockResolvedValue({
data: 'data',
to: '0xParaswapContractAddress',
from: '0x123',
value: '0x0',
chainId: 123,
someExtraParam: '123',
}),
} as any);

Expand Down Expand Up @@ -585,13 +601,121 @@ describe('contexts/SwapProvider', () => {
);
});

it('verifies Paraswap API response for correct parameters', async () => {
const requestMock = jest.fn();

jest.spyOn(global, 'fetch').mockResolvedValue({
json: jest.fn().mockResolvedValue({
data: '',
to: '',
from: '0x123',
value: '0x0',
chainId: 123,
}),
} as any);

jest.mocked(Contract).mockReturnValueOnce({
allowance: jest.fn().mockResolvedValue(Infinity),
} as any);

jest.mocked(useConnectionContext).mockReturnValue({
request: requestMock.mockResolvedValue('0xSwapHash'),
events: jest.fn(),
} as any);

const { swap } = getSwapProvider();

const {
destAmount,
destDecimals,
destToken,
srcAmount,
srcDecimals,
srcToken,
priceRoute,
gasLimit,
slippage,
} = getSwapParams();

await expect(
swap({
srcToken,
srcDecimals,
srcAmount,
destToken,
destDecimals,
destAmount,
gasLimit,
priceRoute,
slippage,
})
).rejects.toThrow('Data Error: Error: Invalid transaction params');
});

it('handles Paraswap API error responses', async () => {
const requestMock = jest.fn();

jest.spyOn(global, 'fetch').mockResolvedValue({
json: jest
.fn()
.mockResolvedValue({ message: 'Some API error happened' }),
} as any);

jest.mocked(Contract).mockReturnValueOnce({
allowance: jest.fn().mockResolvedValue(Infinity),
} as any);

jest.mocked(useConnectionContext).mockReturnValue({
request: requestMock.mockResolvedValue('0xSwapHash'),
events: jest.fn(),
} as any);

const { swap } = getSwapProvider();

const {
destAmount,
destDecimals,
destToken,
srcAmount,
srcDecimals,
srcToken,
priceRoute,
gasLimit,
slippage,
} = getSwapParams();

await expect(
swap({
srcToken,
srcDecimals,
srcAmount,
destToken,
destDecimals,
destAmount,
gasLimit,
priceRoute,
slippage,
})
).rejects.toThrow('Data Error: Error: Some API error happened');
});

describe('when everything goes right', () => {
let allowanceMock;
let requestMock;

beforeEach(() => {
allowanceMock = jest.fn().mockResolvedValue(0);

jest.spyOn(global, 'fetch').mockResolvedValue({
json: async () => ({
data: 'data',
to: '0xParaswapContractAddress',
from: '0x123',
value: '0x0',
chainId: 123,
}),
} as any);

requestMock = jest
.fn()
.mockResolvedValueOnce('0xALLOWANCE_HASH')
Expand Down
32 changes: 29 additions & 3 deletions src/contexts/SwapProvider/SwapProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ import {
hasParaswapError,
DISALLOWED_SWAP_ASSETS,
} from './models';
import Joi from 'joi';
import { isAPIError } from '@src/pages/Swap/utils';

export const SwapContext = createContext<SwapContextAPI>({} as any);

Expand Down Expand Up @@ -198,6 +200,16 @@ export function SwapContextProvider({ children }: { children: any }) {
throw new Error(`Feature (SWAP) is currently unavailable`);
}

const responseSchema = Joi.object({
to: Joi.string().required(),
from: Joi.string().required(),
value: Joi.string().required(),
data: Joi.string().required(),
chainId: Joi.number().required(),
gas: Joi.string().optional(),
gasPrice: Joi.string().optional(),
}).unknown();

const query = new URLSearchParams(options as Record<string, string>);
const txURL = `${
(paraswap as any).apiURL
Expand Down Expand Up @@ -226,7 +238,20 @@ export function SwapContextProvider({ children }: { children: any }) {
},
body: JSON.stringify(txConfig),
});
return await response.json();
const transactionParamsOrError: Transaction | APIError =
await response.json();
const validationResult = responseSchema.validate(
transactionParamsOrError
);

if (!response.ok || validationResult.error) {
if (isAPIError(transactionParamsOrError)) {
throw new Error(transactionParamsOrError.message);
}
throw new Error('Invalid transaction params');
}

return transactionParamsOrError;
},
[featureFlags, paraswap]
);
Expand Down Expand Up @@ -363,7 +388,8 @@ export function SwapContextProvider({ children }: { children: any }) {
params: [
{
chainId: ChainId.AVALANCHE_MAINNET_ID.toString(),
gasLimit: String(approveGasLimit || gasLimit),
gas:
'0x' + Number(approveGasLimit || gasLimit).toString(16),
data,
from: activeAccount.addressC,
to: srcTokenAddress,
Expand Down Expand Up @@ -430,7 +456,7 @@ export function SwapContextProvider({ children }: { children: any }) {
params: [
{
chainId: ChainId.AVALANCHE_MAINNET_ID.toString(),
gasLimit: String(txBuildData.gas),
gas: '0x' + Number(txBuildData.gas).toString(16),
data: txBuildData.data,
to: txBuildData.to,
from: activeAccount.addressC,
Expand Down
Loading