jklepatch / eattheblocks Goto Github PK
View Code? Open in Web Editor NEWSource code for Eat The Blocks, a screencast for Ethereum Dapp Developers
Home Page: https://eattheblocks.com
Source code for Eat The Blocks, a screencast for Ethereum Dapp Developers
Home Page: https://eattheblocks.com
2020-09-19T15:50:26.484916+00:00 app[arbitrage.1]: at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
2020-09-19T15:50:26.484917+00:00 app[arbitrage.1]: at Module.load (internal/modules/cjs/loader.js:985:32)
2020-09-19T15:50:26.484917+00:00 app[arbitrage.1]: at Function.Module._load (internal/modules/cjs/loader.js:878:14)
2020-09-19T15:50:26.484918+00:00 app[arbitrage.1]: at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
2020-09-19T15:50:26.484918+00:00 app[arbitrage.1]: at internal/main/run_main_module.js:17:47 {
2020-09-19T15:50:26.484919+00:00 app[arbitrage.1]: code: 'MODULE_NOT_FOUND',
2020-09-19T15:50:26.484919+00:00 app[arbitrage.1]: requireStack: [ '/app/run-arbitrage.js' ]
2020-09-19T15:50:26.484920+00:00 app[arbitrage.1]: }
2020-09-19T15:50:26.537412+00:00 heroku[arbitrage.1]: Process exited with status 1
2020-09-19T15:50:26.583714+00:00 heroku[arbitrage.1]: State changed from up to crashed
Disconnected from log stream. There may be events happening that you do not see here! Attempting to reconnect...
2020-09-19T15:50:26.484916+00:00 app[arbitrage.1]: at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
2020-09-19T15:50:26.484917+00:00 app[arbitrage.1]: at Module.load (internal/modules/cjs/loader.js:985:32)
2020-09-19T15:50:26.484917+00:00 app[arbitrage.1]: at Function.Module._load (internal/modules/cjs/loader.js:878:14)
2020-09-19T15:50:26.484918+00:00 app[arbitrage.1]: at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
2020-09-19T15:50:26.484918+00:00 app[arbitrage.1]: at internal/main/run_main_module.js:17:47 {
2020-09-19T15:50:26.484919+00:00 app[arbitrage.1]: code: 'MODULE_NOT_FOUND',
2020-09-19T15:50:26.484919+00:00 app[arbitrage.1]: requireStack: [ '/app/run-arbitrage.js' ]
2020-09-19T15:50:26.484920+00:00 app[arbitrage.1]: }
2020-09-19T15:50:26.537412+00:00 heroku[arbitrage.1]: Process exited with status 1
2020-09-19T15:50:26.583714+00:00 heroku[arbitrage.1]: State changed from up to crashed
2020-09-19T16:22:07.834102+00:00 heroku[arbitrage.1]: State changed from crashed to starting
2020-09-19T16:22:12.116264+00:00 heroku[arbitrage.1]: Starting process with command node run-arbitrage.js
2020-09-19T16:22:12.752070+00:00 heroku[arbitrage.1]: State changed from starting to up
2020-09-19T16:22:15.110603+00:00 heroku[arbitrage.1]: Process exited with status 1
2020-09-19T16:22:15.158677+00:00 heroku[arbitrage.1]: State changed from up to crashed
2020-09-19T16:22:15.031185+00:00 app[arbitrage.1]: internal/modules/cjs/loader.js:968
2020-09-19T16:22:15.031200+00:00 app[arbitrage.1]: throw err;
2020-09-19T16:22:15.031200+00:00 app[arbitrage.1]: ^
2020-09-19T16:22:15.031201+00:00 app[arbitrage.1]:
2020-09-19T16:22:15.031201+00:00 app[arbitrage.1]: Error: Cannot find module './build/contracts/Flashloan.json'
2020-09-19T16:22:15.031202+00:00 app[arbitrage.1]: Require stack:
2020-09-19T16:22:15.031202+00:00 app[arbitrage.1]: - /app/run-arbitrage.js
2020-09-19T16:22:15.031203+00:00 app[arbitrage.1]: at Function.Module._resolveFilename (internal/modules/cjs/loader.js:965:15)
2020-09-19T16:22:15.031203+00:00 app[arbitrage.1]: at Function.Module._load (internal/modules/cjs/loader.js:841:27)
2020-09-19T16:22:15.031204+00:00 app[arbitrage.1]: at Module.require (internal/modules/cjs/loader.js:1025:19)
2020-09-19T16:22:15.031204+00:00 app[arbitrage.1]: at require (internal/modules/cjs/helpers.js:72:18)
2020-09-19T16:22:15.031205+00:00 app[arbitrage.1]: at Object. (/app/run-arbitrage.js:6:19)
2020-09-19T16:22:15.031205+00:00 app[arbitrage.1]: at Module._compile (internal/modules/cjs/loader.js:1137:30)
2020-09-19T16:22:15.031205+00:00 app[arbitrage.1]: at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
2020-09-19T16:22:15.031206+00:00 app[arbitrage.1]: at Module.load (internal/modules/cjs/loader.js:985:32)
2020-09-19T16:22:15.031206+00:00 app[arbitrage.1]: at Function.Module._load (internal/modules/cjs/loader.js:878:14)
2020-09-19T16:22:15.031207+00:00 app[arbitrage.1]: at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
2020-09-19T16:22:15.031207+00:00 app[arbitrage.1]: at internal/main/run_main_module.js:17:47 {
2020-09-19T16:22:15.031207+00:00 app[arbitrage.1]: code: 'MODULE_NOT_FOUND',
2020-09-19T16:22:15.031208+00:00 app[arbitrage.1]: requireStack: [ '/app/run-arbitrage.js' ]
2020-09-19T16:22:15.031208+00:00 app[arbitrage.1]: }
First, thanks for the great content !
Quick question: is there a way to set the gas fees we would like to pay for a transaction calling the swapExactTokensForTokens
method ?
Here is what I have for now:
const tx = await router.swapExactTokensForTokens(
amountIn,
amountOutMin,
[tokenIn, tokenOut],
recipientAddress,
expiryDate,
);
const receipt = await tx.wait();
"T" in the EA'T' THE BLOCKS is missing.
Hello.
I have watched your youtube course on how to create a bot to be used on pancakeswap.
I would like to ask a question after actually using the bot.
https://github.com/jklepatch/eattheblocks/tree/master/screencast/348-pancakeswap-trading-bot
In the bot, the event "PairCreated" is used as a trigger for trade execution when token liquidity is added.
https://github.com/jklepatch/eattheblocks/blob/master/screencast/348-pancakeswap-trading-bot/bot.js#L48
factory.on('PairCreated', async (token0, token1, pairAddress) => {
However, some recent tokens are not "PairCreated" to trigger the token to become available for purchase, probably to prevent bots.
For example, the following thread on reddit
https://www.reddit.com/r/pancakeswap/comments/nk5z95/event_paircreated_not_being_emitted_by_some/
In fact, I tried to trade a token like BSCPAD, which has Launchpad as an agent, with "PairCreated" as the trigger when it was listed on pancakeswap, but I failed.
https://bscpad.com/
I'm looking into alternative events or logic to trigger trades other than "PairCreated", do you have any knowledge or ideas about this?
I'm having troubles migrating the TimeLock.sol file. In the repo there is no migration file for the contract.
Hello I am following the pro course on profitable-arbitrage, 15 Poll Uniswap Prices. When i run run-arbitrage.js I get the following error. What does this mean and how I proceed? Thanks
Blair@DESKTOP-L81FL5C MINGW64 ~/profitable-flashloans
$ node run-arbitrage.js
C:\Users\Blair\profitable-flashloans\run-arbitrage.js:24
Token.fetchData(
^
TypeError: Token.fetchData is not a function
at C:\Users\Blair\profitable-flashloans\run-arbitrage.js:24:19
at Array.map ()
at init (C:\Users\Blair\profitable-flashloans\run-arbitrage.js:23:55)
at Object. (C:\Users\Blair\profitable-flashloans\run-arbitrage.js
:78:1)
at Module._compile (node:internal/modules/cjs/loader:1109:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1138:10)
at Module.load (node:internal/modules/cjs/loader:989:32)
at Function.Module._load (node:internal/modules/cjs/loader:829:14)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_ma
in:76:12)
at node:internal/main/run_main_module:17:47
Hi guys,
I'm getting this error:
(node:10292) UnhandledPromiseRejectionWarning: ReferenceError: amounOutMin is not defined
CODE:
//We buy for 0.1 BNB of the new token
//ethers was originally created for Ethereum, both also work for BSC
//'ether' === 'bnb' on BSC
const amountIn = ethers.utils.parseUnits('0.0001', 'ether');
console.log(amountIn);
const amounts = await router.getAmountsOut(amountIn, [tokenIn, tokenOut]);
console.log(amounts);
//Our execution price will be a bit different, we need some flexbility
const amountOutMin = amounts[1].sub(amounts[1].div(10));
console.log(Buying new token ================= tokenIn: ${amountIn.toString()} ${tokenIn} (WBNB) tokenOut: ${amounOutMin.toString()} ${tokenOut}
);
Hi Julien,
After deploy the Arbitrage contract on BSC testnet, when performing transaction by calling the startArbitrage function in Remix, it fails and bscscan outputs following messages:
Fail with error 'Pancake: INSUFFICIENT_LIQUIDITY'
Warning! Error encountered during contract execution [execution reverted]
The values used for the transaction are:
token0: 0xae13d989dac2f0debff460ac112a837c89baa7cd
token1: 0xd66c6b4f0be8ce5b39d52e0fd1344c389929b378
amount0: 1000000000000000000
amount1: 1000000000000000000
Can you help to solve? Thanks
Hi, I've got my trading bot finally working. And I tried to make another script to sell a single token which I bought with the buying bot.
Can anyone help me out please?
const ethers = require('ethers');
const Web3 = require('web3');
const config = require('./config.json');
const web3 = new Web3('https://bsc-dataseed1.binance.org:443')
const addresses = {
WBNB: '0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c',
MYTOKEN: '',
router: '0x10ED43C718714eb63d5aA57B78B54704E256024E',
recipient: '
//First address of this mnemonic must have enough BNB to pay for tx fess
const mnemonic = config.memo;
const provider = new ethers.providers.WebSocketProvider('your websocket url');
const wallet = ethers.Wallet.fromMnemonic(mnemonic);
const account = wallet.connect(provider);
const router = new ethers.Contract(
addresses.router,
[
'function getAmountsOut(uint amountIn, address[] memory path) public view returns (uint[] memory amounts)',
'function swapExactTokensForTokens(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts)'
],
account
);
const wbnb = new ethers.Contract(
addresses.WBNB,
[
'function approve(address spender, uint amount) public returns(bool)',
],
account
);
let tokenIn = addresses.WBNB, tokenOut = addresses.MYTOKEN;
const amountIn = ethers.utils.parseUnits('0.005', 'ether');
const tokenswap = async () => {
console.log('amountIn ######');
console.log(amountIn);
const amounts = await router.getAmountsOut(amountIn, [tokenIn, tokenOut]);
console.log('amounts $$$$$$');
console.log(amounts);
//Our execution price will be a bit different, we need some flexbility
const amountOutMin = amounts[1].sub(amounts[1].div(10));
console.log(Buying new token ================= tokenIn: ${amountIn.toString()} ${tokenIn} (WBNB) tokenOut: ${amountOutMin.toString()} ${tokenOut}
);
console.log('##### gas #######');
console.log(ethers.BigNumber.from(web3.utils.toWei('20', 'gwei')).toHexString());
// Create signer
const wallet = new ethers.Wallet(
Buffer.from(
config.from.privkey, // paste your private key from metamask here
"hex"
)
)
const signer = wallet.connect(provider)
const pancakeswap = new ethers.Contract(
addresses.router,
['function swapExactTokensForTokens(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts)'],
signer
)
/* const txApprove = await wbnb.approve(
router.address,
amountIn
);
let receipt = await txApprove.wait();
console.log('receipt');
console.log(receipt); */
try {
console.log('here in try block');
const tx = await pancakeswap.swapExactTokensForTokens(
amountIn,
amountOutMin,
[tokenIn, tokenOut],
addresses.recipient,
Date.now() + 1000 * 60 * 10, //10 minutes
{
nonce: 441,
gasLimit: web3.utils.toHex(500000),
gasPrice: web3.utils.toHex(web3.utils.toWei('15', 'gwei')),
}
);
const receipt1 = await tx.wait();
console.log('Transaction receipt of tx');
console.log(receipt1);
} catch (err) {
console.log('### Error ######')
console.log(err);
}
}
const init = async () => {
const txApprove = await wbnb.approve(
router.address,
amountIn
);
const receipt = await txApprove.wait();
console.log('Transaction receipt of bnb');
console.log(receipt);
tokenswap();
}
init();
./build/contracts/MyContract.json is missing from the project screencast/264-intro-to-ethers
Still very new to this crypto programming.
It would be really helpful to see what is inside or how to make it.
Thank you for your time.
Hey,
can someone explain how should it work,
ethers.utils.parseUnits('0.1', 'ether');
So then we have:
tokenIn: 100000000000000000 (WETH)
I don't get it.
Hey
Hi,
I need to contact the maintainer of this repo. Can you please provide an email in the readme? Thank you.
Hello Everbody ,
PancakeSwap trading bot very complicated for beginner , I propose ; part by part.
stage : Only detected : "New pair detected"
stage : Buy new shit token
so , ı need only "New pair detected" bot
Like this : Only detected :
New pair detected
=================
token0: 0x48aBf1Ac9f66B508Ed40F07F1741eB62289e0051
token1: 0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c
pairAddress: 0x1b540C8411843463DdFF4A1Ac8D8930B1291C4F7
how can do this ? , can you help me for code , it must be very easy
I am looking to add .gasLimit and or .gasPrice to solve the estimate gas error..
I get the WBNB approval to work but then the script errors with estimate gas during the swap
Hey Julien.
on remix ...
I like your videos and I would like to offer you an improvement proposal:
Background:
I watched many of your videos and tried things out. When trying things out which you present, a lot of times it becomes clear that one needs to do significant adjustments before things work completely together - this issue is imo one example for this.
Solution Proposal:
It would be great if you could add the "plug and play part" at the end of your videos. Often times you will imo see that otherwise you would have missed out essential additional information or updates. I would be available for pair programming if this is appreciated.
Hi, the dapp created seem to only work with the first account connected. Is there a way to make it work for all connected account?
Hi Julien
I watch you flashloan course, run the code .
I have some question about this code
`
if(arbInfo.direction == Direction.KyberToUniswap) {
//Buy ETH on Kyber
dai.approve(address(kyber), balanceDai);
(uint expectedRate, ) = kyber.getExpectedRate(
dai,
IERC20(KYBER_ETH_ADDRESS),
balanceDai
);
kyber.swapTokenToEther(dai, balanceDai, expectedRate);
//Sell ETH on Uniswap
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = address(dai);
uint[] memory minOuts = uniswap.getAmountsOut(address(this).balance, path);
uniswap.swapExactETHForTokens.value(address(this).balance)(
minOuts[1],
path,
address(this),
now
);
}
`
why sell all eth balance at uniswap?
Why not the quantity of eth bought from kybar in the previous step?
amounOutMin -> amountOutMin
Here:
When running the frontend on a web browser, connected to ganache-cli, the web page is unable to execute the function getAll() and retrieve the array from the blockchain.
Error printed on the console [F12] is:
Uncaught (in promise) Error: Returned values aren't valid, did it run Out of Gas?
at ABICoder.decodeParameters (index.js:226)
at Contract._decodeMethodReturn (index.js:465)
at Method.outputFormatter (index.js:818)
at Method.formatOutput (index.js:163)
at sendTxCallback (index.js:473)
at eval (index.js:147)
at XMLHttpRequest.request.onreadystatechange (index.js:96)
at XMLHttpRequestEventTarget.dispatchEvent (xml-http-request-event-target.js:34)
at XMLHttpRequest._setReadyState (xml-http-request.js:208)
at XMLHttpRequest._onHttpResponseEnd
I searched in the forums and found that the issue could be with web3 or solc version used.
Could you review and do the needful.
got this error message:
./src/utils.js
Module not found: Can't resolve './contracts/Wallet.json' in 'C:\Users\James McClure\wallet\client\src'
Went back and check all code. It matches the repo code. Can you resolve please?
the bot do not work it says.....
Error: connect ECONNREFUSED 38.77.226.115:443
and some websocket error
and error: invalid bignumber string.
========= NOTICE =========
Request-Rate Exceeded (this message will not be repeated)
The default API keys for each service are provided as a highly-throttled,
community resource for low-traffic projects and early prototyping.
While your application will continue to function, we highly recommended
signing up for your own API keys to improve performance, increase your
request rate/limit and enable other perks, such as metrics and advanced APIs.
For more details: https://docs.ethers.io/api-keys
==========================
I'm getting this notice, although I am using my own Infura project ID and I can see the requests getting charted in my Infura dashboard.
I know it's not vital, and everything is running fine, but since it says using your own keys will improve performance etc., it might be important to get this working properly. I searched for this problem and someone suggested that perhaps 'somewhere in your code you are still using the default keys'.
As far as I understand, the only place where I need to refer to my Infura url (which includes my project ID), is in run-arbitrage.js, like this:
require("dotenv").config()
const Web3 = require('web3');
const { ChainId, Token, TokenAmount, Pair } = require('@uniswap/sdk');
const abis = require('./abis');
const { mainnet: addresses } = require('./addresses');
const Flashloan = require('./build/contracts/Flashloan.json');
const web3 = new Web3(
new Web3.providers.WebsocketProvider(process.env.INFURA_URL)
);
and then put this line in .env
INFURA_URL = wss://mainnet.infura.io/ws/v3/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
with xxxxxxxxxxxxxxxxxxxxxxxxxxx being the project ID.
Is it possible that some of the dependencies are somehow still using the default keys and also need to be provided with the personal key?
Trying to run the uniswap trading nodejs code without any modifications and running in to this error.
Error parsing defi/eattheblocks/screencast/330-uniswap-trading-nodejs/contracts/Router.sol: ParsedContract.sol:7:24:
ParserError: Expected token Comma got 'Identifier'
address[] calldata path,
^
Compilation failed. See above.
İf ı run node bot.js
I watch this problem . What can I do?
provider
wallet
account
factory
router
wbnb
PairCreated
Transaction receipt11
events.js:292
throw er; // Unhandled 'error' event
^
Error: Unexpected server response: 200
at ClientRequest. (C:\Users\ozgur\bot2\node_modules\ws\lib\websocket.js:580:7)
at ClientRequest.emit (events.js:315:20)
at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:641:27)
at HTTPParser.parserOnHeadersComplete (_http_common.js:126:17)
at TLSSocket.socketOnData (_http_client.js:509:22)
at TLSSocket.emit (events.js:315:20)
at addChunk (internal/streams/readable.js:309:12)
at readableAddChunk (internal/streams/readable.js:284:9)
at TLSSocket.Readable.push (internal/streams/readable.js:223:10)
at TLSWrap.onStreamRead (internal/stream_base_commons.js:188:23)
Emitted 'error' event on WebSocket instance at:
at abortHandshake (C:\Users\ozgur\bot2\node_modules\ws\lib\websocket.js:698:15)
at ClientRequest. (C:\Users\ozgur\bot2\node_modules\ws\lib\websocket.js:580:7)
[... lines matching original stack trace ...]
at TLSSocket.Readable.push (internal/streams/readable.js:223:10)
Bot.js does not executes transactions because of a simple check should be changed in the factory.on() body.
The factory returns token0 and token1 and the WBNB address contains uppercased letters which are different as hardcoded in the adresses.WBNB.
in Bot.js in the body of factory.on() there is a check:
if(token0 === addresses.WBNB)...
if(token1 === addresses.WBNB)...
should be:
if(token0.toUpperCase() === addresses.WBNB.toUpperCase())...
if(token1.toUpperCase() === addresses.WBNB.toUpperCase())...
The === is an explicit check that checks the data, as well as the datatype. But the letter 'a' is not equal to 'A'. If we uppercase all letters, then this issue is fixed.
The reason for this is that when you receive token0 and token1, the WBNB address contains letters that are uppercased and lowercased while adresses.WBNB contains all lowercase letters.
Hope this helps other devs out.
Hello,
Given recent changes introduced in Solidity 0.6.0, issues are appearing during compilation of project based on code from your lessons and repo:
The new keyword abstract can be used to mark contracts as abstract. It has to be used if a contract does not implement all its functions. Abstract contracts cannot be created using the new operator, and it is not possible to generate bytecode for them during compilation.
Libraries have to implement all their functions, not only the internal ones
Functions can now only be overridden when they are either marked with the virtual keyword or defined in an interface. Functions without implementation outside an interface have to be marked virtual. When overriding a function or modifier, the new keyword override must be used. When overriding a function or modifier defined in multiple parallel bases, all bases must be listed in parentheses after the keyword like so: override(Base1, Base2).
In case you add abstract to contract:
IUniswapV2Router02.sol:5:1: ParserError: Expected pragma, import directive o
r contract/interface/library definition.
abstract contract IUniswapV2Router02 is IUniswapV2Router01 {
^------^
Could you please provide some documentation reference and guidance how to proceed with latest versions of Solidity?
So I have been trying to adjust the bot to buy a specific token using swapExactETHForTokens instead of swapExactTokensForTokens since I heard that there is no need to approve when using the former.
const addresses = {
WBNB: '0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c',
factory: '0xcA143Ce32Fe78f1f7019d7d551a6402fC5350c73',
router: '0x10ed43c718714eb63d5aa57b78b54704e256024e',
recipient: 'my_wallet_address'
}
const mnemonic = 'seed phrase left our for obvious reasons';
const provider = new ethers.providers.WebSocketProvider('wss://bsc-ws-node.nariox.org:443');
const wallet = ethers.Wallet.fromMnemonic(mnemonic);
const account = wallet.connect(provider);
const router = new ethers.Contract(
addresses.router,
[
'function swapExactETHForTokens(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts)'
],
account
);
const init = async () => {
const options = {gasPrice: 5000000000, gasLimit: 400000 };
const amountIn = ethers.utils.parseUnits('0.1', 'ether');
const amountOutMin = 1
const tx = await router.swapExactETHForTokens(
amountIn,
amountOutMin,
[addresses.WBNB, '0xb3225ac90b741f762beca76dea1ead278ef26a96'], //just used a random token address, LOF in this case
addresses.recipient,
Date.now() + 1000 * 60 * 10, //10 minutes
options
);
console.log(`Transaction hash: ${tx.hash}`);
const receipt = await tx.wait();
console.log(`Transaction was mined in block ${receipt.blockNumber}`);
}
init();
But I get the following error all the time:
(node:22256) UnhandledPromiseRejectionWarning: Error: transaction failed (transactionHash="0x35bb3f987f4f99fab4572db341886220a400f791cb68bce401dcf00fd5099396", transaction={"nonce":348,"gasPrice":{"type":"BigNumber","hex":"0x012a05f200"},"gasLimit":{"type":"BigNumber","hex":"0x061a80"},"to":"0x10ED43C718714eb63d5aA57B78B54704E256024E","value":{"type":"BigNumber","hex":"0x00"},"data":"0xa5be382e000000000000000000000000000000000000000000000000000009184e72a000000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000b083653f11a5133868d56dacd723b837e27b7d17000000000000000000000000000000000000000000000000000001799a15a8690000000000000000000000000000000000000000000000000000000000000002000000000000000000000000bb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c000000000000000000000000b3225ac90b741f762beca76dea1ead278ef26a96","chainId":56,"v":148,"r":"0xb536f633a90b06f69a33467d24478dad64f868006a417ebbcd5525a372d6c9bf","s":"0x67c071f07c38723651c1b0e26dfa2bb42cc279587dc43326a2a4d52c81ed65d0","from":"it_shows_my_wallet_address_here_but_i_left_it_out","hash":"0x35bb3f987f4f99fab4572db341886220a400f791cb68bce401dcf00fd5099396"}, receipt={"to":"0x10ED43C718714eb63d5aA57B78B54704E256024E","from":"it_shows_my_wallet_address_here_but_i_left_it_out","contractAddress":null,"transactionIndex":324,"gasUsed":{"type":"BigNumber","hex":"0x5a8b"},"logsBloom":"0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","blockHash":"0x2ee5c5c282a605193f282aa34e31fa18c62ff3fdc6cd996e1592be49cdb60e03","transactionHash":"0x35bb3f987f4f99fab4572db341886220a400f791cb68bce401dcf00fd5099396","logs":[],"blockNumber":7663738,"confirmations":1,"cumulativeGasUsed":{"type":"BigNumber","hex":"0x02bf7565"},"status":0,"byzantium":true}, code=CALL_EXCEPTION, version=providers/5.0.24)
at Logger.makeError (C:\Users\Genray\Desktop\trading-bot\node_modules\@ethersproject\logger\lib\index.js:180:21)
at Logger.throwError (C:\Users\Genray\Desktop\trading-bot\node_modules\@ethersproject\logger\lib\index.js:189:20)
at WebSocketProvider.<anonymous> (C:\Users\Genray\Desktop\trading-bot\node_modules\@ethersproject\providers\lib\base-provider.js:1162:36)
at step (C:\Users\Genray\Desktop\trading-bot\node_modules\@ethersproject\providers\lib\base-provider.js:48:23)
at Object.next (C:\Users\Genray\Desktop\trading-bot\node_modules\@ethersproject\providers\lib\base-provider.js:29:53)
at fulfilled (C:\Users\Genray\Desktop\trading-bot\node_modules\@ethersproject\providers\lib\base-provider.js:20:58)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:22256) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:22256) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
When I look up the taransaction details at Bscscan it always says Status: Fail
and after a little bit of time
Warning! Error encountered during contract execution [execution reverted]
Could someone help me? I can not seem to locate where the error lies.
Hey! I'm trying to buy and sell tokens on pancakeswap v2. I'm buying tokens with WBNB and it's working correctly.. but when I try to sell my tokens (so my tokenOut is WBNB) transaction fails.
My code and output..
Sending parameters are:
slippageTolerance => 10
gasPrice => 5
gasLimit => 210000
`
const http = require('http');
const ethers = require('ethers');
http.createServer(function (req, res) {
const baseURL = req.protocol + '://' + req.headers.host + '/';
const reqUrl = new URL(req.url,baseURL);
if (reqUrl.searchParams.get('walletId') === null) {
res.write('alive');
res.end();
return;
}
const action = reqUrl.searchParams.get('action');
const addresses = {
originAddress: reqUrl.searchParams.get('originAddress'),
targetAddress: reqUrl.searchParams.get('targetAddress'),
factory: reqUrl.searchParams.get('factory'),
router: reqUrl.searchParams.get('router'),
recipient: reqUrl.searchParams.get('walletId')
}
const privateKey = reqUrl.searchParams.get('privateKey');
const myGasPrice = ethers.utils.parseUnits(reqUrl.searchParams.get('gasPrice'), 'gwei');
const provider = new ethers.providers.JsonRpcProvider('https://bsc-dataseed1.binance.org/');
const wallet = new ethers.Wallet(privateKey);
const account = wallet.connect(provider);
const router = new ethers.Contract(
addresses.router,
[
'function getAmountsOut(uint amountIn, address[] memory path) public view returns (uint[] memory amounts)',
'function swapExactTokensForTokens(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts)'
],
account
);
const originContract = new ethers.Contract(
addresses.originAddress,
[
'function approve(address spender, uint amount) public returns(bool)',
],
account
);
const testTx = async () => {
console.log('after testtx');
const tokenIn = addresses.originAddress , tokenOut = addresses.targetAddress;
const amountIn = ethers.utils.parseUnits(reqUrl.searchParams.get('amountIn'), 'ether');
const amounts = await router.getAmountsOut(amountIn, [tokenIn, tokenOut]);
//Our execution price will be a bit different, we need some flexbility
const amountOutMin = amounts[1].sub(amounts[1].div(parseInt(reqUrl.searchParams.get('slippageTolerance'))));
console.log('
tokenIn: ${amountIn} ${tokenIn}
tokenOut: ${amountOutMin} ${tokenOut}
');
const tx = await router.swapExactTokensForTokens(
amountIn,
amountOutMin,
[tokenIn, tokenOut],
addresses.recipient,
Math.floor(Date.now() / 1000) + 60 * 20, // 20 minutes from the current Unix time
{
gasPrice: myGasPrice,
gasLimit: parseInt(reqUrl.searchParams.get('gasLimit'))
}
);
console.log('line 115');
const receipt = await tx.wait();
console.log('Transaction receipt');
console.log(receipt);
console.log('Transaction amounts');
console.log(amounts);
}
if (action === 'swapOnly') {
testTx();
} else {
console.log('Before Approve');
const valueToApprove = ethers.utils.parseUnits(reqUrl.searchParams.get('valueToApprove'), 'ether');
const init = async () => {
const tx = await originContract.approve(
router.address,
valueToApprove,
{
gasPrice: myGasPrice,
gasLimit: parseInt(reqUrl.searchParams.get('gasLimit'))
}
);
console.log('After Approve');
const receipt = await tx.wait();
console.log('Transaction receipt');
console.log(receipt);
console.log('Run TEST-TX');
if (action !== 'approveOnly') {
testTx();
}
}
init();
}
res.write('success');
res.end();
}).listen(3030);`
`
tokenIn: 250296617395320000000000000 0x4cbdfad03b968bf43449d0908f319ae4a5a33371
tokenOut: 761663233022492496404 0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c
line 115
(node:1) UnhandledPromiseRejectionWarning: Error: transaction failed (transactionHash="0x78225d5214194dd0683b2cff32e2b57c37a3c4ae39b39f42f49db802be60b190", transaction={"nonce":85,"gasPrice":{"type":"BigNumber","hex":"0x012a05f200"},"gasLimit":{"type":"BigNumber","hex":"0x03d090"},"to":"0x10ED43C718714eb63d5aA57B78B54704E256024E","value":{"type":"BigNumber","hex":"0x00"},"data":"0x38ed1739000000000000000000000000000000000000000000cf0a5ed139d9491f9f80000000000000000000000000000000000000000000000000294a3362f81d3d521400000000000000000000000000000000000000000000000000000000000000a000000000000000000000000082084929560e3c274373e5cdcd9a5dbbf8c3b1cd0000000000000000000000000000000000000000000000000000000060b5017d00000000000000000000000000000000000000000000000000000000000000020000000000000000000000004cbdfad03b968bf43449d0908f319ae4a5a33371000000000000000000000000bb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c","chainId":56,"v":147,"r":"0x2427f352d2299477db485ad812d7d47957643489d127e93eeee9ba35e79367ac","s":"0x47b27ad4973c5c339d4ecac9f19e343f2491d8bb22e2dd3cfaf3b9bd03417bb4","from":"0x82084929560E3C274373e5CdCD9A5DBbf8C3b1cD","hash":"0x78225d5214194dd0683b2cff32e2b57c37a3c4ae39b39f42f49db802be60b190","type":null}, receipt={"to":"0x10ED43C718714eb63d5aA57B78B54704E256024E","from":"0x82084929560E3C274373e5CdCD9A5DBbf8C3b1cD","contractAddress":null,"transactionIndex":144,"gasUsed":{"type":"BigNumber","hex":"0xde07"},"logsBloom":"0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","blockHash":"0x0a138a74834c6802e0dd3b3ecfcef62d5b206a6d6a5bd5d78c26b2e0ad878d55","transactionHash":"0x78225d5214194dd0683b2cff32e2b57c37a3c4ae39b39f42f49db802be60b190","logs":[],"blockNumber":7891530,"confirmations":1,"cumulativeGasUsed":{"type":"BigNumber","hex":"0x015737ed"},"status":0,"byzantium":true}, code=CALL_EXCEPTION, version=providers/5.2.0)
at Logger.makeError (/app/node_modules/@ethersproject/logger/lib/index.js:187:21)
at Logger.throwError (/app/node_modules/@ethersproject/logger/lib/index.js:196:20)
at JsonRpcProvider. (/app/node_modules/@ethersproject/providers/lib/base-provider.js:1301:36)
at step (/app/node_modules/@ethersproject/providers/lib/base-provider.js:48:23)
at Object.next (/app/node_modules/@ethersproject/providers/lib/base-provider.js:29:53)
at fulfilled (/app/node_modules/@ethersproject/providers/lib/base-provider.js:20:58)
(node:1) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag '--unhandled-rejections=strict' (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:1) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.`
Whenever i run your code it says eth_subscribe does not exist. Whats happening here?
Julien,
Should the Arbitrage
contract implement the IUniswapV2Callee
interface here?
This issue relates to "348-pancakeswap-trading-bot". I'm running your code 1:1 without any changes except for the WebSocket URL of my Ankr project. Everytime I start, I'm getting this error:
events.js:174
throw er; // Unhandled 'error' event
^
Error: Client network socket disconnected before secure TLS connection was established
at TLSSocket.onConnectEnd (_tls_wrap.js:1095:19)
at Object.onceWrapper (events.js:286:20)
at TLSSocket.emit (events.js:203:15)
at endReadableNT (_stream_readable.js:1145:12)
at process._tickCallback (internal/process/next_tick.js:63:19)
Emitted 'error' event at:
at ClientRequest.req.on (/root/bsc-sniper-bot/node_modules/ws/lib/websocket.js:555:15)
at ClientRequest.emit (events.js:198:13)
at TLSSocket.socketErrorListener (_http_client.js:401:9)
at TLSSocket.emit (events.js:198:13)
at emitErrorNT (internal/streams/destroy.js:91:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:59:3)
at process._tickCallback (internal/process/next_tick.js:63:19)
I've tried it at my desktop, on a server (other network) and at my work laptop. Always the same result. None of the computers does having a proxy setup or alike.
put your wallet address in
put your private key in
put your wss provider in
add bnb and wbnb to your wallet and have fun buying all of the shit coins every 3 secs…
-Mike
const ethers = require(‘ethers’);
const addresses = {
WBNB: ‘0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c’,
BUSD: ‘0xe9e7cea3dedca5984780bafc599bd69add087d56’,
factory: ‘0xcA143Ce32Fe78f1f7019d7d551a6402fC5350c73’,
router: ‘0x10ed43c718714eb63d5aa57b78b54704e256024e’,
recipient: ‘’
}
//First address of this mnemonic must have enough BNB to pay for tx fess
const privateKey = ‘’;
const mygasPrice = ethers.utils.parseUnits(‘5’, ‘gwei’);
const provider = new ethers.providers.WebSocketProvider(‘wss://muddy-young-frost.bsc.quiknode.pro/’);
const wallet = new ethers.Wallet(privateKey);
const account = wallet.connect(provider);
const factory = new ethers.Contract(
addresses.factory,
[‘event PairCreated(address indexed token0, address indexed token1, address pair, uint)’],
account
);
const router = new ethers.Contract(
addresses.router,
[
‘function getAmountsOut(uint amountIn, address[] memory path) public view returns (uint[] memory amounts)’,
‘function swapExactTokensForTokens(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts)’
],
account
);
const wbnb = new ethers.Contract(
addresses.WBNB,
[
‘function approve(address spender, uint amount) public returns(bool)’,
],
account
);
console.log(Before Approve);
const valueToapprove = ethers.utils.parseUnits(‘0.1’, ‘ether’);
const init = async () => {
const tx = await wbnb.approve(
router.address,
valueToapprove,
{
gasPrice: mygasPrice,
gasLimit: ‘162445’
}
);
console.log(After Approve);
const receipt = await tx.wait();
console.log(‘Transaction receipt’);
console.log(receipt);
}
factory.on(‘PairCreated’, async (token0, token1, pairAddress) => {
console.log(after factory.on:);
console.log( New pair detected ================= token0: ${token0} token1: ${token1} pairAddress: ${pairAddress} );
//The quote currency needs to be WBNB (we will pay with WBNB)
let tokenIn, tokenOut;
if(token0 === addresses.WBNB) {
tokenIn = token0;
tokenOut = token1;
}
if(token1 == addresses.WBNB) {
tokenIn = token1;
tokenOut = token0;
}
//The quote currency is not WBNB
if(typeof tokenIn === ‘undefined’) {
return;
}
//We buy for 0.1 BNB of the new token
//ethers was originally created for Ethereum, both also work for BSC
//‘ether’ === ‘bnb’ on BSC
console.log(line 87);
const amountIn = ethers.utils.parseUnits(‘0.01’, ‘ether’);
const amounts = await router.getAmountsOut(amountIn, [tokenIn, tokenOut]);
//Our execution price will be a bit different, we need some flexbility
const amountOutMin = amounts[1].sub(amounts[1].div(10));
console.log(line 92);
console.log( Buying new token ================= tokenIn: ${amountIn} ${tokenIn} (WBNB) tokenOut: ${amountOutMin} ${tokenOut} );
console.log(line 101);
const tx = await router.swapExactTokensForTokens(
amountIn,
amountOutMin,
[tokenIn, tokenOut],
addresses.recipient,
Math.floor(Date.now() / 1000) + 60 * 20, // 20 minutes from the current Unix time
{
gasPrice: mygasPrice,
gasLimit: 162445
}
);
console.log(line 117);
const receipt = await tx.wait();
console.log(‘Transaction receipt’);
console.log(receipt);
});
init();
On line 85 of
https://github.com/jklepatch/eattheblocks/blob/master/screencast/348-pancakeswap-trading-bot/bot.js
'amounOutMin' should be 'amountOutMin'
Hi.
I'm trying to test PancakeSwap bot but I'm stuck with this error. Couldn't find answer anywehere yet so maybe someone can help me. I've created Ankr Api, copied wss websocket adress to the code but get this error:
Error: Unexpected server response: 401
at ClientRequest. (C:\Users\Justinas\Desktop\pcs bot\node_modules\ws\lib\websocket.js:580:7)
at ClientRequest.emit (events.js:376:20)
at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:647:27)
at HTTPParser.parserOnHeadersComplete (_http_common.js:126:17)
at TLSSocket.socketOnData (_http_client.js:515:22)
at TLSSocket.emit (events.js:376:20)
at addChunk (internal/streams/readable.js:309:12)
at readableAddChunk (internal/streams/readable.js:284:9)
at TLSSocket.Readable.push (internal/streams/readable.js:223:10)
at TLSWrap.onStreamRead (internal/stream_base_commons.js:188:23)
Emitted 'error' event on WebSocket instance at:
at abortHandshake (C:\Users\Justinas\Desktop\pcs bot\node_modules\ws\lib\websocket.js:698:15)
at ClientRequest. (C:\Users\Justinas\Desktop\pcs bot\node_modules\ws\lib\websocket.js:580:7)
[... lines matching original stack trace ...]
at TLSSocket.Readable.push (internal/streams/readable.js:223:10)
Hi, I tried this bot and it started buying the tokens but I had around $1 worth of BNB and $15 worth of WBNB in my wallet so the bot bought some of the tokens but once the BNB balance finished for gas fee the program just crashed and wasn't able to sell the bought tokens because a few of them went up a bit in minutes. My question is how do we make the bot remember which tokens it bought and the price to sell it for so that next time when we run the bot it actually tries to sell the previously bought tokens when they hit the target price and also how to make it not crash and keep trying until there is some balance in BNB wallet please?
Following the video exactly, const kyberRates
, buy and sell are returning numbers with 12 decimal places and not the 14 shown in the video.
For example, my numbers all look like 2094.312902559671
.
In the video, numbers all look like 223.45181217123485
.
How do I understand if this is correct?
Thanks!
Hello,
I'm trying to understand what's happening here...
when I declare a variable and call parseUnits:
const amountIn = ethers.utils.parseUnits('0.01', 'ether')
the result is:
tokenIn: 10000000000000000
Do you know why it is 10000000000000000
?
Please help.
Thanks!
Hi,
Following your latest youtube video with PancakeSwap trading bot, I get this error and can't seem to find why or where it happens:
(node:21378) UnhandledPromiseRejectionWarning: Error: invalid BigNumber string (argument="value", value="0.1", code=INVALID_ARGUMENT, version=bignumber/5.1.1)
at Logger.makeError (/home/pancake-trading-bot/node_modules/@ethersproject/logger/lib/index.js:180:21)
at Logger.throwError (/home/pancake-trading-bot/node_modules/@ethersproject/logger/lib/index.js:189:20)
at Logger.throwArgumentError (/home//pancake-trading-bot/node_modules/@ethersproject/logger/lib/index.js:192:21)
at Function.BigNumber.from (/home/pancake-trading-bot/node_modules/@ethersproject/bignumber/lib/bignumber.js:201:27)
at NumberCoder.encode (/home/pancake-trading-bot/node_modules/@ethersproject/abi/lib/coders/number.js:36:39)
at /home/pancake-trading-bot/node_modules/@ethersproject/abi/lib/coders/array.js:74:19
at Array.forEach (<anonymous>)
at Object.pack (/home/pancake-trading-bot/node_modules/@ethersproject/abi/lib/coders/array.js:60:12)
at TupleCoder.encode (/home/pancake-trading-bot/node_modules/@ethersproject/abi/lib/coders/tuple.js:71:24)
at AbiCoder.encode (/home/pancake-trading-bot/node_modules/@ethersproject/abi/lib/abi-coder.js:93:15)
(node:21378) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:21378) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Any idea?
This issue is for 'Profitable Flashloans' but it looks like it applies to other courses. I'm a tech writer with reasonable Python skills + a bit of JS and yet I have no friggin' clue what to do next. Anyone considering Eattheblocks courses should also be interested in this thread - How's the support? How explicit are course instructions? How well are the courses maintained?
Following the course instructions + the Uniswap V2 instructions, I installed npm install @uniswap/sdk
.
The course uses fetchData
which appears to be Uniswap V1.
Saw #53 and verified that some form of fetchTokenData
and fetchPairData
is for Uniswap V2
I thought I was using V2. When I couldn't get Fetcher to work, looked at package.json
and see I have @uniswap/sdk ^3.0.3
I imagine this means I have Uniswap V3 which is weird because the install commands are totally different. Here's the V3 instructions:
Adding to my saga, I don't understand the V3 documentation at all - I see nothing about Fetch, and all of it looks very different from V2.
I need detailed, explicit instructions on what to do here, otherwise the course in unusable for me.
And clearly the courses need updating - the V1 instructions are completely outdated and the V2 - V3 straddle needs to be addressed.
Hi I have followed lesson 15 to the end and there is no output when running run-arbitrage
Visual studio error is **File 'C:/Users/Blair/profitable-flashloans/node_modules/defer-to-connect/dist' not found.
**
When I run run-arbitrage.js in the terminal there is blank space and unresponsiveness. What is the problem and how to proceed? Thank you
are you able to send thru email?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.