Refer to the documentation of the ParaSwap API: https://developers.paraswap.network
Features
Versatility: works with both web3 and ethers without direct dependency
Canonical: bring only the functions you actually need
Lightweight: 400B Gzipped for the minimal variant
Installing ParaSwap SDK
yarn add @paraswap/sdk
Using ParaSwap SDK
There are multiple ways to use ParaSwap SDK, ranging from a simple construct-and-use approach to a fully composable bring what you need approach which allows for advanced tree-shaking and minimizes bundle size.
Simple SDK
Can be created by providing chainId and either axios or window.fetch (or alternative fetch implementation). The resulting SDK will be able to use all methods that query the API.
import { constructSimpleSDK } from '@paraswap/sdk';
import axios from 'axios';
// construct minimal SDK with fetcher only
const paraSwapMin = constructSimpleSDK({chainId: 1, axios});
// or
const paraSwapMin = constructSimpleSDK({chainId: 1, fetch: window.fetch});
const ETH = '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee';
const DAI = '0x6B175474E89094C44Da98b954EedeAC495271d0F';
async function swapExample() {
// or any other signer/provider
const signer: JsonRpcSigner = ethers.Wallet.fromMnmemonic('__your_mnemonic__');
const senderAddress = signer.address;
const priceRoute = await paraSwapMin.swap.getRate({
srcToken: ETH,
destToken: DAI,
amount: srcAmount,
userAddress: senderAddress,
side: SwapSide.SELL,
});
const txParams = await paraSwapMin.swap.buildTx(
{
srcToken,
destToken,
srcAmount,
destAmount,
priceRoute,
userAddress: senderAddress,
partner: referrer,
}
);
const transaction = {
...txParams,
gasPrice: '0x' + new BigNumber(txParams.gasPrice).toString(16),
gasLimit: '0x' + new BigNumber(5000000).toString(16),
value: '0x' + new BigNumber(txParams.value).toString(16),
};
const txr = await signer.sendTransaction(transaction);
}
async function approveTokenYourselfExample() {
const TransferProxy = await paraSwapMin.swap.getSpender();
const DAI_CONTRACT = new ethers.Contract(DAI, ERC20_ABI, ethersSignerOrProvider);
const tx = await DAI_CONTRACT.approve(TransferProxy, amountInWei);
const txReceipt = await tx.wait(1);
}
If optional providerOptions is provided as the second parameter, then the resulting SDK will also be able to approve Tokens for swap.
Refer to SDK API documentation for detailed documentation on the methods provided in this SDK.
Tests
To run yarn test it is necessary to provide PROVIDER_URL=<mainnet_rpc_url> environment variable. If it is necessary to run tests against a different API endpoint, provide API_URL=url_to_API environment variable.