We were unable to load Disqus. If you are a moderator please see our troubleshooting guide.
Thank you Markus, this is saving quite a lot of time for me. Keep up the good work!
Hi Markus. This has been tremendous help. Thanks a lot!
I've tried your REMIX example and `getEstimatedETHforDAI()` works just fine. However, when I tried `convertETHToDAI` with "1", it gives me
Fail with error 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT' error. I believe someone asked this question before.
Tx detail is here:
https://kovan.etherscan.io/...
Thank you in advance!
You're right, previous comment was here http://disq.us/p/2c3cage. In his case, he forgot to send along any Ether with the transaction. In the top left in Remix you can enter the Ether amount. Does that fix it?
Ok now I'm confused.. xD
so the amount of ETH you put into that box above "DEPLOY" is the gas price for the transaction I'm trying to do?
If I enter "1" to convertETHToDAI(), where does the DAI go to?
This is the successful tx. https://kovan.etherscan.io/...
I might have to go through more basic IDE tutorials.
https://uploads.disquscdn.c...
This is what I meant. The ether value here. It determines how much Ether you send along. This is the actual msg.value in Solidity. The gas price has nothing to do with it. You need Ether to pay for the gas, yes. But you can also send extra Ether on top which in our case you need to do to pay for the DAI.
I just can't find where that DAI i exchanged went to :( Adding DAI to my metamask account does not show any transaction. It looks like the DAI went to and stuck at the smart contract itself. How do I retrieve it?
I had to change the account(this) in `swapETHForExactTokens` param to msg.sender in order to receieve the token i swapped for. Thanks a lot for your help!
Yeah, you might also want to read the comment here: http://disq.us/p/2dmndii. This addresses the part where funds are sent.
Can't believe I missed that haha. Thank you!
I've not been able to find a working faucet to test this on Kovan. I've tried to get this working on Ropsten but not had luck. Has anyone got a working example on Ropsten?
why deadline now is bad from solidity?
I want to add liquidity to uniswap from my smart contract.
I am receiving ether from users. when pot reaches to 0.4 ethers. I am swapping swapETHForExactTokens(half to total balance) and then adding liquidity with remaining ether and DaiTokens.
It is giving me error.
https://kovan.etherscan.io/...
This is my code.
function Participate() payable public {
require(msg.value == ticketPrice,"please set correct price");
if(pot < winningsLimit || pot == winningsLimit) {
pot += msg.value;
participants.push(msg.sender);
}
if (pot > winningsLimit || pot == winningsLimit) {
EndLottery();
}
}
function EndLottery() internal{
//total payments in pot
uint totalPayout = pot;
pot = 0;
// Take 75% for the Liquidity Pool (rounded down by int-division)
uint liquidityAmount = totalPayout.mul(liquidityPercentage).div(100);
emit liquidityAmountEvent(liquidityAmount);
// Pay 25% to the winner
uint payoutToWinner = totalPayout.sub(liquidityAmount);
winner = pickWinner();
winner.transfer(payoutToWinner);
// split the contract balance into halves
uint half = liquidityAmount.div(2);
uint otherHalf = liquidityAmount.sub(half);
//swap ETH for tokens
require(convertEthToDai(half,half) == true,"convertEthToDai: Failed");
//using remaining half to add liqdity
addLiquidityEthereum(half, 0.1 ether);
emit Payout(winner, pot, participants.length);
delete participants;
}
function convertEthToDai(uint daiAmountToBuy, uint ethAmount) internal returns(bool){
uint deadline = block.timestamp + 15; // using 'now' for convenience, for mainnet pass deadline from frontend!
uniswapRouter.swapETHForExactTokens{ value: ethAmount }(daiAmountToBuy, getPathForETHtoDAI(), address(this), deadline);
// refund leftover ETH to user
(bool success,) = msg.sender.call{ value: address(this).balance }("");
require(success, "refund failed");
return true;
}
function addLiquidityEthereum(uint256 tokenAmount, uint256 ethAmount) internal returns(bool){
// uint bal = payable(address(this)).balance;
uint newTokenAmount = tokenAmount * 10^18;
//approving tokens to uniswapRouter
IERC20(daiToken).approve(UNISWAP_ROUTER_ADDRESS, newTokenAmount);
require(daiToken.allowance(address(this), UNISWAP_ROUTER_ADDRESS) != 0,"zero allowance, pleae approve DAI first to be used by this contract");
uniswapRouter.addLiquidityETH{value: ethAmount}(
address(daiToken),
newTokenAmount,//tkn amount
0, // slippage is unavoidable
0, // slippage is unavoidable
address(this),
block.timestamp + 15
);
// refund leftover ETH to user
(bool success,) = msg.sender.call{ value: address(this).balance }("");
require(success, "refund failed");
}
Please guide me
Thank you Markus. Like many others here, very grateful for this tutorial.
Do you have suggestions or references you’d recommend for swapping from Token A through WETH to Token B? Ideally I’d like to use this to swap Token A with DAI but using WETH as a pass through due to liquidity.
Token A -> WETH -> DAI
Is it essentially adding additional inputs/outputs to the above function, the address state variables, and editing the mapping like below?
Rough example of mapping:
function //name//() private view returns (address[] memory) {
address[] memory path = new address[](2);
path[0] = TokenA;
path[1] = uniswapRouter.WETH();
path[2] = multiDaiKovan;
Does this still work? When I copy and paste this into remix, deploy and test I get this error when calling convertEthToDAI() I get:
"transact to OrderPayment.convertEthToDAI errored: VM error: revert. revert The transaction has been reverted to the initial state. Note: The called function should be payable if you send value and the value you send should be less than your current balance. Debug the transaction to get more information."
When I try getEstimatedEthToDAI() I get:
"call to OrderPayment.getEstimatedETHforDAI errored: VM error: revert. revert The transaction has been reverted to the initial state. Note: The called function should be payable if you send value and the value you send should be less than your current balance. Debug the transaction to get more information."
Really unsure of what is wrong. I have tried with sending 1 eth with initial contract so it has funds for gas but that has not helped.
Any help would be greatly appreciated
I've got the same issue. Are you testing on Kovan?
Thank you Markus. I run the Remix code with Injected Metamask in Kovan Network, the convertEthToDai() gets called succesfully. I give in 0.01 ETH to swap for 5 DAI, the function works but I dont see any new DAI in my wallet. Correct me if I'm doing things wrong anywhere.
Can you share the Etherscan link to the transaction?
Hey Markus, thanks very very much for the quick response. I want to write a function that will accept payment from user to transfer tokens to another user. The function can accept payments both in Ether and Dai. If user sends DAI then well n good and carry out the rest of the function but if he pays in Eth then convert the Eth to Dai and use those Dai to carry out the rest of the function. The function should also return back leftover Eth back to user after conversion.
Is it possible for the pay function to accept payment from Ether , convert into Dai and transfer Dai to different address/contract all in one function. I have searched the entire internet and this blog came as a SAVIOUR to me which is exactly the use case I'm looking for.
I have deployed the remix example above on Kovan with 0.01 Eth to swap for 5 DAI tokens, the convertEthToDai() gets called successfully but I dont see any DAI in my wallet. Please correct me if I'm wrong anywhere.
https://kovan.etherscan.io/...
I have added the custom token in my metamask wallet at this contract address 0x4f96fe3b7a6cf9725f59d353f723c1bdb64ca6aa . Wanted to make sure if this is the right DAI token.
You can get an idea on what's happening in the token transferred section in Etherscan: https://uploads.disquscdn.c...
As you can see the DAI token is transferred to the contract. If you see at the top my function pay, it has the comment // do something with that DAI. So that's exactly what you're missing.
You just want to return it to the person that called the function? Add this line:
require(daiToken.transfer(msg.sender, daiToken.balanceOf(address(this)));
Cheers.
Hey Markus, thanks a lot for figuring it out, I got where exactly I'm doing wrong. That was very silly of me that I couldn't see a simple thing right infront of my eyes. I didn't quite see where exactly the tokens were going ( the contract has those tokens ) and I was searching in my wallet !!
Just so anyone else doesn't confuse as the pay() function isn't written on the final contract.
You can either
1. write the pay() in the contract exactly as in the blog and add the extra line as explained above by markus require(daiToken.transfer(msg.sender, daiToken.balanceOf(address(this)); at the place // do something with that DAI
2. Change the second line in function convertEthToDai() to uniswapRouter.swapETHForExactTokens{ value: msg.value }(daiAmount, getPathForETHtoDAI(), msg.sender , deadline);
quick tip: 1KDAI = 0.022486825925570405 Eth (approx)
Once again, thanks Markus for the AMAZING blog.
Hey, I have done my code a little bit different. Instead of converting eth to dai and sending eth back to my account. I have:
1. Created contract
2. Sent eth from my metamask to the contract
3. I buy dai token with exact amount of eth in the contract
4. I have dai tokens within the contract
Now I am not sure on how to send the dai tokens within my contract back to my address.
You can have a look at my transaction on the kovan test network:
my address: 0x4c31c93DACD6940b8B96022AcF1a5a1215c9f9dB
contract address: 0xD3bC6c4B838710477caE981C6D7f9d8F20C6A2FE
I tried what you have said here but I am not able to implement it correctly, it gives me this error: ParserError: Expected ',' but got ';' daiToken.balanceOf(address(this))); ^
I am not exactly sure where to place the pay() function and what changes to make to it as I have commented the function convertEthToDai and created new function:
function buyExactDaiWithEth() public payable returns(uint256){
uint deadline = block.timestamp + 15;
uniswapRouter.swapExactETHForTokens{ value: msg.value }(0, getPathForETHtoDAI(), address(this), deadline);
return 1000;
Apart from this, I have not made any changes,
I appreciate your time reading this.
If you require any other things let me know.
Markus Waas
Remix is giving gas error for me. I am failing on the convertEthToDai function on both Ropstein and Rinkeby networks:
Gas estimation errored with the following message (see below). The transaction execution will likely fail. Do you want to force sending?
gas required exceeds allowance (10000000) or always failing transaction
it fails right away, even when using higher gas on remix. Can someone tell me what I'm doing wrong? I am running the exact example as shown here.
If you are not using Kovan, you need to use different addresses for the tokens. Are you doing that?
I am seeing a similar problem to this. Is there some approve function that I need to run before running the remix example?
Hello George, if you want to sell ETH as I did in the tutorial here, then you don't need any approve. Otherwise yes you might be missing the token.approve(yourContractAddress, amount) call, see also http://disq.us/p/2cvggyu.
Yes, I used the correct address on Ropstein and Rinkeby respectively
Hi Markus, Hope you are staying safe! i have been trying to swap a token with eth via uniswap but it's throwing error "The transaction cannot succeed due to error: TransferHelper: TRANSFER_FROM_FAILED. This is probably an issue with one of the tokens you are swapping" is there any way to swap to eth?
Via contracts you can use swapTokensForExactEth. If you're using the UI, it seems strange you would get this error as I would think the UI verifies that 1. you have enough token to sell and 2. the tokens are approved to the pool.
Markus, do you happen to know if we can use 'swapExactTokensForTokens' to convert WETH to DAI? Or one must always unwrap the WETH and then use 'swapExactETHForTokens'? Thanks for the post!
No of course you can use swapExactTokensForTokens. In fact even swapETHForExactTokens is actually just wrapping the ETH under the hood and calling swapExactTokensForTokens afterwards.
Is there any possible to combine multiple swapETHForExactTokens() or swapTokensForExactETH() in one function in my contract like below?
I try SEVERAL time but I always got "Fail with error ' TransferHelper: TRANSFER_FROM_FAILED' " message on etherscan
https://uploads.disquscdn.c... t?
Hi,I used your function "convertDaiToEth" in my contract,but when I swap token for eth I still geting error "TRANSFER_FROM_FAILED",can you help me or tell me how to solve it? THX a lot
Kovan network? Are you passing non-zero Wei value in Remix?
my code is copied from @Randy 's reply
Rinkeby testnet, and my test code here :function test(
address to,
uint256 deadline,
address[] memory path,uint amountOutMin) public payable returns (bool){
if(creator !=msg.sender){
return false;
}
address tokenAddr=address(path[0]);
IERC20 token=IERC20(tokenAddr);
uint256 balance0 =token.balanceOf(address(this));
//require(token.approve(address(uniswapV2Router02),0),'approve failed');
require(token.approve(address(uniswapV2Router02),balance0),'approve failed');
deadline=block.timestamp+1000;
uint[] memory re=uniswapV2Router02.swapExactTokensForETH(balance0,amountOutMin,path,address(this),deadline);
return true;
}
when I call this "test" function on rinkeby, I got "TRANSFER_FROM_FAILED" transaction status,my purpose is selling all my tokens through my own contract,but it seem that it dosen't work. I passed 0 wei value in remix,but I think the function "swapExactTokensForETH" do not require for ether value (perhaps?) ,is this code wrong?
I have met the same issue on rinkeby.
I want to transfer dai to uni, the path is [dai contract address, weth contract address, uni contract address], is this right?
UNISWAP_ROUTER_ADDRESS = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address daiContract = 0xc7AD46e0b8a400Bb3C915120d284AafbA8fc4735;
address uniContract = 0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984;
IERC20 token=IERC20(daiContract);
require(token.approve(address(UNISWAP_ROUTER_ADDRESS), amount),'approve failed');
deadline=block.timestamp+100;
path=[daiContract, uniswapRouter.WETH(), uniContract];
uint[] memory re=uniswapRouter.swapExactTokensForTokens(amount,0,path,address(this),deadline);
It reports "TRANSFER_FROM_FAILED".
I have seen the error info in DAI's contract:
function transferFrom(address src, address dst, uint wad)
public returns (bool)
{
require(balanceOf[src] >= wad, "Dai/insufficient-balance");
if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) {
require(allowance[src][msg.sender] >= wad, "Dai/insufficient-allowance");
allowance[src][msg.sender] = sub(allowance[src][msg.sender], wad);
}
balanceOf[src] = sub(balanceOf[src], wad);
balanceOf[dst] = add(balanceOf[dst], wad);
emit Transfer(src, dst, wad);
return true;
}
require(balanceOf[src] >= wad, "Dai/insufficient-balance"); leads to the transaction reverted, the input amount of DAI is 1000000000000000000, equals to 1 DAI. There are more than one DAI in my account.
I have resolved the issue, before approve, you should call transferFrom() to transfer the token to contract.
Thanks.
Hello, the path doesn't look correct. It should contain only tokens. Leave out the uniswap: path=[daiContract, uniswapRouter.WETH()];. That doesn't really explain your error message though. The reasons seems to be you're missing a transferFrom. You might have more than 1 DAI, but you're not transferring it to the contract. Add a token.transferFrom(msg.sender, address(this), amount. And before that don't forget to approve the DAI from your ETH account towards your own contract address.
Thanks a lot for your reply, I want to transfer DAI to UNI, so the path is right, I have verified it.
Add a token.transferFrom(msg.sender, address(this), amount. And before that don't forget to approve the DAI from your ETH account towards your own contract address.
Yes, with token.transferFrom(), DAI has been transfered to UNI successfully.
So you want to buy tokens and then immediately sell them again? What's the use case? Is it working now?
I'm Just test on several Uniswap function. lol
I finally got it work. :)
The reason I failed is that I don't have any DAI in the contract address.
I think "swapTokenForEth" is different from "swapEthForToken".
"swapEthForToken" will automatically transfer Eth from your address to your contract address and trade it on Uniswap. But the other Don't
Further selling token need to Approve that token for Uniswap just like below pic.
I'm not sure if you will see this Randy or @Markus, but it seems my implementation doesn't work at all :( did you put any value to msg.value when you call this function? did you call dai.approve(address(this), daiAmount) before you call this? Mine always gets dai/Insufficient Allowance error and everyone says I have to approve the allowance. It seems obvious but none of what I'm doing is working :(
I test on kovan.
this is transaction id
tx/0xcec92ed0fd1752321bb4480374bbae11719408a68034ec96c40d8171d249acf4
Hi, I run the code and I always get error messge like "Fail with error
Fail with error 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT'
plz tell me what happened!
In the Kovan testnet?
I finally know what's happen.
I did not set ether value on remix. :(
Thank you!
Ah yes! I think Remix could give better errors in such a case to be honest.
yes in Kovan
this is transcation id
tx/0xdca4dae4c7264346bf9a001e26f8eeb4fbef009b7d82e96681d6a482ab22e7f5
this is transcation url https://kovan.etherscan.io/...
Can anyone offer some help with an issue I have between Uniswap and Metamask please? I tried to buy some 2KEY and confirmed the transaction ok, however the 2KEY didn't arrive in my Metamask wallet. I manually created a wallet in Metamask as it didn't do it automatically. It almost looks like the transaction hasn't completed and I'm seeing this message on the wallet I manually created... Swap E T H For Exact Tokens
Hey I want to make a contract for swapping dai to eth how can I do it can anybody help?