Created
July 6, 2021 15:23
-
-
Save xgracias/3b233a46cb965783f4c818bda9057fb0 to your computer and use it in GitHub Desktop.
Deposit some _amount in ERC20 _token ( USDC, DAI, etc )
This file contains hidden or 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
// get web3 | |
let web3 = await initAccount() | |
// get contract instance | |
let main = new web3.eth.Contract( | |
JSON_ABI, | |
CONTRACT_ADDRESS, | |
) | |
// usdc contract instance | |
let usdcContract = new web3.eth.Contract( | |
erc20Abi, | |
USDC_TOKEN_CONTRACT_ADDRESS, | |
) | |
// dai contract instance | |
let daiContract = new web3.eth.Contract( | |
erc20Abi, | |
DAI_TOKEN_CONTRACT_ADDRESS, | |
) | |
// approve | |
try { | |
if (tokenType === 'USDC') { | |
await usdcContract.methods | |
.approve( | |
CONTRACT_ADDRESS, | |
web3.utils.toWei(amount.toString(), 'mwei'), | |
) | |
.send({ from: address }) | |
.on('receipt', function (receipt) { | |
console.log({ receipt }) | |
}) | |
} else if (tokenType === 'DAI') { | |
await daiContract.methods | |
.approve( | |
CONTRACT_ADDRESS, | |
web3.utils.toWei(amount.toString()), | |
) | |
.send({ from: address }) | |
.on('receipt', function (receipt) { | |
console.log({ receipt }) | |
}) | |
} | |
} catch (error) { | |
throw error | |
} | |
// deposit | |
await main.methods | |
.deposit( | |
web3.utils.toWei( | |
amount.toString(), | |
tokenType === 'USDC' ? 'mwei' : 'ether', | |
), | |
tokenType === 'USDC' | |
? USDC_TOKEN_CONTRACT_ADDRESS | |
: DAI_TOKEN_CONTRACT_ADDRESS, | |
) | |
.send({ from: address }) | |
.on('transactionHash', function (hash) { | |
console.log({ hash }) | |
}) | |
.on('receipt', function (receipt) { | |
console.log({ receipt }) | |
}) | |
.on('error', function (error) { | |
throw error | |
}) |
This file contains hidden or 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
function deposit(uint256 _amount, address _token) external onlyInitialized { | |
require( | |
_token == tokens[0] || _token == tokens[1] || _token == tokens[2], | |
"token not accepted" | |
); | |
require( | |
IERC20(_token).transferFrom(msg.sender, address(this), _amount), | |
"Transfer from failed" | |
); | |
balances[msg.sender][_token] = balances[msg.sender][_token].add( | |
_amount | |
); | |
emit Deposit(msg.sender, _amount); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment