Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Sample React TypeScript Code for integrating WardenSwap SDK
import React from 'react';
import { ethers } from 'ethers'
import erc20Abi from './abi/ERC20.abi.json'
import wardenRouter2Abi from './abi/WardenRouter_2_0.abi.json'
import { useWeb3React, Web3ReactProvider } from '@web3-react/core';
import { Web3Provider } from "@ethersproject/providers";
import { WardenBestRate } from '@wardenswap/bestrate-sdk';
import { InjectedConnector } from '@web3-react/injected-connector';
const injected = new InjectedConnector({
supportedChainIds: [56],
})
const WARDEN_ROUTER_ADDRESS_V2 = '0x451ef8D6B645a60115EB8b8bEa76B39C0C761004'
function SwapComponent({ wardenClient, srcAddr, destAddr, amountIn }: { wardenClient: WardenBestRate, srcAddr: string, destAddr: string, amountIn: ethers.BigNumber }) {
const { active, account, library, activate } = useWeb3React()
const handleConnect = async () => { activate(injected).catch(err => console.error(err)) }
const handleApprove = async () => {
if (!active) {
alert('please connect wallet')
return
}
// init erc20 contract for token
const signer = library.getSigner(account).connectUnchecked()
const erc20Contract = new ethers.Contract(srcAddr, erc20Abi, signer)
try {
// check if the token is already approved
const allowance = await erc20Contract.allowance(account, WARDEN_ROUTER_ADDRESS_V2)
if (allowance.gte(amountIn)) {
alert('already approved')
return
}
// if not approved, approve the maximum limit
// may consider approve minimum needed as well
// metamask will pop-up to let user confirm
const maxUint256 = ethers.BigNumber.from('0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff')
const approveTx = await erc20Contract.approve(WARDEN_ROUTER_ADDRESS_V2, maxUint256)
console.log('[handleApprove] approve result:', approveTx)
} catch (err) {
console.error('[handleApprove] error:', err)
alert(`Approve error: ${JSON.stringify(err)}`)
}
}
const handleSwap = async () => {
if (!active) {
alert('please connect wallet')
return
}
const signer = library.getSigner(account).connectUnchecked()
const contract = new ethers.Contract(WARDEN_ROUTER_ADDRESS_V2, wardenRouter2Abi, signer)
try {
// get the gas price to include in calculating the rate
const gasPrice = await library.getGasPrice()
const quote = await wardenClient.getQuote(srcAddr, destAddr, amountIn, gasPrice)
console.log('[handleSwap] quote:', quote)
let overrides: { [key: string]: any } = {}
if (srcAddr.toLowerCase() === '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee') {
overrides['value'] = amountIn.toString()
}
// Add 2% slippage protection
const minAmountOut = ethers.BigNumber.from(quote.amountOut).mul(98).div(100)
if (quote.type === 'strategies') {
const swap = await contract.swap(
quote.swapAddress,
quote.data,
quote.depositAddress,
srcAddr,
amountIn,
destAddr,
minAmountOut,
account,
0,
0,
overrides)
console.log('[handleSwap] swap result:', swap)
} else if (quote.type === 'split') {
const swap = await contract.swapSplit(
quote.swapAddress,
quote.data,
quote.depositAddresses,
quote.volumns,
srcAddr,
amountIn,
destAddr,
minAmountOut,
account,
0,
0,
overrides)
console.log('[handleSwap] swapSplit result:', swap)
}
else {
alert('not supported')
}
} catch (err) {
console.error('[handleSwap] error:', err)
alert(`Swap error: ${JSON.stringify(err)}`)
}
}
return (
<>
<div>
{
active
? `wallet connected: ${account}`
: <button onClick={handleConnect}>Connect Wallet</button>
}
</div>
<button onClick={handleApprove}>Approve</button>
<button onClick={handleSwap}>Swap</button>
</>
)
}
function getLibrary(provider: any) {
const library = new Web3Provider(provider);
library.pollingInterval = 12000;
return library;
}
function App() {
const jsonRpcUrl = 'https://bsc-dataseed.binance.org/'
const provider = new ethers.providers.JsonRpcProvider(jsonRpcUrl)
const wardenClient = new WardenBestRate(provider, 'bsc')
return (
<Web3ReactProvider getLibrary={getLibrary}>
<SwapComponent
wardenClient={wardenClient}
srcAddr={'0xe9e7cea3dedca5984780bafc599bd69add087d56'} // BUSD
destAddr={'0x0feadcc3824e7f3c12f40e324a60c23ca51627fc'} // WAD
amountIn={ethers.utils.parseUnits('20', 18)} // 20 BUSD in BigNumber
/>
</Web3ReactProvider>
)
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment