Hi, I just coded my first dex using React and following the 1Inch youtube tutorial! Almost there but when I try to complete the swap I get an error…Please excuse the mess of code. Thanks!
useEffect(() => {
async function init() {
await Moralis.initPlugins();
await Moralis.enable();
listAvailableTokens();
}
init();
// token info from 1inch
const listAvailableTokens = async () => {
const result = await Moralis.Plugins.oneInch.getSupportedTokens({
chain: "eth", // The blockchain you want to use (eth/bsc/polygon)
});
const tokensObject = await result.tokens;
setTokens(tokensObject)
// const tokensImg = Object.values(tokensObject).map(val => val.logoURI);
// setImgVal(tokensImg)
};
}, []);
const getQuote = async function() {
if(!fromAmount)
return;
let amount = Number(fromAmount) * 10**fromTokenDecimals;
const quote = await Moralis.Plugins.oneInch.quote({
chain: 'eth',
fromTokenAddress: tokenAddress,
toTokenAddress: totokenAddress,
amount: amount,
})
console.log(quote)
setToAmount(quote.toTokenAmount.length < 40 ? (quote.toTokenAmount / 10**quote.toToken.decimals).toFixed(8) : 'Too Much!');
setGasAmount(quote.estimatedGas)
if(fromAmount) {
setOrder(true)
}
}
async function trySwap() {
let address = Moralis.User.current().get("ethAddress");
let amount = Number(fromAmount) * 10**fromTokenDecimals;
if (tokenSymbol !== "ETH") {
const allowance = await Moralis.Plugins.oneInch.hasAllowance({
chain: "eth", // The blockchain you want to use (eth/bsc/polygon)
fromTokenAddress: tokenAddress, // The token you want to swap
fromAddress: address, // Your wallet address
amount: amount,
});
console.log(allowance);
console.log(address)
if (!allowance) {
await Moralis.Plugins.oneInch.approve({
chain: "eth", // The blockchain you want to use (eth/bsc/polygon)
tokenAddress: tokenAddress, // The token you want to swap
fromAddress: address, // Your wallet address
});
}
}
try {
await doSwap(address, amount);
alert("Swap Complete");
} catch (error) {
console.log(error);
}
}
function doSwap(userAddress, amount) {
return Moralis.Plugins.oneInch.swap({
chain: "eth", // The blockchain you want to use (eth/bsc/polygon)
fromTokenAddress: tokenAddress, // The token you want to swap
toTokenAddress: totokenAddress, // The token you want to receive
amount: amount,
fromAddress: userAddress, // Your wallet address
slippage: 1,
});
}