Created
June 19, 2021 05:30
-
-
Save korrio/431f3bdf404bb9c4fc2272a5a24078b5 to your computer and use it in GitHub Desktop.
wrapUnwrap.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default function useWrapCallback( | |
inputCurrency: Currency | undefined, | |
outputCurrency: Currency | undefined, | |
typedValue: string | undefined | |
): { wrapType: WrapType; execute?: undefined | (() => Promise<void>); inputError?: string } { | |
const { chainId, account } = useActiveWeb3React() | |
const wethContract = useWETHContract() | |
const balance = useCurrencyBalance(account ?? undefined, inputCurrency) | |
// we can always parse the amount typed as the input currency, since wrapping is 1:1 | |
const inputAmount = useMemo(() => tryParseAmount(typedValue, inputCurrency), [inputCurrency, typedValue]) | |
const addTransaction = useTransactionAdder() | |
return useMemo(() => { | |
if (!wethContract || !chainId || !inputCurrency || !outputCurrency) return NOT_APPLICABLE | |
console.log("WETH[chainId]"); | |
console.log(WETH[chainId]); | |
console.log("inputCurrency"); | |
console.log(inputCurrency); | |
console.log("outputCurrency"); | |
console.log(outputCurrency); | |
const sufficientBalance = inputAmount && balance && !balance.lessThan(inputAmount) | |
if (inputCurrency === ETHER && currencyEquals(WETH[chainId], outputCurrency)) { | |
return { | |
wrapType: WrapType.WRAP, | |
execute: | |
sufficientBalance && inputAmount | |
? async () => { | |
try { | |
const txReceipt = await wethContract.deposit({ value: `0x${inputAmount.raw.toString(16)}` }) | |
addTransaction(txReceipt, { summary: `Wrap ${inputAmount.toSignificant(6)} KUB to KUB` }) | |
} catch (error) { | |
console.error('Could not deposit', error) | |
} | |
} | |
: undefined, | |
inputError: sufficientBalance ? undefined : 'Insufficient KUB balance' | |
} | |
} if (currencyEquals(WETH[chainId], inputCurrency) && outputCurrency === ETHER) { | |
return { | |
wrapType: WrapType.UNWRAP, | |
execute: | |
sufficientBalance && inputAmount | |
? async () => { | |
try { | |
const txReceipt = await wethContract.withdraw(`0x${inputAmount.raw.toString(16)}`) | |
addTransaction(txReceipt, { summary: `Unwrap ${inputAmount.toSignificant(6)} KKUB to KUB` }) | |
} catch (error) { | |
console.error('Could not withdraw', error) | |
} | |
} | |
: undefined, | |
inputError: sufficientBalance ? undefined : 'Insufficient WBNB balance' | |
} | |
} | |
return NOT_APPLICABLE | |
}, [wethContract, chainId, inputCurrency, outputCurrency, inputAmount, balance, addTransaction]) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment