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: getSwap #503

Merged
merged 8 commits into from
Jun 11, 2024
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
5 changes: 5 additions & 0 deletions .changeset/honest-jeans-change.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@coinbase/onchainkit": minor
---

**feat**: add `getSwap` by @0xAlec #503
1 change: 1 addition & 0 deletions jest.config.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ module.exports = {
statements: 100,
},
},
maxWorkers: 1,
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is to enable serialization for bigint by jest

jestjs/jest#11617 (comment)

modulePathIgnorePatterns: ['<rootDir>/framegear/'],
setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
transform: {
Expand Down
1 change: 1 addition & 0 deletions src/definitions/swap.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export const CDP_LISTSWAPASSETS = 'cdp_listSwapAssets';
export const CDP_GETSWAPQUOTE = 'cdp_getSwapQuote';
export const CDP_GETSWAPTRADE = 'cdp_getSwapTrade';
Comment on lines 1 to +3
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thoughts on updating these to be snake case?

Suggested change
export const CDP_LISTSWAPASSETS = 'cdp_listSwapAssets';
export const CDP_GETSWAPQUOTE = 'cdp_getSwapQuote';
export const CDP_GETSWAPTRADE = 'cdp_getSwapTrade';
export const CDP_LIST_SWAP_ASSETS = 'cdp_listSwapAssets';
export const CDP_GET_SWAP_QUOTE = 'cdp_getSwapQuote';
export const CDP_GET_SWAP_TRADE = 'cdp_getSwapTrade';

6 changes: 4 additions & 2 deletions src/swap/core/getParamsForToken.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
import { formatDecimals } from './formatDecimals';
import type { GetQuoteParams, GetQuoteAPIParams } from '../types';
import type { SwapParams, SwapAPIParams, GetSwapParams } from '../types';
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These seem very similar to each other in terms of naming


/**
* Converts parameters with `Token` to ones with address. Additionally adds default values for optional request fields.
*/
export function getParamsForToken(params: GetQuoteParams): GetQuoteAPIParams {
export function getParamsForToken(params: SwapParams): SwapAPIParams {
const { from, to, amount, amountReference, isAmountInDecimals } = params;
const { fromAddress } = params as GetSwapParams;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we add more comments here, I am a bit confused. Like who needs fromAddress and how they use it. And when is not there, will just be empty?


const decimals = amountReference === 'from' ? from.decimals : to.decimals;

return {
fromAddress: fromAddress,
from: from.address || 'ETH',
to: to.address || 'ETH',
amount: isAmountInDecimals ? amount : formatDecimals(amount, false, decimals),
Expand Down
12 changes: 3 additions & 9 deletions src/swap/core/getQuote.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,12 @@
import { CDP_GETSWAPQUOTE } from '../../definitions/swap';
import { sendRequest } from '../../queries/request';
import type {
GetQuoteResponse,
GetQuoteParams,
GetQuoteAPIParams,
Quote,
SwapError,
} from '../types';
import { getParamsForToken } from './getParamsForToken';
import type { GetQuoteResponse, Quote, SwapError, SwapParams, SwapAPIParams } from '../types';

/**
* Retrieves a quote for a swap from Token A to Token B.
*/
export async function getQuote(params: GetQuoteParams): Promise<GetQuoteResponse> {
export async function getQuote(params: SwapParams): Promise<GetQuoteResponse> {
// Default parameters
const defaultParams = {
amountReference: 'from',
Expand All @@ -22,7 +16,7 @@ export async function getQuote(params: GetQuoteParams): Promise<GetQuoteResponse
const apiParams = getParamsForToken({ ...defaultParams, ...params });

try {
const res = await sendRequest<GetQuoteAPIParams, Quote>(CDP_GETSWAPQUOTE, [apiParams]);
const res = await sendRequest<SwapAPIParams, Quote>(CDP_GETSWAPQUOTE, [apiParams]);

if (res.error) {
return {
Expand Down
287 changes: 287 additions & 0 deletions src/swap/core/getSwap.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,287 @@
import { getParamsForToken } from './getParamsForToken';
import { getSwap } from './getSwap';
import { getTransaction } from './getTransaction';
import { sendRequest } from '../../queries/request';
import { CDP_GETSWAPTRADE } from '../../definitions/swap';
import type { Token } from '../../token/types';
import { Swap } from '../types';

jest.mock('../../queries/request');

const ETH: Token = {
name: 'ETH',
address: '',
symbol: 'ETH',
decimals: 18,
image: 'https://wallet-api-production.s3.amazonaws.com/uploads/tokens/eth_288.png',
chainId: 8453,
};
const DEGEN: Token = {
name: 'DEGEN',
address: '0x4ed4e862860bed51a9570b96d89af5e1b0efefed',
symbol: 'DEGEN',
decimals: 18,
image:
'https://d3r81g40ycuhqg.cloudfront.net/wallet/wais/3b/bf/3bbf118b5e6dc2f9e7fc607a6e7526647b4ba8f0bea87125f971446d57b296d2-MDNmNjY0MmEtNGFiZi00N2I0LWIwMTItMDUyMzg2ZDZhMWNm',
chainId: 8453,
};
const testFromAddress = '0x6Cd01c0F55ce9E0Bf78f5E90f72b4345b16d515d';
const testAmount = '3305894409732200';
const testAmountReference = 'from';

describe('getSwap', () => {
beforeEach(() => {
jest.clearAllMocks();
});

it('should return a swap', async () => {
const mockParams = {
fromAddress: testFromAddress as `0x${string}`,
amountReference: testAmountReference,
from: ETH,
to: DEGEN,
amount: testAmount,
};
const mockApiParams = getParamsForToken(mockParams);

const mockResponse = {
id: 1,
jsonrpc: '2.0',
result: {
tx: {
data: '0x0000000000000',
gas: '463613',
gasPrice: '2106527',
from: '0xaeE5834a78a30F6762407F6F8c3A2090054b0086',
to: '0xdef1c0ded9bec7f1a1670819833240f027b25eff',
value: '100000000000000',
},
quote: {
from: {
address: '',
chainId: 8453,
decimals: 18,
image: 'https://wallet-api-production.s3.amazonaws.com/uploads/tokens/eth_288.png',
name: 'ETH',
symbol: 'ETH',
},
to: {
address: '0x4ed4e862860bed51a9570b96d89af5e1b0efefed',
chainId: 8453,
decimals: 18,
image:
'https://d3r81g40ycuhqg.cloudfront.net/wallet/wais/3b/bf/3bbf118b5e6dc2f9e7fc607a6e7526647b4ba8f0bea87125f971446d57b296d2-MDNmNjY0MmEtNGFiZi00N2I0LWIwMTItMDUyMzg2ZDZhMWNm',
name: 'DEGEN',
symbol: 'DEGEN',
},
fromAmount: '100000000000000',
toAmount: '19395353519910973703',
amountReference: 'from',
priceImpact: '0.94',
chainId: 8453,
highPriceImpact: false,
slippage: '3',
warning: undefined,
},
fee: {
baseAsset: {
name: 'DEGEN',
address: '0x4ed4e862860bed51a9570b96d89af5e1b0efefed',
currencyCode: 'DEGEN',
decimals: 18,
imageURL:
'https://d3r81g40ycuhqg.cloudfront.net/wallet/wais/3b/bf/3bbf118b5e6dc2f9e7fc607a6e7526647b4ba8f0bea87125f971446d57b296d2-MDNmNjY0MmEtNGFiZi00N2I0LWIwMTItMDUyMzg2ZDZhMWNm',
blockchain: 'eth',
aggregators: [Array],
swappable: true,
unverified: false,
chainId: 8453,
},
percentage: '1',
amount: '195912661817282562',
},
approveTx: undefined,
chainId: '8453',
},
};

(sendRequest as jest.Mock).mockResolvedValue(mockResponse);

const trade = mockResponse.result;
const expectedResponse = {
approveTransaction: trade.approveTx
? getTransaction(trade.approveTx, trade.chainId)
: undefined,
fee: trade.fee,
quote: trade.quote,
transaction: getTransaction(trade.tx, trade.chainId),
warning: trade.quote.warning,
};

const quote = (await getSwap(mockParams)) as Swap;

expect(quote.approveTransaction?.transaction).toEqual(
expectedResponse.approveTransaction?.transaction,
);
expect(quote.transaction.transaction).toEqual(expectedResponse.transaction.transaction);
expect(quote.fee).toEqual(expectedResponse.fee);
expect(quote.warning).toEqual(expectedResponse.warning);

expect(sendRequest).toHaveBeenCalledTimes(1);
expect(sendRequest).toHaveBeenCalledWith(CDP_GETSWAPTRADE, [mockApiParams]);
});

it('should return a swap with an approve transaction', async () => {
const mockParams = {
fromAddress: testFromAddress as `0x${string}`,
amountReference: testAmountReference,
from: DEGEN,
to: ETH,
amount: testAmount,
};
const mockApiParams = getParamsForToken(mockParams);

const mockResponse = {
id: 1,
jsonrpc: '2.0',
result: {
approveTx: {
data: '0x0000000000000',
gas: '463613',
gasPrice: '2106527',
from: '0xaeE5834a78a30F6762407F6F8c3A2090054b0086',
to: '0xdef1c0ded9bec7f1a1670819833240f027b25eff',
value: '100000000000000',
},
tx: {
data: '0x0000000000000',
gas: '463613',
gasPrice: '2106527',
from: '0xaeE5834a78a30F6762407F6F8c3A2090054b0086',
to: '0xdef1c0ded9bec7f1a1670819833240f027b25eff',
value: '100000000000000',
},
quote: {
from: {
address: '',
chainId: 8453,
decimals: 18,
image: 'https://wallet-api-production.s3.amazonaws.com/uploads/tokens/eth_288.png',
name: 'ETH',
symbol: 'ETH',
},
to: {
address: '0x4ed4e862860bed51a9570b96d89af5e1b0efefed',
chainId: 8453,
decimals: 18,
image:
'https://d3r81g40ycuhqg.cloudfront.net/wallet/wais/3b/bf/3bbf118b5e6dc2f9e7fc607a6e7526647b4ba8f0bea87125f971446d57b296d2-MDNmNjY0MmEtNGFiZi00N2I0LWIwMTItMDUyMzg2ZDZhMWNm',
name: 'DEGEN',
symbol: 'DEGEN',
},
fromAmount: '100000000000000',
toAmount: '19395353519910973703',
amountReference: 'from',
priceImpact: '0.94',
chainId: 8453,
highPriceImpact: false,
slippage: '3',
warning: undefined,
},
fee: {
baseAsset: {
name: 'DEGEN',
address: '0x4ed4e862860bed51a9570b96d89af5e1b0efefed',
currencyCode: 'DEGEN',
decimals: 18,
imageURL:
'https://d3r81g40ycuhqg.cloudfront.net/wallet/wais/3b/bf/3bbf118b5e6dc2f9e7fc607a6e7526647b4ba8f0bea87125f971446d57b296d2-MDNmNjY0MmEtNGFiZi00N2I0LWIwMTItMDUyMzg2ZDZhMWNm',
blockchain: 'eth',
aggregators: [Array],
swappable: true,
unverified: false,
chainId: 8453,
},
percentage: '1',
amount: '195912661817282562',
},
chainId: '8453',
},
};

(sendRequest as jest.Mock).mockResolvedValue(mockResponse);

const trade = mockResponse.result;
const expectedResponse = {
approveTransaction: trade.approveTx
? getTransaction(trade.approveTx, trade.chainId)
: undefined,
fee: trade.fee,
quote: trade.quote,
transaction: getTransaction(trade.tx, trade.chainId),
warning: trade.quote.warning,
};

const quote = (await getSwap(mockParams)) as Swap;

expect(quote.approveTransaction?.transaction).toEqual(
expectedResponse.approveTransaction?.transaction,
);
expect(quote.transaction.transaction).toEqual(expectedResponse.transaction.transaction);
expect(quote.fee).toEqual(expectedResponse.fee);
expect(quote.warning).toEqual(expectedResponse.warning);

expect(sendRequest).toHaveBeenCalledTimes(1);
expect(sendRequest).toHaveBeenCalledWith(CDP_GETSWAPTRADE, [mockApiParams]);
});

it('should throw an error if sendRequest fails', async () => {
const mockParams = {
fromAddress: testFromAddress as `0x${string}`,
amountReference: testAmountReference,
from: ETH,
to: DEGEN,
amount: testAmount,
};
const mockApiParams = getParamsForToken(mockParams);

const mockError = new Error('getSwap: Error: Failed to send request');
(sendRequest as jest.Mock).mockRejectedValue(mockError);

await expect(getSwap(mockParams)).rejects.toThrow('getSwap: Error: Failed to send request');

expect(sendRequest).toHaveBeenCalledTimes(1);
expect(sendRequest).toHaveBeenCalledWith(CDP_GETSWAPTRADE, [mockApiParams]);
});

it('should return an error object from getSwap', async () => {
const mockParams = {
fromAddress: testFromAddress as `0x${string}`,
amountReference: testAmountReference,
from: ETH,
to: DEGEN,
amount: testAmount,
};
const mockApiParams = getParamsForToken(mockParams);

const mockResponse = {
id: 1,
jsonrpc: '2.0',
error: {
code: -1,
message: 'Invalid response',
},
};

(sendRequest as jest.Mock).mockResolvedValue(mockResponse);

const error = await getSwap(mockParams);
expect(error).toEqual({
code: -1,
error: 'Invalid response',
});

expect(sendRequest).toHaveBeenCalledTimes(1);
expect(sendRequest).toHaveBeenCalledWith(CDP_GETSWAPTRADE, [mockApiParams]);
});
});
41 changes: 41 additions & 0 deletions src/swap/core/getSwap.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { CDP_GETSWAPTRADE } from '../../definitions/swap';
import { sendRequest } from '../../queries/request';
import { getParamsForToken } from './getParamsForToken';
import { getTransaction } from './getTransaction';
import type { GetSwapParams, Trade, SwapError, SwapAPIParams, GetSwapResponse } from '../types';

/**
* Retrieves an unsigned transaction for a swap from Token A to Token B.
*/
export async function getSwap(params: GetSwapParams): Promise<GetSwapResponse> {
// Default parameters
const defaultParams = {
amountReference: 'from',
isAmountInDecimals: false,
};

const apiParams = getParamsForToken({ ...defaultParams, ...params });

try {
const res = await sendRequest<SwapAPIParams, Trade>(CDP_GETSWAPTRADE, [apiParams]);
if (res.error) {
return {
code: res.error.code,
error: res.error.message,
} as SwapError;
}

const trade = res.result;
return {
approveTransaction: trade.approveTx
? getTransaction(trade.approveTx, trade.chainId)
: undefined,
fee: trade.fee,
quote: trade.quote,
transaction: getTransaction(trade.tx, trade.chainId),
warning: trade.quote.warning,
};
} catch (error) {
throw new Error(`getSwap: ${error}`);
Copy link
Contributor

@Zizzamia Zizzamia Jun 10, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Something we should write on, is also an Error page in our docs, and overtime re-align all our code to it.

}
}
Loading
Loading