Skip to content

Instantly share code, notes, and snippets.

@wardenluna
Forked from AncientWarden/App.tsx
Last active Apr 12, 2022
Embed
What would you like to do?
Sample React TypeScript Code for integrating WardenSwap SDK
import { ethers } from "ethers";
import { useWeb3React, Web3ReactProvider } from "@web3-react/core";
import { Web3Provider } from "@ethersproject/providers";
import { initProvider, WardenBestRate } from "@wardenswap/bestrate-sdk";
import { InjectedConnector } from "@web3-react/injected-connector";
const injected = new InjectedConnector({
supportedChainIds: [56],
});
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();
try {
// amountIn can be omitted to approve with MaxUint256 allowance
// return null if no need to be approved
const tx = await wardenClient.approve(signer, srcAddr, amountIn);
console.log("[handleApprove] approve result:", tx);
if (tx !== null) {
await tx.wait();
}
} 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();
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);
const tx = await wardenClient.swap(
signer,
srcAddr,
destAddr,
amountIn,
minAmountOut,
quote
);
await tx.wait();
} 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 = initProvider(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