Skip to content

Instantly share code, notes, and snippets.

@Aziz87
Forked from korrio/wrapUnwrap.js
Created July 26, 2021 05:50
Show Gist options
  • Save Aziz87/c80c223ecf3d29172b0bbbc7bf280e32 to your computer and use it in GitHub Desktop.
Save Aziz87/c80c223ecf3d29172b0bbbc7bf280e32 to your computer and use it in GitHub Desktop.
wrapUnwrap.js
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