Creating a Python Wrapper from a JavaScript code - javascript
Problem Statement
I wrote a JavaScript code to pull data from Uniswap V3 SDK (https://www.npmjs.com/package/#uniswap/v3-sdk) and I would like to open-source this code on GitHub because currently this isn't possible (for specific use cases). I am not an amazing system designer/programmer so please bare with me (I can only code in Python and barely understand JavaScript).
Essentially, I have a JavaScript code that pulls data and I wanted to wrap it in a Python code, so I can then take the data and do other things with the data (create alerts, flask app, etc.)
I am using Ubuntu, JS6, npm v8.19.2 and Node v16.18.1.
In my research, I found two packages that could help enable me wrapping this JS code in Python:
py2js - https://github.com/PiotrDabkowski/Js2Py
stpyv8 - https://github.com/cloudflare/stpyv8
Coding Attempt
py2js attempt
This package only works for JS5 and below, not JS6. Here is a quote from the GitHub that helps explain the workaround for this issue (which uses babel) https://github.com/PiotrDabkowski/Js2Py:
JavaScript 6 support was achieved by using Js2Py to translate javascript library called Babel. Babel translates JS 6 to JS 5 and afterwards Js2Py translates JS 5 to Python.
While trying this solution out, I am getting the following error:
/home/bobby/uni_balances/uni_venv/lib/python3.10/site-packages/js2py/es6/__init__.py:10: UserWarning:
Importing babel.py for the first time - this can take some time.
Please note that currently Javascript 6 in Js2Py is unstable and slow. Use only for tiny scripts!
warnings.warn(
/home/bobby/uni_balances/uni_venv/lib/python3.10/site-packages/js2py/base.py:2854: FutureWarning: Possible nested set at position 5
self.pat = re.compile(
Initialised babel!
Traceback (most recent call last):
File "/home/bobby/uni_balances/main.py", line 104, in <module>
result = js2py.eval_js6(js) # executing JavaScript and converting the result to python string
File "/home/bobby/uni_balances/uni_venv/lib/python3.10/site-packages/js2py/evaljs.py", line 120, in eval_js6
return eval_js(js6_to_js5(js))
File "/home/bobby/uni_balances/uni_venv/lib/python3.10/site-packages/js2py/evaljs.py", line 115, in eval_js
return e.eval(js)
File "/home/bobby/uni_balances/uni_venv/lib/python3.10/site-packages/js2py/evaljs.py", line 204, in eval
self.execute(code, use_compilation_plan=use_compilation_plan)
File "/home/bobby/uni_balances/uni_venv/lib/python3.10/site-packages/js2py/evaljs.py", line 199, in execute
exec (compiled, self._context)
File "<EvalJS snippet>", line 4, in <module>
File "<EvalJS snippet>", line 3, in PyJs_LONG_0_
File "/home/bobby/uni_balances/uni_venv/lib/python3.10/site-packages/js2py/base.py", line 949, in __call__
return self.call(self.GlobalObject, args)
File "/home/bobby/uni_balances/uni_venv/lib/python3.10/site-packages/js2py/base.py", line 1464, in call
return Js(self.code(*args))
File "/home/bobby/uni_balances/uni_venv/lib/python3.10/site-packages/js2py/host/jseval.py", line 17, in Eval
py_code = translate_js(code.to_string().value, '')
File "/home/bobby/uni_balances/uni_venv/lib/python3.10/site-packages/js2py/translators/translator.py", line 70, in translate_js
parsed = parse_fn(js)
File "/home/bobby/uni_balances/uni_venv/lib/python3.10/site-packages/js2py/translators/translator.py", line 62, in pyjsparser_parse_fn
return parser.parse(code)
File "/home/bobby/uni_balances/uni_venv/lib/python3.10/site-packages/pyjsparser/parser.py", line 3008, in parse
program = self.parseProgram()
File "/home/bobby/uni_balances/uni_venv/lib/python3.10/site-packages/pyjsparser/parser.py", line 2974, in parseProgram
body = self.parseScriptBody()
File "/home/bobby/uni_balances/uni_venv/lib/python3.10/site-packages/pyjsparser/parser.py", line 2963, in parseScriptBody
statement = self.parseStatementListItem()
File "/home/bobby/uni_balances/uni_venv/lib/python3.10/site-packages/pyjsparser/parser.py", line 2110, in parseStatementListItem
return self.parseStatement()
File "/home/bobby/uni_balances/uni_venv/lib/python3.10/site-packages/pyjsparser/parser.py", line 2718, in parseStatement
self.consumeSemicolon()
File "/home/bobby/uni_balances/uni_venv/lib/python3.10/site-packages/pyjsparser/parser.py", line 1120, in consumeSemicolon
self.throwUnexpectedToken(self.lookahead)
File "/home/bobby/uni_balances/uni_venv/lib/python3.10/site-packages/pyjsparser/parser.py", line 1046, in throwUnexpectedToken
raise self.unexpectedTokenError(token, message)
js2py.internals.simplex.JsException: SyntaxError: Line 34: Unexpected token function
What have I done to try to fix this?
I have updated node and even downgraded to version 5 as some suggested, but nothing worked.
JavaScript Code
Here is the JavaScript code (note that you would need an Alchemy API ID to run this script):
import { JSBI } from "#uniswap/sdk";
import { ethers } from 'ethers';
import * as fs from 'fs';
// ERC20 json abi file
let ERC20Abi = fs.readFileSync('Erc20.json');
const ERC20 = JSON.parse(ERC20Abi);
// V3 pool abi json file
let pool = fs.readFileSync('V3PairAbi.json');
const IUniswapV3PoolABI = JSON.parse(pool);
// V3 factory abi json
let facto = fs.readFileSync('V3factory.json');
const IUniswapV3FactoryABI = JSON.parse(facto);
let NFT = fs.readFileSync('UniV3NFT.json');
const IUniswapV3NFTmanagerABI = JSON.parse(NFT);
const provider = new ethers.providers.JsonRpcProvider(ALCHEMY_API_ID)
// V3 standard addresses (different for celo)
const factory = "0x1F98431c8aD98523631AE4a59f267346ea31F984";
const NFTmanager = "0xC36442b4a4522E871399CD717aBDD847Ab11FE88";
async function getData(tokenID){
let FactoryContract = new ethers.Contract(factory, IUniswapV3FactoryABI, provider);
let NFTContract = new ethers.Contract(NFTmanager, IUniswapV3NFTmanagerABI, provider);
let position = await NFTContract.positions(tokenID);
let token0contract = new ethers.Contract(position.token0, ERC20, provider);
let token1contract = new ethers.Contract(position.token1, ERC20, provider);
let token0Decimal = await token0contract.decimals();
let token1Decimal = await token1contract.decimals();
let token0sym = await token0contract.symbol();
let token1sym = await token1contract.symbol();
let V3pool = await FactoryContract.getPool(position.token0, position.token1, position.fee);
let poolContract = new ethers.Contract(V3pool, IUniswapV3PoolABI, provider);
let slot0 = await poolContract.slot0();
let pairName = token0sym +"/"+ token1sym;
let dict = {"SqrtX96" : slot0.sqrtPriceX96.toString(), "Pair": pairName, "T0d": token0Decimal, "T1d": token1Decimal, "tickLow": position.tickLower, "tickHigh": position.tickUpper, "liquidity": position.liquidity.toString()}
return dict
}
const Q96 = JSBI.exponentiate(JSBI.BigInt(2), JSBI.BigInt(96));
const MIN_TICK = -887272;
const MAX_TICK = 887272;
function getTickAtSqrtRatio(sqrtPriceX96){
let tick = Math.floor(Math.log((sqrtPriceX96/Q96)**2)/Math.log(1.0001));
return tick;
}
async function getTokenAmounts(liquidity,sqrtPriceX96,tickLow,tickHigh,token0Decimal,token1Decimal){
let sqrtRatioA = Math.sqrt(1.0001**tickLow).toFixed(18);
let sqrtRatioB = Math.sqrt(1.0001**tickHigh).toFixed(18);
let currentTick = getTickAtSqrtRatio(sqrtPriceX96);
let sqrtPrice = sqrtPriceX96 / Q96;
let amount0wei = 0;
let amount1wei = 0;
if(currentTick <= tickLow){
amount0wei = Math.floor(liquidity*((sqrtRatioB-sqrtRatioA)/(sqrtRatioA*sqrtRatioB)));
}
if(currentTick > tickHigh){
amount1wei = Math.floor(liquidity*(sqrtRatioB-sqrtRatioA));
}
if(currentTick >= tickLow && currentTick < tickHigh){
amount0wei = Math.floor(liquidity*((sqrtRatioB-sqrtPrice)/(sqrtPrice*sqrtRatioB)));
amount1wei = Math.floor(liquidity*(sqrtPrice-sqrtRatioA));
}
let amount0Human = (amount0wei/(10**token0Decimal)).toFixed(token0Decimal);
let amount1Human = (amount1wei/(10**token1Decimal)).toFixed(token1Decimal);
console.log("Amount Token0 wei: "+amount0wei);
console.log("Amount Token1 wei: "+amount1wei);
console.log("Amount Token0 : "+amount0Human);
console.log("Amount Token1 : "+amount1Human);
return [amount0wei, amount1wei]
}
async function start(positionID){
let data = await getData(positionID);
let tokens = await getTokenAmounts(data.liquidity, data.SqrtX96, data.tickLow, data.tickHigh, data.T0d, data.T1d);
}
start(273381)
// Also it can be used without the position data if you pull the data it will work for any range
getTokenAmounts(12558033400096537032, 20259533801624375790673555415)
Python Code
Here is the python code I wrote using the js2py package. To save space, I removed the JS Code in the js variable below, but you can copy it from above and place it in the triple quotes:
import js2py
js = """
<<< JS CODE COPIED HERE >>>
""".replace("document.write", "return ")
result = js2py.eval_js6(js) # executing JavaScript and converting the result to python string
One other note, you will need to install babel as well to make it work. Babel will help convert the code from JS6 to JS5.
stpyv8 attempt
This package is maintained by Cloudflare, which makes this a much more attractive approach, but I am having difficulty installing the pyv8 package on my machine.
I was able to successfully run:
sudo apt install python3 python3-dev build-essential libboost-dev libboost-system-dev libboost-python-dev libboost-iostreams-dev
The probem is that I now need to run setup.py, which I can't find. I also below, if you look at the pyv8 installation I tried below, it does it automatically, but it throws an error. Seems like I am getting stuck at trying to run setup.py
pyv8 attempt (alternative to stpyv8 I believe)
https://code.google.com/archive/p/pyv8/
When I run pip3 install -v pyv8, I get the following error:
Using pip 22.0.2 from /home/bobby/uni_balances/uni_venv/lib/python3.10/site-packages/pip (python 3.10)
Collecting pyv8
Using cached PyV8-0.5.zip (22 kB)
Running command python setup.py egg_info
running egg_info
creating /tmp/pip-pip-egg-info-g__o7shf/PyV8.egg-info
writing /tmp/pip-pip-egg-info-g__o7shf/PyV8.egg-info/PKG-INFO
writing dependency_links to /tmp/pip-pip-egg-info-g__o7shf/PyV8.egg-info/dependency_links.txt
writing top-level names to /tmp/pip-pip-egg-info-g__o7shf/PyV8.egg-info/top_level.txt
writing manifest file '/tmp/pip-pip-egg-info-g__o7shf/PyV8.egg-info/SOURCES.txt'
reading manifest file '/tmp/pip-pip-egg-info-g__o7shf/PyV8.egg-info/SOURCES.txt'
writing manifest file '/tmp/pip-pip-egg-info-g__o7shf/PyV8.egg-info/SOURCES.txt'
Preparing metadata (setup.py) ... done
Using legacy 'setup.py install' for pyv8, since package 'wheel' is not installed.
Installing collected packages: pyv8
Running command Running setup.py install for pyv8
running install
/home/bobby/uni_balances/uni_venv/lib/python3.10/site-packages/setuptools/command/install.py:34: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.
warnings.warn(
running build
running build_py
creating build
creating build/lib.linux-x86_64-3.10
copying PyV8.py -> build/lib.linux-x86_64-3.10
running build_ext
building '_PyV8' extension
creating build/temp.linux-x86_64-3.10
creating build/temp.linux-x86_64-3.10/src
x86_64-linux-gnu-gcc -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -g -fwrapv -O2 -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -DBOOST_PYTHON_STATIC_LIB -Ilib/python/inc -Ilib/boost/inc -Ilib/v8/inc -I/home/bobby/uni_balances/uni_venv/include -I/usr/include/python3.10 -c src/Context.cpp -o build/temp.linux-x86_64-3.10/src/Context.o
In file included from src/Wrapper.h:8,
from src/Context.h:7,
from src/Context.cpp:1:
src/Exception.h:6:10: fatal error: v8.h: No such file or directory
6 | #include <v8.h>
| ^~~~~~
compilation terminated.
error: command '/usr/bin/x86_64-linux-gnu-gcc' failed with exit code 1
error: subprocess-exited-with-error
× Running setup.py install for pyv8 did not run successfully.
│ exit code: 1
╰─> See above for output.
note: This error originates from a subprocess, and is likely not a problem with pip.
full command: /home/bobby/uni_balances/uni_venv/bin/python3 -u -c '
exec(compile('"'"''"'"''"'"'
# This is <pip-setuptools-caller> -- a caller that pip uses to run setup.py
#
# - It imports setuptools before invoking setup.py, to enable projects that directly
# import from `distutils.core` to work with newer packaging standards.
# - It provides a clear error message when setuptools is not installed.
# - It sets `sys.argv[0]` to the underlying `setup.py`, when invoking `setup.py` so
# setuptools doesn'"'"'t think the script is `-c`. This avoids the following warning:
# manifest_maker: standard file '"'"'-c'"'"' not found".
# - It generates a shim setup.py, for handling setup.cfg-only projects.
import os, sys, tokenize
try:
import setuptools
except ImportError as error:
print(
"ERROR: Can not execute `setup.py` since setuptools is not available in "
"the build environment.",
file=sys.stderr,
)
sys.exit(1)
__file__ = %r
sys.argv[0] = __file__
if os.path.exists(__file__):
filename = __file__
with tokenize.open(__file__) as f:
setup_py_code = f.read()
else:
filename = "<auto-generated setuptools caller>"
setup_py_code = "from setuptools import setup; setup()"
exec(compile(setup_py_code, filename, "exec"))
'"'"''"'"''"'"' % ('"'"'/tmp/pip-install-b9d0zoul/pyv8_c9dfd2e4ec0e4c66a2bff47f44972004/setup.py'"'"',), "<pip-setuptools-caller>", "exec"))' install --record /tmp/pip-record-pel12p8h/install-record.txt --single-version-externally-managed --compile --install-headers /home/bobby/uni_balances/uni_venv/include/site/python3.10/pyv8
cwd: /tmp/pip-install-b9d0zoul/pyv8_c9dfd2e4ec0e4c66a2bff47f44972004/
Running setup.py install for pyv8 ... error
error: legacy-install-failure
× Encountered error while trying to install package.
╰─> pyv8
note: This is an issue with the package mentioned above, not pip.
hint: See above for output from the failure.
Conclusion
I am not married to using the two options I mentioned above, but I would like to pull the data into Python from the JS code.
Also this is the output from the JS code that I need to port over into Python:
Related
Mongo shell script - How to use libraries?
In a Mongo shell script I need to read a file to delete documents by _id but I can't import the FileReader library. I launch script from bash to do simple find() and it works: mongosh --host xxx --port 27017 --username xxx --password xxx --eval "var country='$country';var file='$inputDataFile'" --file scriptFile.js But whenever I try to import a library in the js it shows the error: TypeError: Cannot assign to read only property 'message' of object 'SyntaxError: 'import' and 'export' may appear only with 'sourceType The same js file I call from nodejs and the import is correct. Right now I do the deletion of _ids contained in a file using nodejs. I would like to find a way to use Mongo shell script for all my queries
I managed to solve my problem with the help of Include External Files and Modules in Scripts Create package.json in the same directory as your js Add the necessary libraries to package.json Install libraries Use require to import it Code var fs = require('fs'); console.log(country) console.log(file) db = db.getSiblingDB('mongotest') const allFileContents = fs.readFileSync(file, 'utf-8'); var lines = allFileContents.split("\r") for (var i = 0; i < lines.length; i++) { const user = JSON.parse(lines[i]); var userId = user._id if (!(userId instanceof ObjectId)) { userId = new ObjectId(userId); } db.userChat.deleteOne({ _id: userId }) } Thanks for your help
My Javascript file won't run because of bigint error
I am trying to use #metaplex/js to do some NFT minting. Usually my .js files work properly but when I run the file this error comes up. bigint: Failed to load bindings, pure JS will be used (try npm run rebuild?) I don't really get what that means. So, I tried to run npm run rebuild but rebuild is said to be a missing script and I couldn't find a way to install it. Here is my code: import { Connection, programs} from "#metaplex/js"; import { Loader } from "#solana/web3.js"; const { metadata: {Metadata}} = programs; const connection = new Connection("devnet"); const tokenPublicKey = 'my_adress'; const run = async() => { try{ const ownedMetadata = await Metadata.Loader(connection,tokenPublicKey) console.log(ownedMetadata) } catch{ console.log('Failed to fetch') } }; run(); If you have any idea, or simply an explanation of what my error means, I'd be grateful.
You are getting this error because a nested dependency has a compilation step that might not succeed in your platform. This issue provides a good explanation. [...] This happens because one of our dependencies (bigint-buffer) runs a compilation step on installation and this can step may fail for a couple of reasons. One of the reasons is that your system might not have the build-tools the library is looking for. You can install these build tools on Windows (see https://www.npmjs.com/package/windows-build-tools), but you don't actually need to as it automatically falls back to a pure JS solution instead. Though I agree... that warning is very annoying. However, this should give you a warning and still allow you to compile your code. It is worth noting that the current JS SDK from Metaplex is going to be deprecated in favour of the new one: https://github.com/metaplex-foundation/js-next With the new JS SDK, you can fetch an NFT using the following piece of code. import { Metaplex } from "#metaplex-foundation/js"; import { Connection, clusterApiUrl } from "#solana/web3.js"; const connection = new Connection(clusterApiUrl("mainnet-beta")); const metaplex = new Metaplex(connection); const mintAddress = new PublicKey("ATe3DymKZadrUoqAMn7HSpraxE4gB88uo1L9zLGmzJeL"); const nft = await metaplex.nfts().findByMint({ mintAddress });
get gulp version in gulpfile
Is there a way to detect what version of Gulp is running (available to utilize in a gulpfile)? I've got two separate gulpfile's I'm using amongst different environments, some that require v3 and some v4. For easier version control, I would prefer it if I could combine those files and not have to deal with different file names in different environments to eliminate confusion between multiple developers. Obviously to accomplish this I would need the script to differentiate between versions.
Alternatively to #alireza.salemian's solution, you could try to run the command line version command in javascript: Depending on your JavaScript backend, your code may vary slightly, but inspired by this post you could run it as below: const execSync = require('child_process').execSync; // import { execSync } from 'child_process'; // replace ^ if using ES modules const output = execSync('gulp -v', { encoding: 'utf-8' }); // the default is 'buffer' const str_pos = output.search('Local version') + 14; const gulp_version = output.substring( str_pos, str_pos + 5 ); console.log( 'Gulp version: ' + gulp_version );
You can read package.json and find gulp version const pkgJson = fs.readFileSync('./package.json', { encoding: 'utf8' }); const pkg = JSON.parse(pkgJson); const gulpVersion = pkg['devDependencies']['gulp']; It may not be the best solution, but you can quickly determine the gulp version.
Local server by PythonJS
I downloaded this demo server. I follow the instruction, so First, git clone this repo, and then run: npm install python-js. Now you are ready to run the server, run: ./run-demo.js and then open your browser to localhost:8080. Unfortunately I can't run run-demo.js beacuse I have this error --------------------------- Windows Script Host --------------------------- Line: 1 Character: 1 Error: Invalid character Code: 800A03F6 Source: Microsoft JScript - compilation error I try to run this by node.js console but have only "..." and nothing happend. This is code of run-demo.js: #!/usr/bin/env node var fs = require('fs') //var pythonjs = require('../PythonJS/pythonjs/python-js') var pythonjs = require('python-js') var pycode = fs.readFileSync( './server.py', {'encoding':'utf8'} ) var jscode = pythonjs.translator.to_javascript( pycode ) eval( pythonjs.runtime.javascript + jscode ) Any ideas? I want to run local server and use PythonJS
I don't believe # is a valid character in Javascript. If the run0demo.js file is being delivered to your browser, it certainly won't know what to make of the shebang (#!) line, which is used by the UNIX kernel to determine which executbale should be used to process the file.
If anyone else will be looking for solution, here is it: node run-demo.js Simple as... ;)
syntax validator for a less file
I need a validator for a less file. I need to validate a single less file, at only syntax level. I can't get the validator to follow the dependencies or detect if a mixin is declared or not. That is my real problem. I have found a lot of less processors which fail because the file has dependencies that i can't provide in this point of the process. npm package would be perfect.
Finally, I decided to use antlr4 Steps: install antlr in the computer or add to the deployment process get the grammar for your language (less is already done) get the npm package to process the grammar Use it in your app The configuration is: $ cd /usr/local/lib $ sudo curl -O http://www.antlr.org/download/antlr-4.5-complete.jar $ export CLASSPATH=".:/usr/local/lib/antlr-4.5-complete.jar:$CLASSPATH" $ alias antlr4='java -jar /usr/local/lib/antlr-4.5-complete.jar' $ alias grun='java org.antlr.v4.runtime.misc.TestRig This info is directly from the web page. Now you can get the grammar from https://github.com/antlr/grammars-v4 At this point you can generate the javascript version of your grammar In my case, I created a directory, I downloaded the files and coded all my tests inside: antlr4 -Dlanguage=JavaScript LessParser.g4 antlr4 -Dlanguage=JavaScript LessLexer.g4 This process generates a javascript file that you will use, but you need the antlr lib for use this files in your node program. npm link antlr4 Ant now starts to code: var antlr4 = require('antlr4/index'); var MyGrammarLexer = require('./LessLexer.js'); var MyGrammarParser = require('./LessParser.js'); var input = "html{ .hey(); color: #light-blue; background:#333}"; var chars = new antlr4.InputStream(input); var lexer = new MyGrammarLexer.LessLexer(chars); var tokens = new antlr4.CommonTokenStream(lexer); var parser = new MyGrammarParser.LessParser(tokens); parser.buildParseTrees = true; var ErrorListener = antlr4.error.ErrorListener; function CustomErrorListener() { ErrorListener.call(this); return this; } CustomErrorListener.prototype = Object.create(ErrorListener.prototype); CustomErrorListener.prototype.constructor = CustomErrorListener; CustomErrorListener.prototype.syntaxError = function(recognizer, offendingSymbol, line, column, msg, e) { throw ('throw a simple exception'); }; parser.addErrorListener(new CustomErrorListener()); try{ var tree = parser.stylesheet(); } catch (e){ console.log('I catch you!!!') } The important parts in this code are the function lessLexer, lessParser, and parser.stylesheet(); This are different per grammar. The last one is difficult to know, but it is the point in the grammar that you want to validate. In my case, I get the file LessParser.g4, and you have the different node in the grammar in the definition: parser grammar LessParser; options { tokenVocab=LessLexer; } stylesheet : statement* ; statement : importDeclaration | ruleset | variableDeclaration ';' | mixinDefinition ; variableName : AT variableName | AT Identifier ; commandStatement : (expression+) mathStatement? ; mathCharacter : TIMES | PLUS | DIV | MINUS | PERC ; In this case, you can validate the string like a stylesheet, statement, variableName ... The last interesting point is the Error Validation, I use it to stop the validation in the first error, my case is very simple, but you can improve this point